Skip to content
Snippets Groups Projects
ffmpeg.c 163 KiB
Newer Older
  • Learn to ignore specific revisions
  •                 dec->flags |= CODEC_FLAG_EMU_EDGE;
                }
    
                if (dec->time_base.den != rfps*dec->ticks_per_frame || dec->time_base.num != rfps_base) {
    
                    if (verbose >= 0)
                        fprintf(stderr,"\nSeems stream %d codec frame rate differs from container frame rate: %2.2f (%d/%d) -> %2.2f (%d/%d)\n",
                                i, (float)dec->time_base.den / dec->time_base.num, dec->time_base.den, dec->time_base.num,
    
                        (float)rfps / rfps_base, rfps, rfps_base);
                }
    
    
                if (o->video_disable)
    
                    st->discard= AVDISCARD_ALL;
                else if(video_discard)
                    st->discard= video_discard;
                break;
            case AVMEDIA_TYPE_DATA:
                break;
            case AVMEDIA_TYPE_SUBTITLE:
                if(!ist->dec)
                    ist->dec = avcodec_find_decoder(dec->codec_id);
    
                if(o->subtitle_disable)
    
                    st->discard = AVDISCARD_ALL;
                break;
            case AVMEDIA_TYPE_ATTACHMENT:
            case AVMEDIA_TYPE_UNKNOWN:
                break;
            default:
                abort();
            }
        }
    }
    
    
    static int opt_input_file(OptionsContext *o, const char *opt, const char *filename)
    
    Fabrice Bellard's avatar
    Fabrice Bellard committed
    {
        AVFormatContext *ic;
    
        AVInputFormat *file_iformat = NULL;
    
        int err, i, ret;
    
        int64_t timestamp;
    
        uint8_t buf[128];
    
        AVDictionary **opts;
        int orig_nb_streams;                     // number of streams before avformat_find_stream_info
    
    Fabrice Bellard's avatar
    Fabrice Bellard committed
    
    
        if (o->format) {
            if (!(file_iformat = av_find_input_format(o->format))) {
                fprintf(stderr, "Unknown input format: '%s'\n", o->format);
    
                exit_program(1);
    
        if (!strcmp(filename, "-"))
            filename = "pipe:";
    
    
        using_stdin |= !strncmp(filename, "pipe:", 5) ||
    
    Fabrice Bellard's avatar
    Fabrice Bellard committed
        /* get default parameters from command line */
    
        if (!ic) {
            print_error(filename, AVERROR(ENOMEM));
    
            exit_program(1);
    
        if (o->nb_audio_sample_rate) {
            snprintf(buf, sizeof(buf), "%d", o->audio_sample_rate[o->nb_audio_sample_rate - 1].u.i);
    
            av_dict_set(&format_opts, "sample_rate", buf, 0);
        }
    
        if (o->nb_audio_channels) {
            snprintf(buf, sizeof(buf), "%d", o->audio_channels[o->nb_audio_channels - 1].u.i);
    
            av_dict_set(&format_opts, "channels", buf, 0);
        }
    
        if (o->nb_frame_rates) {
            av_dict_set(&format_opts, "framerate", o->frame_rates[o->nb_frame_rates - 1].u.str, 0);
    
        if (o->nb_frame_sizes) {
            av_dict_set(&format_opts, "video_size", o->frame_sizes[o->nb_frame_sizes - 1].u.str, 0);
    
        if (o->nb_frame_pix_fmts)
            av_dict_set(&format_opts, "pixel_format", o->frame_pix_fmts[o->nb_frame_pix_fmts - 1].u.str, 0);
    
        ic->flags |= AVFMT_FLAG_NONBLOCK;
    
    Carl Eugen Hoyos's avatar
    Carl Eugen Hoyos committed
        if (loop_input) {
            av_log(NULL, AV_LOG_WARNING, "-loop_input is deprecated, use -loop 1\n");
            ic->loop_input = loop_input;
        }
    
    
        /* open the input file with generic libav function */
    
        err = avformat_open_input(&ic, filename, file_iformat, &format_opts);
    
    Fabrice Bellard's avatar
    Fabrice Bellard committed
        if (err < 0) {
    
            exit_program(1);
    
    Fabrice Bellard's avatar
    Fabrice Bellard committed
        }
    
        assert_avoptions(format_opts);
    
    
        /* apply forced codec ids */
        for (i = 0; i < ic->nb_streams; i++)
    
            choose_codec(o, ic, ic->streams[i], ic->streams[i]->codec->codec_type);
    
        /* Set AVCodecContext options for avformat_find_stream_info */
    
        opts = setup_find_stream_info_opts(ic, codec_opts);
    
        orig_nb_streams = ic->nb_streams;
    
        /* If not enough info to get the stream parameters, we decode the
           first frames to get it. (used in mpeg case for example) */
    
        ret = avformat_find_stream_info(ic, opts);
    
        if (ret < 0 && verbose >= 0) {
    
    Fabrice Bellard's avatar
    Fabrice Bellard committed
            fprintf(stderr, "%s: could not find codec parameters\n", filename);
    
            av_close_input_file(ic);
    
            exit_program(1);
    
    Fabrice Bellard's avatar
    Fabrice Bellard committed
        }
    
    
        timestamp = o->start_time;
    
        /* add the stream start time */
        if (ic->start_time != AV_NOPTS_VALUE)
            timestamp += ic->start_time;
    
    
        /* if seeking requested, we execute it */
    
        if (o->start_time != 0) {
    
            ret = av_seek_frame(ic, -1, timestamp, AVSEEK_FLAG_BACKWARD);
    
                fprintf(stderr, "%s: could not seek to position %0.3f\n",
    
    Fabrice Bellard's avatar
    Fabrice Bellard committed
        /* update the current parameters so that they match the one of the input stream */
    
        add_input_streams(o, ic);
    
    Fabrice Bellard's avatar
    Fabrice Bellard committed
        /* dump the file content */
    
            av_dump_format(ic, nb_input_files, filename, 0);
    
        input_files = grow_array(input_files, sizeof(*input_files), &nb_input_files, nb_input_files + 1);
        input_files[nb_input_files - 1].ctx        = ic;
        input_files[nb_input_files - 1].ist_index  = nb_input_streams - ic->nb_streams;
    
        input_files[nb_input_files - 1].ts_offset  = o->input_ts_offset - (copy_ts ? 0 : timestamp);
    
        input_files[nb_input_files - 1].nb_streams = ic->nb_streams;
    
    Michael Niedermayer's avatar
    Michael Niedermayer committed
        input_files[nb_input_files - 1].rate_emu   = o->rate_emu;
    
        for (i = 0; i < orig_nb_streams; i++)
            av_dict_free(&opts[i]);
        av_freep(&opts);
    
        return 0;
    
    Fabrice Bellard's avatar
    Fabrice Bellard committed
    }
    
    
    static void parse_forced_key_frames(char *kf, OutputStream *ost,
                                        AVCodecContext *avctx)
    {
        char *p;
        int n = 1, i;
        int64_t t;
    
        for (p = kf; *p; p++)
            if (*p == ',')
                n++;
        ost->forced_kf_count = n;
        ost->forced_kf_pts = av_malloc(sizeof(*ost->forced_kf_pts) * n);
        if (!ost->forced_kf_pts) {
            av_log(NULL, AV_LOG_FATAL, "Could not allocate forced key frames array.\n");
            exit_program(1);
        }
        for (i = 0; i < n; i++) {
            p = i ? strchr(p, ',') + 1 : kf;
            t = parse_time_or_die("force_key_frames", p, 1);
            ost->forced_kf_pts[i] = av_rescale_q(t, AV_TIME_BASE_Q, avctx->time_base);
        }
    }
    
    
    static OutputStream *new_output_stream(OptionsContext *o, AVFormatContext *oc, enum AVMediaType type)
    
    {
        OutputStream *ost;
    
        AVStream *st = av_new_stream(oc, oc->nb_streams < o->nb_streamid_map ? o->streamid_map[oc->nb_streams] : 0);
    
        int idx      = oc->nb_streams - 1;
    
        int64_t max_frames = INT64_MAX;
    
        char *bsf = NULL, *next, *codec_tag = NULL;
    
        AVBitStreamFilterContext *bsfc, *bsfc_prev = NULL;
    
    
        if (!st) {
            av_log(NULL, AV_LOG_ERROR, "Could not alloc stream.\n");
            exit_program(1);
        }
    
    
        output_streams = grow_array(output_streams, sizeof(*output_streams), &nb_output_streams,
                                    nb_output_streams + 1);
        ost = &output_streams[nb_output_streams - 1];
    
        ost->file_index = nb_output_files;
    
        ost->index = idx;
        ost->st    = st;
        st->codec->codec_type = type;
    
        ost->enc = choose_codec(o, oc, st, type);
    
        if (ost->enc) {
            ost->opts  = filter_codec_opts(codec_opts, ost->enc->id, oc, st);
        }
    
        avcodec_get_context_defaults3(st->codec, ost->enc);
        st->codec->codec_type = type; // XXX hack, avcodec_get_context_defaults2() sets type to unknown for stream copy
    
    
        MATCH_PER_STREAM_OPT(max_frames, i64, max_frames, oc, st);
        ost->max_frames = max_frames;
    
        MATCH_PER_STREAM_OPT(bitstream_filters, str, bsf, oc, st);
        while (bsf) {
            if (next = strchr(bsf, ','))
                *next++ = 0;
            if (!(bsfc = av_bitstream_filter_init(bsf))) {
                av_log(NULL, AV_LOG_ERROR, "Unknown bitstream filter %s\n", bsf);
                exit_program(1);
    
            if (bsfc_prev)
                bsfc_prev->next = bsfc;
            else
                ost->bitstream_filters = bsfc;
    
            bsfc_prev = bsfc;
            bsf       = next;
    
        MATCH_PER_STREAM_OPT(codec_tags, str, codec_tag, oc, st);
        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 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 OutputStream *new_video_stream(OptionsContext *o, AVFormatContext *oc)
    
    Fabrice Bellard's avatar
    Fabrice Bellard committed
    {
        AVStream *st;
    
        OutputStream *ost;
    
        ost = new_output_stream(o, oc, AVMEDIA_TYPE_VIDEO);
    
        if(oc->oformat->flags & AVFMT_GLOBALHEADER) {
    
            video_enc->flags |= CODEC_FLAG_GLOBAL_HEADER;
    
        if (!st->stream_copy) {
            const char *p = NULL;
            char *forced_key_frames = NULL, *frame_rate = NULL, *frame_size = NULL;
            char *frame_aspect_ratio = NULL, *frame_pix_fmt = NULL;
            char *intra_matrix = NULL, *inter_matrix = NULL, *filters = NULL;
            int i, force_fps = 0, top_field_first = -1;
    
            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);
    
            video_enc->bits_per_raw_sample = frame_bits_per_raw_sample;
    
            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;
    
            MATCH_PER_STREAM_OPT(intra_matrices, str, intra_matrix, oc, st);
            if (intra_matrix) {
                if (!(video_enc->intra_matrix = av_mallocz(sizeof(*video_enc->intra_matrix) * 64))) {
                    av_log(NULL, AV_LOG_ERROR, "Could not allocate memory for intra matrix.\n");
                    exit_program(1);
                }
                parse_matrix_coeffs(video_enc->intra_matrix, intra_matrix);
            }
            MATCH_PER_STREAM_OPT(inter_matrices, str, inter_matrix, oc, st);
            if (inter_matrix) {
                if (!(video_enc->inter_matrix = av_mallocz(sizeof(*video_enc->inter_matrix) * 64))) {
                    av_log(NULL, AV_LOG_ERROR, "Could not allocate memory for inter matrix.\n");
                    exit_program(1);
                }
                parse_matrix_coeffs(video_enc->inter_matrix, inter_matrix);
    
            MATCH_PER_STREAM_OPT(rc_overrides, str, p, oc, st);
    
            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->intra_dc_precision= intra_dc_precision - 8;
    
            /* 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;
    
            MATCH_PER_STREAM_OPT(top_field_first, i, top_field_first, oc, st);
            ost->top_field_first = top_field_first;
    
    #if CONFIG_AVFILTER
            MATCH_PER_STREAM_OPT(filters, str, filters, oc, st);
            if (filters)
                ost->avfilter = av_strdup(filters);
    #endif
    
        return ost;
    
    static OutputStream *new_audio_stream(OptionsContext *o, AVFormatContext *oc)
    
        OutputStream *ost;
    
        ost = new_output_stream(o, oc, AVMEDIA_TYPE_AUDIO);
    
        audio_enc->codec_type = AVMEDIA_TYPE_AUDIO;
    
        if (oc->oformat->flags & AVFMT_GLOBALHEADER) {
    
            audio_enc->flags |= CODEC_FLAG_GLOBAL_HEADER;
    
            char *sample_fmt = NULL;
    
            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);
    
    static OutputStream *new_data_stream(OptionsContext *o, AVFormatContext *oc)
    
        AVCodecContext *data_enc;
    
    
        ost = new_output_stream(o, oc, AVMEDIA_TYPE_DATA);
    
        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)
    
        OutputStream *ost;
    
        ost = new_output_stream(o, oc, AVMEDIA_TYPE_SUBTITLE);
    
        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(OptionsContext *o, const char *opt, const char *arg)
    
        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);
    
        idx = parse_number_or_die(opt, idx_str, OPT_INT, 0, MAX_STREAMS-1);
    
        o->streamid_map = grow_array(o->streamid_map, sizeof(*o->streamid_map), &o->nb_streamid_map, idx+1);
        o->streamid_map[idx] = parse_number_or_die(opt, p, OPT_INT, 0, INT_MAX);
    
    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);
    
    
                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_ffserver_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 = av_malloc(sizeof(*st->info));
            memcpy(st->info, ic->streams[i]->info, sizeof(*st->info));
            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;
    
        int i, err;
    
        AVOutputFormat *file_oformat;
    
        OutputStream *ost;
        InputStream  *ist;
    
    Fabrice Bellard's avatar
    Fabrice Bellard committed
    
        if (!strcmp(filename, "-"))
            filename = "pipe:";
    
    
        err = avformat_alloc_output_context2(&oc, NULL, o->format, filename);
    
            exit_program(1);
    
    Fabrice Bellard's avatar
    Fabrice Bellard committed
    
    
        if (!strcmp(file_oformat->name, "ffm") &&
    
            av_strstart(filename, "http:", NULL)) {
    
    Fabrice Bellard's avatar
    Fabrice Bellard committed
            /* special case for files sent to ffserver: we get the stream
               parameters from ffserver */
    
            int err = read_ffserver_streams(o, oc, filename);
    
            if (err < 0) {
                print_error(filename, err);
    
                exit_program(1);
    
    Fabrice Bellard's avatar
    Fabrice Bellard committed
            }
    
        } 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 || subtitle_codec_name)) {
    
                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? */
    
    Fabrice Bellard's avatar
    Fabrice Bellard committed
        } else {
    
            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;
            }
    
    Fabrice Bellard's avatar
    Fabrice Bellard committed
        }
    
    
        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);
    
    Fabrice Bellard's avatar
    Fabrice Bellard committed
    
    
        /* check filename in case of an image number is expected */
    
        if (oc->oformat->flags & AVFMT_NEEDNUMBER) {
    
                print_error(oc->filename, AVERROR(EINVAL));
    
                exit_program(1);
    
        if (!(oc->oformat->flags & AVFMT_NOFILE)) {
    
    Fabrice Bellard's avatar
    Fabrice Bellard committed
            /* test if it already exists to avoid loosing precious files */
    
            if (!file_overwrite &&
    
    Fabrice Bellard's avatar
    Fabrice Bellard committed
                (strchr(filename, ':') == NULL ||
    
                 av_strstart(filename, "file:", NULL))) {
    
                if (avio_check(filename, 0) == 0) {
    
                        fprintf(stderr,"File '%s' already exists. Overwrite ? [y/N] ", filename);
                        fflush(stderr);
    
                        if (!read_yesno()) {
    
                            fprintf(stderr, "Not overwriting - exiting\n");
    
                            exit_program(1);
    
                        fprintf(stderr,"File '%s' already exists. Exiting.\n", filename);
    
                        exit_program(1);
    
    Fabrice Bellard's avatar
    Fabrice Bellard committed
                }
            }
    
    Fabrice Bellard's avatar
    Fabrice Bellard committed
            /* open the file */
    
            if ((err = avio_open(&oc->pb, filename, AVIO_FLAG_WRITE)) < 0) {
    
                exit_program(1);
    
    Fabrice Bellard's avatar
    Fabrice Bellard committed
            }
        }
    
    
        oc->preload   = (int)(o->mux_preload   * AV_TIME_BASE);
        oc->max_delay = (int)(o->mux_max_delay * AV_TIME_BASE);
    
        if (loop_output >= 0) {
            av_log(NULL, AV_LOG_WARNING, "-loop_output is deprecated, use -loop\n");
            oc->loop_output = loop_output;
        }
    
        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->recording_time != INT64_MAX)
                av_dict_set(&oc->metadata, "duration", NULL, 0);
        }
    
        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[index]->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[index]->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);
        }
    
    Fabrice Bellard's avatar
    Fabrice Bellard committed
    }
    
    
    /* 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)
    
    Fabrice Bellard's avatar
    Fabrice Bellard committed
    {
    
        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
    
    Ramiro Polla's avatar
    Ramiro Polla committed
        return av_gettime();
    
    Ramiro Polla's avatar
    Ramiro Polla committed
    #endif
    
    Fabrice Bellard's avatar
    Fabrice Bellard committed
    }
    
    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 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);
    
    static int opt_help(const char *opt, const char *arg)
    
        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);
    
        class = avcodec_get_class();
        av_opt_show2(&class, NULL, AV_OPT_FLAG_ENCODING_PARAM|AV_OPT_FLAG_DECODING_PARAM, 0);
    
    
        /* 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);
    
    
        /* 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"};
    
            arg += 4;
        } else if(!strncmp(arg, "ntsc-", 5)) {
    
        } else if(!strncmp(arg, "film-", 5)) {
    
            /* 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;
    
                    if(norm != UNKNOWN)
                        break;
    
            if(verbose > 0 && norm != UNKNOWN)
    
                fprintf(stderr, "Assuming %s for target.\n", norm == PAL ? "PAL" : "NTSC");
    
            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);
    
            opt_video_codec(o, "c:v", "mpeg1video");
            opt_audio_codec(o, "c:a", "mp2");