]> git.sesse.net Git - ffmpeg/blobdiff - ffmpeg.c
Merge remote-tracking branch 'qatar/master'
[ffmpeg] / ffmpeg.c
index 5a1651edff499e98f754e2e6a5d1c3f04556feaa..54e10103d62f134a271e2e78da33039e995afc6e 100644 (file)
--- a/ffmpeg.c
+++ b/ffmpeg.c
@@ -109,14 +109,9 @@ typedef struct MetadataMap {
 
 static const OptionDef options[];
 
-#define MAX_FILES 100
 #define MAX_STREAMS 1024    /* arbitrary sanity check value */
-static const char *last_asked_format = NULL;
 static AVDictionary *ts_scale;
 
-static StreamMap *stream_maps = NULL;
-static int nb_stream_maps;
-
 static AVDictionary *codec_names;
 
 /* first item specifies output metadata, second is input */
@@ -146,6 +141,7 @@ static uint16_t *inter_matrix = NULL;
 static const char *video_rc_override_string=NULL;
 static int video_disable = 0;
 static int video_discard = 0;
+static char *video_codec_name = NULL;
 static unsigned int video_codec_tag = 0;
 static char *video_language = NULL;
 static int same_quant = 0;
@@ -166,22 +162,22 @@ static int audio_sample_rate = 0;
 static float audio_qscale = QSCALE_NONE;
 static int audio_disable = 0;
 static int audio_channels = 0;
+static char  *audio_codec_name = NULL;
 static unsigned int audio_codec_tag = 0;
 static char *audio_language = NULL;
 
 static int subtitle_disable = 0;
+static char *subtitle_codec_name = NULL;
 static char *subtitle_language = NULL;
 static unsigned int subtitle_codec_tag = 0;
 
 static int data_disable = 0;
+static char *data_codec_name = NULL;
 static unsigned int data_codec_tag = 0;
 
 static float mux_preload= 0.5;
 static float mux_max_delay= 0.7;
 
-static int64_t recording_time = INT64_MAX;
-static int64_t start_time = 0;
-static int64_t input_ts_offset = 0;
 static int file_overwrite = 0;
 static AVDictionary *metadata;
 static int do_benchmark = 0;
@@ -217,14 +213,11 @@ static int64_t extra_size = 0;
 static int nb_frames_dup = 0;
 static int nb_frames_drop = 0;
 static int input_sync;
-static uint64_t limit_filesize = 0;
 static int force_fps = 0;
 static char *forced_key_frames = NULL;
 
 static float dts_delta_threshold = 10;
 
-static int64_t timer_start;
-
 static uint8_t *audio_buf;
 static uint8_t *audio_out;
 static unsigned int allocated_audio_out_size, allocated_audio_buf_size;
@@ -235,9 +228,36 @@ static AVBitStreamFilterContext *video_bitstream_filters=NULL;
 static AVBitStreamFilterContext *audio_bitstream_filters=NULL;
 static AVBitStreamFilterContext *subtitle_bitstream_filters=NULL;
 
+static uint8_t *input_tmp= NULL;
+
 #define DEFAULT_PASS_LOGFILENAME_PREFIX "ffmpeg2pass"
 
-struct InputStream;
+typedef struct InputStream {
+    int file_index;
+    AVStream *st;
+    int discard;             /* true if stream data should be discarded */
+    int decoding_needed;     /* true if the packets must be decoded in 'raw_fifo' */
+    AVCodec *dec;
+
+    int64_t       start;     /* time when read started */
+    int64_t       next_pts;  /* synthetic pts for cases where pkt.pts
+                                is not defined */
+    int64_t       pts;       /* current pts */
+    double ts_scale;
+    int is_start;            /* is 1 at the start and after a discontinuity */
+    int showed_multi_packet_warning;
+    AVDictionary *opts;
+} InputStream;
+
+typedef struct InputFile {
+    AVFormatContext *ctx;
+    int eof_reached;      /* true if eof reached */
+    int ist_index;        /* index of first stream in ist_table */
+    int buffer_size;      /* current total buffer size */
+    int64_t ts_offset;
+    int nb_streams;       /* number of stream that avconv is aware of; may be different
+                             from ctx.nb_streams if new streams appear during av_read_frame() */
+} InputFile;
 
 typedef struct OutputStream {
     int file_index;          /* file index */
@@ -291,37 +311,9 @@ typedef struct OutputStream {
 
    int sws_flags;
    AVDictionary *opts;
+   int is_past_recording_time;
 } OutputStream;
 
-static OutputStream **output_streams_for_file[MAX_FILES] = { NULL };
-static int nb_output_streams_for_file[MAX_FILES] = { 0 };
-
-typedef struct InputStream {
-    int file_index;
-    AVStream *st;
-    int discard;             /* true if stream data should be discarded */
-    int decoding_needed;     /* true if the packets must be decoded in 'raw_fifo' */
-    AVCodec *dec;
-
-    int64_t       start;     /* time when read started */
-    int64_t       next_pts;  /* synthetic pts for cases where pkt.pts
-                                is not defined */
-    int64_t       pts;       /* current pts */
-    double ts_scale;
-    int is_start;            /* is 1 at the start and after a discontinuity */
-    int showed_multi_packet_warning;
-    int is_past_recording_time;
-    AVDictionary *opts;
-} InputStream;
-
-typedef struct InputFile {
-    AVFormatContext *ctx;
-    int eof_reached;      /* true if eof reached */
-    int ist_index;        /* index of first stream in ist_table */
-    int buffer_size;      /* current total buffer size */
-    int nb_streams;
-    int64_t ts_offset;
-} InputFile;
 
 #if HAVE_TERMIOS_H
 
@@ -332,6 +324,10 @@ static struct termios oldtty;
 typedef struct OutputFile {
     AVFormatContext *ctx;
     AVDictionary *opts;
+    int ost_index;       /* index of the first stream in output_streams */
+    int64_t recording_time; /* desired length of the resulting file in microseconds */
+    int64_t start_time;     /* start time in microseconds */
+    uint64_t limit_filesize;
 } OutputFile;
 
 static InputStream *input_streams = NULL;
@@ -339,9 +335,61 @@ static int         nb_input_streams = 0;
 static InputFile   *input_files   = NULL;
 static int         nb_input_files   = 0;
 
+static OutputStream *output_streams = NULL;
+static int        nb_output_streams = 0;
 static OutputFile   *output_files   = NULL;
 static int        nb_output_files   = 0;
 
+typedef struct OptionsContext {
+    /* input/output options */
+    int64_t start_time;
+    const char *format;
+
+    /* input options */
+    int64_t input_ts_offset;
+
+    /* output options */
+    StreamMap *stream_maps;
+    int     nb_stream_maps;
+
+    int64_t recording_time;
+    uint64_t limit_filesize;
+} OptionsContext;
+
+static void reset_options(OptionsContext *o)
+{
+    const OptionDef *po = options;
+
+    /* all OPT_SPEC and OPT_STRING can be freed in generic way */
+    while (po->name) {
+        void *dst = (uint8_t*)o + po->u.off;
+
+        if (po->flags & OPT_SPEC) {
+            SpecifierOpt **so = dst;
+            int i, *count = (int*)(so + 1);
+            for (i = 0; i < *count; i++) {
+                av_freep(&(*so)[i].specifier);
+                if (po->flags & OPT_STRING)
+                    av_freep(&(*so)[i].u.str);
+            }
+            av_freep(so);
+            *count = 0;
+        } else if (po->flags & OPT_OFFSET && po->flags & OPT_STRING)
+            av_freep(dst);
+        po++;
+    }
+
+    av_freep(&o->stream_maps);
+
+    memset(o, 0, sizeof(*o));
+
+    o->recording_time = INT64_MAX;
+    o->limit_filesize = UINT64_MAX;
+
+    uninit_opts();
+    init_opts();
+}
+
 #if CONFIG_AVFILTER
 
 static int configure_video_filters(InputStream *ist, OutputStream *ost)
@@ -420,7 +468,7 @@ static int configure_video_filters(InputStream *ist, OutputStream *ost)
     codec->width  = ost->output_video_filter->inputs[0]->w;
     codec->height = ost->output_video_filter->inputs[0]->h;
     codec->sample_aspect_ratio = ost->st->sample_aspect_ratio =
-        ost->frame_aspect_ratio ? // overriden by the -aspect cli option
+        ost->frame_aspect_ratio ? // overridden by the -aspect cli option
         av_d2q(ost->frame_aspect_ratio*codec->height/codec->width, 255) :
         ost->output_video_filter->inputs[0]->sample_aspect_ratio;
 
@@ -481,9 +529,9 @@ static void term_init(void)
 /* read a key without blocking */
 static int read_key(void)
 {
+    unsigned char ch;
 #if HAVE_TERMIOS_H
     int n = 1;
-    unsigned char ch;
     struct timeval tv;
     fd_set rfds;
 
@@ -503,6 +551,32 @@ static int read_key(void)
         return n;
     }
 #elif HAVE_KBHIT
+#    if HAVE_PEEKNAMEDPIPE
+    static int is_pipe;
+    static HANDLE input_handle;
+    DWORD dw, nchars;
+    if(!input_handle){
+        input_handle = GetStdHandle(STD_INPUT_HANDLE);
+        is_pipe = !GetConsoleMode(input_handle, &dw);
+    }
+
+    if (stdin->_cnt > 0) {
+        read(0, &ch, 1);
+        return ch;
+    }
+    if (is_pipe) {
+        /* When running under a GUI, you will end here. */
+        if (!PeekNamedPipe(input_handle, NULL, 0, NULL, &nchars, NULL))
+            return -1;
+        //Read it
+        if(nchars != 0) {
+            read(0, &ch, 1);
+            return ch;
+        }else{
+            return -1;
+        }
+    }
+#    endif
     if(kbhit())
         return(getch());
 #endif
@@ -515,7 +589,7 @@ static int decode_interrupt_cb(void)
     return q_pressed > 1;
 }
 
-static int exit_program(int ret)
+void exit_program(int ret)
 {
     int i;
 
@@ -525,7 +599,6 @@ static int exit_program(int ret)
         if (!(s->oformat->flags & AVFMT_NOFILE) && s->pb)
             avio_close(s->pb);
         avformat_free_context(s);
-        av_free(output_streams_for_file[i]);
         av_dict_free(&output_files[i].opts);
     }
     for(i=0;i<nb_input_files;i++) {
@@ -541,11 +614,11 @@ static int exit_program(int ret)
         fclose(vstats_file);
     av_free(vstats_filename);
 
-    av_free(streamid_map);
     av_free(meta_data_maps);
 
     av_freep(&input_streams);
     av_freep(&input_files);
+    av_freep(&output_streams);
     av_freep(&output_files);
 
     uninit_opts();
@@ -558,6 +631,8 @@ static int exit_program(int ret)
     avfilter_uninit();
 #endif
 
+    av_freep(&input_tmp);
+
     if (received_sigterm) {
         fprintf(stderr,
             "Received signal %d: terminating.\n",
@@ -566,7 +641,6 @@ static int exit_program(int ret)
     }
 
     exit(ret); /* not all OS-es handle main() return value */
-    return ret;
 }
 
 static void assert_avoptions(AVDictionary *m)
@@ -595,26 +669,6 @@ static void assert_codec_experimental(AVCodecContext *c, int encoder)
     }
 }
 
-/* similar to ff_dynarray_add() and av_fast_realloc() */
-static void *grow_array(void *array, int elem_size, int *size, int new_size)
-{
-    if (new_size >= INT_MAX / elem_size) {
-        fprintf(stderr, "Array too big.\n");
-        exit_program(1);
-    }
-    if (*size < new_size) {
-        uint8_t *tmp = av_realloc(array, new_size*elem_size);
-        if (!tmp) {
-            fprintf(stderr, "Could not alloc buffer.\n");
-            exit_program(1);
-        }
-        memset(tmp + *size*elem_size, 0, (new_size-*size) * elem_size);
-        *size = new_size;
-        return tmp;
-    }
-    return array;
-}
-
 static void choose_sample_fmt(AVStream *st, AVCodec *codec)
 {
     if(codec && codec->sample_fmts){
@@ -688,7 +742,8 @@ static double
 get_sync_ipts(const OutputStream *ost)
 {
     const InputStream *ist = ost->sync_ist;
-    return (double)(ist->pts - start_time)/AV_TIME_BASE;
+    OutputFile *of = &output_files[ost->file_index];
+    return (double)(ist->pts - of->start_time)/AV_TIME_BASE;
 }
 
 static void write_frame(AVFormatContext *s, AVPacket *pkt, AVCodecContext *avctx, AVBitStreamFilterContext *bsfc){
@@ -723,8 +778,6 @@ static void write_frame(AVFormatContext *s, AVPacket *pkt, AVCodecContext *avctx
     }
 }
 
-#define MAX_AUDIO_PACKET_SIZE (128 * 1024)
-
 static void do_audio_out(AVFormatContext *s,
                          OutputStream *ost,
                          InputStream *ist,
@@ -842,7 +895,6 @@ need_realloc:
                         return;
                     ist->is_start=0;
                 }else{
-                    static uint8_t *input_tmp= NULL;
                     input_tmp= av_realloc(input_tmp, byte_delta + size);
 
                     if(byte_delta > allocated_for_size - size){
@@ -1008,9 +1060,6 @@ static void pre_process_video_frame(InputStream *ist, AVPicture *picture, void *
     *bufp = buf;
 }
 
-/* we begin to correct av delay at this threshold */
-#define AV_DELAY_MAX 0.100
-
 static void do_subtitle_out(AVFormatContext *s,
                             OutputStream *ost,
                             InputStream *ist,
@@ -1082,14 +1131,16 @@ static void do_video_resample(OutputStream *ost,
                               AVFrame *in_picture,
                               AVFrame **out_picture)
 {
-    int resample_changed = 0;
-    AVCodecContext *dec = ist->st->codec;
+#if CONFIG_AVFILTER
     *out_picture = in_picture;
-#if !CONFIG_AVFILTER
-    resample_changed = ost->resample_width   != dec->width  ||
-                       ost->resample_height  != dec->height ||
-                       ost->resample_pix_fmt != dec->pix_fmt;
+#else
+    AVCodecContext *dec = ist->st->codec;
+    AVCodecContext *enc = ost->st->codec;
+    int resample_changed = ost->resample_width   != dec->width  ||
+                           ost->resample_height  != dec->height ||
+                           ost->resample_pix_fmt != dec->pix_fmt;
 
+    *out_picture = in_picture;
     if (resample_changed) {
         av_log(NULL, AV_LOG_INFO,
                "Input stream #%d.%d frame changed from size:%dx%d fmt:%s to size:%dx%d fmt:%s\n",
@@ -1142,11 +1193,10 @@ static void do_video_out(AVFormatContext *s,
 {
     int nb_frames, i, ret, format_video_sync;
     AVFrame *final_picture;
-    AVCodecContext *enc, *dec;
+    AVCodecContext *enc;
     double sync_ipts;
 
     enc = ost->st->codec;
-    dec = ist->st->codec;
 
     sync_ipts = get_sync_ipts(ost) / av_q2d(enc->time_base);
 
@@ -1198,17 +1248,16 @@ static void do_video_out(AVFormatContext *s,
 
         if (s->oformat->flags & AVFMT_RAWPICTURE) {
             /* raw pictures are written as AVPicture structure to
-               avoid any copies. We support temorarily the older
+               avoid any copies. We support temporarily the older
                method. */
-            AVFrame* old_frame = enc->coded_frame;
-            enc->coded_frame = dec->coded_frame; //FIXME/XXX remove this hack
+            enc->coded_frame->interlaced_frame = in_picture->interlaced_frame;
+            enc->coded_frame->top_field_first  = in_picture->top_field_first;
             pkt.data= (uint8_t *)final_picture;
             pkt.size=  sizeof(AVPicture);
             pkt.pts= av_rescale_q(ost->sync_opts, enc->time_base, ost->st->time_base);
             pkt.flags |= AV_PKT_FLAG_KEY;
 
             write_frame(s, &pkt, ost->st->codec, ost->bitstream_filters);
-            enc->coded_frame = old_frame;
         } else {
             AVFrame big_picture;
 
@@ -1314,8 +1363,8 @@ static void do_video_stats(AVFormatContext *os, OutputStream *ost,
 }
 
 static void print_report(OutputFile *output_files,
-                         OutputStream **ost_table, int nb_ostreams,
-                         int is_last_report)
+                         OutputStream *ost_table, int nb_ostreams,
+                         int is_last_report, int64_t timer_start)
 {
     char buf[1024];
     OutputStream *ost;
@@ -1352,7 +1401,7 @@ static void print_report(OutputFile *output_files,
     vid = 0;
     for(i=0;i<nb_ostreams;i++) {
         float q = -1;
-        ost = ost_table[i];
+        ost = &ost_table[i];
         enc = ost->st->codec;
         if (!ost->st->stream_copy && enc->coded_frame)
             q = enc->coded_frame->quality/(float)FF_QP2LAMBDA;
@@ -1452,9 +1501,94 @@ static void generate_silence(uint8_t* buf, enum AVSampleFormat sample_fmt, size_
     memset(buf, fill_char, size);
 }
 
+static void flush_encoders(OutputStream *ost_table, int nb_ostreams)
+{
+    int i, ret;
+
+    for (i = 0; i < nb_ostreams; i++) {
+        OutputStream   *ost = &ost_table[i];
+        AVCodecContext *enc = ost->st->codec;
+        AVFormatContext *os = output_files[ost->file_index].ctx;
+
+        if (!ost->encoding_needed)
+            continue;
+
+        if (ost->st->codec->codec_type == AVMEDIA_TYPE_AUDIO && enc->frame_size <=1)
+            continue;
+        if (ost->st->codec->codec_type == AVMEDIA_TYPE_VIDEO && (os->oformat->flags & AVFMT_RAWPICTURE))
+            continue;
+
+        for(;;) {
+            AVPacket pkt;
+            int fifo_bytes;
+            av_init_packet(&pkt);
+            pkt.stream_index= ost->index;
+
+            switch (ost->st->codec->codec_type) {
+            case AVMEDIA_TYPE_AUDIO:
+                fifo_bytes = av_fifo_size(ost->fifo);
+                ret = 0;
+                /* encode any samples remaining in fifo */
+                if (fifo_bytes > 0) {
+                    int osize = av_get_bytes_per_sample(enc->sample_fmt);
+                    int fs_tmp = enc->frame_size;
+
+                    av_fifo_generic_read(ost->fifo, audio_buf, fifo_bytes, NULL);
+                    if (enc->codec->capabilities & CODEC_CAP_SMALL_LAST_FRAME) {
+                        enc->frame_size = fifo_bytes / (osize * enc->channels);
+                    } else { /* pad */
+                        int frame_bytes = enc->frame_size*osize*enc->channels;
+                        if (allocated_audio_buf_size < frame_bytes)
+                            exit_program(1);
+                        generate_silence(audio_buf+fifo_bytes, enc->sample_fmt, frame_bytes - fifo_bytes);
+                    }
+
+                    ret = avcodec_encode_audio(enc, bit_buffer, bit_buffer_size, (short *)audio_buf);
+                    pkt.duration = av_rescale((int64_t)enc->frame_size*ost->st->time_base.den,
+                                              ost->st->time_base.num, enc->sample_rate);
+                    enc->frame_size = fs_tmp;
+                }
+                if (ret <= 0) {
+                    ret = avcodec_encode_audio(enc, bit_buffer, bit_buffer_size, NULL);
+                }
+                if (ret < 0) {
+                    fprintf(stderr, "Audio encoding failed\n");
+                    exit_program(1);
+                }
+                audio_size += ret;
+                pkt.flags |= AV_PKT_FLAG_KEY;
+                break;
+            case AVMEDIA_TYPE_VIDEO:
+                ret = avcodec_encode_video(enc, bit_buffer, bit_buffer_size, NULL);
+                if (ret < 0) {
+                    fprintf(stderr, "Video encoding failed\n");
+                    exit_program(1);
+                }
+                video_size += ret;
+                if(enc->coded_frame && enc->coded_frame->key_frame)
+                    pkt.flags |= AV_PKT_FLAG_KEY;
+                if (ost->logfile && enc->stats_out) {
+                    fprintf(ost->logfile, "%s", enc->stats_out);
+                }
+                break;
+            default:
+                ret=-1;
+            }
+
+            if (ret <= 0)
+                break;
+            pkt.data = bit_buffer;
+            pkt.size = ret;
+            if (enc->coded_frame && enc->coded_frame->pts != AV_NOPTS_VALUE)
+                pkt.pts= av_rescale_q(enc->coded_frame->pts, enc->time_base, ost->st->time_base);
+            write_frame(os, &pkt, ost->st->codec, ost->bitstream_filters);
+        }
+    }
+}
+
 /* pkt = NULL means EOF (needed to flush decoder buffers) */
 static int output_packet(InputStream *ist, int ist_index,
-                         OutputStream **ost_table, int nb_ostreams,
+                         OutputStream *ost_table, int nb_ostreams,
                          const AVPacket *pkt)
 {
     AVFormatContext *os;
@@ -1597,15 +1731,15 @@ static int output_packet(InputStream *ist, int ist_index,
                 }
                 break;
             }
-            ret = avpkt.size;
             avpkt.size = 0;
         }
 
 #if CONFIG_AVFILTER
         if(ist->st->codec->codec_type == AVMEDIA_TYPE_VIDEO)
-        if (start_time == 0 || ist->pts >= start_time) {
-            for(i=0;i<nb_ostreams;i++) {
-                ost = ost_table[i];
+        for(i=0;i<nb_ostreams;i++) {
+            OutputFile *of = &output_files[ost_table[i].file_index];
+            if (of->start_time == 0 || ist->pts >= of->start_time) {
+                ost = &ost_table[i];
                 if (ost->input_video_filter && ost->source_index == ist_index) {
                     if (!picture.sample_aspect_ratio.num)
                         picture.sample_aspect_ratio = ist->st->sample_aspect_ratio;
@@ -1624,9 +1758,7 @@ static int output_packet(InputStream *ist, int ist_index,
                 volp = samples;
                 for(i=0;i<(decoded_data_size / sizeof(short));i++) {
                     int v = ((*volp) * audio_volume + 128) >> 8;
-                    if (v < -32768) v = -32768;
-                    if (v >  32767) v = 32767;
-                    *volp++ = v;
+                    *volp++ = av_clip_int16(v);
                 }
             }
         }
@@ -1640,139 +1772,141 @@ static int output_packet(InputStream *ist, int ist_index,
         }
         /* if output time reached then transcode raw format,
            encode packets and output them */
-        if (start_time == 0 || ist->pts >= start_time)
-            for(i=0;i<nb_ostreams;i++) {
-                int frame_size;
+        for (i = 0; i < nb_ostreams; i++) {
+            OutputFile *of = &output_files[ost_table[i].file_index];
+            int frame_size;
 
-                ost = ost_table[i];
+            ost = &ost_table[i];
+            if (ost->source_index != ist_index)
+                continue;
+
+            if (of->start_time && ist->pts < of->start_time)
+                continue;
+
+            if (of->recording_time != INT64_MAX &&
+                av_compare_ts(ist->pts, AV_TIME_BASE_Q, of->recording_time + of->start_time,
+                              (AVRational){1, 1000000}) >= 0) {
+                ost->is_past_recording_time = 1;
+                continue;
+            }
 
-                /* finish if recording time exhausted */
-                if (recording_time != INT64_MAX &&
-                        av_compare_ts(ist->pts, AV_TIME_BASE_Q, recording_time + start_time, (AVRational){1, 1000000})
-                    >= 0) {
-                    ist->is_past_recording_time = 1;
-                    continue;
-                }
-                if (ost->source_index == ist_index) {
 #if CONFIG_AVFILTER
-                frame_available = ist->st->codec->codec_type != AVMEDIA_TYPE_VIDEO ||
-                    !ost->output_video_filter || avfilter_poll_frame(ost->output_video_filter->inputs[0]);
-                while (frame_available) {
-                    if (ist->st->codec->codec_type == AVMEDIA_TYPE_VIDEO && ost->output_video_filter) {
-                        AVRational ist_pts_tb = ost->output_video_filter->inputs[0]->time_base;
-                        if (av_vsink_buffer_get_video_buffer_ref(ost->output_video_filter, &ost->picref, 0) < 0)
-                            goto cont;
-                        if (ost->picref) {
-                            avfilter_fill_frame_from_video_buffer_ref(&picture, ost->picref);
-                            ist->pts = av_rescale_q(ost->picref->pts, ist_pts_tb, AV_TIME_BASE_Q);
-                        }
+            frame_available = ist->st->codec->codec_type != AVMEDIA_TYPE_VIDEO ||
+                !ost->output_video_filter || avfilter_poll_frame(ost->output_video_filter->inputs[0]);
+            while (frame_available) {
+                if (ist->st->codec->codec_type == AVMEDIA_TYPE_VIDEO && ost->output_video_filter) {
+                    AVRational ist_pts_tb = ost->output_video_filter->inputs[0]->time_base;
+                    if (av_vsink_buffer_get_video_buffer_ref(ost->output_video_filter, &ost->picref, 0) < 0)
+                        goto cont;
+                    if (ost->picref) {
+                        avfilter_fill_frame_from_video_buffer_ref(&picture, ost->picref);
+                        ist->pts = av_rescale_q(ost->picref->pts, ist_pts_tb, AV_TIME_BASE_Q);
                     }
+                }
 #endif
-                    os = output_files[ost->file_index].ctx;
+                os = output_files[ost->file_index].ctx;
 
-                    /* set the input output pts pairs */
-                    //ost->sync_ipts = (double)(ist->pts + input_files[ist->file_index].ts_offset - start_time)/ AV_TIME_BASE;
+                /* set the input output pts pairs */
+                //ost->sync_ipts = (double)(ist->pts + input_files[ist->file_index].ts_offset - start_time)/ AV_TIME_BASE;
 
-                    if (ost->encoding_needed) {
-                        av_assert0(ist->decoding_needed);
-                        switch(ost->st->codec->codec_type) {
-                        case AVMEDIA_TYPE_AUDIO:
-                            do_audio_out(os, ost, ist, decoded_data_buf, decoded_data_size);
-                            break;
-                        case AVMEDIA_TYPE_VIDEO:
+                if (ost->encoding_needed) {
+                    av_assert0(ist->decoding_needed);
+                    switch(ost->st->codec->codec_type) {
+                    case AVMEDIA_TYPE_AUDIO:
+                        do_audio_out(os, ost, ist, decoded_data_buf, decoded_data_size);
+                        break;
+                    case AVMEDIA_TYPE_VIDEO:
 #if CONFIG_AVFILTER
-                            if (ost->picref->video && !ost->frame_aspect_ratio)
-                                ost->st->codec->sample_aspect_ratio = ost->picref->video->sample_aspect_ratio;
+                        if (ost->picref->video && !ost->frame_aspect_ratio)
+                            ost->st->codec->sample_aspect_ratio = ost->picref->video->sample_aspect_ratio;
 #endif
-                            do_video_out(os, ost, ist, &picture, &frame_size,
-                                         same_quant ? quality : ost->st->codec->global_quality);
-                            if (vstats_filename && frame_size)
-                                do_video_stats(os, ost, frame_size);
-                            break;
-                        case AVMEDIA_TYPE_SUBTITLE:
-                            do_subtitle_out(os, ost, ist, &subtitle,
-                                            pkt->pts);
-                            break;
-                        default:
-                            abort();
-                        }
-                    } else {
-                        AVFrame avframe; //FIXME/XXX remove this
-                        AVPicture pict;
-                        AVPacket opkt;
-                        int64_t ost_tb_start_time= av_rescale_q(start_time, AV_TIME_BASE_Q, ost->st->time_base);
-
-                        av_init_packet(&opkt);
+                        do_video_out(os, ost, ist, &picture, &frame_size,
+                                        same_quant ? quality : ost->st->codec->global_quality);
+                        if (vstats_filename && frame_size)
+                            do_video_stats(os, ost, frame_size);
+                        break;
+                    case AVMEDIA_TYPE_SUBTITLE:
+                        do_subtitle_out(os, ost, ist, &subtitle,
+                                        pkt->pts);
+                        break;
+                    default:
+                        abort();
+                    }
+                } else {
+                    AVFrame avframe; //FIXME/XXX remove this
+                    AVPicture pict;
+                    AVPacket opkt;
+                    int64_t ost_tb_start_time= av_rescale_q(of->start_time, AV_TIME_BASE_Q, ost->st->time_base);
+                    av_init_packet(&opkt);
 
-                        if ((!ost->frame_number && !(pkt->flags & AV_PKT_FLAG_KEY)) && !copy_initial_nonkeyframes)
+                    if ((!ost->frame_number && !(pkt->flags & AV_PKT_FLAG_KEY)) && !copy_initial_nonkeyframes)
 #if !CONFIG_AVFILTER
-                            continue;
+                        continue;
 #else
-                            goto cont;
+                        goto cont;
 #endif
 
-                        /* no reencoding needed : output the packet directly */
-                        /* force the input stream PTS */
+                    /* no reencoding needed : output the packet directly */
+                    /* force the input stream PTS */
 
-                        avcodec_get_frame_defaults(&avframe);
-                        ost->st->codec->coded_frame= &avframe;
-                        avframe.key_frame = pkt->flags & AV_PKT_FLAG_KEY;
+                    avcodec_get_frame_defaults(&avframe);
+                    ost->st->codec->coded_frame= &avframe;
+                    avframe.key_frame = pkt->flags & AV_PKT_FLAG_KEY;
 
-                        if(ost->st->codec->codec_type == AVMEDIA_TYPE_AUDIO)
-                            audio_size += data_size;
-                        else if (ost->st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
-                            video_size += data_size;
-                            ost->sync_opts++;
-                        }
+                    if(ost->st->codec->codec_type == AVMEDIA_TYPE_AUDIO)
+                        audio_size += data_size;
+                    else if (ost->st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
+                        video_size += data_size;
+                        ost->sync_opts++;
+                    }
 
-                        opkt.stream_index= ost->index;
-                        if(pkt->pts != AV_NOPTS_VALUE)
-                            opkt.pts= av_rescale_q(pkt->pts, ist->st->time_base, ost->st->time_base) - ost_tb_start_time;
-                        else
-                            opkt.pts= AV_NOPTS_VALUE;
-
-                        if (pkt->dts == AV_NOPTS_VALUE)
-                            opkt.dts = av_rescale_q(ist->pts, AV_TIME_BASE_Q, ost->st->time_base);
-                        else
-                            opkt.dts = av_rescale_q(pkt->dts, ist->st->time_base, ost->st->time_base);
-                        opkt.dts -= ost_tb_start_time;
-
-                        opkt.duration = av_rescale_q(pkt->duration, ist->st->time_base, ost->st->time_base);
-                        opkt.flags= pkt->flags;
-
-                        //FIXME remove the following 2 lines they shall be replaced by the bitstream filters
-                        if(   ost->st->codec->codec_id != CODEC_ID_H264
-                           && ost->st->codec->codec_id != CODEC_ID_MPEG1VIDEO
-                           && ost->st->codec->codec_id != CODEC_ID_MPEG2VIDEO
-                           ) {
-                            if(av_parser_change(ist->st->parser, ost->st->codec, &opkt.data, &opkt.size, data_buf, data_size, pkt->flags & AV_PKT_FLAG_KEY))
-                                opkt.destruct= av_destruct_packet;
-                        } else {
-                            opkt.data = data_buf;
-                            opkt.size = data_size;
-                        }
+                    opkt.stream_index= ost->index;
+                    if(pkt->pts != AV_NOPTS_VALUE)
+                        opkt.pts= av_rescale_q(pkt->pts, ist->st->time_base, ost->st->time_base) - ost_tb_start_time;
+                    else
+                        opkt.pts= AV_NOPTS_VALUE;
+
+                    if (pkt->dts == AV_NOPTS_VALUE)
+                        opkt.dts = av_rescale_q(ist->pts, AV_TIME_BASE_Q, ost->st->time_base);
+                    else
+                        opkt.dts = av_rescale_q(pkt->dts, ist->st->time_base, ost->st->time_base);
+                    opkt.dts -= ost_tb_start_time;
+
+                    opkt.duration = av_rescale_q(pkt->duration, ist->st->time_base, ost->st->time_base);
+                    opkt.flags= pkt->flags;
+
+                    //FIXME remove the following 2 lines they shall be replaced by the bitstream filters
+                    if(   ost->st->codec->codec_id != CODEC_ID_H264
+                       && ost->st->codec->codec_id != CODEC_ID_MPEG1VIDEO
+                       && ost->st->codec->codec_id != CODEC_ID_MPEG2VIDEO
+                       ) {
+                        if(av_parser_change(ist->st->parser, ost->st->codec, &opkt.data, &opkt.size, data_buf, data_size, pkt->flags & AV_PKT_FLAG_KEY))
+                            opkt.destruct= av_destruct_packet;
+                    } else {
+                        opkt.data = data_buf;
+                        opkt.size = data_size;
+                    }
 
-                        if (os->oformat->flags & AVFMT_RAWPICTURE) {
-                            /* store AVPicture in AVPacket, as expected by the output format */
-                            avpicture_fill(&pict, opkt.data, ost->st->codec->pix_fmt, ost->st->codec->width, ost->st->codec->height);
-                            opkt.data = (uint8_t *)&pict;
-                            opkt.size = sizeof(AVPicture);
-                            opkt.flags |= AV_PKT_FLAG_KEY;
-                        }
-                        write_frame(os, &opkt, ost->st->codec, ost->bitstream_filters);
-                        ost->st->codec->frame_number++;
-                        ost->frame_number++;
-                        av_free_packet(&opkt);
+                    if (os->oformat->flags & AVFMT_RAWPICTURE) {
+                        /* store AVPicture in AVPacket, as expected by the output format */
+                        avpicture_fill(&pict, opkt.data, ost->st->codec->pix_fmt, ost->st->codec->width, ost->st->codec->height);
+                        opkt.data = (uint8_t *)&pict;
+                        opkt.size = sizeof(AVPicture);
+                        opkt.flags |= AV_PKT_FLAG_KEY;
                     }
-#if CONFIG_AVFILTER
-                    cont:
-                    frame_available = (ist->st->codec->codec_type == AVMEDIA_TYPE_VIDEO) &&
-                                       ost->output_video_filter && avfilter_poll_frame(ost->output_video_filter->inputs[0]);
-                    avfilter_unref_buffer(ost->picref);
-                }
-#endif
+                    write_frame(os, &opkt, ost->st->codec, ost->bitstream_filters);
+                    ost->st->codec->frame_number++;
+                    ost->frame_number++;
+                    av_free_packet(&opkt);
                 }
+#if CONFIG_AVFILTER
+                cont:
+                frame_available = (ist->st->codec->codec_type == AVMEDIA_TYPE_VIDEO) &&
+                                   ost->output_video_filter && avfilter_poll_frame(ost->output_video_filter->inputs[0]);
+                avfilter_unref_buffer(ost->picref);
             }
+#endif
+        }
 
         av_free(buffer_to_free);
         /* XXX: allocate the subtitles in the codec ? */
@@ -1782,90 +1916,6 @@ static int output_packet(InputStream *ist, int ist_index,
         }
     }
  discard_packet:
-    if (pkt == NULL) {
-        /* EOF handling */
-
-        for(i=0;i<nb_ostreams;i++) {
-            ost = ost_table[i];
-            if (ost->source_index == ist_index) {
-                AVCodecContext *enc= ost->st->codec;
-                os = output_files[ost->file_index].ctx;
-
-                if(ost->st->codec->codec_type == AVMEDIA_TYPE_AUDIO && enc->frame_size <=1)
-                    continue;
-                if(ost->st->codec->codec_type == AVMEDIA_TYPE_VIDEO && (os->oformat->flags & AVFMT_RAWPICTURE))
-                    continue;
-
-                if (ost->encoding_needed) {
-                    for(;;) {
-                        AVPacket pkt;
-                        int fifo_bytes;
-                        av_init_packet(&pkt);
-                        pkt.stream_index= ost->index;
-
-                        switch(ost->st->codec->codec_type) {
-                        case AVMEDIA_TYPE_AUDIO:
-                            fifo_bytes = av_fifo_size(ost->fifo);
-                            ret = 0;
-                            /* encode any samples remaining in fifo */
-                            if (fifo_bytes > 0) {
-                                int osize = av_get_bytes_per_sample(enc->sample_fmt);
-                                int fs_tmp = enc->frame_size;
-
-                                av_fifo_generic_read(ost->fifo, audio_buf, fifo_bytes, NULL);
-                                if (enc->codec->capabilities & CODEC_CAP_SMALL_LAST_FRAME) {
-                                    enc->frame_size = fifo_bytes / (osize * enc->channels);
-                                } else { /* pad */
-                                    int frame_bytes = enc->frame_size*osize*enc->channels;
-                                    if (allocated_audio_buf_size < frame_bytes)
-                                        exit_program(1);
-                                    generate_silence(audio_buf+fifo_bytes, enc->sample_fmt, frame_bytes - fifo_bytes);
-                                }
-
-                                ret = avcodec_encode_audio(enc, bit_buffer, bit_buffer_size, (short *)audio_buf);
-                                pkt.duration = av_rescale((int64_t)enc->frame_size*ost->st->time_base.den,
-                                                          ost->st->time_base.num, enc->sample_rate);
-                                enc->frame_size = fs_tmp;
-                            }
-                            if(ret <= 0) {
-                                ret = avcodec_encode_audio(enc, bit_buffer, bit_buffer_size, NULL);
-                            }
-                            if (ret < 0) {
-                                fprintf(stderr, "Audio encoding failed\n");
-                                exit_program(1);
-                            }
-                            audio_size += ret;
-                            pkt.flags |= AV_PKT_FLAG_KEY;
-                            break;
-                        case AVMEDIA_TYPE_VIDEO:
-                            ret = avcodec_encode_video(enc, bit_buffer, bit_buffer_size, NULL);
-                            if (ret < 0) {
-                                fprintf(stderr, "Video encoding failed\n");
-                                exit_program(1);
-                            }
-                            video_size += ret;
-                            if(enc->coded_frame && enc->coded_frame->key_frame)
-                                pkt.flags |= AV_PKT_FLAG_KEY;
-                            if (ost->logfile && enc->stats_out) {
-                                fprintf(ost->logfile, "%s", enc->stats_out);
-                            }
-                            break;
-                        default:
-                            ret=-1;
-                        }
-
-                        if(ret<=0)
-                            break;
-                        pkt.data= bit_buffer;
-                        pkt.size= ret;
-                        if(enc->coded_frame && enc->coded_frame->pts != AV_NOPTS_VALUE)
-                            pkt.pts= av_rescale_q(enc->coded_frame->pts, enc->time_base, ost->st->time_base);
-                        write_frame(os, &pkt, ost->st->codec, ost->bitstream_filters);
-                    }
-                }
-            }
-        }
-    }
 
     return 0;
 }
@@ -1887,95 +1937,63 @@ static void print_sdp(OutputFile *output_files, int n)
     av_freep(&avc);
 }
 
-/*
- * The following code is the main loop of the file converter
- */
-static int transcode(OutputFile *output_files,
-                     int nb_output_files,
-                     InputFile *input_files,
-                     int nb_input_files)
+static int init_input_stream(int ist_index, OutputStream *output_streams, int nb_output_streams,
+                             char *error, int error_len)
 {
-    int ret = 0, i, j, k, n, nb_ostreams = 0, step;
+    InputStream *ist = &input_streams[ist_index];
+    if (ist->decoding_needed) {
+        AVCodec *codec = ist->dec;
+        if (!codec) {
+            snprintf(error, error_len, "Decoder (codec %s) not found for input stream #%d.%d",
+                    avcodec_get_name(ist->st->codec->codec_id), ist->file_index, ist->st->index);
+            return AVERROR(EINVAL);
+        }
+        if (avcodec_open2(ist->st->codec, codec, &ist->opts) < 0) {
+            snprintf(error, error_len, "Error while opening decoder for input stream #%d.%d",
+                    ist->file_index, ist->st->index);
+            return AVERROR(EINVAL);
+        }
+        assert_codec_experimental(ist->st->codec, 0);
+        assert_avoptions(ist->opts);
+    }
 
-    AVFormatContext *is, *os;
+    ist->pts = ist->st->avg_frame_rate.num ? - ist->st->codec->has_b_frames*AV_TIME_BASE / av_q2d(ist->st->avg_frame_rate) : 0;
+    ist->next_pts = AV_NOPTS_VALUE;
+    ist->is_start = 1;
+
+    return 0;
+}
+
+static int transcode_init(OutputFile *output_files,
+                          int nb_output_files,
+                          InputFile *input_files,
+                          int nb_input_files)
+{
+    int ret = 0, i;
+    AVFormatContext *os;
     AVCodecContext *codec, *icodec;
-    OutputStream *ost, **ost_table = NULL;
+    OutputStream *ost;
     InputStream *ist;
     char error[1024];
-    int key;
     int want_sdp = 1;
-    uint8_t no_packet[MAX_FILES]={0};
-    int no_packet_count=0;
-    int nb_frame_threshold[AVMEDIA_TYPE_NB]={0};
-    int nb_streams[AVMEDIA_TYPE_NB]={0};
 
     if (rate_emu)
         for (i = 0; i < nb_input_streams; i++)
             input_streams[i].start = av_gettime();
 
     /* output stream init */
-    nb_ostreams = 0;
     for(i=0;i<nb_output_files;i++) {
         os = output_files[i].ctx;
         if (!os->nb_streams && !(os->oformat->flags & AVFMT_NOSTREAMS)) {
             av_dump_format(os, i, os->filename, 1);
             fprintf(stderr, "Output file #%d does not contain any stream\n", i);
-            ret = AVERROR(EINVAL);
-            goto fail;
-        }
-        nb_ostreams += os->nb_streams;
-    }
-
-    ost_table = av_mallocz(sizeof(OutputStream *) * nb_ostreams);
-    if (!ost_table)
-        goto fail;
-
-    for(k=0;k<nb_output_files;k++) {
-        os = output_files[k].ctx;
-        for(i=0;i<os->nb_streams;i++,n++) {
-            nb_streams[os->streams[i]->codec->codec_type]++;
-        }
-    }
-    for(step=1<<30; step; step>>=1){
-        int found_streams[AVMEDIA_TYPE_NB]={0};
-        for(j=0; j<AVMEDIA_TYPE_NB; j++)
-            nb_frame_threshold[j] += step;
-
-        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
-                && nb_frame_threshold[ist->st->codec->codec_type] <= ist->st->codec_info_nb_frames){
-                found_streams[ist->st->codec->codec_type]++;
-            }
+            return AVERROR(EINVAL);
         }
-        for(j=0; j<AVMEDIA_TYPE_NB; j++)
-            if(found_streams[j] < nb_streams[j])
-                nb_frame_threshold[j] -= step;
-    }
-    n = 0;
-    for(k=0;k<nb_output_files;k++) {
-        os = output_files[k].ctx;
-        for (i = 0; i < os->nb_streams; i++, n++)
-            ost_table[n] = output_streams_for_file[k][i];
     }
 
     /* for each output stream, we compute the right encoding parameters */
-    for(i=0;i<nb_ostreams;i++) {
-        ost = ost_table[i];
+    for (i = 0; i < nb_output_streams; i++) {
+        ost = &output_streams[i];
         os = output_files[ost->file_index].ctx;
         ist = &input_streams[ost->source_index];
 
@@ -1989,8 +2007,9 @@ static int transcode(OutputFile *output_files,
         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;
+            if (extra_size > INT_MAX) {
+                return AVERROR(EINVAL);
+            }
 
             /* if stream_copy is selected, no need to decode or encode */
             codec->codec_id = icodec->codec_id;
@@ -2007,8 +2026,9 @@ static int transcode(OutputFile *output_files,
             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;
+            if (!codec->extradata) {
+                return AVERROR(ENOMEM);
+            }
             memcpy(codec->extradata, icodec->extradata, icodec->extradata_size);
             codec->extradata_size= icodec->extradata_size;
 
@@ -2073,8 +2093,9 @@ static int transcode(OutputFile *output_files,
             switch(codec->codec_type) {
             case AVMEDIA_TYPE_AUDIO:
                 ost->fifo= av_fifo_alloc(1024);
-                if(!ost->fifo)
-                    goto fail;
+                if (!ost->fifo) {
+                    return AVERROR(ENOMEM);
+                }
                 ost->reformat_pair = MAKE_SFMT_PAIR(AV_SAMPLE_FMT_NONE,AV_SAMPLE_FMT_NONE);
                 if (!codec->sample_rate) {
                     codec->sample_rate = icodec->sample_rate;
@@ -2193,13 +2214,12 @@ static int transcode(OutputFile *output_files,
     if (!bit_buffer) {
         fprintf(stderr, "Cannot allocate %d bytes output buffer\n",
                 bit_buffer_size);
-        ret = AVERROR(ENOMEM);
-        goto fail;
+        return AVERROR(ENOMEM);
     }
 
     /* open each encoder */
-    for(i=0;i<nb_ostreams;i++) {
-        ost = ost_table[i];
+    for (i = 0; i < nb_output_streams; i++) {
+        ost = &output_streams[i];
         if (ost->encoding_needed) {
             AVCodec *codec = ost->enc;
             AVCodecContext *dec = input_streams[ost->source_index].st->codec;
@@ -2233,39 +2253,10 @@ static int transcode(OutputFile *output_files,
         }
     }
 
-    /* open each decoder */
-    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 %s) not found for input stream #%d.%d",
-                        avcodec_get_name(ist->st->codec->codec_id), ist->file_index, ist->st->index);
-                ret = AVERROR(EINVAL);
-                goto dump_format;
-            }
-            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);
-        }
-    }
-
-    /* init pts */
-    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;
-        ist->is_start = 1;
-    }
+    /* init input streams */
+    for (i = 0; i < nb_input_streams; i++)
+        if ((ret = init_input_stream(i, output_streams, nb_output_streams, error, sizeof(error))) < 0)
+            goto dump_format;
 
     /* open files and write file headers */
     for (i = 0; i < nb_output_files; i++) {
@@ -2291,8 +2282,8 @@ static int transcode(OutputFile *output_files,
     /* dump the stream mapping */
     if (verbose >= 0) {
         fprintf(stderr, "Stream mapping:\n");
-        for(i=0;i<nb_ostreams;i++) {
-            ost = ost_table[i];
+        for (i = 0; i < nb_output_streams;i ++) {
+            ost = &output_streams[i];
             fprintf(stderr, "  Stream #%d.%d -> #%d.%d",
                     input_streams[ost->source_index].file_index,
                     input_streams[ost->source_index].st->index,
@@ -2302,26 +2293,52 @@ static int transcode(OutputFile *output_files,
                 fprintf(stderr, " [sync #%d.%d]",
                         ost->sync_ist->file_index,
                         ost->sync_ist->st->index);
-            if(ost->encoding_needed)
-                fprintf(stderr, ": %s -> %s",
-                    input_streams[ost->source_index].dec ?
-                        input_streams[ost->source_index].dec->name : "?",
-                    ost->enc ? ost->enc->name : "?");
+            if (ost->st->stream_copy)
+                fprintf(stderr, " (copy)");
             else
-                fprintf(stderr, ": copy");
+                fprintf(stderr, " (%s -> %s)", input_streams[ost->source_index].dec ?
+                        input_streams[ost->source_index].dec->name : "?",
+                        ost->enc ? ost->enc->name : "?");
             fprintf(stderr, "\n");
         }
     }
 
     if (ret) {
         fprintf(stderr, "%s\n", error);
-        goto fail;
+        return ret;
     }
 
     if (want_sdp) {
         print_sdp(output_files, nb_output_files);
     }
 
+    return 0;
+}
+
+/*
+ * The following code is the main loop of the file converter
+ */
+static int transcode(OutputFile *output_files,
+                     int nb_output_files,
+                     InputFile *input_files,
+                     int nb_input_files)
+{
+    int ret, i;
+    AVFormatContext *is, *os;
+    OutputStream *ost;
+    InputStream *ist;
+    uint8_t *no_packet;
+    int no_packet_count=0;
+    int64_t timer_start;
+    int key;
+
+    if (!(no_packet = av_mallocz(nb_input_files)))
+        exit_program(1);
+
+    ret = transcode_init(output_files, nb_output_files, input_files, nb_input_files);
+    if (ret < 0)
+        goto fail;
+
     if (!using_stdin) {
         if(verbose >= 0)
             fprintf(stderr, "Press [q] to stop, [?] for help\n");
@@ -2337,7 +2354,6 @@ static int transcode(OutputFile *output_files,
         int64_t ipts_min;
         double opts_min;
 
-    redo:
         ipts_min= INT64_MAX;
         opts_min= 1e100;
         /* if 'q' pressed, exits */
@@ -2360,14 +2376,20 @@ static int transcode(OutputFile *output_files,
                     do_pkt_dump = 1;
                 av_log_set_level(AV_LOG_DEBUG);
             }
+#if CONFIG_AVFILTER
             if (key == 'c' || key == 'C'){
                 char ret[4096], target[64], cmd[256], arg[256]={0};
                 double ts;
+                int k;
                 fprintf(stderr, "\nEnter command: <target> <time> <command>[ <argument>]\n");
-                if(scanf("%4095[^\n\r]%*c", ret) == 1 && sscanf(ret, "%63[^ ] %lf %255[^ ] %255[^\n]", target, &ts, cmd, arg) >= 3){
-                    for(i=0;i<nb_ostreams;i++) {
+                i=0;
+                while((k=read_key()) !='\n' && k!='\r' && i<sizeof(ret)-1)
+                    if(k>0) ret[i++]= k;
+                ret[i]= 0;
+                if(k>0 && sscanf(ret, "%63[^ ] %lf %255[^ ] %255[^\n]", target, &ts, cmd, arg) >= 3){
+                    for(i=0;i<nb_output_streams;i++) {
                         int r;
-                        ost = ost_table[i];
+                        ost = &output_streams[i];
                         if(ost->graph){
                             if(ts<0){
                                 r= avfilter_graph_send_command(ost->graph, target, cmd, arg, ret, sizeof(ret), key == 'c' ? AVFILTER_CMD_FLAG_ONE : 0);
@@ -2381,6 +2403,7 @@ static int transcode(OutputFile *output_files,
                     fprintf(stderr, "Parse error\n");
                 }
             }
+#endif
             if (key == 'd' || key == 'D'){
                 int debug=0;
                 if(key == 'D') {
@@ -2393,8 +2416,8 @@ static int transcode(OutputFile *output_files,
                 for(i=0;i<nb_input_streams;i++) {
                     input_streams[i].st->codec->debug = debug;
                 }
-                for(i=0;i<nb_ostreams;i++) {
-                    ost = ost_table[i];
+                for(i=0;i<nb_output_streams;i++) {
+                    ost = &output_streams[i];
                     ost->st->codec->debug = debug;
                 }
                 if(debug) av_log_set_level(AV_LOG_DEBUG);
@@ -2417,15 +2440,18 @@ static int transcode(OutputFile *output_files,
         /* select the stream that we must read now by looking at the
            smallest output pts */
         file_index = -1;
-        for(i=0;i<nb_ostreams;i++) {
+        for (i = 0; i < nb_output_streams; i++) {
+            OutputFile *of;
             int64_t ipts;
             double  opts;
-            ost = ost_table[i];
+            ost = &output_streams[i];
+            of = &output_files[ost->file_index];
             os = output_files[ost->file_index].ctx;
             ist = &input_streams[ost->source_index];
-            if(ist->is_past_recording_time || no_packet[ist->file_index])
+            if (ost->is_past_recording_time || no_packet[ist->file_index] ||
+                (os->pb && avio_tell(os->pb) >= of->limit_filesize))
                 continue;
-                opts = ost->st->pts.val * av_q2d(ost->st->time_base);
+            opts = ost->st->pts.val * av_q2d(ost->st->time_base);
             ipts = ist->pts;
             if (!input_files[ist->file_index].eof_reached){
                 if(ipts < ipts_min) {
@@ -2446,17 +2472,13 @@ static int transcode(OutputFile *output_files,
         if (file_index < 0) {
             if(no_packet_count){
                 no_packet_count=0;
-                memset(no_packet, 0, sizeof(no_packet));
+                memset(no_packet, 0, nb_input_files);
                 usleep(10000);
                 continue;
             }
             break;
         }
 
-        /* finish if limit size exhausted */
-        if (limit_filesize != 0 && limit_filesize <= avio_tell(output_files[0].ctx->pb))
-            break;
-
         /* read a frame from it and output it in the fifo */
         is = input_files[file_index].ctx;
         ret= av_read_frame(is, &pkt);
@@ -2474,7 +2496,7 @@ static int transcode(OutputFile *output_files,
         }
 
         no_packet_count=0;
-        memset(no_packet, 0, sizeof(no_packet));
+        memset(no_packet, 0, nb_input_files);
 
         if (do_pkt_dump) {
             av_pkt_dump_log2(NULL, AV_LOG_DEBUG, &pkt, do_hex_dump,
@@ -2521,7 +2543,7 @@ static int transcode(OutputFile *output_files,
         }
 
         //fprintf(stderr,"read #%d.%d size=%d\n", ist->file_index, ist->st->index, pkt.size);
-        if (output_packet(ist, ist_index, ost_table, nb_ostreams, &pkt) < 0) {
+        if (output_packet(ist, ist_index, output_streams, nb_output_streams, &pkt) < 0) {
 
             if (verbose >= 0)
                 fprintf(stderr, "Error while decoding stream #%d.%d\n",
@@ -2529,23 +2551,24 @@ static int transcode(OutputFile *output_files,
             if (exit_on_error)
                 exit_program(1);
             av_free_packet(&pkt);
-            goto redo;
+            continue;
         }
 
     discard_packet:
         av_free_packet(&pkt);
 
         /* dump report by using the output first video and audio streams */
-        print_report(output_files, ost_table, nb_ostreams, 0);
+        print_report(output_files, output_streams, nb_output_streams, 0, timer_start);
     }
 
     /* at the end of stream, we must flush the decoder buffers */
     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);
+            output_packet(ist, i, output_streams, nb_output_streams, NULL);
         }
     }
+    flush_encoders(output_streams, nb_output_streams);
 
     term_exit();
 
@@ -2556,11 +2579,11 @@ static int transcode(OutputFile *output_files,
     }
 
     /* dump report by using the first video and audio streams */
-    print_report(output_files, ost_table, nb_ostreams, 1);
+    print_report(output_files, output_streams, nb_output_streams, 1, timer_start);
 
     /* close each encoder */
-    for(i=0;i<nb_ostreams;i++) {
-        ost = ost_table[i];
+    for (i = 0; i < nb_output_streams; i++) {
+        ost = &output_streams[i];
         if (ost->encoding_needed) {
             av_freep(&ost->st->codec->stats_in);
             avcodec_close(ost->st->codec);
@@ -2583,10 +2606,11 @@ static int transcode(OutputFile *output_files,
 
  fail:
     av_freep(&bit_buffer);
+    av_freep(&no_packet);
 
-    if (ost_table) {
-        for(i=0;i<nb_ostreams;i++) {
-            ost = ost_table[i];
+    if (output_streams) {
+        for (i = 0; i < nb_output_streams; i++) {
+            ost = &output_streams[i];
             if (ost) {
                 if (ost->st->stream_copy)
                     av_freep(&ost->st->codec->extradata);
@@ -2606,20 +2630,12 @@ static int transcode(OutputFile *output_files,
                 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;
 }
 
-static int opt_format(const char *opt, const char *arg)
-{
-    last_asked_format = arg;
-    return 0;
-}
-
 static int opt_video_rc_override_string(const char *opt, const char *arg)
 {
     video_rc_override_string = arg;
@@ -2792,6 +2808,12 @@ static int opt_video_standard(const char *opt, const char *arg)
 
 static int opt_codec(const char *opt, const char *arg)
 {
+    switch(opt[strlen(opt)-1]){
+    case 'a':    audio_codec_name = arg; break;
+    case 'v':    video_codec_name = arg; break;
+    case 's': subtitle_codec_name = arg; break;
+    }
+
     return av_dict_set(&codec_names, opt, arg, 0);
 }
 
@@ -2833,7 +2855,7 @@ static int opt_codec_tag(const char *opt, const char *arg)
     return 0;
 }
 
-static int opt_map(const char *opt, const char *arg)
+static int opt_map(OptionsContext *o, const char *opt, const char *arg)
 {
     StreamMap *m = NULL;
     int i, negative = 0, file_idx;
@@ -2857,13 +2879,13 @@ static int opt_map(const char *opt, const char *arg)
         }
         if (*sync)
             sync++;
-        for (i = 0; i < input_files[sync_file_idx].ctx->nb_streams; i++)
+        for (i = 0; i < input_files[sync_file_idx].nb_streams; i++)
             if (check_stream_specifier(input_files[sync_file_idx].ctx,
                                        input_files[sync_file_idx].ctx->streams[i], sync) == 1) {
                 sync_stream_idx = i;
                 break;
             }
-        if (i == input_files[sync_file_idx].ctx->nb_streams) {
+        if (i == input_files[sync_file_idx].nb_streams) {
             av_log(NULL, AV_LOG_ERROR, "Sync stream specification in map %s does not "
                                        "match any streams.\n", arg);
             exit_program(1);
@@ -2878,20 +2900,21 @@ static int opt_map(const char *opt, const char *arg)
     }
     if (negative)
         /* disable some already defined maps */
-        for (i = 0; i < nb_stream_maps; i++) {
-            m = &stream_maps[i];
+        for (i = 0; i < o->nb_stream_maps; i++) {
+            m = &o->stream_maps[i];
             if (check_stream_specifier(input_files[m->file_index].ctx,
                                        input_files[m->file_index].ctx->streams[m->stream_index],
                                        *p == ':' ? p + 1 : p) > 0)
                 m->disabled = 1;
         }
     else
-        for (i = 0; i < input_files[file_idx].ctx->nb_streams; i++) {
+        for (i = 0; i < input_files[file_idx].nb_streams; i++) {
             if (check_stream_specifier(input_files[file_idx].ctx, input_files[file_idx].ctx->streams[i],
                         *p == ':' ? p + 1 : p) <= 0)
                 continue;
-            stream_maps = grow_array(stream_maps, sizeof(*stream_maps), &nb_stream_maps, nb_stream_maps + 1);
-            m = &stream_maps[nb_stream_maps - 1];
+            o->stream_maps = grow_array(o->stream_maps, sizeof(*o->stream_maps),
+                                        &o->nb_stream_maps, o->nb_stream_maps + 1);
+            m = &o->stream_maps[o->nb_stream_maps - 1];
 
             m->file_index   = file_idx;
             m->stream_index = i;
@@ -2975,18 +2998,6 @@ static int opt_input_ts_scale(const char *opt, const char *arg)
     return av_dict_set(&ts_scale, opt, arg, 0);
 }
 
-static int opt_recording_time(const char *opt, const char *arg)
-{
-    recording_time = parse_time_or_die(opt, arg, 1);
-    return 0;
-}
-
-static int opt_start_time(const char *opt, const char *arg)
-{
-    start_time = parse_time_or_die(opt, arg, 1);
-    return 0;
-}
-
 static int opt_recording_timestamp(const char *opt, const char *arg)
 {
     char buf[128];
@@ -3000,12 +3011,6 @@ static int opt_recording_timestamp(const char *opt, const char *arg)
     return 0;
 }
 
-static int opt_input_ts_offset(const char *opt, const char *arg)
-{
-    input_ts_offset = parse_time_or_die(opt, arg, 1);
-    return 0;
-}
-
 static enum CodecID find_codec_or_die(const char *name, enum AVMediaType type, int encoder)
 {
     const char *codec_string = encoder ? "encoder" : "decoder";
@@ -3094,6 +3099,8 @@ static void add_input_streams(AVFormatContext *ic)
             ist->ts_scale = strtod(scale, NULL);
 
         ist->dec = choose_codec(ic, st, dec->codec_type, codec_names);
+        if (!ist->dec)
+            ist->dec = avcodec_find_decoder(dec->codec_id);
 
         switch (dec->codec_type) {
         case AVMEDIA_TYPE_AUDIO:
@@ -3144,7 +3151,7 @@ static void add_input_streams(AVFormatContext *ic)
     }
 }
 
-static int opt_input_file(const char *opt, const char *filename)
+static int opt_input_file(OptionsContext *o, const char *opt, const char *filename)
 {
     AVFormatContext *ic;
     AVInputFormat *file_iformat = NULL;
@@ -3154,12 +3161,11 @@ static int opt_input_file(const char *opt, const char *filename)
     AVDictionary **opts;
     int orig_nb_streams;                     // number of streams before avformat_find_stream_info
 
-    if (last_asked_format) {
-        if (!(file_iformat = av_find_input_format(last_asked_format))) {
-            fprintf(stderr, "Unknown input format: '%s'\n", last_asked_format);
+    if (o->format) {
+        if (!(file_iformat = av_find_input_format(o->format))) {
+            fprintf(stderr, "Unknown input format: '%s'\n", o->format);
             exit_program(1);
         }
-        last_asked_format = NULL;
     }
 
     if (!strcmp(filename, "-"))
@@ -3249,20 +3255,18 @@ static int opt_input_file(const char *opt, const char *filename)
         exit_program(1);
     }
 
-    timestamp = start_time;
+    timestamp = o->start_time;
     /* add the stream start time */
     if (ic->start_time != AV_NOPTS_VALUE)
         timestamp += ic->start_time;
 
     /* if seeking requested, we execute it */
-    if (start_time != 0) {
+    if (o->start_time != 0) {
         ret = av_seek_frame(ic, -1, timestamp, AVSEEK_FLAG_BACKWARD);
         if (ret < 0) {
             fprintf(stderr, "%s: could not seek to position %0.3f\n",
                     filename, (double)timestamp / AV_TIME_BASE);
         }
-        /* reset seek info */
-        start_time = 0;
     }
 
     /* update the current parameters so that they match the one of the input stream */
@@ -3275,7 +3279,7 @@ static int opt_input_file(const char *opt, const char *filename)
     input_files = grow_array(input_files, sizeof(*input_files), &nb_input_files, nb_input_files + 1);
     input_files[nb_input_files - 1].ctx        = ic;
     input_files[nb_input_files - 1].ist_index  = nb_input_streams - ic->nb_streams;
-    input_files[nb_input_files - 1].ts_offset  = input_ts_offset - (copy_ts ? 0 : timestamp);
+    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;
 
     top_field_first = -1;
@@ -3292,8 +3296,8 @@ static int opt_input_file(const char *opt, const char *filename)
         av_dict_free(&opts[i]);
     av_freep(&opts);
     av_dict_free(&codec_names);
-    uninit_opts();
-    init_opts();
+
+    reset_options(o);
     return 0;
 }
 
@@ -3331,17 +3335,9 @@ static OutputStream *new_output_stream(AVFormatContext *oc, enum AVMediaType typ
         exit_program(1);
     }
 
-    output_streams_for_file[nb_output_files] =
-        grow_array(output_streams_for_file[nb_output_files],
-                   sizeof(*output_streams_for_file[nb_output_files]),
-                   &nb_output_streams_for_file[nb_output_files],
-                   oc->nb_streams);
-    ost = output_streams_for_file[nb_output_files][idx] =
-        av_mallocz(sizeof(OutputStream));
-    if (!ost) {
-        fprintf(stderr, "Could not alloc output stream\n");
-        exit_program(1);
-    }
+    output_streams = grow_array(output_streams, sizeof(*output_streams), &nb_output_streams,
+                                nb_output_streams + 1);
+    ost = &output_streams[nb_output_streams - 1];
     ost->file_index = nb_output_files;
     ost->index = idx;
     ost->st    = st;
@@ -3632,18 +3628,18 @@ static int read_ffserver_streams(AVFormatContext *s, const char *filename)
 }
 
 
-static int copy_chapters(int infile, int outfile)
+static int copy_chapters(InputFile *ifile, OutputFile *ofile)
 {
-    AVFormatContext *is = input_files[infile].ctx;
-    AVFormatContext *os = output_files[outfile].ctx;
+    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(start_time - input_files[infile].ts_offset,
+        int64_t ts_off   = av_rescale_q(ofile->start_time - ifile->ts_offset,
                                       AV_TIME_BASE_Q, in_ch->time_base);
-        int64_t rt       = (recording_time == INT64_MAX) ? INT64_MAX :
-                           av_rescale_q(recording_time, 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)
@@ -3672,8 +3668,9 @@ static int copy_chapters(int infile, int outfile)
     return 0;
 }
 
-static int opt_output_file(const char *opt, const char *filename)
+static void opt_output_file(void *optctx, const char *filename)
 {
+    OptionsContext *o = optctx;
     AVFormatContext *oc;
     int i, err;
     AVOutputFormat *file_oformat;
@@ -3683,8 +3680,7 @@ static int opt_output_file(const char *opt, const char *filename)
     if (!strcmp(filename, "-"))
         filename = "pipe:";
 
-    err = avformat_alloc_output_context2(&oc, NULL, last_asked_format, filename);
-    last_asked_format = NULL;
+    err = avformat_alloc_output_context2(&oc, NULL, o->format, filename);
     if (!oc) {
         print_error(filename, err);
         exit_program(1);
@@ -3700,7 +3696,7 @@ static int opt_output_file(const char *opt, const char *filename)
             print_error(filename, err);
             exit_program(1);
         }
-    } else if (!nb_stream_maps) {
+    } else if (!o->nb_stream_maps) {
         /* pick the "best" stream of each type */
 #define NEW_STREAM(type, index)\
         if (index >= 0) {\
@@ -3748,8 +3744,8 @@ static int opt_output_file(const char *opt, const char *filename)
         }
         /* do something with data? */
     } else {
-        for (i = 0; i < nb_stream_maps; i++) {
-            StreamMap *map = &stream_maps[i];
+        for (i = 0; i < o->nb_stream_maps; i++) {
+            StreamMap *map = &o->stream_maps[i];
 
             if (map->disabled)
                 continue;
@@ -3777,10 +3773,12 @@ static int opt_output_file(const char *opt, const char *filename)
     av_dict_free(&metadata);
 
 
-    if (nb_output_files == MAX_FILES)
-        exit_program(1);                /* a temporary hack until all the other MAX_FILES-sized arrays are removed */
     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 */
@@ -3845,7 +3843,7 @@ static int opt_output_file(const char *opt, const char *filename)
         }
     }
     if (chapters_input_file >= 0)
-        copy_chapters(chapters_input_file, nb_output_files - 1);
+        copy_chapters(&input_files[chapters_input_file], &output_files[nb_output_files - 1]);
 
     /* copy metadata */
     for (i = 0; i < nb_meta_data_maps; i++) {
@@ -3898,9 +3896,9 @@ static int opt_output_file(const char *opt, const char *filename)
         av_dict_copy(&oc->metadata, input_files[0].ctx->metadata,
                      AV_DICT_DONT_OVERWRITE);
     if (metadata_streams_autocopy)
-        for (i = 0; i < oc->nb_streams; i++) {
-            InputStream *ist = &input_streams[output_streams_for_file[nb_output_files-1][i]->source_index];
-            av_dict_copy(&oc->streams[i]->metadata, ist->st->metadata, AV_DICT_DONT_OVERWRITE);
+        for (i = output_files[nb_output_files - 1].ost_index; i < nb_output_streams; i++) {
+            InputStream *ist = &input_streams[output_streams[i].source_index];
+            av_dict_copy(&output_streams[i].st->metadata, ist->st->metadata, AV_DICT_DONT_OVERWRITE);
         }
 
     frame_rate    = (AVRational){0, 0};
@@ -3916,15 +3914,13 @@ static int opt_output_file(const char *opt, const char *filename)
     metadata_global_autocopy   = 1;
     metadata_streams_autocopy  = 1;
     metadata_chapters_autocopy = 1;
-    av_freep(&stream_maps);
-    nb_stream_maps = 0;
+    av_freep(&streamid_map);
+    nb_streamid_map = 0;
 
     av_dict_free(&codec_names);
 
     av_freep(&forced_key_frames);
-    uninit_opts();
-    init_opts();
-    return 0;
+    reset_options(o);
 }
 
 /* same option as mencoder */
@@ -4013,6 +4009,7 @@ static int opt_help(const char *opt, const char *arg)
     AVCodec *c;
     AVOutputFormat *oformat = NULL;
     AVInputFormat  *iformat = NULL;
+    const AVClass *class;
 
     av_log_set_callback(log_callback_help);
     show_usage();
@@ -4040,7 +4037,8 @@ static int opt_help(const char *opt, const char *arg)
                       OPT_GRAB,
                       OPT_GRAB);
     printf("\n");
-    av_opt_show2(avcodec_opts[0], NULL, AV_OPT_FLAG_ENCODING_PARAM|AV_OPT_FLAG_DECODING_PARAM, 0);
+    class = avcodec_get_class();
+    av_opt_show2(&class, NULL, AV_OPT_FLAG_ENCODING_PARAM|AV_OPT_FLAG_DECODING_PARAM, 0);
     printf("\n");
 
     /* individual codec options */
@@ -4052,7 +4050,8 @@ static int opt_help(const char *opt, const char *arg)
         }
     }
 
-    av_opt_show2(avformat_opts, NULL, AV_OPT_FLAG_ENCODING_PARAM|AV_OPT_FLAG_DECODING_PARAM, 0);
+    class = avformat_get_class();
+    av_opt_show2(&class, NULL, AV_OPT_FLAG_ENCODING_PARAM|AV_OPT_FLAG_DECODING_PARAM, 0);
     printf("\n");
 
     /* individual muxer options */
@@ -4071,11 +4070,12 @@ static int opt_help(const char *opt, const char *arg)
         }
     }
 
-    av_opt_show2(sws_opts, NULL, AV_OPT_FLAG_ENCODING_PARAM|AV_OPT_FLAG_DECODING_PARAM, 0);
+    class = sws_get_class();
+    av_opt_show2(&class, NULL, AV_OPT_FLAG_ENCODING_PARAM|AV_OPT_FLAG_DECODING_PARAM, 0);
     return 0;
 }
 
-static int opt_target(const char *opt, const char *arg)
+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"};
@@ -4102,7 +4102,7 @@ static int opt_target(const char *opt, const char *arg)
             if(nb_input_files) {
                 int i, j;
                 for (j = 0; j < nb_input_files; j++) {
-                    for (i = 0; i < input_files[j].ctx->nb_streams; i++) {
+                    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;
@@ -4134,7 +4134,7 @@ static int opt_target(const char *opt, const char *arg)
     if(!strcmp(arg, "vcd")) {
         opt_codec("c:v", "mpeg1video");
         opt_codec("c:a", "mp2");
-        opt_format("f", "vcd");
+        parse_option(o, "f", "vcd", options);
 
         opt_frame_size("s", norm == PAL ? "352x288" : "352x240");
         opt_frame_rate("r", frame_rates[norm]);
@@ -4162,7 +4162,7 @@ static int opt_target(const char *opt, const char *arg)
 
         opt_codec("c:v", "mpeg2video");
         opt_codec("c:a", "mp2");
-        opt_format("f", "svcd");
+        parse_option(o, "f", "svcd", options);
 
         opt_frame_size("s", norm == PAL ? "480x576" : "480x480");
         opt_frame_rate("r", frame_rates[norm]);
@@ -4185,7 +4185,7 @@ static int opt_target(const char *opt, const char *arg)
 
         opt_codec("c:v", "mpeg2video");
         opt_codec("c:a", "ac3");
-        opt_format("f", "dvd");
+        parse_option(o, "f", "dvd", options);
 
         opt_frame_size("vcodec", norm == PAL ? "720x576" : "720x480");
         opt_frame_rate("r", frame_rates[norm]);
@@ -4205,7 +4205,7 @@ static int opt_target(const char *opt, const char *arg)
 
     } else if(!strncmp(arg, "dv", 2)) {
 
-        opt_format("f", "dv");
+        parse_option(o, "f", "dv", options);
 
         opt_frame_size("s", norm == PAL ? "720x576" : "720x480");
         opt_frame_pix_fmt("pix_fmt", !strncmp(arg, "dv50", 4) ? "yuv422p" :
@@ -4261,6 +4261,47 @@ static int opt_bsf(const char *opt, const char *arg)
     return 0;
 }
 
+static int opt_preset(const char *opt, const char *arg)
+{
+    FILE *f=NULL;
+    char filename[1000], tmp[1000], tmp2[1000], line[1000];
+    char *codec_name = *opt == 'v' ? video_codec_name :
+                       *opt == 'a' ? audio_codec_name :
+                                     subtitle_codec_name;
+
+    if (!(f = get_preset_file(filename, sizeof(filename), arg, *opt == 'f', codec_name))) {
+        fprintf(stderr, "File for preset '%s' not found\n", arg);
+        exit_program(1);
+    }
+
+    while(!feof(f)){
+        int e= fscanf(f, "%999[^\n]\n", line) - 1;
+        if(line[0] == '#' && !e)
+            continue;
+        e|= sscanf(line, "%999[^=]=%999[^\n]\n", tmp, tmp2) - 2;
+        if(e){
+            fprintf(stderr, "%s: Invalid syntax: '%s'\n", filename, line);
+            exit_program(1);
+        }
+        if(!strcmp(tmp, "acodec")){
+            opt_audio_codec(tmp, tmp2);
+        }else if(!strcmp(tmp, "vcodec")){
+            opt_video_codec(tmp, tmp2);
+        }else if(!strcmp(tmp, "scodec")){
+            opt_subtitle_codec(tmp, tmp2);
+        }else if(!strcmp(tmp, "dcodec")){
+            opt_data_codec(tmp, tmp2);
+        }else if(opt_default(tmp, tmp2) < 0){
+            fprintf(stderr, "%s: Invalid option or argument: '%s', parsed as '%s' = '%s'\n", filename, line, tmp, tmp2);
+            exit_program(1);
+        }
+    }
+
+    fclose(f);
+
+    return 0;
+}
+
 static void log_callback_null(void* ptr, int level, const char* fmt, va_list vl)
 {
 }
@@ -4275,24 +4316,25 @@ static int opt_passlogfile(const char *opt, const char *arg)
 #endif
 }
 
+#define OFFSET(x) offsetof(OptionsContext, x)
 static const OptionDef options[] = {
     /* main options */
 #include "cmdutils_common_opts.h"
-    { "f", HAS_ARG, {(void*)opt_format}, "force format", "fmt" },
-    { "i", HAS_ARG, {(void*)opt_input_file}, "input file name", "filename" },
+    { "f", HAS_ARG | OPT_STRING | OPT_OFFSET, {.off = OFFSET(format)}, "force format", "fmt" },
+    { "i", HAS_ARG | OPT_FUNC2, {(void*)opt_input_file}, "input file name", "filename" },
     { "y", OPT_BOOL, {(void*)&file_overwrite}, "overwrite output files" },
     { "c", HAS_ARG, {(void*)opt_codec}, "codec name", "codec" },
     { "codec", HAS_ARG, {(void*)opt_codec}, "codec name", "codec" },
-    { "map", HAS_ARG | OPT_EXPERT, {(void*)opt_map}, "set input stream mapping", "file.stream[:syncfile.syncstream]" },
+    { "map", HAS_ARG | OPT_EXPERT | OPT_FUNC2, {(void*)opt_map}, "set input stream mapping", "file.stream[:syncfile.syncstream]" },
     { "map_meta_data", HAS_ARG | OPT_EXPERT, {(void*)opt_map_meta_data}, "DEPRECATED set meta data information of outfile from infile",
       "outfile[,metadata]:infile[,metadata]" },
     { "map_metadata", HAS_ARG | OPT_EXPERT, {(void*)opt_map_metadata}, "set metadata information of outfile from infile",
       "outfile[,metadata]:infile[,metadata]" },
     { "map_chapters",  OPT_INT | HAS_ARG | OPT_EXPERT, {(void*)&chapters_input_file},  "set chapters mapping", "input_file_index" },
-    { "t", HAS_ARG, {(void*)opt_recording_time}, "record or transcode \"duration\" seconds of audio/video", "duration" },
-    { "fs", HAS_ARG | OPT_INT64, {(void*)&limit_filesize}, "set the limit file size in bytes", "limit_size" }, //
-    { "ss", HAS_ARG, {(void*)opt_start_time}, "set the start time offset", "time_off" },
-    { "itsoffset", HAS_ARG, {(void*)opt_input_ts_offset}, "set the input ts offset", "time_off" },
+    { "t", HAS_ARG | OPT_TIME | OPT_OFFSET, {.off = OFFSET(recording_time)}, "record or transcode \"duration\" seconds of audio/video", "duration" },
+    { "fs", HAS_ARG | OPT_INT64 | OPT_OFFSET, {.off = OFFSET(limit_filesize)}, "set the limit file size in bytes", "limit_size" }, //
+    { "ss", HAS_ARG | OPT_TIME | OPT_OFFSET, {.off = OFFSET(start_time)}, "set the start time offset", "time_off" },
+    { "itsoffset", HAS_ARG | OPT_TIME | OPT_OFFSET, {.off = OFFSET(input_ts_offset)}, "set the input ts offset", "time_off" },
     { "itsscale", HAS_ARG, {(void*)opt_input_ts_scale}, "set the input ts scale", "scale" },
     { "timestamp", HAS_ARG, {(void*)opt_recording_timestamp}, "set the recording timestamp ('now' to set the current time)", "time" },
     { "metadata", HAS_ARG, {(void*)opt_metadata}, "add metadata", "string=string" },
@@ -4308,7 +4350,7 @@ static const OptionDef options[] = {
     { "loop_input", OPT_BOOL | OPT_EXPERT, {(void*)&loop_input}, "deprecated, use -loop" },
     { "loop_output", HAS_ARG | OPT_INT | OPT_EXPERT, {(void*)&loop_output}, "deprecated, use -loop", "" },
     { "v", HAS_ARG, {(void*)opt_verbose}, "set the verbosity level", "number" },
-    { "target", HAS_ARG, {(void*)opt_target}, "specify target file type (\"vcd\", \"svcd\", \"dvd\", \"dv\", \"dv50\", \"pal-vcd\", \"ntsc-svcd\", ...)", "type" },
+    { "target", HAS_ARG | OPT_FUNC2, {(void*)opt_target}, "specify target file type (\"vcd\", \"svcd\", \"dvd\", \"dv\", \"dv50\", \"pal-vcd\", \"ntsc-svcd\", ...)", "type" },
     { "threads",  HAS_ARG | OPT_EXPERT, {(void*)opt_thread_count}, "thread count", "count" },
     { "vsync", HAS_ARG | OPT_INT | OPT_EXPERT, {(void*)&video_sync_method}, "video sync method", "" },
     { "async", HAS_ARG | OPT_INT | OPT_EXPERT, {(void*)&audio_sync_method}, "audio sync method", "" },
@@ -4343,7 +4385,7 @@ static const OptionDef options[] = {
     { "qscale", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_qscale}, "use fixed video quantizer scale (VBR)", "q" },
     { "rc_override", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_video_rc_override_string}, "rate control override for specific intervals", "override" },
     { "vcodec", HAS_ARG | OPT_VIDEO, {(void*)opt_video_codec}, "force video codec ('copy' to copy stream)", "codec" },
-    { "me_threshold", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_me_threshold}, "motion estimaton threshold",  "threshold" },
+    { "me_threshold", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_me_threshold}, "motion estimation threshold",  "threshold" },
     { "sameq", OPT_BOOL | OPT_VIDEO, {(void*)&same_quant}, "use same quantizer as source (implies VBR)" },
     { "same_quant", OPT_BOOL | OPT_VIDEO, {(void*)&same_quant}, "use same quantizer as source (implies VBR)" },
     { "pass", HAS_ARG | OPT_VIDEO, {(void*)opt_pass}, "select the pass number (1 or 2)", "n" },
@@ -4398,6 +4440,10 @@ static const OptionDef options[] = {
     { "vbsf", HAS_ARG | OPT_VIDEO | OPT_EXPERT, {(void*)opt_bsf}, "", "bitstream_filter" },
     { "sbsf", HAS_ARG | OPT_SUBTITLE | OPT_EXPERT, {(void*)opt_bsf}, "", "bitstream_filter" },
 
+    { "apre", HAS_ARG | OPT_AUDIO | OPT_EXPERT, {(void*)opt_preset}, "set the audio options to the indicated preset", "preset" },
+    { "vpre", HAS_ARG | OPT_VIDEO | OPT_EXPERT, {(void*)opt_preset}, "set the video options to the indicated preset", "preset" },
+    { "spre", HAS_ARG | OPT_SUBTITLE | OPT_EXPERT, {(void*)opt_preset}, "set the subtitle options to the indicated preset", "preset" },
+    { "fpre", HAS_ARG | OPT_EXPERT, {(void*)opt_preset}, "set options from indicated preset file", "filename" },
     /* data codec support */
     { "dcodec", HAS_ARG | OPT_DATA, {(void*)opt_data_codec}, "force data codec ('copy' to copy stream)", "codec" },
 
@@ -4407,8 +4453,11 @@ static const OptionDef options[] = {
 
 int main(int argc, char **argv)
 {
+    OptionsContext o = { 0 };
     int64_t ti;
 
+    reset_options(&o);
+
     av_log_set_flags(AV_LOG_SKIP_REPEATED);
 
     if(argc>1 && !strcmp(argv[1], "-d")){
@@ -4433,13 +4482,11 @@ int main(int argc, char **argv)
         avio_set_interrupt_cb(decode_interrupt_cb);
 #endif
 
-    init_opts();
-
     if(verbose>=0)
         show_banner();
 
     /* parse options */
-    parse_options(argc, argv, options, opt_output_file);
+    parse_options(&o, argc, argv, options, opt_output_file);
 
     if(nb_output_files <= 0 && nb_input_files == 0) {
         show_usage();
@@ -4467,5 +4514,6 @@ int main(int argc, char **argv)
         printf("bench: utime=%0.3fs maxrss=%ikB\n", ti / 1000000.0, maxrss);
     }
 
-    return exit_program(0);
+    exit_program(0);
+    return 0;
 }