Skip to content
Snippets Groups Projects
avconv.c 150 KiB
Newer Older
  • Learn to ignore specific revisions
  •     if (codec_tag) {
            uint32_t tag = strtol(codec_tag, &next, 0);
            if (*next)
                tag = AV_RL32(codec_tag);
            st->codec->codec_tag = tag;
        }
    
    
        MATCH_PER_STREAM_OPT(qscale, dbl, qscale, oc, st);
        if (qscale >= 0 || same_quant) {
            st->codec->flags |= CODEC_FLAG_QSCALE;
            st->codec->global_quality = FF_QP2LAMBDA * qscale;
        }
    
    
        ost->sws_flags = av_get_int(sws_opts, "sws_flags", NULL);
        return ost;
    }
    
    
    static OutputStream *new_video_stream(OptionsContext *o, AVFormatContext *oc)
    
    {
        AVStream *st;
        OutputStream *ost;
        AVCodecContext *video_enc;
    
    
        ost = new_output_stream(o, oc, AVMEDIA_TYPE_VIDEO);
    
    #if CONFIG_AVFILTER
            ost->avfilter= vfilters;
            vfilters = NULL;
    #endif
        }
    
        video_enc = st->codec;
    
        if(oc->oformat->flags & AVFMT_GLOBALHEADER) {
            video_enc->flags |= CODEC_FLAG_GLOBAL_HEADER;
        }
    
    
        if (!st->stream_copy) {
    
            char *forced_key_frames = NULL, *frame_rate = NULL, *frame_size = NULL;
    
            char *frame_aspect_ratio = NULL, *frame_pix_fmt = NULL;
    
            int i, force_fps = 0;
    
            MATCH_PER_STREAM_OPT(frame_rates, str, frame_rate, oc, st);
            if (frame_rate && av_parse_video_rate(&ost->frame_rate, frame_rate) < 0) {
                av_log(NULL, AV_LOG_ERROR, "Invalid framerate value: %s\n", frame_rate);
                exit_program(1);
            }
    
            MATCH_PER_STREAM_OPT(frame_sizes, str, frame_size, oc, st);
            if (frame_size && av_parse_video_size(&video_enc->width, &video_enc->height, frame_size) < 0) {
                av_log(NULL, AV_LOG_ERROR, "Invalid frame size: %s.\n", frame_size);
                exit_program(1);
            }
    
    
            MATCH_PER_STREAM_OPT(frame_aspect_ratios, str, frame_aspect_ratio, oc, st);
            if (frame_aspect_ratio)
                ost->frame_aspect_ratio = parse_frame_aspect_ratio(frame_aspect_ratio);
    
    
            MATCH_PER_STREAM_OPT(frame_pix_fmts, str, frame_pix_fmt, oc, st);
            if (frame_pix_fmt && (video_enc->pix_fmt = av_get_pix_fmt(frame_pix_fmt)) == PIX_FMT_NONE) {
                av_log(NULL, AV_LOG_ERROR, "Unknown pixel format requested: %s.\n", frame_pix_fmt);
                exit_program(1);
            }
    
            st->sample_aspect_ratio = video_enc->sample_aspect_ratio;
    
            if(intra_matrix)
                video_enc->intra_matrix = intra_matrix;
            if(inter_matrix)
                video_enc->inter_matrix = inter_matrix;
    
            p= video_rc_override_string;
            for(i=0; p; i++){
                int start, end, q;
                int e=sscanf(p, "%d,%d,%d", &start, &end, &q);
                if(e!=3){
                    fprintf(stderr, "error parsing rc_override\n");
                    exit_program(1);
                }
                video_enc->rc_override=
                    av_realloc(video_enc->rc_override,
                               sizeof(RcOverride)*(i+1));
                video_enc->rc_override[i].start_frame= start;
                video_enc->rc_override[i].end_frame  = end;
                if(q>0){
                    video_enc->rc_override[i].qscale= q;
                    video_enc->rc_override[i].quality_factor= 1.0;
                }
                else{
                    video_enc->rc_override[i].qscale= 0;
                    video_enc->rc_override[i].quality_factor= -q/100.0;
                }
                p= strchr(p, '/');
                if(p) p++;
            }
            video_enc->rc_override_count=i;
            if (!video_enc->rc_initial_buffer_occupancy)
                video_enc->rc_initial_buffer_occupancy = video_enc->rc_buffer_size*3/4;
            video_enc->me_threshold= me_threshold;
            video_enc->intra_dc_precision= intra_dc_precision - 8;
    
            if (do_psnr)
                video_enc->flags|= CODEC_FLAG_PSNR;
    
            /* two pass mode */
            if (do_pass) {
                if (do_pass == 1) {
                    video_enc->flags |= CODEC_FLAG_PASS1;
                } else {
                    video_enc->flags |= CODEC_FLAG_PASS2;
                }
            }
    
    
            MATCH_PER_STREAM_OPT(forced_key_frames, str, forced_key_frames, oc, st);
    
            if (forced_key_frames)
                parse_forced_key_frames(forced_key_frames, ost, video_enc);
    
    
            MATCH_PER_STREAM_OPT(force_fps, i, force_fps, oc, st);
            ost->force_fps = force_fps;
    
        return ost;
    
    static OutputStream *new_audio_stream(OptionsContext *o, AVFormatContext *oc)
    
    {
        AVStream *st;
        OutputStream *ost;
        AVCodecContext *audio_enc;
    
    
        ost = new_output_stream(o, oc, AVMEDIA_TYPE_AUDIO);
    
        st  = ost->st;
    
        audio_enc = st->codec;
        audio_enc->codec_type = AVMEDIA_TYPE_AUDIO;
    
        if (oc->oformat->flags & AVFMT_GLOBALHEADER) {
            audio_enc->flags |= CODEC_FLAG_GLOBAL_HEADER;
        }
    
            MATCH_PER_STREAM_OPT(audio_channels, i, audio_enc->channels, oc, st);
    
    
            MATCH_PER_STREAM_OPT(sample_fmts, str, sample_fmt, oc, st);
            if (sample_fmt &&
                (audio_enc->sample_fmt = av_get_sample_fmt(sample_fmt)) == AV_SAMPLE_FMT_NONE) {
                av_log(NULL, AV_LOG_ERROR, "Invalid sample format '%s'\n", sample_fmt);
                exit_program(1);
            }
    
    
            MATCH_PER_STREAM_OPT(audio_sample_rate, i, audio_enc->sample_rate, oc, st);
    
        return ost;
    
    static OutputStream *new_data_stream(OptionsContext *o, AVFormatContext *oc)
    
    {
        AVStream *st;
        OutputStream *ost;
        AVCodecContext *data_enc;
    
    
        ost = new_output_stream(o, oc, AVMEDIA_TYPE_DATA);
    
        st  = ost->st;
        data_enc = st->codec;
    
            fprintf(stderr, "Data stream encoding not supported yet (only streamcopy)\n");
            exit_program(1);
        }
    
        if (oc->oformat->flags & AVFMT_GLOBALHEADER) {
            data_enc->flags |= CODEC_FLAG_GLOBAL_HEADER;
        }
    
    
        return ost;
    
    static OutputStream *new_subtitle_stream(OptionsContext *o, AVFormatContext *oc)
    
    {
        AVStream *st;
        OutputStream *ost;
        AVCodecContext *subtitle_enc;
    
    
        ost = new_output_stream(o, oc, AVMEDIA_TYPE_SUBTITLE);
    
        st  = ost->st;
        subtitle_enc = st->codec;
    
        subtitle_enc->codec_type = AVMEDIA_TYPE_SUBTITLE;
    
        if (oc->oformat->flags & AVFMT_GLOBALHEADER) {
            subtitle_enc->flags |= CODEC_FLAG_GLOBAL_HEADER;
        }
    
    
        return ost;
    
    }
    
    /* arg format is "output-stream-index:streamid-value". */
    static int opt_streamid(const char *opt, const char *arg)
    {
        int idx;
        char *p;
        char idx_str[16];
    
        av_strlcpy(idx_str, arg, sizeof(idx_str));
        p = strchr(idx_str, ':');
        if (!p) {
            fprintf(stderr,
                    "Invalid value '%s' for option '%s', required syntax is 'index:value'\n",
                    arg, opt);
            exit_program(1);
        }
        *p++ = '\0';
        idx = parse_number_or_die(opt, idx_str, OPT_INT, 0, INT_MAX);
        streamid_map = grow_array(streamid_map, sizeof(*streamid_map), &nb_streamid_map, idx+1);
        streamid_map[idx] = parse_number_or_die(opt, p, OPT_INT, 0, INT_MAX);
        return 0;
    }
    
    
    static int copy_chapters(InputFile *ifile, OutputFile *ofile, int copy_metadata)
    
        AVFormatContext *is = ifile->ctx;
        AVFormatContext *os = ofile->ctx;
    
        int i;
    
        for (i = 0; i < is->nb_chapters; i++) {
            AVChapter *in_ch = is->chapters[i], *out_ch;
    
            int64_t ts_off   = av_rescale_q(ofile->start_time - ifile->ts_offset,
    
                                          AV_TIME_BASE_Q, in_ch->time_base);
    
            int64_t rt       = (ofile->recording_time == INT64_MAX) ? INT64_MAX :
                               av_rescale_q(ofile->recording_time, AV_TIME_BASE_Q, in_ch->time_base);
    
    
    
            if (in_ch->end < ts_off)
                continue;
            if (rt != INT64_MAX && in_ch->start > rt + ts_off)
                break;
    
            out_ch = av_mallocz(sizeof(AVChapter));
            if (!out_ch)
                return AVERROR(ENOMEM);
    
            out_ch->id        = in_ch->id;
            out_ch->time_base = in_ch->time_base;
            out_ch->start     = FFMAX(0,  in_ch->start - ts_off);
            out_ch->end       = FFMIN(rt, in_ch->end   - ts_off);
    
    
            if (copy_metadata)
    
                av_dict_copy(&out_ch->metadata, in_ch->metadata, 0);
    
            os->nb_chapters++;
            os->chapters = av_realloc(os->chapters, sizeof(AVChapter)*os->nb_chapters);
            if (!os->chapters)
                return AVERROR(ENOMEM);
            os->chapters[os->nb_chapters - 1] = out_ch;
        }
        return 0;
    }
    
    
    static int read_avserver_streams(OptionsContext *o, AVFormatContext *s, const char *filename)
    
    {
        int i, err;
        AVFormatContext *ic = NULL;
    
        err = avformat_open_input(&ic, filename, NULL, NULL);
        if (err < 0)
            return err;
        /* copy stream format */
        for(i=0;i<ic->nb_streams;i++) {
            AVStream *st;
            OutputStream *ost;
            AVCodec *codec;
    
            codec = avcodec_find_encoder(ic->streams[i]->codec->codec_id);
    
            ost   = new_output_stream(o, s, codec->type);
    
            st    = ost->st;
    
            // FIXME: a more elegant solution is needed
            memcpy(st, ic->streams[i], sizeof(AVStream));
            st->info = NULL;
            avcodec_copy_context(st->codec, ic->streams[i]->codec);
    
            if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO && !st->stream_copy)
                choose_sample_fmt(st, codec);
            else if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO && !st->stream_copy)
                choose_pixel_fmt(st, codec);
        }
    
        av_close_input_file(ic);
        return 0;
    }
    
    
    static void opt_output_file(void *optctx, const char *filename)
    
        OptionsContext *o = optctx;
    
        AVFormatContext *oc;
    
        int i, err;
    
        AVOutputFormat *file_oformat;
    
        OutputStream *ost;
        InputStream  *ist;
    
    
        if (!strcmp(filename, "-"))
            filename = "pipe:";
    
        oc = avformat_alloc_context();
        if (!oc) {
            print_error(filename, AVERROR(ENOMEM));
            exit_program(1);
        }
    
    
        if (o->format) {
            file_oformat = av_guess_format(o->format, NULL, NULL);
    
            if (!file_oformat) {
    
                fprintf(stderr, "Requested output format '%s' is not a suitable output format\n", o->format);
    
                exit_program(1);
            }
        } else {
            file_oformat = av_guess_format(NULL, filename, NULL);
            if (!file_oformat) {
                fprintf(stderr, "Unable to find a suitable output format for '%s'\n",
                        filename);
                exit_program(1);
            }
        }
    
        oc->oformat = file_oformat;
        av_strlcpy(oc->filename, filename, sizeof(oc->filename));
    
        if (!strcmp(file_oformat->name, "ffm") &&
            av_strstart(filename, "http:", NULL)) {
            /* special case for files sent to avserver: we get the stream
               parameters from avserver */
    
            int err = read_avserver_streams(o, oc, filename);
    
            if (err < 0) {
                print_error(filename, err);
                exit_program(1);
            }
    
        } else if (!o->nb_stream_maps) {
    
            /* pick the "best" stream of each type */
    #define NEW_STREAM(type, index)\
            if (index >= 0) {\
    
                ost = new_ ## type ## _stream(o, oc);\
    
                ost->source_index = index;\
                ost->sync_ist     = &input_streams[index];\
                input_streams[index].discard = 0;\
            }
    
            /* video: highest resolution */
    
            if (!o->video_disable && oc->oformat->video_codec != CODEC_ID_NONE) {
    
                int area = 0, idx = -1;
                for (i = 0; i < nb_input_streams; i++) {
                    ist = &input_streams[i];
                    if (ist->st->codec->codec_type == AVMEDIA_TYPE_VIDEO &&
                        ist->st->codec->width * ist->st->codec->height > area) {
                        area = ist->st->codec->width * ist->st->codec->height;
                        idx = i;
                    }
                }
                NEW_STREAM(video, idx);
            }
    
            /* audio: most channels */
    
            if (!o->audio_disable && oc->oformat->audio_codec != CODEC_ID_NONE) {
    
                int channels = 0, idx = -1;
                for (i = 0; i < nb_input_streams; i++) {
                    ist = &input_streams[i];
                    if (ist->st->codec->codec_type == AVMEDIA_TYPE_AUDIO &&
                        ist->st->codec->channels > channels) {
                        channels = ist->st->codec->channels;
                        idx = i;
                    }
                }
                NEW_STREAM(audio, idx);
            }
    
            /* subtitles: pick first */
    
            if (!o->subtitle_disable && oc->oformat->subtitle_codec != CODEC_ID_NONE) {
    
                for (i = 0; i < nb_input_streams; i++)
                    if (input_streams[i].st->codec->codec_type == AVMEDIA_TYPE_SUBTITLE) {
                        NEW_STREAM(subtitle, i);
                        break;
                    }
            }
            /* do something with data? */
    
            for (i = 0; i < o->nb_stream_maps; i++) {
                StreamMap *map = &o->stream_maps[i];
    
                if (map->disabled)
                    continue;
    
                ist = &input_streams[input_files[map->file_index].ist_index + map->stream_index];
    
                switch (ist->st->codec->codec_type) {
    
                case AVMEDIA_TYPE_VIDEO:    ost = new_video_stream(o, oc);    break;
                case AVMEDIA_TYPE_AUDIO:    ost = new_audio_stream(o, oc);    break;
                case AVMEDIA_TYPE_SUBTITLE: ost = new_subtitle_stream(o, oc); break;
                case AVMEDIA_TYPE_DATA:     ost = new_data_stream(o, oc);     break;
    
                default:
                    av_log(NULL, AV_LOG_ERROR, "Cannot map stream #%d.%d - unsupported type.\n",
                           map->file_index, map->stream_index);
                    exit_program(1);
                }
    
    
                ost->source_index = input_files[map->file_index].ist_index + map->stream_index;
    
                ost->sync_ist = &input_streams[input_files[map->sync_file_index].ist_index +
                                               map->sync_stream_index];
                ist->discard = 0;
            }
    
        output_files = grow_array(output_files, sizeof(*output_files), &nb_output_files, nb_output_files + 1);
        output_files[nb_output_files - 1].ctx       = oc;
    
        output_files[nb_output_files - 1].ost_index = nb_output_streams - oc->nb_streams;
    
        output_files[nb_output_files - 1].recording_time = o->recording_time;
        output_files[nb_output_files - 1].start_time     = o->start_time;
    
        output_files[nb_output_files - 1].limit_filesize = o->limit_filesize;
    
        av_dict_copy(&output_files[nb_output_files - 1].opts, format_opts, 0);
    
    
        /* check filename in case of an image number is expected */
        if (oc->oformat->flags & AVFMT_NEEDNUMBER) {
            if (!av_filename_number_test(oc->filename)) {
                print_error(oc->filename, AVERROR(EINVAL));
                exit_program(1);
            }
        }
    
        if (!(oc->oformat->flags & AVFMT_NOFILE)) {
            /* test if it already exists to avoid loosing precious files */
            if (!file_overwrite &&
                (strchr(filename, ':') == NULL ||
                 filename[1] == ':' ||
                 av_strstart(filename, "file:", NULL))) {
                if (avio_check(filename, 0) == 0) {
                    if (!using_stdin) {
                        fprintf(stderr,"File '%s' already exists. Overwrite ? [y/N] ", filename);
                        fflush(stderr);
                        if (!read_yesno()) {
                            fprintf(stderr, "Not overwriting - exiting\n");
                            exit_program(1);
                        }
                    }
                    else {
                        fprintf(stderr,"File '%s' already exists. Exiting.\n", filename);
                        exit_program(1);
                    }
                }
            }
    
            /* open the file */
            if ((err = avio_open(&oc->pb, filename, AVIO_FLAG_WRITE)) < 0) {
                print_error(filename, err);
                exit_program(1);
            }
        }
    
    
        oc->preload   = (int)(o->mux_preload   * AV_TIME_BASE);
        oc->max_delay = (int)(o->mux_max_delay * AV_TIME_BASE);
    
        oc->flags |= AVFMT_FLAG_NONBLOCK;
    
    
        if (o->chapters_input_file >= nb_input_files) {
            if (o->chapters_input_file == INT_MAX) {
    
                /* copy chapters from the first input file that has them*/
    
                o->chapters_input_file = -1;
    
                for (i = 0; i < nb_input_files; i++)
                    if (input_files[i].ctx->nb_chapters) {
    
                        o->chapters_input_file = i;
    
                        break;
                    }
            } else {
                av_log(NULL, AV_LOG_ERROR, "Invalid input file index %d in chapter mapping.\n",
    
                       o->chapters_input_file);
    
        if (o->chapters_input_file >= 0)
            copy_chapters(&input_files[o->chapters_input_file], &output_files[nb_output_files - 1],
    
                          o->metadata_chapters_manual);
    
        for (i = 0; i < o->nb_meta_data_maps; i++) {
    
            AVFormatContext *files[2];
            AVDictionary    **meta[2];
            int j;
    
    #define METADATA_CHECK_INDEX(index, nb_elems, desc)\
            if ((index) < 0 || (index) >= (nb_elems)) {\
                av_log(NULL, AV_LOG_ERROR, "Invalid %s index %d while processing metadata maps\n",\
                         (desc), (index));\
                exit_program(1);\
            }
    
    
            int in_file_index = o->meta_data_maps[i][1].file;
    
            if (in_file_index < 0)
                continue;
            METADATA_CHECK_INDEX(in_file_index, nb_input_files, "input file")
    
            files[0] = oc;
            files[1] = input_files[in_file_index].ctx;
    
            for (j = 0; j < 2; j++) {
    
                MetadataMap *map = &o->meta_data_maps[i][j];
    
    
                switch (map->type) {
                case 'g':
                    meta[j] = &files[j]->metadata;
                    break;
                case 's':
                    METADATA_CHECK_INDEX(map->index, files[j]->nb_streams, "stream")
                    meta[j] = &files[j]->streams[map->index]->metadata;
                    break;
                case 'c':
                    METADATA_CHECK_INDEX(map->index, files[j]->nb_chapters, "chapter")
                    meta[j] = &files[j]->chapters[map->index]->metadata;
                    break;
                case 'p':
                    METADATA_CHECK_INDEX(map->index, files[j]->nb_programs, "program")
                    meta[j] = &files[j]->programs[map->index]->metadata;
                    break;
                }
            }
    
            av_dict_copy(meta[0], *meta[1], AV_DICT_DONT_OVERWRITE);
        }
    
        /* copy global metadata by default */
    
        if (!o->metadata_global_manual && nb_input_files)
    
            av_dict_copy(&oc->metadata, input_files[0].ctx->metadata,
                         AV_DICT_DONT_OVERWRITE);
    
        if (!o->metadata_streams_manual)
    
            for (i = output_files[nb_output_files - 1].ost_index; i < nb_output_streams; i++) {
                InputStream *ist = &input_streams[output_streams[i].source_index];
                av_dict_copy(&output_streams[i].st->metadata, ist->st->metadata, AV_DICT_DONT_OVERWRITE);
    
        /* process manually set metadata */
        for (i = 0; i < o->nb_metadata; i++) {
            AVDictionary **m;
            char type, *val;
            int index = 0;
    
            val = strchr(o->metadata[i].u.str, '=');
            if (!val) {
                av_log(NULL, AV_LOG_ERROR, "No '=' character in metadata string %s.\n",
                       o->metadata[i].u.str);
                exit_program(1);
            }
            *val++ = 0;
    
            parse_meta_type(o->metadata[i].specifier, &type, &index);
            switch (type) {
            case 'g':
                m = &oc->metadata;
                break;
            case 's':
                if (index < 0 || index >= oc->nb_streams) {
                    av_log(NULL, AV_LOG_ERROR, "Invalid stream index %d in metadata specifier.\n", index);
                    exit_program(1);
                }
                m = &oc->streams[i]->metadata;
                break;
            case 'c':
                if (index < 0 || index >= oc->nb_chapters) {
                    av_log(NULL, AV_LOG_ERROR, "Invalid chapter index %d in metadata specifier.\n", index);
                    exit_program(1);
                }
                m = &oc->chapters[i]->metadata;
                break;
            default:
                av_log(NULL, AV_LOG_ERROR, "Invalid metadata specifier %s.\n", o->metadata[i].specifier);
                exit_program(1);
            }
    
            av_dict_set(m, o->metadata[i].u.str, *val ? val : NULL, 0);
        }
    
    
        av_freep(&streamid_map);
        nb_streamid_map = 0;
    
        reset_options(o);
    
    }
    
    /* same option as mencoder */
    static int opt_pass(const char *opt, const char *arg)
    {
        do_pass = parse_number_or_die(opt, arg, OPT_INT, 1, 2);
        return 0;
    }
    
    static int64_t getutime(void)
    {
    #if HAVE_GETRUSAGE
        struct rusage rusage;
    
        getrusage(RUSAGE_SELF, &rusage);
        return (rusage.ru_utime.tv_sec * 1000000LL) + rusage.ru_utime.tv_usec;
    #elif HAVE_GETPROCESSTIMES
        HANDLE proc;
        FILETIME c, e, k, u;
        proc = GetCurrentProcess();
        GetProcessTimes(proc, &c, &e, &k, &u);
        return ((int64_t) u.dwHighDateTime << 32 | u.dwLowDateTime) / 10;
    #else
        return av_gettime();
    #endif
    }
    
    static int64_t getmaxrss(void)
    {
    #if HAVE_GETRUSAGE && HAVE_STRUCT_RUSAGE_RU_MAXRSS
        struct rusage rusage;
        getrusage(RUSAGE_SELF, &rusage);
        return (int64_t)rusage.ru_maxrss * 1024;
    #elif HAVE_GETPROCESSMEMORYINFO
        HANDLE proc;
        PROCESS_MEMORY_COUNTERS memcounters;
        proc = GetCurrentProcess();
        memcounters.cb = sizeof(memcounters);
        GetProcessMemoryInfo(proc, &memcounters, sizeof(memcounters));
        return memcounters.PeakPagefileUsage;
    #else
        return 0;
    #endif
    }
    
    static void parse_matrix_coeffs(uint16_t *dest, const char *str)
    {
        int i;
        const char *p = str;
        for(i = 0;; i++) {
            dest[i] = atoi(p);
            if(i == 63)
                break;
            p = strchr(p, ',');
            if(!p) {
                fprintf(stderr, "Syntax error in matrix \"%s\" at coeff %d\n", str, i);
                exit_program(1);
            }
            p++;
        }
    }
    
    static void opt_inter_matrix(const char *arg)
    {
        inter_matrix = av_mallocz(sizeof(uint16_t) * 64);
        parse_matrix_coeffs(inter_matrix, arg);
    }
    
    static void opt_intra_matrix(const char *arg)
    {
        intra_matrix = av_mallocz(sizeof(uint16_t) * 64);
        parse_matrix_coeffs(intra_matrix, arg);
    }
    
    
    static int opt_audio_qscale(OptionsContext *o, const char *opt, const char *arg)
    {
        return parse_option(o, "q:a", arg, options);
    }
    
    
    static void show_usage(void)
    {
        printf("Hyper fast Audio and Video encoder\n");
        printf("usage: %s [options] [[infile options] -i infile]... {[outfile options] outfile}...\n", program_name);
        printf("\n");
    }
    
    static void show_help(void)
    {
        AVCodec *c;
        AVOutputFormat *oformat = NULL;
        AVInputFormat  *iformat = NULL;
    
    
        av_log_set_callback(log_callback_help);
        show_usage();
        show_help_options(options, "Main options:\n",
                          OPT_EXPERT | OPT_AUDIO | OPT_VIDEO | OPT_SUBTITLE | OPT_GRAB, 0);
        show_help_options(options, "\nAdvanced options:\n",
                          OPT_EXPERT | OPT_AUDIO | OPT_VIDEO | OPT_SUBTITLE | OPT_GRAB,
                          OPT_EXPERT);
        show_help_options(options, "\nVideo options:\n",
                          OPT_EXPERT | OPT_AUDIO | OPT_VIDEO | OPT_GRAB,
                          OPT_VIDEO);
        show_help_options(options, "\nAdvanced Video options:\n",
                          OPT_EXPERT | OPT_AUDIO | OPT_VIDEO | OPT_GRAB,
                          OPT_VIDEO | OPT_EXPERT);
        show_help_options(options, "\nAudio options:\n",
                          OPT_EXPERT | OPT_AUDIO | OPT_VIDEO | OPT_GRAB,
                          OPT_AUDIO);
        show_help_options(options, "\nAdvanced Audio options:\n",
                          OPT_EXPERT | OPT_AUDIO | OPT_VIDEO | OPT_GRAB,
                          OPT_AUDIO | OPT_EXPERT);
        show_help_options(options, "\nSubtitle options:\n",
                          OPT_SUBTITLE | OPT_GRAB,
                          OPT_SUBTITLE);
        show_help_options(options, "\nAudio/Video grab options:\n",
                          OPT_GRAB,
                          OPT_GRAB);
        printf("\n");
    
        class = avcodec_get_class();
        av_opt_show2(&class, NULL, AV_OPT_FLAG_ENCODING_PARAM|AV_OPT_FLAG_DECODING_PARAM, 0);
    
        printf("\n");
    
        /* individual codec options */
        c = NULL;
        while ((c = av_codec_next(c))) {
            if (c->priv_class) {
                av_opt_show2(&c->priv_class, NULL, AV_OPT_FLAG_ENCODING_PARAM|AV_OPT_FLAG_DECODING_PARAM, 0);
                printf("\n");
            }
        }
    
    
        class = avformat_get_class();
        av_opt_show2(&class, NULL, AV_OPT_FLAG_ENCODING_PARAM|AV_OPT_FLAG_DECODING_PARAM, 0);
    
        printf("\n");
    
        /* individual muxer options */
        while ((oformat = av_oformat_next(oformat))) {
            if (oformat->priv_class) {
                av_opt_show2(&oformat->priv_class, NULL, AV_OPT_FLAG_ENCODING_PARAM, 0);
                printf("\n");
            }
        }
    
        /* individual demuxer options */
        while ((iformat = av_iformat_next(iformat))) {
            if (iformat->priv_class) {
                av_opt_show2(&iformat->priv_class, NULL, AV_OPT_FLAG_DECODING_PARAM, 0);
                printf("\n");
            }
        }
    
    
        class = sws_get_class();
        av_opt_show2(&class, NULL, AV_OPT_FLAG_ENCODING_PARAM|AV_OPT_FLAG_DECODING_PARAM, 0);
    
    static int opt_target(OptionsContext *o, const char *opt, const char *arg)
    
    {
        enum { PAL, NTSC, FILM, UNKNOWN } norm = UNKNOWN;
        static const char *const frame_rates[] = {"25", "30000/1001", "24000/1001"};
    
        if(!strncmp(arg, "pal-", 4)) {
            norm = PAL;
            arg += 4;
        } else if(!strncmp(arg, "ntsc-", 5)) {
            norm = NTSC;
            arg += 5;
        } else if(!strncmp(arg, "film-", 5)) {
            norm = FILM;
            arg += 5;
        } else {
    
            /* Try to determine PAL/NTSC by peeking in the input files */
            if(nb_input_files) {
                int i, j, fr;
                for (j = 0; j < nb_input_files; j++) {
                    for (i = 0; i < input_files[j].nb_streams; i++) {
                        AVCodecContext *c = input_files[j].ctx->streams[i]->codec;
                        if(c->codec_type != AVMEDIA_TYPE_VIDEO)
                            continue;
                        fr = c->time_base.den * 1000 / c->time_base.num;
                        if(fr == 25000) {
                            norm = PAL;
    
                        } else if((fr == 29970) || (fr == 23976)) {
                            norm = NTSC;
                            break;
                        }
    
                    if(norm != UNKNOWN)
                        break;
    
                }
            }
            if(verbose > 0 && norm != UNKNOWN)
                fprintf(stderr, "Assuming %s for target.\n", norm == PAL ? "PAL" : "NTSC");
        }
    
        if(norm == UNKNOWN) {
            fprintf(stderr, "Could not determine norm (PAL/NTSC/NTSC-Film) for target.\n");
            fprintf(stderr, "Please prefix target with \"pal-\", \"ntsc-\" or \"film-\",\n");
            fprintf(stderr, "or set a framerate with \"-r xxx\".\n");
            exit_program(1);
        }
    
        if(!strcmp(arg, "vcd")) {
    
            opt_video_codec(o, "c:v", "mpeg1video");
            opt_audio_codec(o, "c:a", "mp2");
    
            parse_option(o, "f", "vcd", options);
    
            parse_option(o, "s", norm == PAL ? "352x288" : "352x240", options);
    
            parse_option(o, "r", frame_rates[norm], options);
    
            opt_default("g", norm == PAL ? "15" : "18");
    
            opt_default("b", "1150000");
            opt_default("maxrate", "1150000");
            opt_default("minrate", "1150000");
            opt_default("bufsize", "327680"); // 40*1024*8;
    
    
            opt_default("b:a", "224000");
    
            parse_option(o, "ar", "44100", options);
    
            parse_option(o, "ac", "2", options);
    
    
            opt_default("packetsize", "2324");
            opt_default("muxrate", "1411200"); // 2352 * 75 * 8;
    
            /* We have to offset the PTS, so that it is consistent with the SCR.
               SCR starts at 36000, but the first two packs contain only padding
               and the first pack from the other stream, respectively, may also have
               been written before.
               So the real data starts at SCR 36000+3*1200. */
    
            o->mux_preload = (36000+3*1200) / 90000.0; //0.44
    
        } else if(!strcmp(arg, "svcd")) {
    
    
            opt_video_codec(o, "c:v", "mpeg2video");
            opt_audio_codec(o, "c:a", "mp2");
    
            parse_option(o, "f", "svcd", options);
    
            parse_option(o, "s", norm == PAL ? "480x576" : "480x480", options);
    
            parse_option(o, "r", frame_rates[norm], options);
    
            opt_default("g", norm == PAL ? "15" : "18");
    
            opt_default("b", "2040000");
            opt_default("maxrate", "2516000");
            opt_default("minrate", "0"); //1145000;
            opt_default("bufsize", "1835008"); //224*1024*8;
            opt_default("flags", "+scan_offset");
    
    
    
            opt_default("b:a", "224000");
    
            parse_option(o, "ar", "44100", options);
    
    
            opt_default("packetsize", "2324");
    
        } else if(!strcmp(arg, "dvd")) {
    
    
            opt_video_codec(o, "c:v", "mpeg2video");
            opt_audio_codec(o, "c:a", "ac3");
    
            parse_option(o, "f", "dvd", options);
    
            parse_option(o, "s", norm == PAL ? "720x576" : "720x480", options);
    
            parse_option(o, "r", frame_rates[norm], options);
    
            opt_default("g", norm == PAL ? "15" : "18");
    
            opt_default("b", "6000000");
            opt_default("maxrate", "9000000");
            opt_default("minrate", "0"); //1500000;
            opt_default("bufsize", "1835008"); //224*1024*8;
    
            opt_default("packetsize", "2048");  // from www.mpucoder.com: DVD sectors contain 2048 bytes of data, this is also the size of one pack.
            opt_default("muxrate", "10080000"); // from mplex project: data_rate = 1260000. mux_rate = data_rate * 8
    
    
            opt_default("b:a", "448000");
    
            parse_option(o, "ar", "48000", options);
    
    
        } else if(!strncmp(arg, "dv", 2)) {
    
    
            parse_option(o, "f", "dv", options);
    
            parse_option(o, "s", norm == PAL ? "720x576" : "720x480", options);
    
            parse_option(o, "pix_fmt", !strncmp(arg, "dv50", 4) ? "yuv422p" :
                              norm == PAL ? "yuv420p" : "yuv411p", options);
    
            parse_option(o, "r", frame_rates[norm], options);
    
            parse_option(o, "ar", "48000", options);
    
            parse_option(o, "ac", "2", options);
    
    
        } else {
            fprintf(stderr, "Unknown target: %s\n", arg);
            return AVERROR(EINVAL);
        }
        return 0;
    }
    
    static int opt_vstats_file(const char *opt, const char *arg)
    {
        av_free (vstats_filename);
        vstats_filename=av_strdup (arg);
        return 0;
    }
    
    static int opt_vstats(const char *opt, const char *arg)
    {
        char filename[40];
        time_t today2 = time(NULL);
        struct tm *today = localtime(&today2);
    
        snprintf(filename, sizeof(filename), "vstats_%02d%02d%02d.log", today->tm_hour, today->tm_min,
                 today->tm_sec);
        return opt_vstats_file(opt, filename);
    }
    
    
    static int opt_video_frames(OptionsContext *o, const char *opt, const char *arg)
    {
        return parse_option(o, "frames:v", arg, options);
    }
    
    static int opt_audio_frames(OptionsContext *o, const char *opt, const char *arg)
    {
        return parse_option(o, "frames:a", arg, options);
    }
    
    static int opt_data_frames(OptionsContext *o, const char *opt, const char *arg)
    {
        return parse_option(o, "frames:d", arg, options);
    }
    
    
    static int opt_video_tag(OptionsContext *o, const char *opt, const char *arg)
    {
        return parse_option(o, "tag:v", arg, options);
    }
    
    static int opt_audio_tag(OptionsContext *o, const char *opt, const char *arg)
    {
        return parse_option(o, "tag:a", arg, options);
    }
    
    static int opt_subtitle_tag(OptionsContext *o, const char *opt, const char *arg)
    {
        return parse_option(o, "tag:s", arg, options);
    }
    
    
    #define OFFSET(x) offsetof(OptionsContext, x)
    
    static const OptionDef options[] = {
        /* main options */
    #include "cmdutils_common_opts.h"
    
        { "f", HAS_ARG | OPT_STRING | OPT_OFFSET, {.off = OFFSET(format)}, "force format", "fmt" },
    
        { "i", HAS_ARG | OPT_FUNC2, {(void*)opt_input_file}, "input file name", "filename" },
    
        { "y", OPT_BOOL, {(void*)&file_overwrite}, "overwrite output files" },
    
        { "c", HAS_ARG | OPT_STRING | OPT_SPEC, {.off = OFFSET(codec_names)}, "codec name", "codec" },
        { "codec", HAS_ARG | OPT_STRING | OPT_SPEC, {.off = OFFSET(codec_names)}, "codec name", "codec" },
    
        { "map", HAS_ARG | OPT_EXPERT | OPT_FUNC2, {(void*)opt_map}, "set input stream mapping", "file.stream[:syncfile.syncstream]" },
    
        { "map_metadata", HAS_ARG | OPT_EXPERT | OPT_FUNC2, {(void*)opt_map_metadata}, "set metadata information of outfile from infile",
    
          "outfile[,metadata]:infile[,metadata]" },
    
        { "map_chapters",  OPT_INT | HAS_ARG | OPT_EXPERT | OPT_OFFSET, {.off = OFFSET(chapters_input_file)},  "set chapters mapping", "input_file_index" },
    
        { "t", HAS_ARG | OPT_TIME | OPT_OFFSET, {.off = OFFSET(recording_time)}, "record or transcode \"duration\" seconds of audio/video", "duration" },
    
        { "fs", HAS_ARG | OPT_INT64 | OPT_OFFSET, {.off = OFFSET(limit_filesize)}, "set the limit file size in bytes", "limit_size" }, //
    
        { "ss", HAS_ARG | OPT_TIME | OPT_OFFSET, {.off = OFFSET(start_time)}, "set the start time offset", "time_off" },
        { "itsoffset", HAS_ARG | OPT_TIME | OPT_OFFSET, {.off = OFFSET(input_ts_offset)}, "set the input ts offset", "time_off" },
    
        { "itsscale", HAS_ARG | OPT_DOUBLE | OPT_SPEC, {.off = OFFSET(ts_scale)}, "set the input ts scale", "scale" },
    
        { "metadata", HAS_ARG | OPT_STRING | OPT_SPEC, {.off = OFFSET(metadata)}, "add metadata", "string=string" },
    
        { "dframes", HAS_ARG | OPT_FUNC2, {(void*)opt_data_frames}, "set the number of data frames to record", "number" },
    
        { "benchmark", OPT_BOOL | OPT_EXPERT, {(void*)&do_benchmark},
          "add timings for benchmarking" },
        { "timelimit", HAS_ARG, {(void*)opt_timelimit}, "set max runtime in seconds", "limit" },
        { "dump", OPT_BOOL | OPT_EXPERT, {(void*)&do_pkt_dump},
          "dump each input packet" },
        { "hex", OPT_BOOL | OPT_EXPERT, {(void*)&do_hex_dump},
          "when dumping packets, also dump the payload" },
    
        { "re", OPT_BOOL | OPT_EXPERT | OPT_OFFSET, {.off = OFFSET(rate_emu)}, "read input at native frame rate", "" },
    
        { "v", HAS_ARG, {(void*)opt_verbose}, "set the verbosity level", "number" },
    
        { "target", HAS_ARG | OPT_FUNC2, {(void*)opt_target}, "specify target file type (\"vcd\", \"svcd\", \"dvd\", \"dv\", \"dv50\", \"pal-vcd\", \"ntsc-svcd\", ...)", "type" },
    
        { "vsync", HAS_ARG | OPT_INT | OPT_EXPERT, {(void*)&video_sync_method}, "video sync method", "" },
        { "async", HAS_ARG | OPT_INT | OPT_EXPERT, {(void*)&audio_sync_method}, "audio sync method", "" },
        { "adrift_threshold", HAS_ARG | OPT_FLOAT | OPT_EXPERT, {(void*)&audio_drift_threshold}, "audio drift threshold", "threshold" },
        { "copyts", OPT_BOOL | OPT_EXPERT, {(void*)&copy_ts}, "copy timestamps" },
        { "copytb", OPT_BOOL | OPT_EXPERT, {(void*)&copy_tb}, "copy input stream time base when stream copying" },
        { "shortest", OPT_BOOL | OPT_EXPERT, {(void*)&opt_shortest}, "finish encoding within shortest input" }, //
        { "dts_delta_threshold", HAS_ARG | OPT_FLOAT | OPT_EXPERT, {(void*)&dts_delta_threshold}, "timestamp discontinuity delta threshold", "threshold" },
        { "xerror", OPT_BOOL, {(void*)&exit_on_error}, "exit on error", "error" },
        { "copyinkf", OPT_BOOL | OPT_EXPERT, {(void*)&copy_initial_nonkeyframes}, "copy initial non-keyframes" },
    
        { "frames", OPT_INT64 | HAS_ARG | OPT_SPEC, {.off = OFFSET(max_frames)}, "set the number of frames to record", "number" },
    
        { "tag",   OPT_STRING | HAS_ARG | OPT_SPEC, {.off = OFFSET(codec_tags)}, "force codec tag/fourcc", "fourcc/tag" },
    
        { "q", HAS_ARG | OPT_EXPERT | OPT_DOUBLE | OPT_SPEC, {.off = OFFSET(qscale)}, "use fixed quality scale (VBR)", "q" },
        { "qscale", HAS_ARG | OPT_EXPERT | OPT_DOUBLE | OPT_SPEC, {.off = OFFSET(qscale)}, "use fixed quality scale (VBR)", "q" },
    
        { "vframes", HAS_ARG | OPT_VIDEO | OPT_FUNC2, {(void*)opt_video_frames}, "set the number of video frames to record", "number" },
    
        { "r", HAS_ARG | OPT_VIDEO | OPT_STRING | OPT_SPEC, {.off = OFFSET(frame_rates)}, "set frame rate (Hz value, fraction or abbreviation)", "rate" },
    
        { "s", HAS_ARG | OPT_VIDEO | OPT_STRING | OPT_SPEC, {.off = OFFSET(frame_sizes)}, "set frame size (WxH or abbreviation)", "size" },
    
        { "aspect", HAS_ARG | OPT_VIDEO | OPT_STRING | OPT_SPEC, {.off = OFFSET(frame_aspect_ratios)}, "set aspect ratio (4:3, 16:9 or 1.3333, 1.7777)", "aspect" },
    
        { "pix_fmt", HAS_ARG | OPT_EXPERT | OPT_VIDEO | OPT_STRING | OPT_SPEC, {.off = OFFSET(frame_pix_fmts)}, "set pixel format", "format" },
    
        { "vn", OPT_BOOL | OPT_VIDEO | OPT_OFFSET, {.off = OFFSET(video_disable)}, "disable video" },
    
        { "vdt", OPT_INT | HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)&video_discard}, "discard threshold", "n" },
        { "rc_override", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_video_rc_override_string}, "rate control override for specific intervals", "override" },
    
        { "vcodec", HAS_ARG | OPT_VIDEO | OPT_FUNC2, {(void*)opt_video_codec}, "force video codec ('copy' to copy stream)", "codec" },
    
        { "me_threshold", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_me_threshold}, "motion estimation threshold",  "threshold" },
    
        { "same_quant", OPT_BOOL | OPT_VIDEO, {(void*)&same_quant},
    
          "use same quantizer as source (implies VBR)" },
        { "pass", HAS_ARG | OPT_VIDEO, {(void*)opt_pass}, "select the pass number (1 or 2)", "n" },
        { "passlogfile", HAS_ARG | OPT_STRING | OPT_VIDEO, {(void*)&pass_logfilename_prefix}, "select two pass log file name prefix", "prefix" },
        { "deinterlace", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, {(void*)&do_deinterlace},
          "deinterlace pictures" },
        { "psnr", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, {(void*)&do_psnr}, "calculate PSNR of compressed frames" },
        { "vstats", OPT_EXPERT | OPT_VIDEO, {(void*)&opt_vstats}, "dump video coding statistics to file" },
        { "vstats_file", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_vstats_file}, "dump video coding statistics to file", "file" },
    #if CONFIG_AVFILTER
        { "vf", OPT_STRING | HAS_ARG, {(void*)&vfilters}, "video filters", "filter list" },
    #endif
        { "intra_matrix", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_intra_matrix}, "specify intra matrix coeffs", "matrix" },
        { "inter_matrix", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_inter_matrix}, "specify inter matrix coeffs", "matrix" },
        { "top", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_top_field_first}, "top=1/bottom=0/auto=-1 field first", "" },
        { "dc", OPT_INT | HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)&intra_dc_precision}, "intra_dc_precision", "precision" },
    
        { "vtag", HAS_ARG | OPT_EXPERT | OPT_VIDEO | OPT_FUNC2, {(void*)opt_video_tag}, "force video tag/fourcc", "fourcc/tag" },
    
        { "qphist", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, { (void *)&qp_hist }, "show QP histogram" },
    
        { "force_fps", OPT_BOOL | OPT_EXPERT | OPT_VIDEO | OPT_SPEC, {.off = OFFSET(force_fps)}, "force the selected framerate, disable the best supported framerate selection" },
    
        { "streamid", HAS_ARG | OPT_EXPERT, {(void*)opt_streamid}, "set the value of an outfile streamid", "streamIndex:value" },
    
        { "force_key_frames", OPT_STRING | HAS_ARG | OPT_EXPERT | OPT_VIDEO | OPT_SPEC, {.off = OFFSET(forced_key_frames)}, "force key frames at specified timestamps", "timestamps" },
    
        { "aframes", HAS_ARG | OPT_AUDIO | OPT_FUNC2, {(void*)opt_audio_frames}, "set the number of audio frames to record", "number" },