memset(file_table, 0, sizeof(file_table));
static int av_encode(AVFormatContext **output_files,                     int nb_output_files,                     AVFormatContext **input_files,                     int nb_input_files,                     AVStreamMap *stream_maps, int nb_stream_maps){    int ret, i, j, k, n, nb_istreams = 0, nb_ostreams = 0;    AVFormatContext *is, *os;    AVCodecContext *codec, *icodec;    AVOutputStream *ost, **ost_table = NULL;    AVInputStream *ist, **ist_table = NULL;    INT64 min_pts, start_time;    AVInputFile *file_table;    file_table= (AVInputFile*) malloc(nb_input_files * sizeof(AVInputFile));    if (!file_table)        goto fail;    memset(file_table, 0, sizeof(file_table));        /* input stream init */    j = 0;    for(i=0;i<nb_input_files;i++) {        is = input_files[i];        file_table[i].ist_index = j;        j += is->nb_streams;    }    nb_istreams = j;    ist_table = av_mallocz(nb_istreams * sizeof(AVInputStream *));    if (!ist_table)        goto fail;        for(i=0;i<nb_istreams;i++) {        ist = av_mallocz(sizeof(AVInputStream));        if (!ist)            goto fail;        ist_table[i] = ist;    }    j = 0;    for(i=0;i<nb_input_files;i++) {        is = input_files[i];        for(k=0;k<is->nb_streams;k++) {            ist = ist_table[j++];            ist->st = is->streams[k];            ist->file_index = i;            ist->index = k;            ist->discard = 1; /* the stream is discarded by default                                 (changed later) */        }    }    /* output stream init */    nb_ostreams = 0;    for(i=0;i<nb_output_files;i++) {        os = output_files[i];        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");        exit(1);    }    ost_table = av_mallocz(sizeof(AVOutputStream *) * nb_ostreams);    if (!ost_table)        goto fail;    for(i=0;i<nb_ostreams;i++) {        ost = av_mallocz(sizeof(AVOutputStream));        if (!ost)            goto fail;        ost_table[i] = ost;    }        n = 0;    for(k=0;k<nb_output_files;k++) {        os = output_files[k];        for(i=0;i<os->nb_streams;i++) {            int found;            ost = ost_table[n++];            ost->file_index = k;            ost->index = i;            ost->st = os->streams[i];            if (nb_stream_maps > 0) {                ost->source_index = file_table[stream_maps[n-1].file_index].ist_index +                     stream_maps[n-1].stream_index;            } else {                /* get corresponding input stream index : we select the first one with the right type */                found = 0;                for(j=0;j<nb_istreams;j++) {                    ist = ist_table[j];                    if (ist->discard &&                         ist->st->codec.codec_type == ost->st->codec.codec_type) {                        ost->source_index = j;                        found = 1;                    }                }                                if (!found) {                    /* try again and reuse existing stream */                    for(j=0;j<nb_istreams;j++) {                        ist = ist_table[j];                        if (ist->st->codec.codec_type == ost->st->codec.codec_type) {                            ost->source_index = j;                            found = 1;                        }                    }                    if (!found) {                        fprintf(stderr, "Could not find input stream matching output stream #%d.%d\n",                                ost->file_index, ost->index);                        exit(1);                    }                }            }            ist = ist_table[ost->source_index];            ist->discard = 0;        }    }    /* dump the stream mapping */    fprintf(stderr, "Stream mapping:\n");    for(i=0;i<nb_ostreams;i++) {        ost = ost_table[i];        fprintf(stderr, "  Stream #%d.%d -> #%d.%d\n",                ist_table[ost->source_index]->file_index,                ist_table[ost->source_index]->index,                ost->file_index,                 ost->index);    }    /* for each output stream, we compute the right encoding parameters */    for(i=0;i<nb_ostreams;i++) {        ost = ost_table[i];        ist = ist_table[ost->source_index];        codec = &ost->st->codec;        icodec = &ist->st->codec;        switch(codec->codec_type) {        case CODEC_TYPE_AUDIO:            /* check if same codec with same parameters. If so, no               reencoding is needed */            if (codec->codec_id == icodec->codec_id &&                codec->bit_rate == icodec->bit_rate &&                codec->sample_rate == icodec->sample_rate &&                codec->channels == icodec->channels) {                /* no reencoding */                /* use the same frame size */                codec->frame_size = icodec->frame_size;                //codec->frame_size = 8*icodec->sample_rate*icodec->frame_size/                //                    icodec->bit_rate;                //fprintf(stderr,"\nFrame size: %d", codec->frame_size);            } else {                if (fifo_init(&ost->fifo, 2 * MAX_AUDIO_PACKET_SIZE))                    goto fail;                if (codec->channels == icodec->channels &&                    codec->sample_rate == icodec->sample_rate) {                    ost->audio_resample = 0;                } else {                    if (codec->channels != icodec->channels &&                        icodec->codec_id == CODEC_ID_AC3) {                        /* Special case for 5:1 AC3 input */                        /* and mono or stereo output      */                        ost->audio_resample = 0;                        /* Request specific number of channels */                        icodec->channels = codec->channels;                    } else {                        ost->audio_resample = 1;                         ost->resample = audio_resample_init(codec->channels, icodec->channels,                                                        codec->sample_rate,                                                         icodec->sample_rate);                    }                }                ist->decoding_needed = 1;                ost->encoding_needed = 1;            }            break;        case CODEC_TYPE_VIDEO:            /* check if same codec with same parameters. If so, no               reencoding is needed */            if (codec->codec_id == icodec->codec_id &&                codec->bit_rate == icodec->bit_rate &&                codec->frame_rate == icodec->frame_rate &&                codec->width == icodec->width &&                codec->height == icodec->height) {                /* no reencoding */            } else {                if (codec->width == icodec->width &&                    codec->height == icodec->height) {                    ost->video_resample = 0;                } else {                    UINT8 *buf;                    ost->video_resample = 1;                    buf = malloc((codec->width * codec->height * 3) / 2);                    if (!buf)                        goto fail;                    ost->pict_tmp.data[0] = buf;                    ost->pict_tmp.data[1] = ost->pict_tmp.data[0] + (codec->width * codec->height);                    ost->pict_tmp.data[2] = ost->pict_tmp.data[1] + (codec->width * codec->height) / 4;                    ost->pict_tmp.linesize[0] = codec->width;                    ost->pict_tmp.linesize[1] = codec->width / 2;                    ost->pict_tmp.linesize[2] = codec->width / 2;                    ost->img_resample_ctx = img_resample_init(                                       ost->st->codec.width, ost->st->codec.height,                                      ist->st->codec.width, ist->st->codec.height);                }                ost->encoding_needed = 1;                ist->decoding_needed = 1;            }            break;        }    }    /* open each encoder */    for(i=0;i<nb_ostreams;i++) {        ost = ost_table[i];        if (ost->encoding_needed) {            AVCodec *codec;            codec = avcodec_find_encoder(ost->st->codec.codec_id);            if (!codec) {                fprintf(stderr, "Unsupported codec for output stream #%d.%d\n",                         ost->file_index, ost->index);                exit(1);            }            if (avcodec_open(&ost->st->codec, codec) < 0) {                fprintf(stderr, "Error while opening codec for stream #%d.%d - maybe incorrect parameters such as bit_rate, rate, width or height\n",                         ost->file_index, ost->index);                exit(1);            }        }    }    /* open each decoder */    for(i=0;i<nb_istreams;i++) {        ist = ist_table[i];        if (ist->decoding_needed) {            AVCodec *codec;            codec = avcodec_find_decoder(ist->st->codec.codec_id);            if (!codec) {                fprintf(stderr, "Unsupported codec for input stream #%d.%d\n",                         ist->file_index, ist->index);                exit(1);            }            if (avcodec_open(&ist->st->codec, codec) < 0) {                fprintf(stderr, "Error while opening codec for input stream #%d.%d\n",                         ist->file_index, ist->index);                exit(1);            }        }    }    /* init pts */    for(i=0;i<nb_istreams;i++) {        ist = ist_table[i];        ist->pts = 0;        ist->frame_number = 0;    }        /* compute buffer size max (should use a complete heuristic) */    for(i=0;i<nb_input_files;i++) {        file_table[i].buffer_size_max = 2048;    }    /* open files and write file headers */    for(i=0;i<nb_output_files;i++) {        os = output_files[i];        if (os->format->write_header(os) < 0) {            fprintf(stderr, "Could not write header for output file #%d (incorrect codec paramters ?)\n", i);            ret = -EINVAL;            goto fail;        }    }#ifndef CONFIG_WIN32    if (!do_play) {        fprintf(stderr, "Press [q] to stop encoding\n");    } else {        fprintf(stderr, "Press [q] to stop playing\n");    }#endif    term_init();    start_time = gettime();    min_pts = 0;    for(;;) {        int file_index, ist_index;        AVPacket pkt;        UINT8 *ptr;        int len;        UINT8 *data_buf;        int data_size, got_picture;        AVPicture picture;        short samples[AVCODEC_MAX_AUDIO_FRAME_SIZE / 2];    redo:        /* if 'q' pressed, exits */        if (read_key() == 'q')            break;        /* select the input file with the smallest pts */        file_index = -1;        min_pts = MAXINT64;        for(i=0;i<nb_istreams;i++) {            ist = ist_table[i];            if (!ist->discard && !file_table[ist->file_index].eof_reached && ist->pts < min_pts) {                min_pts = ist->pts;                file_index = ist->file_index;            }        }        /* if none, if is finished */        if (file_index < 0)            break;        /* finish if recording time exhausted */        if (recording_time > 0 && min_pts >= recording_time)            break;        /* read a packet from it and output it in the fifo */        is = input_files[file_index];        if (av_read_packet(is, &pkt) < 0) {            file_table[file_index].eof_reached = 1;            continue;        }        ist_index = file_table[file_index].ist_index + pkt.stream_index;        ist = ist_table[ist_index];        if (ist->discard) {            continue;        }        if (do_hex_dump) {            printf("stream #%d, size=%d:\n", pkt.stream_index, pkt.size);            hex_dump(pkt.data, pkt.size);        }        //        printf("read #%d.%d size=%d\n", ist->file_index, ist->index, pkt.size);        len = pkt.size;        ptr = pkt.data;        while (len > 0) {            /* decode the packet if needed */            data_buf = NULL; /* fail safe */            data_size = 0;            if (ist->decoding_needed) {                switch(ist->st->codec.codec_type) {                case CODEC_TYPE_AUDIO:                    /* XXX: could avoid copy if PCM 16 bits with same                       endianness as CPU */                    ret = avcodec_decode_audio(&ist->st->codec, samples, &data_size,                                               ptr, len);                    if (ret < 0)                        goto fail_decode;                    if (data_size == 0) {                        /* no audio frame */                        ptr += ret;                        len -= ret;                        continue;                    }                    data_buf = (UINT8 *)samples;                    break;                case CODEC_TYPE_VIDEO:                    if (ist->st->codec.codec_id == CODEC_ID_RAWVIDEO) {                        int size;                        size = (ist->st->codec.width * ist->st->codec.height);                        avpicture_fill(&picture, ptr,                                      ist->st->codec.pix_fmt,                                     ist->st->codec.width,                                     ist->st->codec.height);                        ret = len;                    } else {                        data_size = (ist->st->codec.width * ist->st->codec.height * 3) / 2;                        ret = avcodec_decode_video(&ist->st->codec,                                                    &picture, &got_picture, ptr, len);                        if (ret < 0) {                        fail_decode:                            fprintf(stderr, "Error while decoding stream #%d.%d\n",                                    ist->file_index, ist->index);                            av_free_packet(&pkt);                            goto redo;                        }                        if (!got_picture) {                            /* no picture yet */                            ptr += ret;                            len -= ret;                            continue;                        }                    }                    break;                default:                    goto fail_decode;                }            } else {                data_buf = ptr;                data_size = len;                ret = len;            }            /* update pts */            switch(ist->st->codec.codec_type) {            case CODEC_TYPE_AUDIO:                ist->pts = (INT64)1000000 * ist->sample_index / ist->st->codec.sample_rate;                ist->sample_index += data_size / (2 * ist->st->codec.channels);                break;            case CODEC_TYPE_VIDEO:                ist->frame_number++;                ist->pts = ((INT64)ist->frame_number * 1000000 * FRAME_RATE_BASE) /                     ist->st->codec.frame_rate;                break;            }            ptr += ret;            len -= ret;            /* transcode raw format, encode packets and output them */                        for(i=0;i<nb_ostreams;i++) {                int frame_size;                ost = ost_table[i];                if (ost->source_index == ist_index) {                    os = output_files[ost->file_index];                    if (ost->encoding_needed) {                        switch(ost->st->codec.codec_type) {                        case CODEC_TYPE_AUDIO:                            do_audio_out(os, ost, ist, data_buf, data_size);                            break;                        case CODEC_TYPE_VIDEO:                            do_video_out(os, ost, ist, &picture, &frame_size);                            if (do_vstats)                                do_video_stats(ost, ist, frame_size);                            break;                        }                    } else {                        /* no reencoding needed : output the packet directly */                        /* force the input stream PTS */                        os->format->write_packet(os, ost->index, data_buf, data_size, pkt.pts);                    }                }            }        }        av_free_packet(&pkt);                /* dump report by using the first video and audio streams */        {            char buf[1024];            AVFormatContext *oc;            INT64 total_size, ti;            AVCodecContext *enc;            int frame_number, vid;            double bitrate, ti1;            static INT64 last_time;            if ((min_pts - last_time) >= 500000) {                last_time = min_pts;                                oc = output_files[0];                                total_size = url_ftell(&oc->pb);                                buf[0] = '\0';                ti = MAXINT64;                vid = 0;                for(i=0;i<nb_ostreams;i++) {                    ost = ost_table[i];                    enc = &ost->st->codec;                    ist = ist_table[ost->source_index];                    if (!vid && enc->codec_type == CODEC_TYPE_VIDEO) {                        frame_number = ist->frame_number;                        sprintf(buf + strlen(buf), "frame=%5d q=%2d ",                                frame_number, enc->quality);                        if (do_psnr)                            sprintf(buf + strlen(buf), "PSNR=%6.2f ", enc->psnr_y);                        vid = 1;                    }                    /* compute min pts value */                    if (!ist->discard && ist->pts < ti) {                        ti = ist->pts;                    }                }                ti1 = (double)ti / 1000000.0;                if (ti1 < 0.01)                    ti1 = 0.01;                bitrate = (double)(total_size * 8) / ti1 / 1000.0;                sprintf(buf + strlen(buf),                         "size=%8.0fkB time=%0.1f bitrate=%6.1fkbits/s",                        (double)total_size / 1024, ti1, bitrate);                                fprintf(stderr, "%s   \r", buf);                fflush(stderr);            }        }    }    term_exit();    /* dump report by using the first video and audio streams */    {        char buf[1024];        AVFormatContext *oc;        INT64 total_size, ti;        AVCodecContext *enc;        int frame_number, vid;        double bitrate, ti1;        oc = output_files[0];                total_size = url_ftell(&oc->pb);                buf[0] = '\0';        ti = MAXINT64;        vid = 0;        for(i=0;i<nb_ostreams;i++) {            ost = ost_table[i];            enc = &ost->st->codec;            ist = ist_table[ost->source_index];            if (!vid && enc->codec_type == CODEC_TYPE_VIDEO) {                frame_number = ist->frame_number;                sprintf(buf + strlen(buf), "frame=%5d q=%2d ",                        frame_number, enc->quality);                if (do_psnr)                    sprintf(buf + strlen(buf), "PSNR=%6.2f ", enc->psnr_y);                vid = 1;            }            /* compute min pts value */            if (!ist->discard && ist->pts < ti) {                ti = ist->pts;            }        }                ti1 = ti / 1000000.0;        if (ti1 < 0.01)            ti1 = 0.01;        bitrate = (double)(total_size * 8) / ti1 / 1000.0;                sprintf(buf + strlen(buf),                 "size=%8.0fkB time=%0.1f bitrate=%6.1fkbits/s",                (double)total_size / 1024, ti1, bitrate);                fprintf(stderr, "%s   \n", buf);    }    /* close each encoder */    for(i=0;i<nb_ostreams;i++) {        ost = ost_table[i];        if (ost->encoding_needed) {            avcodec_close(&ost->st->codec);        }    }        /* close each decoder */    for(i=0;i<nb_istreams;i++) {        ist = ist_table[i];        if (ist->decoding_needed) {            avcodec_close(&ist->st->codec);        }    }        /* write the trailer if needed and close file */    for(i=0;i<nb_output_files;i++) {        os = output_files[i];        os->format->write_trailer(os);    }    /* finished ! */        ret = 0; fail1:    free(file_table);    if (ist_table) {        for(i=0;i<nb_istreams;i++) {            ist = ist_table[i];            if (ist) {                free(ist);            }        }        free(ist_table);    }    if (ost_table) {        for(i=0;i<nb_ostreams;i++) {            ost = ost_table[i];            if (ost) {                if (ost->pict_tmp.data[0])                    free(ost->pict_tmp.data[0]);                if (ost->video_resample)                    img_resample_close(ost->img_resample_ctx);                if (ost->audio_resample)                    audio_resample_close(ost->resample);                free(ost);            }        }        free(ost_table);    }    return ret; fail:    ret = -ENOMEM;    goto fail1;}