Skip to content
Snippets Groups Projects
avconv.c 158 KiB
Newer Older
  • Learn to ignore specific revisions
  •     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;
    
        input_files[nb_input_files - 1].rate_emu   = o->rate_emu;
    
        for (i = 0; i < o->nb_dump_attachment; i++) {
            int j;
    
            for (j = 0; j < ic->nb_streams; j++) {
                AVStream *st = ic->streams[j];
    
                if (check_stream_specifier(ic, st, o->dump_attachment[i].specifier) == 1)
                    dump_attachment(st, o->dump_attachment[i].u.str);
            }
        }
    
    
        for (i = 0; i < orig_nb_streams; i++)
            av_dict_free(&opts[i]);
        av_freep(&opts);
    
    
        reset_options(o);
    
    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);
        }
    }
    
    
    Alexandra Khirnova's avatar
    Alexandra Khirnova committed
    static uint8_t *get_line(AVIOContext *s)
    {
        AVIOContext *line;
        uint8_t *buf;
        char c;
    
        if (avio_open_dyn_buf(&line) < 0) {
            av_log(NULL, AV_LOG_FATAL, "Could not alloc buffer for reading preset.\n");
            exit_program(1);
        }
    
        while ((c = avio_r8(s)) && c != '\n')
            avio_w8(line, c);
        avio_w8(line, 0);
        avio_close_dyn_buf(line, &buf);
    
        return buf;
    }
    
    static int get_preset_file_2(const char *preset_name, const char *codec_name, AVIOContext **s)
    {
        int i, ret = 1;
        char filename[1000];
        const char *base[3] = { getenv("AVCONV_DATADIR"),
                                getenv("HOME"),
                                AVCONV_DATADIR,
                                };
    
        for (i = 0; i < FF_ARRAY_ELEMS(base) && ret; i++) {
            if (!base[i])
                continue;
            if (codec_name) {
                snprintf(filename, sizeof(filename), "%s%s/%s-%s.avpreset", base[i],
                         i != 1 ? "" : "/.avconv", codec_name, preset_name);
                ret = avio_open(s, filename, AVIO_FLAG_READ);
            }
            if (ret) {
                snprintf(filename, sizeof(filename), "%s%s/%s.avpreset", base[i],
                         i != 1 ? "" : "/.avconv", preset_name);
                ret = avio_open(s, filename, AVIO_FLAG_READ);
            }
        }
        return ret;
    }
    
    
    static void choose_encoder(OptionsContext *o, AVFormatContext *s, OutputStream *ost)
    {
        char *codec_name = NULL;
    
        MATCH_PER_STREAM_OPT(codec_names, str, codec_name, s, ost->st);
        if (!codec_name) {
            ost->st->codec->codec_id = av_guess_codec(s->oformat, NULL, s->filename,
                                                      NULL, ost->st->codec->codec_type);
            ost->enc = avcodec_find_encoder(ost->st->codec->codec_id);
        } else if (!strcmp(codec_name, "copy"))
    
            ost->stream_copy = 1;
    
        else {
            ost->enc = find_codec_or_die(codec_name, ost->st->codec->codec_type, 1);
            ost->st->codec->codec_id = ost->enc->id;
        }
    }
    
    
    static OutputStream *new_output_stream(OptionsContext *o, AVFormatContext *oc, enum AVMediaType type)
    
    {
        OutputStream *ost;
    
        AVStream *st = avformat_new_stream(oc, NULL);
    
    Alexandra Khirnova's avatar
    Alexandra Khirnova committed
        int idx      = oc->nb_streams - 1, ret = 0;
    
        int64_t max_frames = INT64_MAX;
    
        char *bsf = NULL, *next, *codec_tag = NULL;
    
        AVBitStreamFilterContext *bsfc, *bsfc_prev = NULL;
    
        double qscale = -1;
    
    Alexandra Khirnova's avatar
    Alexandra Khirnova committed
        char *buf = NULL, *arg = NULL, *preset = NULL;
        AVIOContext *s = NULL;
    
            av_log(NULL, AV_LOG_FATAL, "Could not alloc stream.\n");
    
            exit_program(1);
        }
    
    
        if (oc->nb_streams - 1 < o->nb_streamid_map)
            st->id = o->streamid_map[oc->nb_streams - 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;
    
        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
    
    
    Alexandra Khirnova's avatar
    Alexandra Khirnova committed
        MATCH_PER_STREAM_OPT(presets, str, preset, oc, st);
        if (preset && (!(ret = get_preset_file_2(preset, ost->enc->name, &s)))) {
            do  {
                buf = get_line(s);
                if (!buf[0] || buf[0] == '#') {
                    av_free(buf);
                    continue;
                }
                if (!(arg = strchr(buf, '='))) {
                    av_log(NULL, AV_LOG_FATAL, "Invalid line found in the preset file.\n");
                    exit_program(1);
                }
                *arg++ = 0;
                av_dict_set(&ost->opts, buf, arg, AV_DICT_DONT_OVERWRITE);
                av_free(buf);
            } while (!s->eof_reached);
            avio_close(s);
        }
        if (ret) {
            av_log(NULL, AV_LOG_FATAL,
                   "Preset %s specified for stream %d:%d, but could not be opened.\n",
                   preset, ost->file_index, ost->index);
            exit_program(1);
        }
    
    
        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_FATAL, "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;
        }
    
    
        if (oc->oformat->flags & AVFMT_GLOBALHEADER)
            st->codec->flags |= CODEC_FLAG_GLOBAL_HEADER;
    
    
        av_opt_get_int(sws_opts, "sws_flags", 0, &ost->sws_flags);
    
    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) {
    
                av_log(NULL, AV_LOG_FATAL, "Syntax error in matrix \"%s\" at coeff %d\n", str, i);
    
    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);
    
        st  = ost->st;
        video_enc = st->codec;
    
    
        if (!ost->stream_copy) {
    
            char *forced_key_frames = NULL, *frame_rate = NULL, *frame_size = NULL;
    
            char *frame_aspect_ratio = NULL, *frame_pix_fmt = NULL;
    
    Anton Khirnov's avatar
    Anton Khirnov committed
            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_FATAL, "Invalid framerate value: %s\n", frame_rate);
    
            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_FATAL, "Invalid frame size: %s.\n", frame_size);
    
            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_FATAL, "Unknown pixel format requested: %s.\n", frame_pix_fmt);
    
            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_FATAL, "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_FATAL, "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){
    
                    av_log(NULL, AV_LOG_FATAL, "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;
    
            MATCH_PER_STREAM_OPT(copy_initial_nonkeyframes, i, ost->copy_initial_nonkeyframes, oc ,st);
    
    
    Anton Khirnov's avatar
    Anton Khirnov committed
    #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)
    
    {
        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 (!ost->stream_copy) {
    
            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_FATAL, "Invalid sample format '%s'\n", sample_fmt);
    
            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)
    
        ost = new_output_stream(o, oc, AVMEDIA_TYPE_DATA);
    
        if (!ost->stream_copy) {
    
            av_log(NULL, AV_LOG_FATAL, "Data stream encoding not supported yet (only streamcopy)\n");
    
        return ost;
    
    static OutputStream *new_attachment_stream(OptionsContext *o, AVFormatContext *oc)
    {
        OutputStream *ost = new_output_stream(o, oc, AVMEDIA_TYPE_ATTACHMENT);
    
        ost->stream_copy = 1;
    
    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;
    
    
        return ost;
    
    }
    
    /* arg format is "output-stream-index:streamid-value". */
    
    static int opt_streamid(OptionsContext *o, 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) {
    
            av_log(NULL, AV_LOG_FATAL,
                   "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);
    
        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);
    
    
            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 && !ost->stream_copy)
    
                choose_sample_fmt(st, codec);
    
            else if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO && !ost->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) {
    
                av_log(NULL, AV_LOG_FATAL, "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) {
    
                av_log(NULL, AV_LOG_FATAL, "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;
    
                case AVMEDIA_TYPE_ATTACHMENT: ost = new_attachment_stream(o, oc); break;
    
                    av_log(NULL, AV_LOG_FATAL, "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;
            }
    
        /* handle attached files */
        for (i = 0; i < o->nb_attachments; i++) {
            AVIOContext *pb;
            uint8_t *attachment;
            const char *p;
            int64_t len;
    
            if ((err = avio_open(&pb, o->attachments[i], AVIO_FLAG_READ)) < 0) {
                av_log(NULL, AV_LOG_FATAL, "Could not open attachment file %s.\n",
                       o->attachments[i]);
                exit_program(1);
            }
            if ((len = avio_size(pb)) <= 0) {
                av_log(NULL, AV_LOG_FATAL, "Could not get size of the attachment %s.\n",
                       o->attachments[i]);
                exit_program(1);
            }
            if (!(attachment = av_malloc(len))) {
                av_log(NULL, AV_LOG_FATAL, "Attachment %s too large to fit into memory.\n",
                       o->attachments[i]);
                exit_program(1);
            }
            avio_read(pb, attachment, len);
    
            ost = new_attachment_stream(o, oc);
            ost->stream_copy               = 0;
            ost->source_index              = -1;
            ost->attachment_filename       = o->attachments[i];
            ost->st->codec->extradata      = attachment;
            ost->st->codec->extradata_size = len;
    
            p = strrchr(o->attachments[i], '/');
            av_dict_set(&ost->st->metadata, "filename", (p && *p) ? p + 1 : o->attachments[i], AV_DICT_DONT_OVERWRITE);
            avio_close(pb);
        }
    
    
        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 */
    
            assert_file_overwrite(filename);
    
    
            /* open the file */
            if ((err = avio_open(&oc->pb, filename, AVIO_FLAG_WRITE)) < 0) {
                print_error(filename, err);
                exit_program(1);
            }
        }
    
    
        if (o->mux_preload) {
            uint8_t buf[64];
            snprintf(buf, sizeof(buf), "%d", (int)(o->mux_preload*AV_TIME_BASE));
            av_dict_set(&output_files[nb_output_files - 1].opts, "preload", buf, 0);
        }
    
        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;
    
                av_log(NULL, AV_LOG_FATAL, "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_FATAL, "Invalid %s index %d while processing metadata maps\n",\
    
            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;
                if (output_streams[i].source_index < 0)         /* this is true e.g. for attached files */
                    continue;
                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_FATAL, "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_FATAL, "Invalid stream index %d in metadata specifier.\n", index);
    
                m = &oc->streams[index]->metadata;
    
                break;
            case 'c':
                if (index < 0 || index >= oc->nb_chapters) {
    
                    av_log(NULL, AV_LOG_FATAL, "Invalid chapter index %d in metadata specifier.\n", index);
    
                m = &oc->chapters[index]->metadata;
    
                av_log(NULL, AV_LOG_FATAL, "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);
        }
    
    
        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 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)
    {
    
        int flags = AV_OPT_FLAG_DECODING_PARAM | AV_OPT_FLAG_ENCODING_PARAM;
    
        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");
    
        show_help_children(avcodec_get_class(), flags);
        show_help_children(avformat_get_class(), flags);
        show_help_children(sws_get_class(), flags);
    
    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 (norm != UNKNOWN)
                av_log(NULL, AV_LOG_INFO, "Assuming %s for target.\n", norm == PAL ? "PAL" : "NTSC");
    
            av_log(NULL, AV_LOG_FATAL, "Could not determine norm (PAL/NTSC/NTSC-Film) for target.\n");
            av_log(NULL, AV_LOG_FATAL, "Please prefix target with \"pal-\", \"ntsc-\" or \"film-\",\n");
            av_log(NULL, AV_LOG_FATAL, "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);