static int transcode(AVFormatContext **output_files,
                     int nb_output_files,
                     InputFile *input_files,
                     int nb_input_files,
                     StreamMap *stream_maps, int nb_stream_maps)
{
    int ret = 0, i, j, k, n, nb_ostreams = 0;
    AVFormatContext *is, *os;
    AVCodecContext *codec, *icodec;
    OutputStream *ost, **ost_table = NULL;
    InputStream *ist;
    char error[1024];
    int want_sdp = 1;
    uint8_t no_packet[MAX_FILES]={0};
    int no_packet_count=0;
    if (rate_emu)
        for (i = 0; i < nb_input_streams; i++)
            input_streams[i].start = av_gettime();
    nb_ostreams = 0;
    for(i=0;i<nb_output_files;i++) {
        os = output_files[i];
        if (!os->nb_streams && !(os->oformat->flags & AVFMT_NOSTREAMS)) {
            av_dump_format(output_files[i], i, output_files[i]->filename, 1);
            fprintf(stderr, "Output file #%d does not contain any stream\n", i);
            ret = AVERROR(EINVAL);
            goto fail;
        }
        nb_ostreams += os->nb_streams;
    }
    if (nb_stream_maps > 0 && nb_stream_maps != nb_ostreams) {
        fprintf(stderr, "Number of stream maps must match number of output streams\n");
        ret = AVERROR(EINVAL);
        goto fail;
    }
    for(i=0;i<nb_stream_maps;i++) {
        int fi = stream_maps[i].file_index;
        int si = stream_maps[i].stream_index;
        if (fi < 0 || fi > nb_input_files - 1 ||
            si < 0 || si > input_files[fi].ctx->nb_streams - 1) {
            fprintf(stderr,"Could not find input stream #%d.%d\n", fi, si);
            ret = AVERROR(EINVAL);
            goto fail;
        }
        fi = stream_maps[i].sync_file_index;
        si = stream_maps[i].sync_stream_index;
        if (fi < 0 || fi > nb_input_files - 1 ||
            si < 0 || si > input_files[fi].ctx->nb_streams - 1) {
            fprintf(stderr,"Could not find sync stream #%d.%d\n", fi, si);
            ret = AVERROR(EINVAL);
            goto fail;
        }
    }
    ost_table = av_mallocz(sizeof(OutputStream *) * nb_ostreams);
    if (!ost_table)
        goto fail;
    n = 0;
    for(k=0;k<nb_output_files;k++) {
        os = output_files[k];
        for(i=0;i<os->nb_streams;i++,n++) {
            int found;
            ost = ost_table[n] = output_streams_for_file[k][i];
            if (nb_stream_maps > 0) {
                ost->source_index = input_files[stream_maps[n].file_index].ist_index +
                    stream_maps[n].stream_index;
                if (input_streams[ost->source_index].st->codec->codec_type != ost->st->codec->codec_type) {
                    int i= ost->file_index;
                    av_dump_format(output_files[i], i, output_files[i]->filename, 1);
                    fprintf(stderr, "Codec type mismatch for mapping #%d.%d -> #%d.%d\n",
                        stream_maps[n].file_index, stream_maps[n].stream_index,
                        ost->file_index, ost->index);
                    exit_program(1);
                }
            } else {
                int best_nb_frames=-1;
                found = 0;
                for (j = 0; j < nb_input_streams; j++) {
                    int skip=0;
                    ist = &input_streams[j];
                    if(opt_programid){
                        int pi,si;
                        AVFormatContext *f = input_files[ist->file_index].ctx;
                        skip=1;
                        for(pi=0; pi<f->nb_programs; pi++){
                            AVProgram *p= f->programs[pi];
                            if(p->id == opt_programid)
                                for(si=0; si<p->nb_stream_indexes; si++){
                                    if(f->streams[ p->stream_index[si] ] == ist->st)
                                        skip=0;
                                }
                        }
                    }
                    if (ist->discard && ist->st->discard != AVDISCARD_ALL && !skip &&
                        ist->st->codec->codec_type == ost->st->codec->codec_type) {
                        if(best_nb_frames < ist->st->codec_info_nb_frames){
                            best_nb_frames= ist->st->codec_info_nb_frames;
                            ost->source_index = j;
                            found = 1;
                        }
                    }
                }
                if (!found) {
                    if(! opt_programid) {
                        for (j = 0; j < nb_input_streams; j++) {
                            ist = &input_streams[j];
                            if (   ist->st->codec->codec_type == ost->st->codec->codec_type
                                && ist->st->discard != AVDISCARD_ALL) {
                                ost->source_index = j;
                                found = 1;
                            }
                        }
                    }
                    if (!found) {
                        int i= ost->file_index;
                        av_dump_format(output_files[i], i, output_files[i]->filename, 1);
                        fprintf(stderr, "Could not find input stream matching output stream #%d.%d\n",
                                ost->file_index, ost->index);
                        exit_program(1);
                    }
                }
            }
            ist = &input_streams[ost->source_index];
            ist->discard = 0;
            ost->sync_ist = (nb_stream_maps > 0) ?
                &input_streams[input_files[stream_maps[n].sync_file_index].ist_index +
                         stream_maps[n].sync_stream_index] : ist;
        }
    }
    for(i=0;i<nb_ostreams;i++) {
        ost = ost_table[i];
        os = output_files[ost->file_index];
        ist = &input_streams[ost->source_index];
        codec = ost->st->codec;
        icodec = ist->st->codec;
        if (metadata_streams_autocopy)
            av_dict_copy(&ost->st->metadata, ist->st->metadata,
                         AV_DICT_DONT_OVERWRITE);
        ost->st->disposition = ist->st->disposition;
        codec->bits_per_raw_sample= icodec->bits_per_raw_sample;
        codec->chroma_sample_location = icodec->chroma_sample_location;
        if (ost->st->stream_copy) {
            uint64_t extra_size = (uint64_t)icodec->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE;
            if (extra_size > INT_MAX)
                goto fail;
            codec->codec_id = icodec->codec_id;
            codec->codec_type = icodec->codec_type;
            if(!codec->codec_tag){
                if(   !os->oformat->codec_tag
                   || av_codec_get_id (os->oformat->codec_tag, icodec->codec_tag) == codec->codec_id
                   || av_codec_get_tag(os->oformat->codec_tag, icodec->codec_id) <= 0)
                    codec->codec_tag = icodec->codec_tag;
            }
            codec->bit_rate = icodec->bit_rate;
            codec->rc_max_rate    = icodec->rc_max_rate;
            codec->rc_buffer_size = icodec->rc_buffer_size;
            codec->extradata= av_mallocz(extra_size);
            if (!codec->extradata)
                goto fail;
            memcpy(codec->extradata, icodec->extradata, icodec->extradata_size);
            codec->extradata_size= icodec->extradata_size;
            if(!copy_tb && av_q2d(icodec->time_base)*icodec->ticks_per_frame > av_q2d(ist->st->time_base) && av_q2d(ist->st->time_base) < 1.0/500){
                codec->time_base = icodec->time_base;
                codec->time_base.num *= icodec->ticks_per_frame;
                av_reduce(&codec->time_base.num, &codec->time_base.den,
                          codec->time_base.num, codec->time_base.den, INT_MAX);
            }else
                codec->time_base = ist->st->time_base;
            switch(codec->codec_type) {
            case AVMEDIA_TYPE_AUDIO:
                if(audio_volume != 256) {
                    fprintf(stderr,"-acodec copy and -vol are incompatible (frames are not decoded)\n");
                    exit_program(1);
                }
                codec->channel_layout = icodec->channel_layout;
                codec->sample_rate = icodec->sample_rate;
                codec->channels = icodec->channels;
                codec->frame_size = icodec->frame_size;
                codec->audio_service_type = icodec->audio_service_type;
                codec->block_align= icodec->block_align;
                if(codec->block_align == 1 && codec->codec_id == CODEC_ID_MP3)
                    codec->block_align= 0;
                if(codec->codec_id == CODEC_ID_AC3)
                    codec->block_align= 0;
                break;
            case AVMEDIA_TYPE_VIDEO:
                codec->pix_fmt = icodec->pix_fmt;
                codec->width = icodec->width;
                codec->height = icodec->height;
                codec->has_b_frames = icodec->has_b_frames;
                if (!codec->sample_aspect_ratio.num) {
                    codec->sample_aspect_ratio =
                    ost->st->sample_aspect_ratio =
                        ist->st->sample_aspect_ratio.num ? ist->st->sample_aspect_ratio :
                        ist->st->codec->sample_aspect_ratio.num ?
                        ist->st->codec->sample_aspect_ratio : (AVRational){0, 1};
                }
                break;
            case AVMEDIA_TYPE_SUBTITLE:
                codec->width = icodec->width;
                codec->height = icodec->height;
                break;
            case AVMEDIA_TYPE_DATA:
                break;
            default:
                abort();
            }
        } else {
            if (!ost->enc)
                ost->enc = avcodec_find_encoder(ost->st->codec->codec_id);
            switch(codec->codec_type) {
            case AVMEDIA_TYPE_AUDIO:
                ost->fifo= av_fifo_alloc(1024);
                if(!ost->fifo)
                    goto fail;
                ost->reformat_pair = MAKE_SFMT_PAIR(AV_SAMPLE_FMT_NONE,AV_SAMPLE_FMT_NONE);
                if (!codec->sample_rate) {
                    codec->sample_rate = icodec->sample_rate;
                    if (icodec->lowres)
                        codec->sample_rate >>= icodec->lowres;
                }
                choose_sample_rate(ost->st, ost->enc);
                codec->time_base = (AVRational){1, codec->sample_rate};
                if (codec->sample_fmt == AV_SAMPLE_FMT_NONE)
                    codec->sample_fmt = icodec->sample_fmt;
                choose_sample_fmt(ost->st, ost->enc);
                if (!codec->channels)
                    codec->channels = icodec->channels;
                codec->channel_layout = icodec->channel_layout;
                if (av_get_channel_layout_nb_channels(codec->channel_layout) != codec->channels)
                    codec->channel_layout = 0;
                ost->audio_resample = codec->sample_rate != icodec->sample_rate || audio_sync_method > 1;
                icodec->request_channels = codec->channels;
                ist->decoding_needed = 1;
                ost->encoding_needed = 1;
                ost->resample_sample_fmt  = icodec->sample_fmt;
                ost->resample_sample_rate = icodec->sample_rate;
                ost->resample_channels    = icodec->channels;
                break;
            case AVMEDIA_TYPE_VIDEO:
                if (codec->pix_fmt == PIX_FMT_NONE)
                    codec->pix_fmt = icodec->pix_fmt;
                choose_pixel_fmt(ost->st, ost->enc);
                if (ost->st->codec->pix_fmt == PIX_FMT_NONE) {
                    fprintf(stderr, "Video pixel format is unknown, stream cannot be encoded\n");
                    exit_program(1);
                }
                if (!codec->width || !codec->height) {
                    codec->width  = icodec->width;
                    codec->height = icodec->height;
                }
                ost->video_resample = codec->width   != icodec->width  ||
                                      codec->height  != icodec->height ||
                                      codec->pix_fmt != icodec->pix_fmt;
                if (ost->video_resample) {
#if !CONFIG_AVFILTER
                    avcodec_get_frame_defaults(&ost->pict_tmp);
                    if(avpicture_alloc((AVPicture*)&ost->pict_tmp, codec->pix_fmt,
                                       codec->width, codec->height)) {
                        fprintf(stderr, "Cannot allocate temp picture, check pix fmt\n");
                        exit_program(1);
                    }
                    ost->img_resample_ctx = sws_getContext(
                        icodec->width,
                        icodec->height,
                        icodec->pix_fmt,
                        codec->width,
                        codec->height,
                        codec->pix_fmt,
                        ost->sws_flags, NULL, NULL, NULL);
                    if (ost->img_resample_ctx == NULL) {
                        fprintf(stderr, "Cannot get resampling context\n");
                        exit_program(1);
                    }
#endif
                    codec->bits_per_raw_sample= 0;
                }
                ost->resample_height = icodec->height;
                ost->resample_width  = icodec->width;
                ost->resample_pix_fmt= icodec->pix_fmt;
                ost->encoding_needed = 1;
                ist->decoding_needed = 1;
                if (!ost->frame_rate.num)
                    ost->frame_rate = ist->st->r_frame_rate.num ? ist->st->r_frame_rate : (AVRational){25,1};
                if (ost->enc && ost->enc->supported_framerates && !force_fps) {
                    int idx = av_find_nearest_q_idx(ost->frame_rate, ost->enc->supported_framerates);
                    ost->frame_rate = ost->enc->supported_framerates[idx];
                }
                codec->time_base = (AVRational){ost->frame_rate.den, ost->frame_rate.num};
#if CONFIG_AVFILTER
                if (configure_video_filters(ist, ost)) {
                    fprintf(stderr, "Error opening filters!\n");
                    exit(1);
                }
#endif
                break;
            case AVMEDIA_TYPE_SUBTITLE:
                ost->encoding_needed = 1;
                ist->decoding_needed = 1;
                break;
            default:
                abort();
                break;
            }
            if (ost->encoding_needed &&
                (codec->flags & (CODEC_FLAG_PASS1 | CODEC_FLAG_PASS2))) {
                char logfilename[1024];
                FILE *f;
                snprintf(logfilename, sizeof(logfilename), "%s-%d.log",
                         pass_logfilename_prefix ? pass_logfilename_prefix : DEFAULT_PASS_LOGFILENAME_PREFIX,
                         i);
                if (codec->flags & CODEC_FLAG_PASS1) {
                    f = fopen(logfilename, "wb");
                    if (!f) {
                        fprintf(stderr, "Cannot write log file '%s' for pass-1 encoding: %s\n", logfilename, strerror(errno));
                        exit_program(1);
                    }
                    ost->logfile = f;
                } else {
                    char  *logbuffer;
                    size_t logbuffer_size;
                    if (read_file(logfilename, &logbuffer, &logbuffer_size) < 0) {
                        fprintf(stderr, "Error reading log file '%s' for pass-2 encoding\n", logfilename);
                        exit_program(1);
                    }
                    codec->stats_in = logbuffer;
                }
            }
        }
        if(codec->codec_type == AVMEDIA_TYPE_VIDEO){
            int size= codec->width * codec->height;
            bit_buffer_size= FFMAX(bit_buffer_size, 6*size + 200);
        }
    }
    if (!bit_buffer)
        bit_buffer = av_malloc(bit_buffer_size);
    if (!bit_buffer) {
        fprintf(stderr, "Cannot allocate %d bytes output buffer\n",
                bit_buffer_size);
        ret = AVERROR(ENOMEM);
        goto fail;
    }
    for(i=0;i<nb_ostreams;i++) {
        ost = ost_table[i];
        if (ost->encoding_needed) {
            AVCodec *codec = ost->enc;
            AVCodecContext *dec = input_streams[ost->source_index].st->codec;
            if (!codec) {
                snprintf(error, sizeof(error), "Encoder (codec id %d) not found for output stream #%d.%d",
                         ost->st->codec->codec_id, ost->file_index, ost->index);
                ret = AVERROR(EINVAL);
                goto dump_format;
            }
            if (dec->subtitle_header) {
                ost->st->codec->subtitle_header = av_malloc(dec->subtitle_header_size);
                if (!ost->st->codec->subtitle_header) {
                    ret = AVERROR(ENOMEM);
                    goto dump_format;
                }
                memcpy(ost->st->codec->subtitle_header, dec->subtitle_header, dec->subtitle_header_size);
                ost->st->codec->subtitle_header_size = dec->subtitle_header_size;
            }
            if (avcodec_open2(ost->st->codec, codec, &ost->opts) < 0) {
                snprintf(error, sizeof(error), "Error while opening encoder for output stream #%d.%d - maybe incorrect parameters such as bit_rate, rate, width or height",
                        ost->file_index, ost->index);
                ret = AVERROR(EINVAL);
                goto dump_format;
            }
            assert_codec_experimental(ost->st->codec, 1);
            assert_avoptions(ost->opts);
            if (ost->st->codec->bit_rate && ost->st->codec->bit_rate < 1000)
                av_log(NULL, AV_LOG_WARNING, "The bitrate parameter is set too low."
                                             "It takes bits/s as argument, not kbits/s\n");
            extra_size += ost->st->codec->extradata_size;
        }
    }
    for (i = 0; i < nb_input_streams; i++) {
        ist = &input_streams[i];
        if (ist->decoding_needed) {
            AVCodec *codec = ist->dec;
            if (!codec)
                codec = avcodec_find_decoder(ist->st->codec->codec_id);
            if (!codec) {
                snprintf(error, sizeof(error), "Decoder (codec id %d) not found for input stream #%d.%d",
                        ist->st->codec->codec_id, ist->file_index, ist->st->index);
                ret = AVERROR(EINVAL);
                goto dump_format;
            }
            for (j = 0; j < nb_ostreams; j++) {
                ost = ost_table[j];
                if (ost->source_index == i) {
                    update_sample_fmt(ist->st->codec, codec, ost->st->codec);
                    break;
                }
            }
            if (avcodec_open2(ist->st->codec, codec, &ist->opts) < 0) {
                snprintf(error, sizeof(error), "Error while opening decoder for input stream #%d.%d",
                        ist->file_index, ist->st->index);
                ret = AVERROR(EINVAL);
                goto dump_format;
            }
            assert_codec_experimental(ist->st->codec, 0);
            assert_avoptions(ost->opts);
        }
    }
    for (i = 0; i < nb_input_streams; i++) {
        AVStream *st;
        ist = &input_streams[i];
        st= ist->st;
        ist->pts = st->avg_frame_rate.num ? - st->codec->has_b_frames*AV_TIME_BASE / av_q2d(st->avg_frame_rate) : 0;
        ist->next_pts = AV_NOPTS_VALUE;
        init_pts_correction(&ist->pts_ctx);
        ist->is_start = 1;
    }
    for (i=0;i<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)) {\
            snprintf(error, sizeof(error), "Invalid %s index %d while processing metadata maps\n",\
                     (desc), (index));\
            ret = AVERROR(EINVAL);\
            goto dump_format;\
        }
        int out_file_index = meta_data_maps[i][0].file;
        int in_file_index = meta_data_maps[i][1].file;
        if (in_file_index < 0 || out_file_index < 0)
            continue;
        METADATA_CHECK_INDEX(out_file_index, nb_output_files, "output file")
        METADATA_CHECK_INDEX(in_file_index, nb_input_files, "input file")
        files[0] = output_files[out_file_index];
        files[1] = input_files[in_file_index].ctx;
        for (j = 0; j < 2; j++) {
            MetadataMap *map = &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);
    }
    if (metadata_global_autocopy) {
        for (i = 0; i < nb_output_files; i++)
            av_dict_copy(&output_files[i]->metadata, input_files[0].ctx->metadata,
                         AV_DICT_DONT_OVERWRITE);
    }
    for (i = 0; i < nb_chapter_maps; i++) {
        int infile  = chapter_maps[i].in_file;
        int outfile = chapter_maps[i].out_file;
        if (infile < 0 || outfile < 0)
            continue;
        if (infile >= nb_input_files) {
            snprintf(error, sizeof(error), "Invalid input file index %d in chapter mapping.\n", infile);
            ret = AVERROR(EINVAL);
            goto dump_format;
        }
        if (outfile >= nb_output_files) {
            snprintf(error, sizeof(error), "Invalid output file index %d in chapter mapping.\n",outfile);
            ret = AVERROR(EINVAL);
            goto dump_format;
        }
        copy_chapters(infile, outfile);
    }
    if (!nb_chapter_maps)
        for (i = 0; i < nb_input_files; i++) {
            if (!input_files[i].ctx->nb_chapters)
                continue;
            for (j = 0; j < nb_output_files; j++)
                if ((ret = copy_chapters(i, j)) < 0)
                    goto dump_format;
            break;
        }
    for(i=0;i<nb_output_files;i++) {
        os = output_files[i];
        if (avformat_write_header(os, &output_opts[i]) < 0) {
            snprintf(error, sizeof(error), "Could not write header for output file #%d (incorrect codec parameters ?)", i);
            ret = AVERROR(EINVAL);
            goto dump_format;
        }
        assert_avoptions(output_opts[i]);
        if (strcmp(output_files[i]->oformat->name, "rtp")) {
            want_sdp = 0;
        }
    }
 dump_format:
    for(i=0;i<nb_output_files;i++) {
        av_dump_format(output_files[i], i, output_files[i]->filename, 1);
    }
    if (verbose >= 0) {
        fprintf(stderr, "Stream mapping:\n");
        for(i=0;i<nb_ostreams;i++) {
            ost = ost_table[i];
            fprintf(stderr, "  Stream #%d.%d -> #%d.%d",
                    input_streams[ost->source_index].file_index,
                    input_streams[ost->source_index].st->index,
                    ost->file_index,
                    ost->index);
            if (ost->sync_ist != &input_streams[ost->source_index])
                fprintf(stderr, " [sync #%d.%d]",
                        ost->sync_ist->file_index,
                        ost->sync_ist->st->index);
            fprintf(stderr, "\n");
        }
    }
    if (ret) {
        fprintf(stderr, "%s\n", error);
        goto fail;
    }
    if (want_sdp) {
        print_sdp(output_files, nb_output_files);
    }
    if (verbose >= 0)
        fprintf(stderr, "Press ctrl-c to stop encoding\n");
    term_init();
    timer_start = av_gettime();
    for(; received_sigterm == 0;) {
        int file_index, ist_index;
        AVPacket pkt;
        double ipts_min;
        double opts_min;
    redo:
        ipts_min= 1e100;
        opts_min= 1e100;
        file_index = -1;
        for(i=0;i<nb_ostreams;i++) {
            double ipts, opts;
            ost = ost_table[i];
            os = output_files[ost->file_index];
            ist = &input_streams[ost->source_index];
            if(ist->is_past_recording_time || no_packet[ist->file_index])
                continue;
                opts = ost->st->pts.val * av_q2d(ost->st->time_base);
            ipts = (double)ist->pts;
            if (!input_files[ist->file_index].eof_reached){
                if(ipts < ipts_min) {
                    ipts_min = ipts;
                    if(input_sync ) file_index = ist->file_index;
                }
                if(opts < opts_min) {
                    opts_min = opts;
                    if(!input_sync) file_index = ist->file_index;
                }
            }
            if(ost->frame_number >= max_frames[ost->st->codec->codec_type]){
                file_index= -1;
                break;
            }
        }
        if (file_index < 0) {
            if(no_packet_count){
                no_packet_count=0;
                memset(no_packet, 0, sizeof(no_packet));
                usleep(10000);
                continue;
            }
            break;
        }
        if (limit_filesize != 0 && limit_filesize <= avio_tell(output_files[0]->pb))
            break;
        is = input_files[file_index].ctx;
        ret= av_read_frame(is, &pkt);
        if(ret == AVERROR(EAGAIN)){
            no_packet[file_index]=1;
            no_packet_count++;
            continue;
        }
        if (ret < 0) {
            input_files[file_index].eof_reached = 1;
            if (opt_shortest)
                break;
            else
                continue;
        }
        no_packet_count=0;
        memset(no_packet, 0, sizeof(no_packet));
        if (do_pkt_dump) {
            av_pkt_dump_log2(NULL, AV_LOG_DEBUG, &pkt, do_hex_dump,
                             is->streams[pkt.stream_index]);
        }
        if (pkt.stream_index >= input_files[file_index].ctx->nb_streams)
            goto discard_packet;
        ist_index = input_files[file_index].ist_index + pkt.stream_index;
        ist = &input_streams[ist_index];
        if (ist->discard)
            goto discard_packet;
        if (pkt.dts != AV_NOPTS_VALUE)
            pkt.dts += av_rescale_q(input_files[ist->file_index].ts_offset, AV_TIME_BASE_Q, ist->st->time_base);
        if (pkt.pts != AV_NOPTS_VALUE)
            pkt.pts += av_rescale_q(input_files[ist->file_index].ts_offset, AV_TIME_BASE_Q, ist->st->time_base);
        if (ist->ts_scale) {
            if(pkt.pts != AV_NOPTS_VALUE)
                pkt.pts *= ist->ts_scale;
            if(pkt.dts != AV_NOPTS_VALUE)
                pkt.dts *= ist->ts_scale;
        }
        if (pkt.dts != AV_NOPTS_VALUE && ist->next_pts != AV_NOPTS_VALUE
            && (is->iformat->flags & AVFMT_TS_DISCONT)) {
            int64_t pkt_dts= av_rescale_q(pkt.dts, ist->st->time_base, AV_TIME_BASE_Q);
            int64_t delta= pkt_dts - ist->next_pts;
            if((FFABS(delta) > 1LL*dts_delta_threshold*AV_TIME_BASE || pkt_dts+1<ist->pts)&& !copy_ts){
                input_files[ist->file_index].ts_offset -= delta;
                if (verbose > 2)
                    fprintf(stderr, "timestamp discontinuity %"PRId64", new offset= %"PRId64"\n",
                            delta, input_files[ist->file_index].ts_offset);
                pkt.dts-= av_rescale_q(delta, AV_TIME_BASE_Q, ist->st->time_base);
                if(pkt.pts != AV_NOPTS_VALUE)
                    pkt.pts-= av_rescale_q(delta, AV_TIME_BASE_Q, ist->st->time_base);
            }
        }
        if (recording_time != INT64_MAX &&
            av_compare_ts(pkt.pts, ist->st->time_base, recording_time + start_time, (AVRational){1, 1000000}) >= 0) {
            ist->is_past_recording_time = 1;
            goto discard_packet;
        }
        if (output_packet(ist, ist_index, ost_table, nb_ostreams, &pkt) < 0) {
            if (verbose >= 0)
                fprintf(stderr, "Error while decoding stream #%d.%d\n",
                        ist->file_index, ist->st->index);
            if (exit_on_error)
                exit_program(1);
            av_free_packet(&pkt);
            goto redo;
        }
    discard_packet:
        av_free_packet(&pkt);
        print_report(output_files, ost_table, nb_ostreams, 0);
    }
    for (i = 0; i < nb_input_streams; i++) {
        ist = &input_streams[i];
        if (ist->decoding_needed) {
            output_packet(ist, i, ost_table, nb_ostreams, NULL);
        }
    }
    term_exit();
    for(i=0;i<nb_output_files;i++) {
        os = output_files[i];
        av_write_trailer(os);
    }
    print_report(output_files, ost_table, nb_ostreams, 1);
    for(i=0;i<nb_ostreams;i++) {
        ost = ost_table[i];
        if (ost->encoding_needed) {
            av_freep(&ost->st->codec->stats_in);
            avcodec_close(ost->st->codec);
        }
#if CONFIG_AVFILTER
        avfilter_graph_free(&ost->graph);
#endif
    }
    for (i = 0; i < nb_input_streams; i++) {
        ist = &input_streams[i];
        if (ist->decoding_needed) {
            avcodec_close(ist->st->codec);
        }
    }
    ret = 0;
 fail:
    av_freep(&bit_buffer);
    if (ost_table) {
        for(i=0;i<nb_ostreams;i++) {
            ost = ost_table[i];
            if (ost) {
                if (ost->st->stream_copy)
                    av_freep(&ost->st->codec->extradata);
                if (ost->logfile) {
                    fclose(ost->logfile);
                    ost->logfile = NULL;
                }
                av_fifo_free(ost->fifo);
                av_freep(&ost->st->codec->subtitle_header);
                av_free(ost->pict_tmp.data[0]);
                av_free(ost->forced_kf_pts);
                if (ost->video_resample)
                    sws_freeContext(ost->img_resample_ctx);
                if (ost->resample)
                    audio_resample_close(ost->resample);
                if (ost->reformat_ctx)
                    av_audio_convert_free(ost->reformat_ctx);
                av_dict_free(&ost->opts);
                av_free(ost);
            }
        }
        av_free(ost_table);
    }
    return ret;
}
['int main(int argc, char **argv)\n{\n    int64_t ti;\n    av_log_set_flags(AV_LOG_SKIP_REPEATED);\n    avcodec_register_all();\n#if CONFIG_AVDEVICE\n    avdevice_register_all();\n#endif\n#if CONFIG_AVFILTER\n    avfilter_register_all();\n#endif\n    av_register_all();\n    avio_set_interrupt_cb(decode_interrupt_cb);\n    init_opts();\n    show_banner();\n    av_log(NULL, AV_LOG_WARNING, "This program is not developed anymore and is only "\n                                 "provided for compatibility. Use avconv instead "\n                                 "(see Changelog for the list of incompatible changes).\\n");\n    parse_options(NULL, argc, argv, options, opt_output_file);\n    if(nb_output_files <= 0 && nb_input_files == 0) {\n        show_usage();\n        fprintf(stderr, "Use -h to get full help or, even better, run \'man ffmpeg\'\\n");\n        exit_program(1);\n    }\n    if (nb_output_files <= 0) {\n        fprintf(stderr, "At least one output file must be specified\\n");\n        exit_program(1);\n    }\n    if (nb_input_files == 0) {\n        fprintf(stderr, "At least one input file must be specified\\n");\n        exit_program(1);\n    }\n    ti = getutime();\n    if (transcode(output_files, nb_output_files, input_files, nb_input_files,\n                  stream_maps, nb_stream_maps) < 0)\n        exit_program(1);\n    ti = getutime() - ti;\n    if (do_benchmark) {\n        int maxrss = getmaxrss() / 1024;\n        printf("bench: utime=%0.3fs maxrss=%ikB\\n", ti / 1000000.0, maxrss);\n    }\n    exit_program(0);\n    return 0;\n}', 'static int transcode(AVFormatContext **output_files,\n                     int nb_output_files,\n                     InputFile *input_files,\n                     int nb_input_files,\n                     StreamMap *stream_maps, int nb_stream_maps)\n{\n    int ret = 0, i, j, k, n, nb_ostreams = 0;\n    AVFormatContext *is, *os;\n    AVCodecContext *codec, *icodec;\n    OutputStream *ost, **ost_table = NULL;\n    InputStream *ist;\n    char error[1024];\n    int want_sdp = 1;\n    uint8_t no_packet[MAX_FILES]={0};\n    int no_packet_count=0;\n    if (rate_emu)\n        for (i = 0; i < nb_input_streams; i++)\n            input_streams[i].start = av_gettime();\n    nb_ostreams = 0;\n    for(i=0;i<nb_output_files;i++) {\n        os = output_files[i];\n        if (!os->nb_streams && !(os->oformat->flags & AVFMT_NOSTREAMS)) {\n            av_dump_format(output_files[i], i, output_files[i]->filename, 1);\n            fprintf(stderr, "Output file #%d does not contain any stream\\n", i);\n            ret = AVERROR(EINVAL);\n            goto fail;\n        }\n        nb_ostreams += os->nb_streams;\n    }\n    if (nb_stream_maps > 0 && nb_stream_maps != nb_ostreams) {\n        fprintf(stderr, "Number of stream maps must match number of output streams\\n");\n        ret = AVERROR(EINVAL);\n        goto fail;\n    }\n    for(i=0;i<nb_stream_maps;i++) {\n        int fi = stream_maps[i].file_index;\n        int si = stream_maps[i].stream_index;\n        if (fi < 0 || fi > nb_input_files - 1 ||\n            si < 0 || si > input_files[fi].ctx->nb_streams - 1) {\n            fprintf(stderr,"Could not find input stream #%d.%d\\n", fi, si);\n            ret = AVERROR(EINVAL);\n            goto fail;\n        }\n        fi = stream_maps[i].sync_file_index;\n        si = stream_maps[i].sync_stream_index;\n        if (fi < 0 || fi > nb_input_files - 1 ||\n            si < 0 || si > input_files[fi].ctx->nb_streams - 1) {\n            fprintf(stderr,"Could not find sync stream #%d.%d\\n", fi, si);\n            ret = AVERROR(EINVAL);\n            goto fail;\n        }\n    }\n    ost_table = av_mallocz(sizeof(OutputStream *) * nb_ostreams);\n    if (!ost_table)\n        goto fail;\n    n = 0;\n    for(k=0;k<nb_output_files;k++) {\n        os = output_files[k];\n        for(i=0;i<os->nb_streams;i++,n++) {\n            int found;\n            ost = ost_table[n] = output_streams_for_file[k][i];\n            if (nb_stream_maps > 0) {\n                ost->source_index = input_files[stream_maps[n].file_index].ist_index +\n                    stream_maps[n].stream_index;\n                if (input_streams[ost->source_index].st->codec->codec_type != ost->st->codec->codec_type) {\n                    int i= ost->file_index;\n                    av_dump_format(output_files[i], i, output_files[i]->filename, 1);\n                    fprintf(stderr, "Codec type mismatch for mapping #%d.%d -> #%d.%d\\n",\n                        stream_maps[n].file_index, stream_maps[n].stream_index,\n                        ost->file_index, ost->index);\n                    exit_program(1);\n                }\n            } else {\n                int best_nb_frames=-1;\n                found = 0;\n                for (j = 0; j < nb_input_streams; j++) {\n                    int skip=0;\n                    ist = &input_streams[j];\n                    if(opt_programid){\n                        int pi,si;\n                        AVFormatContext *f = input_files[ist->file_index].ctx;\n                        skip=1;\n                        for(pi=0; pi<f->nb_programs; pi++){\n                            AVProgram *p= f->programs[pi];\n                            if(p->id == opt_programid)\n                                for(si=0; si<p->nb_stream_indexes; si++){\n                                    if(f->streams[ p->stream_index[si] ] == ist->st)\n                                        skip=0;\n                                }\n                        }\n                    }\n                    if (ist->discard && ist->st->discard != AVDISCARD_ALL && !skip &&\n                        ist->st->codec->codec_type == ost->st->codec->codec_type) {\n                        if(best_nb_frames < ist->st->codec_info_nb_frames){\n                            best_nb_frames= ist->st->codec_info_nb_frames;\n                            ost->source_index = j;\n                            found = 1;\n                        }\n                    }\n                }\n                if (!found) {\n                    if(! opt_programid) {\n                        for (j = 0; j < nb_input_streams; j++) {\n                            ist = &input_streams[j];\n                            if (   ist->st->codec->codec_type == ost->st->codec->codec_type\n                                && ist->st->discard != AVDISCARD_ALL) {\n                                ost->source_index = j;\n                                found = 1;\n                            }\n                        }\n                    }\n                    if (!found) {\n                        int i= ost->file_index;\n                        av_dump_format(output_files[i], i, output_files[i]->filename, 1);\n                        fprintf(stderr, "Could not find input stream matching output stream #%d.%d\\n",\n                                ost->file_index, ost->index);\n                        exit_program(1);\n                    }\n                }\n            }\n            ist = &input_streams[ost->source_index];\n            ist->discard = 0;\n            ost->sync_ist = (nb_stream_maps > 0) ?\n                &input_streams[input_files[stream_maps[n].sync_file_index].ist_index +\n                         stream_maps[n].sync_stream_index] : ist;\n        }\n    }\n    for(i=0;i<nb_ostreams;i++) {\n        ost = ost_table[i];\n        os = output_files[ost->file_index];\n        ist = &input_streams[ost->source_index];\n        codec = ost->st->codec;\n        icodec = ist->st->codec;\n        if (metadata_streams_autocopy)\n            av_dict_copy(&ost->st->metadata, ist->st->metadata,\n                         AV_DICT_DONT_OVERWRITE);\n        ost->st->disposition = ist->st->disposition;\n        codec->bits_per_raw_sample= icodec->bits_per_raw_sample;\n        codec->chroma_sample_location = icodec->chroma_sample_location;\n        if (ost->st->stream_copy) {\n            uint64_t extra_size = (uint64_t)icodec->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE;\n            if (extra_size > INT_MAX)\n                goto fail;\n            codec->codec_id = icodec->codec_id;\n            codec->codec_type = icodec->codec_type;\n            if(!codec->codec_tag){\n                if(   !os->oformat->codec_tag\n                   || av_codec_get_id (os->oformat->codec_tag, icodec->codec_tag) == codec->codec_id\n                   || av_codec_get_tag(os->oformat->codec_tag, icodec->codec_id) <= 0)\n                    codec->codec_tag = icodec->codec_tag;\n            }\n            codec->bit_rate = icodec->bit_rate;\n            codec->rc_max_rate    = icodec->rc_max_rate;\n            codec->rc_buffer_size = icodec->rc_buffer_size;\n            codec->extradata= av_mallocz(extra_size);\n            if (!codec->extradata)\n                goto fail;\n            memcpy(codec->extradata, icodec->extradata, icodec->extradata_size);\n            codec->extradata_size= icodec->extradata_size;\n            if(!copy_tb && av_q2d(icodec->time_base)*icodec->ticks_per_frame > av_q2d(ist->st->time_base) && av_q2d(ist->st->time_base) < 1.0/500){\n                codec->time_base = icodec->time_base;\n                codec->time_base.num *= icodec->ticks_per_frame;\n                av_reduce(&codec->time_base.num, &codec->time_base.den,\n                          codec->time_base.num, codec->time_base.den, INT_MAX);\n            }else\n                codec->time_base = ist->st->time_base;\n            switch(codec->codec_type) {\n            case AVMEDIA_TYPE_AUDIO:\n                if(audio_volume != 256) {\n                    fprintf(stderr,"-acodec copy and -vol are incompatible (frames are not decoded)\\n");\n                    exit_program(1);\n                }\n                codec->channel_layout = icodec->channel_layout;\n                codec->sample_rate = icodec->sample_rate;\n                codec->channels = icodec->channels;\n                codec->frame_size = icodec->frame_size;\n                codec->audio_service_type = icodec->audio_service_type;\n                codec->block_align= icodec->block_align;\n                if(codec->block_align == 1 && codec->codec_id == CODEC_ID_MP3)\n                    codec->block_align= 0;\n                if(codec->codec_id == CODEC_ID_AC3)\n                    codec->block_align= 0;\n                break;\n            case AVMEDIA_TYPE_VIDEO:\n                codec->pix_fmt = icodec->pix_fmt;\n                codec->width = icodec->width;\n                codec->height = icodec->height;\n                codec->has_b_frames = icodec->has_b_frames;\n                if (!codec->sample_aspect_ratio.num) {\n                    codec->sample_aspect_ratio =\n                    ost->st->sample_aspect_ratio =\n                        ist->st->sample_aspect_ratio.num ? ist->st->sample_aspect_ratio :\n                        ist->st->codec->sample_aspect_ratio.num ?\n                        ist->st->codec->sample_aspect_ratio : (AVRational){0, 1};\n                }\n                break;\n            case AVMEDIA_TYPE_SUBTITLE:\n                codec->width = icodec->width;\n                codec->height = icodec->height;\n                break;\n            case AVMEDIA_TYPE_DATA:\n                break;\n            default:\n                abort();\n            }\n        } else {\n            if (!ost->enc)\n                ost->enc = avcodec_find_encoder(ost->st->codec->codec_id);\n            switch(codec->codec_type) {\n            case AVMEDIA_TYPE_AUDIO:\n                ost->fifo= av_fifo_alloc(1024);\n                if(!ost->fifo)\n                    goto fail;\n                ost->reformat_pair = MAKE_SFMT_PAIR(AV_SAMPLE_FMT_NONE,AV_SAMPLE_FMT_NONE);\n                if (!codec->sample_rate) {\n                    codec->sample_rate = icodec->sample_rate;\n                    if (icodec->lowres)\n                        codec->sample_rate >>= icodec->lowres;\n                }\n                choose_sample_rate(ost->st, ost->enc);\n                codec->time_base = (AVRational){1, codec->sample_rate};\n                if (codec->sample_fmt == AV_SAMPLE_FMT_NONE)\n                    codec->sample_fmt = icodec->sample_fmt;\n                choose_sample_fmt(ost->st, ost->enc);\n                if (!codec->channels)\n                    codec->channels = icodec->channels;\n                codec->channel_layout = icodec->channel_layout;\n                if (av_get_channel_layout_nb_channels(codec->channel_layout) != codec->channels)\n                    codec->channel_layout = 0;\n                ost->audio_resample = codec->sample_rate != icodec->sample_rate || audio_sync_method > 1;\n                icodec->request_channels = codec->channels;\n                ist->decoding_needed = 1;\n                ost->encoding_needed = 1;\n                ost->resample_sample_fmt  = icodec->sample_fmt;\n                ost->resample_sample_rate = icodec->sample_rate;\n                ost->resample_channels    = icodec->channels;\n                break;\n            case AVMEDIA_TYPE_VIDEO:\n                if (codec->pix_fmt == PIX_FMT_NONE)\n                    codec->pix_fmt = icodec->pix_fmt;\n                choose_pixel_fmt(ost->st, ost->enc);\n                if (ost->st->codec->pix_fmt == PIX_FMT_NONE) {\n                    fprintf(stderr, "Video pixel format is unknown, stream cannot be encoded\\n");\n                    exit_program(1);\n                }\n                if (!codec->width || !codec->height) {\n                    codec->width  = icodec->width;\n                    codec->height = icodec->height;\n                }\n                ost->video_resample = codec->width   != icodec->width  ||\n                                      codec->height  != icodec->height ||\n                                      codec->pix_fmt != icodec->pix_fmt;\n                if (ost->video_resample) {\n#if !CONFIG_AVFILTER\n                    avcodec_get_frame_defaults(&ost->pict_tmp);\n                    if(avpicture_alloc((AVPicture*)&ost->pict_tmp, codec->pix_fmt,\n                                       codec->width, codec->height)) {\n                        fprintf(stderr, "Cannot allocate temp picture, check pix fmt\\n");\n                        exit_program(1);\n                    }\n                    ost->img_resample_ctx = sws_getContext(\n                        icodec->width,\n                        icodec->height,\n                        icodec->pix_fmt,\n                        codec->width,\n                        codec->height,\n                        codec->pix_fmt,\n                        ost->sws_flags, NULL, NULL, NULL);\n                    if (ost->img_resample_ctx == NULL) {\n                        fprintf(stderr, "Cannot get resampling context\\n");\n                        exit_program(1);\n                    }\n#endif\n                    codec->bits_per_raw_sample= 0;\n                }\n                ost->resample_height = icodec->height;\n                ost->resample_width  = icodec->width;\n                ost->resample_pix_fmt= icodec->pix_fmt;\n                ost->encoding_needed = 1;\n                ist->decoding_needed = 1;\n                if (!ost->frame_rate.num)\n                    ost->frame_rate = ist->st->r_frame_rate.num ? ist->st->r_frame_rate : (AVRational){25,1};\n                if (ost->enc && ost->enc->supported_framerates && !force_fps) {\n                    int idx = av_find_nearest_q_idx(ost->frame_rate, ost->enc->supported_framerates);\n                    ost->frame_rate = ost->enc->supported_framerates[idx];\n                }\n                codec->time_base = (AVRational){ost->frame_rate.den, ost->frame_rate.num};\n#if CONFIG_AVFILTER\n                if (configure_video_filters(ist, ost)) {\n                    fprintf(stderr, "Error opening filters!\\n");\n                    exit(1);\n                }\n#endif\n                break;\n            case AVMEDIA_TYPE_SUBTITLE:\n                ost->encoding_needed = 1;\n                ist->decoding_needed = 1;\n                break;\n            default:\n                abort();\n                break;\n            }\n            if (ost->encoding_needed &&\n                (codec->flags & (CODEC_FLAG_PASS1 | CODEC_FLAG_PASS2))) {\n                char logfilename[1024];\n                FILE *f;\n                snprintf(logfilename, sizeof(logfilename), "%s-%d.log",\n                         pass_logfilename_prefix ? pass_logfilename_prefix : DEFAULT_PASS_LOGFILENAME_PREFIX,\n                         i);\n                if (codec->flags & CODEC_FLAG_PASS1) {\n                    f = fopen(logfilename, "wb");\n                    if (!f) {\n                        fprintf(stderr, "Cannot write log file \'%s\' for pass-1 encoding: %s\\n", logfilename, strerror(errno));\n                        exit_program(1);\n                    }\n                    ost->logfile = f;\n                } else {\n                    char  *logbuffer;\n                    size_t logbuffer_size;\n                    if (read_file(logfilename, &logbuffer, &logbuffer_size) < 0) {\n                        fprintf(stderr, "Error reading log file \'%s\' for pass-2 encoding\\n", logfilename);\n                        exit_program(1);\n                    }\n                    codec->stats_in = logbuffer;\n                }\n            }\n        }\n        if(codec->codec_type == AVMEDIA_TYPE_VIDEO){\n            int size= codec->width * codec->height;\n            bit_buffer_size= FFMAX(bit_buffer_size, 6*size + 200);\n        }\n    }\n    if (!bit_buffer)\n        bit_buffer = av_malloc(bit_buffer_size);\n    if (!bit_buffer) {\n        fprintf(stderr, "Cannot allocate %d bytes output buffer\\n",\n                bit_buffer_size);\n        ret = AVERROR(ENOMEM);\n        goto fail;\n    }\n    for(i=0;i<nb_ostreams;i++) {\n        ost = ost_table[i];\n        if (ost->encoding_needed) {\n            AVCodec *codec = ost->enc;\n            AVCodecContext *dec = input_streams[ost->source_index].st->codec;\n            if (!codec) {\n                snprintf(error, sizeof(error), "Encoder (codec id %d) not found for output stream #%d.%d",\n                         ost->st->codec->codec_id, ost->file_index, ost->index);\n                ret = AVERROR(EINVAL);\n                goto dump_format;\n            }\n            if (dec->subtitle_header) {\n                ost->st->codec->subtitle_header = av_malloc(dec->subtitle_header_size);\n                if (!ost->st->codec->subtitle_header) {\n                    ret = AVERROR(ENOMEM);\n                    goto dump_format;\n                }\n                memcpy(ost->st->codec->subtitle_header, dec->subtitle_header, dec->subtitle_header_size);\n                ost->st->codec->subtitle_header_size = dec->subtitle_header_size;\n            }\n            if (avcodec_open2(ost->st->codec, codec, &ost->opts) < 0) {\n                snprintf(error, sizeof(error), "Error while opening encoder for output stream #%d.%d - maybe incorrect parameters such as bit_rate, rate, width or height",\n                        ost->file_index, ost->index);\n                ret = AVERROR(EINVAL);\n                goto dump_format;\n            }\n            assert_codec_experimental(ost->st->codec, 1);\n            assert_avoptions(ost->opts);\n            if (ost->st->codec->bit_rate && ost->st->codec->bit_rate < 1000)\n                av_log(NULL, AV_LOG_WARNING, "The bitrate parameter is set too low."\n                                             "It takes bits/s as argument, not kbits/s\\n");\n            extra_size += ost->st->codec->extradata_size;\n        }\n    }\n    for (i = 0; i < nb_input_streams; i++) {\n        ist = &input_streams[i];\n        if (ist->decoding_needed) {\n            AVCodec *codec = ist->dec;\n            if (!codec)\n                codec = avcodec_find_decoder(ist->st->codec->codec_id);\n            if (!codec) {\n                snprintf(error, sizeof(error), "Decoder (codec id %d) not found for input stream #%d.%d",\n                        ist->st->codec->codec_id, ist->file_index, ist->st->index);\n                ret = AVERROR(EINVAL);\n                goto dump_format;\n            }\n            for (j = 0; j < nb_ostreams; j++) {\n                ost = ost_table[j];\n                if (ost->source_index == i) {\n                    update_sample_fmt(ist->st->codec, codec, ost->st->codec);\n                    break;\n                }\n            }\n            if (avcodec_open2(ist->st->codec, codec, &ist->opts) < 0) {\n                snprintf(error, sizeof(error), "Error while opening decoder for input stream #%d.%d",\n                        ist->file_index, ist->st->index);\n                ret = AVERROR(EINVAL);\n                goto dump_format;\n            }\n            assert_codec_experimental(ist->st->codec, 0);\n            assert_avoptions(ost->opts);\n        }\n    }\n    for (i = 0; i < nb_input_streams; i++) {\n        AVStream *st;\n        ist = &input_streams[i];\n        st= ist->st;\n        ist->pts = st->avg_frame_rate.num ? - st->codec->has_b_frames*AV_TIME_BASE / av_q2d(st->avg_frame_rate) : 0;\n        ist->next_pts = AV_NOPTS_VALUE;\n        init_pts_correction(&ist->pts_ctx);\n        ist->is_start = 1;\n    }\n    for (i=0;i<nb_meta_data_maps;i++) {\n        AVFormatContext *files[2];\n        AVDictionary    **meta[2];\n        int j;\n#define METADATA_CHECK_INDEX(index, nb_elems, desc)\\\n        if ((index) < 0 || (index) >= (nb_elems)) {\\\n            snprintf(error, sizeof(error), "Invalid %s index %d while processing metadata maps\\n",\\\n                     (desc), (index));\\\n            ret = AVERROR(EINVAL);\\\n            goto dump_format;\\\n        }\n        int out_file_index = meta_data_maps[i][0].file;\n        int in_file_index = meta_data_maps[i][1].file;\n        if (in_file_index < 0 || out_file_index < 0)\n            continue;\n        METADATA_CHECK_INDEX(out_file_index, nb_output_files, "output file")\n        METADATA_CHECK_INDEX(in_file_index, nb_input_files, "input file")\n        files[0] = output_files[out_file_index];\n        files[1] = input_files[in_file_index].ctx;\n        for (j = 0; j < 2; j++) {\n            MetadataMap *map = &meta_data_maps[i][j];\n            switch (map->type) {\n            case \'g\':\n                meta[j] = &files[j]->metadata;\n                break;\n            case \'s\':\n                METADATA_CHECK_INDEX(map->index, files[j]->nb_streams, "stream")\n                meta[j] = &files[j]->streams[map->index]->metadata;\n                break;\n            case \'c\':\n                METADATA_CHECK_INDEX(map->index, files[j]->nb_chapters, "chapter")\n                meta[j] = &files[j]->chapters[map->index]->metadata;\n                break;\n            case \'p\':\n                METADATA_CHECK_INDEX(map->index, files[j]->nb_programs, "program")\n                meta[j] = &files[j]->programs[map->index]->metadata;\n                break;\n            }\n        }\n        av_dict_copy(meta[0], *meta[1], AV_DICT_DONT_OVERWRITE);\n    }\n    if (metadata_global_autocopy) {\n        for (i = 0; i < nb_output_files; i++)\n            av_dict_copy(&output_files[i]->metadata, input_files[0].ctx->metadata,\n                         AV_DICT_DONT_OVERWRITE);\n    }\n    for (i = 0; i < nb_chapter_maps; i++) {\n        int infile  = chapter_maps[i].in_file;\n        int outfile = chapter_maps[i].out_file;\n        if (infile < 0 || outfile < 0)\n            continue;\n        if (infile >= nb_input_files) {\n            snprintf(error, sizeof(error), "Invalid input file index %d in chapter mapping.\\n", infile);\n            ret = AVERROR(EINVAL);\n            goto dump_format;\n        }\n        if (outfile >= nb_output_files) {\n            snprintf(error, sizeof(error), "Invalid output file index %d in chapter mapping.\\n",outfile);\n            ret = AVERROR(EINVAL);\n            goto dump_format;\n        }\n        copy_chapters(infile, outfile);\n    }\n    if (!nb_chapter_maps)\n        for (i = 0; i < nb_input_files; i++) {\n            if (!input_files[i].ctx->nb_chapters)\n                continue;\n            for (j = 0; j < nb_output_files; j++)\n                if ((ret = copy_chapters(i, j)) < 0)\n                    goto dump_format;\n            break;\n        }\n    for(i=0;i<nb_output_files;i++) {\n        os = output_files[i];\n        if (avformat_write_header(os, &output_opts[i]) < 0) {\n            snprintf(error, sizeof(error), "Could not write header for output file #%d (incorrect codec parameters ?)", i);\n            ret = AVERROR(EINVAL);\n            goto dump_format;\n        }\n        assert_avoptions(output_opts[i]);\n        if (strcmp(output_files[i]->oformat->name, "rtp")) {\n            want_sdp = 0;\n        }\n    }\n dump_format:\n    for(i=0;i<nb_output_files;i++) {\n        av_dump_format(output_files[i], i, output_files[i]->filename, 1);\n    }\n    if (verbose >= 0) {\n        fprintf(stderr, "Stream mapping:\\n");\n        for(i=0;i<nb_ostreams;i++) {\n            ost = ost_table[i];\n            fprintf(stderr, "  Stream #%d.%d -> #%d.%d",\n                    input_streams[ost->source_index].file_index,\n                    input_streams[ost->source_index].st->index,\n                    ost->file_index,\n                    ost->index);\n            if (ost->sync_ist != &input_streams[ost->source_index])\n                fprintf(stderr, " [sync #%d.%d]",\n                        ost->sync_ist->file_index,\n                        ost->sync_ist->st->index);\n            fprintf(stderr, "\\n");\n        }\n    }\n    if (ret) {\n        fprintf(stderr, "%s\\n", error);\n        goto fail;\n    }\n    if (want_sdp) {\n        print_sdp(output_files, nb_output_files);\n    }\n    if (verbose >= 0)\n        fprintf(stderr, "Press ctrl-c to stop encoding\\n");\n    term_init();\n    timer_start = av_gettime();\n    for(; received_sigterm == 0;) {\n        int file_index, ist_index;\n        AVPacket pkt;\n        double ipts_min;\n        double opts_min;\n    redo:\n        ipts_min= 1e100;\n        opts_min= 1e100;\n        file_index = -1;\n        for(i=0;i<nb_ostreams;i++) {\n            double ipts, opts;\n            ost = ost_table[i];\n            os = output_files[ost->file_index];\n            ist = &input_streams[ost->source_index];\n            if(ist->is_past_recording_time || no_packet[ist->file_index])\n                continue;\n                opts = ost->st->pts.val * av_q2d(ost->st->time_base);\n            ipts = (double)ist->pts;\n            if (!input_files[ist->file_index].eof_reached){\n                if(ipts < ipts_min) {\n                    ipts_min = ipts;\n                    if(input_sync ) file_index = ist->file_index;\n                }\n                if(opts < opts_min) {\n                    opts_min = opts;\n                    if(!input_sync) file_index = ist->file_index;\n                }\n            }\n            if(ost->frame_number >= max_frames[ost->st->codec->codec_type]){\n                file_index= -1;\n                break;\n            }\n        }\n        if (file_index < 0) {\n            if(no_packet_count){\n                no_packet_count=0;\n                memset(no_packet, 0, sizeof(no_packet));\n                usleep(10000);\n                continue;\n            }\n            break;\n        }\n        if (limit_filesize != 0 && limit_filesize <= avio_tell(output_files[0]->pb))\n            break;\n        is = input_files[file_index].ctx;\n        ret= av_read_frame(is, &pkt);\n        if(ret == AVERROR(EAGAIN)){\n            no_packet[file_index]=1;\n            no_packet_count++;\n            continue;\n        }\n        if (ret < 0) {\n            input_files[file_index].eof_reached = 1;\n            if (opt_shortest)\n                break;\n            else\n                continue;\n        }\n        no_packet_count=0;\n        memset(no_packet, 0, sizeof(no_packet));\n        if (do_pkt_dump) {\n            av_pkt_dump_log2(NULL, AV_LOG_DEBUG, &pkt, do_hex_dump,\n                             is->streams[pkt.stream_index]);\n        }\n        if (pkt.stream_index >= input_files[file_index].ctx->nb_streams)\n            goto discard_packet;\n        ist_index = input_files[file_index].ist_index + pkt.stream_index;\n        ist = &input_streams[ist_index];\n        if (ist->discard)\n            goto discard_packet;\n        if (pkt.dts != AV_NOPTS_VALUE)\n            pkt.dts += av_rescale_q(input_files[ist->file_index].ts_offset, AV_TIME_BASE_Q, ist->st->time_base);\n        if (pkt.pts != AV_NOPTS_VALUE)\n            pkt.pts += av_rescale_q(input_files[ist->file_index].ts_offset, AV_TIME_BASE_Q, ist->st->time_base);\n        if (ist->ts_scale) {\n            if(pkt.pts != AV_NOPTS_VALUE)\n                pkt.pts *= ist->ts_scale;\n            if(pkt.dts != AV_NOPTS_VALUE)\n                pkt.dts *= ist->ts_scale;\n        }\n        if (pkt.dts != AV_NOPTS_VALUE && ist->next_pts != AV_NOPTS_VALUE\n            && (is->iformat->flags & AVFMT_TS_DISCONT)) {\n            int64_t pkt_dts= av_rescale_q(pkt.dts, ist->st->time_base, AV_TIME_BASE_Q);\n            int64_t delta= pkt_dts - ist->next_pts;\n            if((FFABS(delta) > 1LL*dts_delta_threshold*AV_TIME_BASE || pkt_dts+1<ist->pts)&& !copy_ts){\n                input_files[ist->file_index].ts_offset -= delta;\n                if (verbose > 2)\n                    fprintf(stderr, "timestamp discontinuity %"PRId64", new offset= %"PRId64"\\n",\n                            delta, input_files[ist->file_index].ts_offset);\n                pkt.dts-= av_rescale_q(delta, AV_TIME_BASE_Q, ist->st->time_base);\n                if(pkt.pts != AV_NOPTS_VALUE)\n                    pkt.pts-= av_rescale_q(delta, AV_TIME_BASE_Q, ist->st->time_base);\n            }\n        }\n        if (recording_time != INT64_MAX &&\n            av_compare_ts(pkt.pts, ist->st->time_base, recording_time + start_time, (AVRational){1, 1000000}) >= 0) {\n            ist->is_past_recording_time = 1;\n            goto discard_packet;\n        }\n        if (output_packet(ist, ist_index, ost_table, nb_ostreams, &pkt) < 0) {\n            if (verbose >= 0)\n                fprintf(stderr, "Error while decoding stream #%d.%d\\n",\n                        ist->file_index, ist->st->index);\n            if (exit_on_error)\n                exit_program(1);\n            av_free_packet(&pkt);\n            goto redo;\n        }\n    discard_packet:\n        av_free_packet(&pkt);\n        print_report(output_files, ost_table, nb_ostreams, 0);\n    }\n    for (i = 0; i < nb_input_streams; i++) {\n        ist = &input_streams[i];\n        if (ist->decoding_needed) {\n            output_packet(ist, i, ost_table, nb_ostreams, NULL);\n        }\n    }\n    term_exit();\n    for(i=0;i<nb_output_files;i++) {\n        os = output_files[i];\n        av_write_trailer(os);\n    }\n    print_report(output_files, ost_table, nb_ostreams, 1);\n    for(i=0;i<nb_ostreams;i++) {\n        ost = ost_table[i];\n        if (ost->encoding_needed) {\n            av_freep(&ost->st->codec->stats_in);\n            avcodec_close(ost->st->codec);\n        }\n#if CONFIG_AVFILTER\n        avfilter_graph_free(&ost->graph);\n#endif\n    }\n    for (i = 0; i < nb_input_streams; i++) {\n        ist = &input_streams[i];\n        if (ist->decoding_needed) {\n            avcodec_close(ist->st->codec);\n        }\n    }\n    ret = 0;\n fail:\n    av_freep(&bit_buffer);\n    if (ost_table) {\n        for(i=0;i<nb_ostreams;i++) {\n            ost = ost_table[i];\n            if (ost) {\n                if (ost->st->stream_copy)\n                    av_freep(&ost->st->codec->extradata);\n                if (ost->logfile) {\n                    fclose(ost->logfile);\n                    ost->logfile = NULL;\n                }\n                av_fifo_free(ost->fifo);\n                av_freep(&ost->st->codec->subtitle_header);\n                av_free(ost->pict_tmp.data[0]);\n                av_free(ost->forced_kf_pts);\n                if (ost->video_resample)\n                    sws_freeContext(ost->img_resample_ctx);\n                if (ost->resample)\n                    audio_resample_close(ost->resample);\n                if (ost->reformat_ctx)\n                    av_audio_convert_free(ost->reformat_ctx);\n                av_dict_free(&ost->opts);\n                av_free(ost);\n            }\n        }\n        av_free(ost_table);\n    }\n    return ret;\n}']