]> git.sesse.net Git - ffmpeg/blob - ffmpeg.c
Merge commit '1e9db41e2a2166be5671b088ef4ad06a40af459f'
[ffmpeg] / ffmpeg.c
1 /*
2  * Copyright (c) 2000-2003 Fabrice Bellard
3  *
4  * This file is part of FFmpeg.
5  *
6  * FFmpeg is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Lesser General Public
8  * License as published by the Free Software Foundation; either
9  * version 2.1 of the License, or (at your option) any later version.
10  *
11  * FFmpeg is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14  * Lesser General Public License for more details.
15  *
16  * You should have received a copy of the GNU Lesser General Public
17  * License along with FFmpeg; if not, write to the Free Software
18  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
19  */
20
21 /**
22  * @file
23  * multimedia converter based on the FFmpeg libraries
24  */
25
26 #include "config.h"
27 #include <ctype.h>
28 #include <string.h>
29 #include <math.h>
30 #include <stdlib.h>
31 #include <errno.h>
32 #include <limits.h>
33 #include <stdint.h>
34
35 #if HAVE_ISATTY
36 #if HAVE_IO_H
37 #include <io.h>
38 #endif
39 #if HAVE_UNISTD_H
40 #include <unistd.h>
41 #endif
42 #endif
43
44 #include "libavformat/avformat.h"
45 #include "libavdevice/avdevice.h"
46 #include "libswresample/swresample.h"
47 #include "libavutil/opt.h"
48 #include "libavutil/channel_layout.h"
49 #include "libavutil/parseutils.h"
50 #include "libavutil/samplefmt.h"
51 #include "libavutil/fifo.h"
52 #include "libavutil/intreadwrite.h"
53 #include "libavutil/dict.h"
54 #include "libavutil/mathematics.h"
55 #include "libavutil/pixdesc.h"
56 #include "libavutil/avstring.h"
57 #include "libavutil/libm.h"
58 #include "libavutil/imgutils.h"
59 #include "libavutil/timestamp.h"
60 #include "libavutil/bprint.h"
61 #include "libavutil/time.h"
62 #include "libavformat/os_support.h"
63
64 #include "libavformat/ffm.h" // not public API
65
66 # include "libavfilter/avcodec.h"
67 # include "libavfilter/avfilter.h"
68 # include "libavfilter/buffersrc.h"
69 # include "libavfilter/buffersink.h"
70
71 #if HAVE_SYS_RESOURCE_H
72 #include <sys/time.h>
73 #include <sys/types.h>
74 #include <sys/resource.h>
75 #elif HAVE_GETPROCESSTIMES
76 #include <windows.h>
77 #endif
78 #if HAVE_GETPROCESSMEMORYINFO
79 #include <windows.h>
80 #include <psapi.h>
81 #endif
82
83 #if HAVE_SYS_SELECT_H
84 #include <sys/select.h>
85 #endif
86
87 #if HAVE_TERMIOS_H
88 #include <fcntl.h>
89 #include <sys/ioctl.h>
90 #include <sys/time.h>
91 #include <termios.h>
92 #elif HAVE_KBHIT
93 #include <conio.h>
94 #endif
95
96 #if HAVE_PTHREADS
97 #include <pthread.h>
98 #endif
99
100 #include <time.h>
101
102 #include "ffmpeg.h"
103 #include "cmdutils.h"
104
105 #include "libavutil/avassert.h"
106
107 const char program_name[] = "ffmpeg";
108 const int program_birth_year = 2000;
109
110 static FILE *vstats_file;
111
112 const char *const forced_keyframes_const_names[] = {
113     "n",
114     "n_forced",
115     "prev_forced_n",
116     "prev_forced_t",
117     "t",
118     NULL
119 };
120
121 static void do_video_stats(OutputStream *ost, int frame_size);
122 static int64_t getutime(void);
123 static int64_t getmaxrss(void);
124
125 static int run_as_daemon  = 0;
126 static int64_t video_size = 0;
127 static int64_t audio_size = 0;
128 static int64_t data_size = 0;
129 static int64_t subtitle_size = 0;
130 static int64_t extra_size = 0;
131 static int nb_frames_dup = 0;
132 static int nb_frames_drop = 0;
133 static int64_t decode_error_stat[2];
134
135 static int current_time;
136 AVIOContext *progress_avio = NULL;
137
138 static uint8_t *subtitle_out;
139
140 #if HAVE_PTHREADS
141 /* signal to input threads that they should exit; set by the main thread */
142 static int transcoding_finished;
143 #endif
144
145 #define DEFAULT_PASS_LOGFILENAME_PREFIX "ffmpeg2pass"
146
147 InputStream **input_streams = NULL;
148 int        nb_input_streams = 0;
149 InputFile   **input_files   = NULL;
150 int        nb_input_files   = 0;
151
152 OutputStream **output_streams = NULL;
153 int         nb_output_streams = 0;
154 OutputFile   **output_files   = NULL;
155 int         nb_output_files   = 0;
156
157 FilterGraph **filtergraphs;
158 int        nb_filtergraphs;
159
160 #if HAVE_TERMIOS_H
161
162 /* init terminal so that we can grab keys */
163 static struct termios oldtty;
164 static int restore_tty;
165 #endif
166
167 static void free_input_threads(void);
168
169
170 /* sub2video hack:
171    Convert subtitles to video with alpha to insert them in filter graphs.
172    This is a temporary solution until libavfilter gets real subtitles support.
173  */
174
175 static int sub2video_get_blank_frame(InputStream *ist)
176 {
177     int ret;
178     AVFrame *frame = ist->sub2video.frame;
179
180     av_frame_unref(frame);
181     ist->sub2video.frame->width  = ist->sub2video.w;
182     ist->sub2video.frame->height = ist->sub2video.h;
183     ist->sub2video.frame->format = AV_PIX_FMT_RGB32;
184     if ((ret = av_frame_get_buffer(frame, 32)) < 0)
185         return ret;
186     memset(frame->data[0], 0, frame->height * frame->linesize[0]);
187     return 0;
188 }
189
190 static void sub2video_copy_rect(uint8_t *dst, int dst_linesize, int w, int h,
191                                 AVSubtitleRect *r)
192 {
193     uint32_t *pal, *dst2;
194     uint8_t *src, *src2;
195     int x, y;
196
197     if (r->type != SUBTITLE_BITMAP) {
198         av_log(NULL, AV_LOG_WARNING, "sub2video: non-bitmap subtitle\n");
199         return;
200     }
201     if (r->x < 0 || r->x + r->w > w || r->y < 0 || r->y + r->h > h) {
202         av_log(NULL, AV_LOG_WARNING, "sub2video: rectangle overflowing\n");
203         return;
204     }
205
206     dst += r->y * dst_linesize + r->x * 4;
207     src = r->pict.data[0];
208     pal = (uint32_t *)r->pict.data[1];
209     for (y = 0; y < r->h; y++) {
210         dst2 = (uint32_t *)dst;
211         src2 = src;
212         for (x = 0; x < r->w; x++)
213             *(dst2++) = pal[*(src2++)];
214         dst += dst_linesize;
215         src += r->pict.linesize[0];
216     }
217 }
218
219 static void sub2video_push_ref(InputStream *ist, int64_t pts)
220 {
221     AVFrame *frame = ist->sub2video.frame;
222     int i;
223
224     av_assert1(frame->data[0]);
225     ist->sub2video.last_pts = frame->pts = pts;
226     for (i = 0; i < ist->nb_filters; i++)
227         av_buffersrc_add_frame_flags(ist->filters[i]->filter, frame,
228                                      AV_BUFFERSRC_FLAG_KEEP_REF |
229                                      AV_BUFFERSRC_FLAG_PUSH);
230 }
231
232 static void sub2video_update(InputStream *ist, AVSubtitle *sub)
233 {
234     int w = ist->sub2video.w, h = ist->sub2video.h;
235     AVFrame *frame = ist->sub2video.frame;
236     int8_t *dst;
237     int     dst_linesize;
238     int num_rects, i;
239     int64_t pts, end_pts;
240
241     if (!frame)
242         return;
243     if (sub) {
244         pts       = av_rescale_q(sub->pts + sub->start_display_time * 1000,
245                                  AV_TIME_BASE_Q, ist->st->time_base);
246         end_pts   = av_rescale_q(sub->pts + sub->end_display_time   * 1000,
247                                  AV_TIME_BASE_Q, ist->st->time_base);
248         num_rects = sub->num_rects;
249     } else {
250         pts       = ist->sub2video.end_pts;
251         end_pts   = INT64_MAX;
252         num_rects = 0;
253     }
254     if (sub2video_get_blank_frame(ist) < 0) {
255         av_log(ist->st->codec, AV_LOG_ERROR,
256                "Impossible to get a blank canvas.\n");
257         return;
258     }
259     dst          = frame->data    [0];
260     dst_linesize = frame->linesize[0];
261     for (i = 0; i < num_rects; i++)
262         sub2video_copy_rect(dst, dst_linesize, w, h, sub->rects[i]);
263     sub2video_push_ref(ist, pts);
264     ist->sub2video.end_pts = end_pts;
265 }
266
267 static void sub2video_heartbeat(InputStream *ist, int64_t pts)
268 {
269     InputFile *infile = input_files[ist->file_index];
270     int i, j, nb_reqs;
271     int64_t pts2;
272
273     /* When a frame is read from a file, examine all sub2video streams in
274        the same file and send the sub2video frame again. Otherwise, decoded
275        video frames could be accumulating in the filter graph while a filter
276        (possibly overlay) is desperately waiting for a subtitle frame. */
277     for (i = 0; i < infile->nb_streams; i++) {
278         InputStream *ist2 = input_streams[infile->ist_index + i];
279         if (!ist2->sub2video.frame)
280             continue;
281         /* subtitles seem to be usually muxed ahead of other streams;
282            if not, substracting a larger time here is necessary */
283         pts2 = av_rescale_q(pts, ist->st->time_base, ist2->st->time_base) - 1;
284         /* do not send the heartbeat frame if the subtitle is already ahead */
285         if (pts2 <= ist2->sub2video.last_pts)
286             continue;
287         if (pts2 >= ist2->sub2video.end_pts || !ist2->sub2video.frame->data[0])
288             sub2video_update(ist2, NULL);
289         for (j = 0, nb_reqs = 0; j < ist2->nb_filters; j++)
290             nb_reqs += av_buffersrc_get_nb_failed_requests(ist2->filters[j]->filter);
291         if (nb_reqs)
292             sub2video_push_ref(ist2, pts2);
293     }
294 }
295
296 static void sub2video_flush(InputStream *ist)
297 {
298     int i;
299
300     for (i = 0; i < ist->nb_filters; i++)
301         av_buffersrc_add_ref(ist->filters[i]->filter, NULL, 0);
302 }
303
304 /* end of sub2video hack */
305
306 static void term_exit_sigsafe(void)
307 {
308 #if HAVE_TERMIOS_H
309     if(restore_tty)
310         tcsetattr (0, TCSANOW, &oldtty);
311 #endif
312 }
313
314 void term_exit(void)
315 {
316     av_log(NULL, AV_LOG_QUIET, "%s", "");
317     term_exit_sigsafe();
318 }
319
320 static volatile int received_sigterm = 0;
321 static volatile int received_nb_signals = 0;
322 static int main_return_code = 0;
323
324 static void
325 sigterm_handler(int sig)
326 {
327     received_sigterm = sig;
328     received_nb_signals++;
329     term_exit_sigsafe();
330     if(received_nb_signals > 3)
331         exit(123);
332 }
333
334 void term_init(void)
335 {
336 #if HAVE_TERMIOS_H
337     if(!run_as_daemon){
338         struct termios tty;
339         int istty = 1;
340 #if HAVE_ISATTY
341         istty = isatty(0) && isatty(2);
342 #endif
343         if (istty && tcgetattr (0, &tty) == 0) {
344             oldtty = tty;
345             restore_tty = 1;
346
347             tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
348                              |INLCR|IGNCR|ICRNL|IXON);
349             tty.c_oflag |= OPOST;
350             tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
351             tty.c_cflag &= ~(CSIZE|PARENB);
352             tty.c_cflag |= CS8;
353             tty.c_cc[VMIN] = 1;
354             tty.c_cc[VTIME] = 0;
355
356             tcsetattr (0, TCSANOW, &tty);
357         }
358         signal(SIGQUIT, sigterm_handler); /* Quit (POSIX).  */
359     }
360 #endif
361     avformat_network_deinit();
362
363     signal(SIGINT , sigterm_handler); /* Interrupt (ANSI).    */
364     signal(SIGTERM, sigterm_handler); /* Termination (ANSI).  */
365 #ifdef SIGXCPU
366     signal(SIGXCPU, sigterm_handler);
367 #endif
368 }
369
370 /* read a key without blocking */
371 static int read_key(void)
372 {
373     unsigned char ch;
374 #if HAVE_TERMIOS_H
375     int n = 1;
376     struct timeval tv;
377     fd_set rfds;
378
379     FD_ZERO(&rfds);
380     FD_SET(0, &rfds);
381     tv.tv_sec = 0;
382     tv.tv_usec = 0;
383     n = select(1, &rfds, NULL, NULL, &tv);
384     if (n > 0) {
385         n = read(0, &ch, 1);
386         if (n == 1)
387             return ch;
388
389         return n;
390     }
391 #elif HAVE_KBHIT
392 #    if HAVE_PEEKNAMEDPIPE
393     static int is_pipe;
394     static HANDLE input_handle;
395     DWORD dw, nchars;
396     if(!input_handle){
397         input_handle = GetStdHandle(STD_INPUT_HANDLE);
398         is_pipe = !GetConsoleMode(input_handle, &dw);
399     }
400
401     if (stdin->_cnt > 0) {
402         read(0, &ch, 1);
403         return ch;
404     }
405     if (is_pipe) {
406         /* When running under a GUI, you will end here. */
407         if (!PeekNamedPipe(input_handle, NULL, 0, NULL, &nchars, NULL)) {
408             // input pipe may have been closed by the program that ran ffmpeg
409             return -1;
410         }
411         //Read it
412         if(nchars != 0) {
413             read(0, &ch, 1);
414             return ch;
415         }else{
416             return -1;
417         }
418     }
419 #    endif
420     if(kbhit())
421         return(getch());
422 #endif
423     return -1;
424 }
425
426 static int decode_interrupt_cb(void *ctx)
427 {
428     return received_nb_signals > 1;
429 }
430
431 const AVIOInterruptCB int_cb = { decode_interrupt_cb, NULL };
432
433 static void ffmpeg_cleanup(int ret)
434 {
435     int i, j;
436
437     if (do_benchmark) {
438         int maxrss = getmaxrss() / 1024;
439         printf("bench: maxrss=%ikB\n", maxrss);
440     }
441
442     for (i = 0; i < nb_filtergraphs; i++) {
443         avfilter_graph_free(&filtergraphs[i]->graph);
444         for (j = 0; j < filtergraphs[i]->nb_inputs; j++) {
445             av_freep(&filtergraphs[i]->inputs[j]->name);
446             av_freep(&filtergraphs[i]->inputs[j]);
447         }
448         av_freep(&filtergraphs[i]->inputs);
449         for (j = 0; j < filtergraphs[i]->nb_outputs; j++) {
450             av_freep(&filtergraphs[i]->outputs[j]->name);
451             av_freep(&filtergraphs[i]->outputs[j]);
452         }
453         av_freep(&filtergraphs[i]->outputs);
454         av_freep(&filtergraphs[i]->graph_desc);
455         av_freep(&filtergraphs[i]);
456     }
457     av_freep(&filtergraphs);
458
459     av_freep(&subtitle_out);
460
461     /* close files */
462     for (i = 0; i < nb_output_files; i++) {
463         AVFormatContext *s = output_files[i]->ctx;
464         if (s && s->oformat && !(s->oformat->flags & AVFMT_NOFILE) && s->pb)
465             avio_close(s->pb);
466         avformat_free_context(s);
467         av_dict_free(&output_files[i]->opts);
468         av_freep(&output_files[i]);
469     }
470     for (i = 0; i < nb_output_streams; i++) {
471         AVBitStreamFilterContext *bsfc = output_streams[i]->bitstream_filters;
472         while (bsfc) {
473             AVBitStreamFilterContext *next = bsfc->next;
474             av_bitstream_filter_close(bsfc);
475             bsfc = next;
476         }
477         output_streams[i]->bitstream_filters = NULL;
478         av_frame_free(&output_streams[i]->filtered_frame);
479
480         av_parser_close(output_streams[i]->parser);
481
482         av_freep(&output_streams[i]->forced_keyframes);
483         av_expr_free(output_streams[i]->forced_keyframes_pexpr);
484         av_freep(&output_streams[i]->avfilter);
485         av_freep(&output_streams[i]->logfile_prefix);
486         av_freep(&output_streams[i]);
487     }
488 #if HAVE_PTHREADS
489     free_input_threads();
490 #endif
491     for (i = 0; i < nb_input_files; i++) {
492         avformat_close_input(&input_files[i]->ctx);
493         av_freep(&input_files[i]);
494     }
495     for (i = 0; i < nb_input_streams; i++) {
496         av_frame_free(&input_streams[i]->decoded_frame);
497         av_frame_free(&input_streams[i]->filter_frame);
498         av_dict_free(&input_streams[i]->opts);
499         avsubtitle_free(&input_streams[i]->prev_sub.subtitle);
500         av_frame_free(&input_streams[i]->sub2video.frame);
501         av_freep(&input_streams[i]->filters);
502         av_freep(&input_streams[i]->hwaccel_device);
503         av_freep(&input_streams[i]);
504     }
505
506     if (vstats_file)
507         fclose(vstats_file);
508     av_free(vstats_filename);
509
510     av_freep(&input_streams);
511     av_freep(&input_files);
512     av_freep(&output_streams);
513     av_freep(&output_files);
514
515     uninit_opts();
516
517     avformat_network_deinit();
518
519     if (received_sigterm) {
520         av_log(NULL, AV_LOG_INFO, "Received signal %d: terminating.\n",
521                (int) received_sigterm);
522     }
523     term_exit();
524 }
525
526 void assert_avoptions(AVDictionary *m)
527 {
528     AVDictionaryEntry *t;
529     if ((t = av_dict_get(m, "", NULL, AV_DICT_IGNORE_SUFFIX))) {
530         av_log(NULL, AV_LOG_FATAL, "Option %s not found.\n", t->key);
531         exit_program(1);
532     }
533 }
534
535 static void abort_codec_experimental(AVCodec *c, int encoder)
536 {
537     exit_program(1);
538 }
539
540 static void update_benchmark(const char *fmt, ...)
541 {
542     if (do_benchmark_all) {
543         int64_t t = getutime();
544         va_list va;
545         char buf[1024];
546
547         if (fmt) {
548             va_start(va, fmt);
549             vsnprintf(buf, sizeof(buf), fmt, va);
550             va_end(va);
551             printf("bench: %8"PRIu64" %s \n", t - current_time, buf);
552         }
553         current_time = t;
554     }
555 }
556
557 static void close_all_output_streams(OutputStream *ost, OSTFinished this_stream, OSTFinished others)
558 {
559     int i;
560     for (i = 0; i < nb_output_streams; i++) {
561         OutputStream *ost2 = output_streams[i];
562         ost2->finished |= ost == ost2 ? this_stream : others;
563     }
564 }
565
566 static void write_frame(AVFormatContext *s, AVPacket *pkt, OutputStream *ost)
567 {
568     AVBitStreamFilterContext *bsfc = ost->bitstream_filters;
569     AVCodecContext          *avctx = ost->st->codec;
570     int ret;
571
572     if ((avctx->codec_type == AVMEDIA_TYPE_VIDEO && video_sync_method == VSYNC_DROP) ||
573         (avctx->codec_type == AVMEDIA_TYPE_AUDIO && audio_sync_method < 0))
574         pkt->pts = pkt->dts = AV_NOPTS_VALUE;
575
576     /*
577      * Audio encoders may split the packets --  #frames in != #packets out.
578      * But there is no reordering, so we can limit the number of output packets
579      * by simply dropping them here.
580      * Counting encoded video frames needs to be done separately because of
581      * reordering, see do_video_out()
582      */
583     if (!(avctx->codec_type == AVMEDIA_TYPE_VIDEO && avctx->codec)) {
584         if (ost->frame_number >= ost->max_frames) {
585             av_free_packet(pkt);
586             return;
587         }
588         ost->frame_number++;
589     }
590
591     while (bsfc) {
592         AVPacket new_pkt = *pkt;
593         int a = av_bitstream_filter_filter(bsfc, avctx, NULL,
594                                            &new_pkt.data, &new_pkt.size,
595                                            pkt->data, pkt->size,
596                                            pkt->flags & AV_PKT_FLAG_KEY);
597         if(a == 0 && new_pkt.data != pkt->data && new_pkt.destruct) {
598             uint8_t *t = av_malloc(new_pkt.size + FF_INPUT_BUFFER_PADDING_SIZE); //the new should be a subset of the old so cannot overflow
599             if(t) {
600                 memcpy(t, new_pkt.data, new_pkt.size);
601                 memset(t + new_pkt.size, 0, FF_INPUT_BUFFER_PADDING_SIZE);
602                 new_pkt.data = t;
603                 new_pkt.buf = NULL;
604                 a = 1;
605             } else
606                 a = AVERROR(ENOMEM);
607         }
608         if (a > 0) {
609             av_free_packet(pkt);
610             new_pkt.buf = av_buffer_create(new_pkt.data, new_pkt.size,
611                                            av_buffer_default_free, NULL, 0);
612             if (!new_pkt.buf)
613                 exit_program(1);
614         } else if (a < 0) {
615             av_log(NULL, AV_LOG_ERROR, "Failed to open bitstream filter %s for stream %d with codec %s",
616                    bsfc->filter->name, pkt->stream_index,
617                    avctx->codec ? avctx->codec->name : "copy");
618             print_error("", a);
619             if (exit_on_error)
620                 exit_program(1);
621         }
622         *pkt = new_pkt;
623
624         bsfc = bsfc->next;
625     }
626
627     if (!(s->oformat->flags & AVFMT_NOTIMESTAMPS) &&
628         (avctx->codec_type == AVMEDIA_TYPE_AUDIO || avctx->codec_type == AVMEDIA_TYPE_VIDEO) &&
629         pkt->dts != AV_NOPTS_VALUE &&
630         ost->last_mux_dts != AV_NOPTS_VALUE) {
631       int64_t max = ost->last_mux_dts + !(s->oformat->flags & AVFMT_TS_NONSTRICT);
632       if (pkt->dts < max) {
633         int loglevel = max - pkt->dts > 2 || avctx->codec_type == AVMEDIA_TYPE_VIDEO ? AV_LOG_WARNING : AV_LOG_DEBUG;
634         av_log(s, loglevel, "Non-monotonous DTS in output stream "
635                "%d:%d; previous: %"PRId64", current: %"PRId64"; ",
636                ost->file_index, ost->st->index, ost->last_mux_dts, pkt->dts);
637         if (exit_on_error) {
638             av_log(NULL, AV_LOG_FATAL, "aborting.\n");
639             exit_program(1);
640         }
641         av_log(s, loglevel, "changing to %"PRId64". This may result "
642                "in incorrect timestamps in the output file.\n",
643                max);
644         if(pkt->pts >= pkt->dts)
645             pkt->pts = FFMAX(pkt->pts, max);
646         pkt->dts = max;
647       }
648     }
649     ost->last_mux_dts = pkt->dts;
650
651     pkt->stream_index = ost->index;
652
653     if (debug_ts) {
654         av_log(NULL, AV_LOG_INFO, "muxer <- type:%s "
655                 "pkt_pts:%s pkt_pts_time:%s pkt_dts:%s pkt_dts_time:%s size:%d\n",
656                 av_get_media_type_string(ost->st->codec->codec_type),
657                 av_ts2str(pkt->pts), av_ts2timestr(pkt->pts, &ost->st->time_base),
658                 av_ts2str(pkt->dts), av_ts2timestr(pkt->dts, &ost->st->time_base),
659                 pkt->size
660               );
661     }
662
663     ret = av_interleaved_write_frame(s, pkt);
664     if (ret < 0) {
665         print_error("av_interleaved_write_frame()", ret);
666         main_return_code = 1;
667         close_all_output_streams(ost, MUXER_FINISHED | ENCODER_FINISHED, ENCODER_FINISHED);
668     }
669 }
670
671 static void close_output_stream(OutputStream *ost)
672 {
673     OutputFile *of = output_files[ost->file_index];
674
675     ost->finished |= ENCODER_FINISHED;
676     if (of->shortest) {
677         int64_t end = av_rescale_q(ost->sync_opts - ost->first_pts, ost->st->codec->time_base, AV_TIME_BASE_Q);
678         of->recording_time = FFMIN(of->recording_time, end);
679     }
680 }
681
682 static int check_recording_time(OutputStream *ost)
683 {
684     OutputFile *of = output_files[ost->file_index];
685
686     if (of->recording_time != INT64_MAX &&
687         av_compare_ts(ost->sync_opts - ost->first_pts, ost->st->codec->time_base, of->recording_time,
688                       AV_TIME_BASE_Q) >= 0) {
689         close_output_stream(ost);
690         return 0;
691     }
692     return 1;
693 }
694
695 static void do_audio_out(AVFormatContext *s, OutputStream *ost,
696                          AVFrame *frame)
697 {
698     AVCodecContext *enc = ost->st->codec;
699     AVPacket pkt;
700     int got_packet = 0;
701
702     av_init_packet(&pkt);
703     pkt.data = NULL;
704     pkt.size = 0;
705
706     if (!check_recording_time(ost))
707         return;
708
709     if (frame->pts == AV_NOPTS_VALUE || audio_sync_method < 0)
710         frame->pts = ost->sync_opts;
711     ost->sync_opts = frame->pts + frame->nb_samples;
712
713     av_assert0(pkt.size || !pkt.data);
714     update_benchmark(NULL);
715     if (debug_ts) {
716         av_log(NULL, AV_LOG_INFO, "encoder <- type:audio "
717                "frame_pts:%s frame_pts_time:%s time_base:%d/%d\n",
718                av_ts2str(frame->pts), av_ts2timestr(frame->pts, &enc->time_base),
719                enc->time_base.num, enc->time_base.den);
720     }
721     if (avcodec_encode_audio2(enc, &pkt, frame, &got_packet) < 0) {
722         av_log(NULL, AV_LOG_FATAL, "Audio encoding failed (avcodec_encode_audio2)\n");
723         exit_program(1);
724     }
725     update_benchmark("encode_audio %d.%d", ost->file_index, ost->index);
726
727     if (got_packet) {
728         if (pkt.pts != AV_NOPTS_VALUE)
729             pkt.pts      = av_rescale_q(pkt.pts,      enc->time_base, ost->st->time_base);
730         if (pkt.dts != AV_NOPTS_VALUE)
731             pkt.dts      = av_rescale_q(pkt.dts,      enc->time_base, ost->st->time_base);
732         if (pkt.duration > 0)
733             pkt.duration = av_rescale_q(pkt.duration, enc->time_base, ost->st->time_base);
734
735         if (debug_ts) {
736             av_log(NULL, AV_LOG_INFO, "encoder -> type:audio "
737                    "pkt_pts:%s pkt_pts_time:%s pkt_dts:%s pkt_dts_time:%s\n",
738                    av_ts2str(pkt.pts), av_ts2timestr(pkt.pts, &ost->st->time_base),
739                    av_ts2str(pkt.dts), av_ts2timestr(pkt.dts, &ost->st->time_base));
740         }
741
742         audio_size += pkt.size;
743         write_frame(s, &pkt, ost);
744
745         av_free_packet(&pkt);
746     }
747 }
748
749 static void do_subtitle_out(AVFormatContext *s,
750                             OutputStream *ost,
751                             InputStream *ist,
752                             AVSubtitle *sub)
753 {
754     int subtitle_out_max_size = 1024 * 1024;
755     int subtitle_out_size, nb, i;
756     AVCodecContext *enc;
757     AVPacket pkt;
758     int64_t pts;
759
760     if (sub->pts == AV_NOPTS_VALUE) {
761         av_log(NULL, AV_LOG_ERROR, "Subtitle packets must have a pts\n");
762         if (exit_on_error)
763             exit_program(1);
764         return;
765     }
766
767     enc = ost->st->codec;
768
769     if (!subtitle_out) {
770         subtitle_out = av_malloc(subtitle_out_max_size);
771     }
772
773     /* Note: DVB subtitle need one packet to draw them and one other
774        packet to clear them */
775     /* XXX: signal it in the codec context ? */
776     if (enc->codec_id == AV_CODEC_ID_DVB_SUBTITLE)
777         nb = 2;
778     else
779         nb = 1;
780
781     /* shift timestamp to honor -ss and make check_recording_time() work with -t */
782     pts = sub->pts;
783     if (output_files[ost->file_index]->start_time != AV_NOPTS_VALUE)
784         pts -= output_files[ost->file_index]->start_time;
785     for (i = 0; i < nb; i++) {
786         ost->sync_opts = av_rescale_q(pts, AV_TIME_BASE_Q, enc->time_base);
787         if (!check_recording_time(ost))
788             return;
789
790         sub->pts = pts;
791         // start_display_time is required to be 0
792         sub->pts               += av_rescale_q(sub->start_display_time, (AVRational){ 1, 1000 }, AV_TIME_BASE_Q);
793         sub->end_display_time  -= sub->start_display_time;
794         sub->start_display_time = 0;
795         if (i == 1)
796             sub->num_rects = 0;
797         subtitle_out_size = avcodec_encode_subtitle(enc, subtitle_out,
798                                                     subtitle_out_max_size, sub);
799         if (subtitle_out_size < 0) {
800             av_log(NULL, AV_LOG_FATAL, "Subtitle encoding failed\n");
801             exit_program(1);
802         }
803
804         av_init_packet(&pkt);
805         pkt.data = subtitle_out;
806         pkt.size = subtitle_out_size;
807         pkt.pts  = av_rescale_q(sub->pts, AV_TIME_BASE_Q, ost->st->time_base);
808         pkt.duration = av_rescale_q(sub->end_display_time, (AVRational){ 1, 1000 }, ost->st->time_base);
809         if (enc->codec_id == AV_CODEC_ID_DVB_SUBTITLE) {
810             /* XXX: the pts correction is handled here. Maybe handling
811                it in the codec would be better */
812             if (i == 0)
813                 pkt.pts += 90 * sub->start_display_time;
814             else
815                 pkt.pts += 90 * sub->end_display_time;
816         }
817         subtitle_size += pkt.size;
818         write_frame(s, &pkt, ost);
819     }
820 }
821
822 static void do_video_out(AVFormatContext *s,
823                          OutputStream *ost,
824                          AVFrame *in_picture)
825 {
826     int ret, format_video_sync;
827     AVPacket pkt;
828     AVCodecContext *enc = ost->st->codec;
829     int nb_frames, i;
830     double sync_ipts, delta;
831     double duration = 0;
832     int frame_size = 0;
833     InputStream *ist = NULL;
834
835     if (ost->source_index >= 0)
836         ist = input_streams[ost->source_index];
837
838     if(ist && ist->st->start_time != AV_NOPTS_VALUE && ist->st->first_dts != AV_NOPTS_VALUE && ost->frame_rate.num)
839         duration = 1/(av_q2d(ost->frame_rate) * av_q2d(enc->time_base));
840
841     sync_ipts = in_picture->pts;
842     delta = sync_ipts - ost->sync_opts + duration;
843
844     /* by default, we output a single frame */
845     nb_frames = 1;
846
847     format_video_sync = video_sync_method;
848     if (format_video_sync == VSYNC_AUTO) {
849         if(!strcmp(s->oformat->name, "avi")) {
850             format_video_sync = VSYNC_VFR;
851         } else
852             format_video_sync = (s->oformat->flags & AVFMT_VARIABLE_FPS) ? ((s->oformat->flags & AVFMT_NOTIMESTAMPS) ? VSYNC_PASSTHROUGH : VSYNC_VFR) : VSYNC_CFR;
853         if (   ist
854             && format_video_sync == VSYNC_CFR
855             && input_files[ist->file_index]->ctx->nb_streams == 1
856             && input_files[ist->file_index]->input_ts_offset == 0) {
857             format_video_sync = VSYNC_VSCFR;
858         }
859         if (format_video_sync == VSYNC_CFR && copy_ts) {
860             format_video_sync = VSYNC_VSCFR;
861         }
862     }
863
864     switch (format_video_sync) {
865     case VSYNC_VSCFR:
866         if (ost->frame_number == 0 && delta - duration >= 0.5) {
867             av_log(NULL, AV_LOG_DEBUG, "Not duplicating %d initial frames\n", (int)lrintf(delta - duration));
868             delta = duration;
869             ost->sync_opts = lrint(sync_ipts);
870         }
871     case VSYNC_CFR:
872         // FIXME set to 0.5 after we fix some dts/pts bugs like in avidec.c
873         if (delta < -1.1)
874             nb_frames = 0;
875         else if (delta > 1.1)
876             nb_frames = lrintf(delta);
877         break;
878     case VSYNC_VFR:
879         if (delta <= -0.6)
880             nb_frames = 0;
881         else if (delta > 0.6)
882             ost->sync_opts = lrint(sync_ipts);
883         break;
884     case VSYNC_DROP:
885     case VSYNC_PASSTHROUGH:
886         ost->sync_opts = lrint(sync_ipts);
887         break;
888     default:
889         av_assert0(0);
890     }
891
892     nb_frames = FFMIN(nb_frames, ost->max_frames - ost->frame_number);
893     if (nb_frames == 0) {
894         nb_frames_drop++;
895         av_log(NULL, AV_LOG_VERBOSE, "*** drop!\n");
896         return;
897     } else if (nb_frames > 1) {
898         if (nb_frames > dts_error_threshold * 30) {
899             av_log(NULL, AV_LOG_ERROR, "%d frame duplication too large, skipping\n", nb_frames - 1);
900             nb_frames_drop++;
901             return;
902         }
903         nb_frames_dup += nb_frames - 1;
904         av_log(NULL, AV_LOG_VERBOSE, "*** %d dup!\n", nb_frames - 1);
905     }
906
907   /* duplicates frame if needed */
908   for (i = 0; i < nb_frames; i++) {
909     av_init_packet(&pkt);
910     pkt.data = NULL;
911     pkt.size = 0;
912
913     in_picture->pts = ost->sync_opts;
914
915 #if 1
916     if (!check_recording_time(ost))
917 #else
918     if (ost->frame_number >= ost->max_frames)
919 #endif
920         return;
921
922     if (s->oformat->flags & AVFMT_RAWPICTURE &&
923         enc->codec->id == AV_CODEC_ID_RAWVIDEO) {
924         /* raw pictures are written as AVPicture structure to
925            avoid any copies. We support temporarily the older
926            method. */
927         enc->coded_frame->interlaced_frame = in_picture->interlaced_frame;
928         enc->coded_frame->top_field_first  = in_picture->top_field_first;
929         if (enc->coded_frame->interlaced_frame)
930             enc->field_order = enc->coded_frame->top_field_first ? AV_FIELD_TB:AV_FIELD_BT;
931         else
932             enc->field_order = AV_FIELD_PROGRESSIVE;
933         pkt.data   = (uint8_t *)in_picture;
934         pkt.size   =  sizeof(AVPicture);
935         pkt.pts    = av_rescale_q(in_picture->pts, enc->time_base, ost->st->time_base);
936         pkt.flags |= AV_PKT_FLAG_KEY;
937
938         video_size += pkt.size;
939         write_frame(s, &pkt, ost);
940     } else {
941         int got_packet, forced_keyframe = 0;
942         double pts_time;
943
944         if (ost->st->codec->flags & (CODEC_FLAG_INTERLACED_DCT|CODEC_FLAG_INTERLACED_ME) &&
945             ost->top_field_first >= 0)
946             in_picture->top_field_first = !!ost->top_field_first;
947
948         if (in_picture->interlaced_frame) {
949             if (enc->codec->id == AV_CODEC_ID_MJPEG)
950                 enc->field_order = in_picture->top_field_first ? AV_FIELD_TT:AV_FIELD_BB;
951             else
952                 enc->field_order = in_picture->top_field_first ? AV_FIELD_TB:AV_FIELD_BT;
953         } else
954             enc->field_order = AV_FIELD_PROGRESSIVE;
955
956         in_picture->quality = ost->st->codec->global_quality;
957         if (!enc->me_threshold)
958             in_picture->pict_type = 0;
959
960         pts_time = in_picture->pts != AV_NOPTS_VALUE ?
961             in_picture->pts * av_q2d(enc->time_base) : NAN;
962         if (ost->forced_kf_index < ost->forced_kf_count &&
963             in_picture->pts >= ost->forced_kf_pts[ost->forced_kf_index]) {
964             ost->forced_kf_index++;
965             forced_keyframe = 1;
966         } else if (ost->forced_keyframes_pexpr) {
967             double res;
968             ost->forced_keyframes_expr_const_values[FKF_T] = pts_time;
969             res = av_expr_eval(ost->forced_keyframes_pexpr,
970                                ost->forced_keyframes_expr_const_values, NULL);
971             av_dlog(NULL, "force_key_frame: n:%f n_forced:%f prev_forced_n:%f t:%f prev_forced_t:%f -> res:%f\n",
972                     ost->forced_keyframes_expr_const_values[FKF_N],
973                     ost->forced_keyframes_expr_const_values[FKF_N_FORCED],
974                     ost->forced_keyframes_expr_const_values[FKF_PREV_FORCED_N],
975                     ost->forced_keyframes_expr_const_values[FKF_T],
976                     ost->forced_keyframes_expr_const_values[FKF_PREV_FORCED_T],
977                     res);
978             if (res) {
979                 forced_keyframe = 1;
980                 ost->forced_keyframes_expr_const_values[FKF_PREV_FORCED_N] =
981                     ost->forced_keyframes_expr_const_values[FKF_N];
982                 ost->forced_keyframes_expr_const_values[FKF_PREV_FORCED_T] =
983                     ost->forced_keyframes_expr_const_values[FKF_T];
984                 ost->forced_keyframes_expr_const_values[FKF_N_FORCED] += 1;
985             }
986
987             ost->forced_keyframes_expr_const_values[FKF_N] += 1;
988         }
989         if (forced_keyframe) {
990             in_picture->pict_type = AV_PICTURE_TYPE_I;
991             av_log(NULL, AV_LOG_DEBUG, "Forced keyframe at time %f\n", pts_time);
992         }
993
994         update_benchmark(NULL);
995         if (debug_ts) {
996             av_log(NULL, AV_LOG_INFO, "encoder <- type:video "
997                    "frame_pts:%s frame_pts_time:%s time_base:%d/%d\n",
998                    av_ts2str(in_picture->pts), av_ts2timestr(in_picture->pts, &enc->time_base),
999                    enc->time_base.num, enc->time_base.den);
1000         }
1001
1002         ret = avcodec_encode_video2(enc, &pkt, in_picture, &got_packet);
1003         update_benchmark("encode_video %d.%d", ost->file_index, ost->index);
1004         if (ret < 0) {
1005             av_log(NULL, AV_LOG_FATAL, "Video encoding failed\n");
1006             exit_program(1);
1007         }
1008
1009         if (got_packet) {
1010             if (debug_ts) {
1011                 av_log(NULL, AV_LOG_INFO, "encoder -> type:video "
1012                        "pkt_pts:%s pkt_pts_time:%s pkt_dts:%s pkt_dts_time:%s\n",
1013                        av_ts2str(pkt.pts), av_ts2timestr(pkt.pts, &enc->time_base),
1014                        av_ts2str(pkt.dts), av_ts2timestr(pkt.dts, &enc->time_base));
1015             }
1016
1017             if (pkt.pts == AV_NOPTS_VALUE && !(enc->codec->capabilities & CODEC_CAP_DELAY))
1018                 pkt.pts = ost->sync_opts;
1019
1020             if (pkt.pts != AV_NOPTS_VALUE)
1021                 pkt.pts = av_rescale_q(pkt.pts, enc->time_base, ost->st->time_base);
1022             if (pkt.dts != AV_NOPTS_VALUE)
1023                 pkt.dts = av_rescale_q(pkt.dts, enc->time_base, ost->st->time_base);
1024
1025             if (debug_ts) {
1026                 av_log(NULL, AV_LOG_INFO, "encoder -> type:video "
1027                     "pkt_pts:%s pkt_pts_time:%s pkt_dts:%s pkt_dts_time:%s\n",
1028                     av_ts2str(pkt.pts), av_ts2timestr(pkt.pts, &ost->st->time_base),
1029                     av_ts2str(pkt.dts), av_ts2timestr(pkt.dts, &ost->st->time_base));
1030             }
1031
1032             frame_size = pkt.size;
1033             video_size += pkt.size;
1034             write_frame(s, &pkt, ost);
1035             av_free_packet(&pkt);
1036
1037             /* if two pass, output log */
1038             if (ost->logfile && enc->stats_out) {
1039                 fprintf(ost->logfile, "%s", enc->stats_out);
1040             }
1041         }
1042     }
1043     ost->sync_opts++;
1044     /*
1045      * For video, number of frames in == number of packets out.
1046      * But there may be reordering, so we can't throw away frames on encoder
1047      * flush, we need to limit them here, before they go into encoder.
1048      */
1049     ost->frame_number++;
1050
1051     if (vstats_filename && frame_size)
1052         do_video_stats(ost, frame_size);
1053   }
1054 }
1055
1056 static double psnr(double d)
1057 {
1058     return -10.0 * log(d) / log(10.0);
1059 }
1060
1061 static void do_video_stats(OutputStream *ost, int frame_size)
1062 {
1063     AVCodecContext *enc;
1064     int frame_number;
1065     double ti1, bitrate, avg_bitrate;
1066
1067     /* this is executed just the first time do_video_stats is called */
1068     if (!vstats_file) {
1069         vstats_file = fopen(vstats_filename, "w");
1070         if (!vstats_file) {
1071             perror("fopen");
1072             exit_program(1);
1073         }
1074     }
1075
1076     enc = ost->st->codec;
1077     if (enc->codec_type == AVMEDIA_TYPE_VIDEO) {
1078         frame_number = ost->st->nb_frames;
1079         fprintf(vstats_file, "frame= %5d q= %2.1f ", frame_number, enc->coded_frame->quality / (float)FF_QP2LAMBDA);
1080         if (enc->flags&CODEC_FLAG_PSNR)
1081             fprintf(vstats_file, "PSNR= %6.2f ", psnr(enc->coded_frame->error[0] / (enc->width * enc->height * 255.0 * 255.0)));
1082
1083         fprintf(vstats_file,"f_size= %6d ", frame_size);
1084         /* compute pts value */
1085         ti1 = ost->st->pts.val * av_q2d(enc->time_base);
1086         if (ti1 < 0.01)
1087             ti1 = 0.01;
1088
1089         bitrate     = (frame_size * 8) / av_q2d(enc->time_base) / 1000.0;
1090         avg_bitrate = (double)(video_size * 8) / ti1 / 1000.0;
1091         fprintf(vstats_file, "s_size= %8.0fkB time= %0.3f br= %7.1fkbits/s avg_br= %7.1fkbits/s ",
1092                (double)video_size / 1024, ti1, bitrate, avg_bitrate);
1093         fprintf(vstats_file, "type= %c\n", av_get_picture_type_char(enc->coded_frame->pict_type));
1094     }
1095 }
1096
1097 /**
1098  * Get and encode new output from any of the filtergraphs, without causing
1099  * activity.
1100  *
1101  * @return  0 for success, <0 for severe errors
1102  */
1103 static int reap_filters(void)
1104 {
1105     AVFrame *filtered_frame = NULL;
1106     int i;
1107     int64_t frame_pts;
1108
1109     /* Reap all buffers present in the buffer sinks */
1110     for (i = 0; i < nb_output_streams; i++) {
1111         OutputStream *ost = output_streams[i];
1112         OutputFile    *of = output_files[ost->file_index];
1113         AVFilterContext *filter;
1114         AVCodecContext *enc = ost->st->codec;
1115         int ret = 0;
1116
1117         if (!ost->filter)
1118             continue;
1119         filter = ost->filter->filter;
1120
1121         if (!ost->filtered_frame && !(ost->filtered_frame = av_frame_alloc())) {
1122             return AVERROR(ENOMEM);
1123         }
1124         filtered_frame = ost->filtered_frame;
1125
1126         while (1) {
1127             ret = av_buffersink_get_frame_flags(filter, filtered_frame,
1128                                                AV_BUFFERSINK_FLAG_NO_REQUEST);
1129             if (ret < 0) {
1130                 if (ret != AVERROR(EAGAIN) && ret != AVERROR_EOF) {
1131                     av_log(NULL, AV_LOG_WARNING,
1132                            "Error in av_buffersink_get_frame_flags(): %s\n", av_err2str(ret));
1133                 }
1134                 break;
1135             }
1136             if (ost->finished) {
1137                 av_frame_unref(filtered_frame);
1138                 continue;
1139             }
1140             frame_pts = AV_NOPTS_VALUE;
1141             if (filtered_frame->pts != AV_NOPTS_VALUE) {
1142                 int64_t start_time = (of->start_time == AV_NOPTS_VALUE) ? 0 : of->start_time;
1143                 filtered_frame->pts = frame_pts =
1144                     av_rescale_q(filtered_frame->pts, filter->inputs[0]->time_base, enc->time_base) -
1145                     av_rescale_q(start_time, AV_TIME_BASE_Q, enc->time_base);
1146             }
1147             //if (ost->source_index >= 0)
1148             //    *filtered_frame= *input_streams[ost->source_index]->decoded_frame; //for me_threshold
1149
1150             switch (filter->inputs[0]->type) {
1151             case AVMEDIA_TYPE_VIDEO:
1152                 filtered_frame->pts = frame_pts;
1153                 if (!ost->frame_aspect_ratio.num)
1154                     enc->sample_aspect_ratio = filtered_frame->sample_aspect_ratio;
1155
1156                 if (debug_ts) {
1157                     av_log(NULL, AV_LOG_INFO, "filter -> pts:%s pts_time:%s time_base:%d/%d\n",
1158                             av_ts2str(filtered_frame->pts), av_ts2timestr(filtered_frame->pts, &enc->time_base),
1159                             enc->time_base.num, enc->time_base.den);
1160                 }
1161
1162                 do_video_out(of->ctx, ost, filtered_frame);
1163                 break;
1164             case AVMEDIA_TYPE_AUDIO:
1165                 filtered_frame->pts = frame_pts;
1166                 if (!(enc->codec->capabilities & CODEC_CAP_PARAM_CHANGE) &&
1167                     enc->channels != av_frame_get_channels(filtered_frame)) {
1168                     av_log(NULL, AV_LOG_ERROR,
1169                            "Audio filter graph output is not normalized and encoder does not support parameter changes\n");
1170                     break;
1171                 }
1172                 do_audio_out(of->ctx, ost, filtered_frame);
1173                 break;
1174             default:
1175                 // TODO support subtitle filters
1176                 av_assert0(0);
1177             }
1178
1179             av_frame_unref(filtered_frame);
1180         }
1181     }
1182
1183     return 0;
1184 }
1185
1186 static void print_report(int is_last_report, int64_t timer_start, int64_t cur_time)
1187 {
1188     char buf[1024];
1189     AVBPrint buf_script;
1190     OutputStream *ost;
1191     AVFormatContext *oc;
1192     int64_t total_size;
1193     AVCodecContext *enc;
1194     int frame_number, vid, i;
1195     double bitrate;
1196     int64_t pts = INT64_MIN;
1197     static int64_t last_time = -1;
1198     static int qp_histogram[52];
1199     int hours, mins, secs, us;
1200
1201     if (!print_stats && !is_last_report && !progress_avio)
1202         return;
1203
1204     if (!is_last_report) {
1205         if (last_time == -1) {
1206             last_time = cur_time;
1207             return;
1208         }
1209         if ((cur_time - last_time) < 500000)
1210             return;
1211         last_time = cur_time;
1212     }
1213
1214
1215     oc = output_files[0]->ctx;
1216
1217     total_size = avio_size(oc->pb);
1218     if (total_size <= 0) // FIXME improve avio_size() so it works with non seekable output too
1219         total_size = avio_tell(oc->pb);
1220
1221     buf[0] = '\0';
1222     vid = 0;
1223     av_bprint_init(&buf_script, 0, 1);
1224     for (i = 0; i < nb_output_streams; i++) {
1225         float q = -1;
1226         ost = output_streams[i];
1227         enc = ost->st->codec;
1228         if (!ost->stream_copy && enc->coded_frame)
1229             q = enc->coded_frame->quality / (float)FF_QP2LAMBDA;
1230         if (vid && enc->codec_type == AVMEDIA_TYPE_VIDEO) {
1231             snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "q=%2.1f ", q);
1232             av_bprintf(&buf_script, "stream_%d_%d_q=%.1f\n",
1233                        ost->file_index, ost->index, q);
1234         }
1235         if (!vid && enc->codec_type == AVMEDIA_TYPE_VIDEO) {
1236             float fps, t = (cur_time-timer_start) / 1000000.0;
1237
1238             frame_number = ost->frame_number;
1239             fps = t > 1 ? frame_number / t : 0;
1240             snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "frame=%5d fps=%3.*f q=%3.1f ",
1241                      frame_number, fps < 9.95, fps, q);
1242             av_bprintf(&buf_script, "frame=%d\n", frame_number);
1243             av_bprintf(&buf_script, "fps=%.1f\n", fps);
1244             av_bprintf(&buf_script, "stream_%d_%d_q=%.1f\n",
1245                        ost->file_index, ost->index, q);
1246             if (is_last_report)
1247                 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "L");
1248             if (qp_hist) {
1249                 int j;
1250                 int qp = lrintf(q);
1251                 if (qp >= 0 && qp < FF_ARRAY_ELEMS(qp_histogram))
1252                     qp_histogram[qp]++;
1253                 for (j = 0; j < 32; j++)
1254                     snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "%X", (int)lrintf(log2(qp_histogram[j] + 1)));
1255             }
1256             if ((enc->flags&CODEC_FLAG_PSNR) && (enc->coded_frame || is_last_report)) {
1257                 int j;
1258                 double error, error_sum = 0;
1259                 double scale, scale_sum = 0;
1260                 double p;
1261                 char type[3] = { 'Y','U','V' };
1262                 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "PSNR=");
1263                 for (j = 0; j < 3; j++) {
1264                     if (is_last_report) {
1265                         error = enc->error[j];
1266                         scale = enc->width * enc->height * 255.0 * 255.0 * frame_number;
1267                     } else {
1268                         error = enc->coded_frame->error[j];
1269                         scale = enc->width * enc->height * 255.0 * 255.0;
1270                     }
1271                     if (j)
1272                         scale /= 4;
1273                     error_sum += error;
1274                     scale_sum += scale;
1275                     p = psnr(error / scale);
1276                     snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "%c:%2.2f ", type[j], p);
1277                     av_bprintf(&buf_script, "stream_%d_%d_psnr_%c=%2.2f\n",
1278                                ost->file_index, ost->index, type[j] | 32, p);
1279                 }
1280                 p = psnr(error_sum / scale_sum);
1281                 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "*:%2.2f ", psnr(error_sum / scale_sum));
1282                 av_bprintf(&buf_script, "stream_%d_%d_psnr_all=%2.2f\n",
1283                            ost->file_index, ost->index, p);
1284             }
1285             vid = 1;
1286         }
1287         /* compute min output value */
1288         if (ost->st->pts.val != AV_NOPTS_VALUE)
1289             pts = FFMAX(pts, av_rescale_q(ost->st->pts.val,
1290                                           ost->st->time_base, AV_TIME_BASE_Q));
1291     }
1292
1293     secs = pts / AV_TIME_BASE;
1294     us = pts % AV_TIME_BASE;
1295     mins = secs / 60;
1296     secs %= 60;
1297     hours = mins / 60;
1298     mins %= 60;
1299
1300     bitrate = pts && total_size >= 0 ? total_size * 8 / (pts / 1000.0) : -1;
1301
1302     if (total_size < 0) snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
1303                                  "size=N/A time=");
1304     else                snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
1305                                  "size=%8.0fkB time=", total_size / 1024.0);
1306     snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
1307              "%02d:%02d:%02d.%02d ", hours, mins, secs,
1308              (100 * us) / AV_TIME_BASE);
1309     if (bitrate < 0) snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
1310                               "bitrate=N/A");
1311     else             snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
1312                               "bitrate=%6.1fkbits/s", bitrate);
1313     if (total_size < 0) av_bprintf(&buf_script, "total_size=N/A\n");
1314     else                av_bprintf(&buf_script, "total_size=%"PRId64"\n", total_size);
1315     av_bprintf(&buf_script, "out_time_ms=%"PRId64"\n", pts);
1316     av_bprintf(&buf_script, "out_time=%02d:%02d:%02d.%06d\n",
1317                hours, mins, secs, us);
1318
1319     if (nb_frames_dup || nb_frames_drop)
1320         snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), " dup=%d drop=%d",
1321                 nb_frames_dup, nb_frames_drop);
1322     av_bprintf(&buf_script, "dup_frames=%d\n", nb_frames_dup);
1323     av_bprintf(&buf_script, "drop_frames=%d\n", nb_frames_drop);
1324
1325     if (print_stats || is_last_report) {
1326         if (print_stats==1 && AV_LOG_INFO > av_log_get_level()) {
1327             fprintf(stderr, "%s    \r", buf);
1328         } else
1329             av_log(NULL, AV_LOG_INFO, "%s    \r", buf);
1330
1331     fflush(stderr);
1332     }
1333
1334     if (progress_avio) {
1335         av_bprintf(&buf_script, "progress=%s\n",
1336                    is_last_report ? "end" : "continue");
1337         avio_write(progress_avio, buf_script.str,
1338                    FFMIN(buf_script.len, buf_script.size - 1));
1339         avio_flush(progress_avio);
1340         av_bprint_finalize(&buf_script, NULL);
1341         if (is_last_report) {
1342             avio_close(progress_avio);
1343             progress_avio = NULL;
1344         }
1345     }
1346
1347     if (is_last_report) {
1348         int64_t raw   = audio_size + video_size + data_size + subtitle_size + extra_size;
1349         float percent = 0.0;
1350
1351         if (raw)
1352             percent = 100.0 * (total_size - raw) / raw;
1353
1354         av_log(NULL, AV_LOG_INFO, "\n");
1355         av_log(NULL, AV_LOG_INFO, "video:%1.0fkB audio:%1.0fkB subtitle:%1.0f data:%1.0f global headers:%1.0fkB muxing overhead %f%%\n",
1356                video_size / 1024.0,
1357                audio_size / 1024.0,
1358                subtitle_size / 1024.0,
1359                data_size / 1024.0,
1360                extra_size / 1024.0,
1361                percent);
1362         if(video_size + data_size + audio_size + subtitle_size + extra_size == 0){
1363             av_log(NULL, AV_LOG_WARNING, "Output file is empty, nothing was encoded (check -ss / -t / -frames parameters if used)\n");
1364         }
1365     }
1366 }
1367
1368 static void flush_encoders(void)
1369 {
1370     int i, ret;
1371
1372     for (i = 0; i < nb_output_streams; i++) {
1373         OutputStream   *ost = output_streams[i];
1374         AVCodecContext *enc = ost->st->codec;
1375         AVFormatContext *os = output_files[ost->file_index]->ctx;
1376         int stop_encoding = 0;
1377
1378         if (!ost->encoding_needed)
1379             continue;
1380
1381         if (ost->st->codec->codec_type == AVMEDIA_TYPE_AUDIO && enc->frame_size <= 1)
1382             continue;
1383         if (ost->st->codec->codec_type == AVMEDIA_TYPE_VIDEO && (os->oformat->flags & AVFMT_RAWPICTURE) && enc->codec->id == AV_CODEC_ID_RAWVIDEO)
1384             continue;
1385
1386         for (;;) {
1387             int (*encode)(AVCodecContext*, AVPacket*, const AVFrame*, int*) = NULL;
1388             const char *desc;
1389             int64_t *size;
1390
1391             switch (ost->st->codec->codec_type) {
1392             case AVMEDIA_TYPE_AUDIO:
1393                 encode = avcodec_encode_audio2;
1394                 desc   = "Audio";
1395                 size   = &audio_size;
1396                 break;
1397             case AVMEDIA_TYPE_VIDEO:
1398                 encode = avcodec_encode_video2;
1399                 desc   = "Video";
1400                 size   = &video_size;
1401                 break;
1402             default:
1403                 stop_encoding = 1;
1404             }
1405
1406             if (encode) {
1407                 AVPacket pkt;
1408                 int pkt_size;
1409                 int got_packet;
1410                 av_init_packet(&pkt);
1411                 pkt.data = NULL;
1412                 pkt.size = 0;
1413
1414                 update_benchmark(NULL);
1415                 ret = encode(enc, &pkt, NULL, &got_packet);
1416                 update_benchmark("flush %s %d.%d", desc, ost->file_index, ost->index);
1417                 if (ret < 0) {
1418                     av_log(NULL, AV_LOG_FATAL, "%s encoding failed\n", desc);
1419                     exit_program(1);
1420                 }
1421                 if (ost->logfile && enc->stats_out) {
1422                     fprintf(ost->logfile, "%s", enc->stats_out);
1423                 }
1424                 if (!got_packet) {
1425                     stop_encoding = 1;
1426                     break;
1427                 }
1428                 if (ost->finished & MUXER_FINISHED) {
1429                     av_free_packet(&pkt);
1430                     continue;
1431                 }
1432                 *size += pkt.size;
1433                 if (pkt.pts != AV_NOPTS_VALUE)
1434                     pkt.pts = av_rescale_q(pkt.pts, enc->time_base, ost->st->time_base);
1435                 if (pkt.dts != AV_NOPTS_VALUE)
1436                     pkt.dts = av_rescale_q(pkt.dts, enc->time_base, ost->st->time_base);
1437                 if (pkt.duration > 0)
1438                     pkt.duration = av_rescale_q(pkt.duration, enc->time_base, ost->st->time_base);
1439                 pkt_size = pkt.size;
1440                 write_frame(os, &pkt, ost);
1441                 if (ost->st->codec->codec_type == AVMEDIA_TYPE_VIDEO && vstats_filename) {
1442                     do_video_stats(ost, pkt_size);
1443                 }
1444             }
1445
1446             if (stop_encoding)
1447                 break;
1448         }
1449     }
1450 }
1451
1452 /*
1453  * Check whether a packet from ist should be written into ost at this time
1454  */
1455 static int check_output_constraints(InputStream *ist, OutputStream *ost)
1456 {
1457     OutputFile *of = output_files[ost->file_index];
1458     int ist_index  = input_files[ist->file_index]->ist_index + ist->st->index;
1459
1460     if (ost->source_index != ist_index)
1461         return 0;
1462
1463     if (ost->finished)
1464         return 0;
1465
1466     if (of->start_time != AV_NOPTS_VALUE && ist->pts < of->start_time)
1467         return 0;
1468
1469     return 1;
1470 }
1471
1472 static void do_streamcopy(InputStream *ist, OutputStream *ost, const AVPacket *pkt)
1473 {
1474     OutputFile *of = output_files[ost->file_index];
1475     InputFile   *f = input_files [ist->file_index];
1476     int64_t start_time = (of->start_time == AV_NOPTS_VALUE) ? 0 : of->start_time;
1477     int64_t ost_tb_start_time = av_rescale_q(start_time, AV_TIME_BASE_Q, ost->st->time_base);
1478     int64_t ist_tb_start_time = av_rescale_q(start_time, AV_TIME_BASE_Q, ist->st->time_base);
1479     AVPicture pict;
1480     AVPacket opkt;
1481
1482     av_init_packet(&opkt);
1483
1484     if ((!ost->frame_number && !(pkt->flags & AV_PKT_FLAG_KEY)) &&
1485         !ost->copy_initial_nonkeyframes)
1486         return;
1487
1488     if (pkt->pts == AV_NOPTS_VALUE) {
1489         if (!ost->frame_number && ist->pts < start_time &&
1490             !ost->copy_prior_start)
1491             return;
1492     } else {
1493         if (!ost->frame_number && pkt->pts < ist_tb_start_time &&
1494             !ost->copy_prior_start)
1495             return;
1496     }
1497
1498     if (of->recording_time != INT64_MAX &&
1499         ist->pts >= of->recording_time + start_time) {
1500         close_output_stream(ost);
1501         return;
1502     }
1503
1504     if (f->recording_time != INT64_MAX) {
1505         start_time = f->ctx->start_time;
1506         if (f->start_time != AV_NOPTS_VALUE)
1507             start_time += f->start_time;
1508         if (ist->pts >= f->recording_time + start_time) {
1509             close_output_stream(ost);
1510             return;
1511         }
1512     }
1513
1514     /* force the input stream PTS */
1515     if (ost->st->codec->codec_type == AVMEDIA_TYPE_AUDIO)
1516         audio_size += pkt->size;
1517     else if (ost->st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
1518         video_size += pkt->size;
1519         ost->sync_opts++;
1520     } else if (ost->st->codec->codec_type == AVMEDIA_TYPE_DATA) {
1521         data_size += pkt->size;
1522     } else if (ost->st->codec->codec_type == AVMEDIA_TYPE_SUBTITLE) {
1523         subtitle_size += pkt->size;
1524     }
1525
1526     if (pkt->pts != AV_NOPTS_VALUE)
1527         opkt.pts = av_rescale_q(pkt->pts, ist->st->time_base, ost->st->time_base) - ost_tb_start_time;
1528     else
1529         opkt.pts = AV_NOPTS_VALUE;
1530
1531     if (pkt->dts == AV_NOPTS_VALUE)
1532         opkt.dts = av_rescale_q(ist->dts, AV_TIME_BASE_Q, ost->st->time_base);
1533     else
1534         opkt.dts = av_rescale_q(pkt->dts, ist->st->time_base, ost->st->time_base);
1535     opkt.dts -= ost_tb_start_time;
1536
1537     if (ost->st->codec->codec_type == AVMEDIA_TYPE_AUDIO && pkt->dts != AV_NOPTS_VALUE) {
1538         int duration = av_get_audio_frame_duration(ist->st->codec, pkt->size);
1539         if(!duration)
1540             duration = ist->st->codec->frame_size;
1541         opkt.dts = opkt.pts = av_rescale_delta(ist->st->time_base, pkt->dts,
1542                                                (AVRational){1, ist->st->codec->sample_rate}, duration, &ist->filter_in_rescale_delta_last,
1543                                                ost->st->time_base) - ost_tb_start_time;
1544     }
1545
1546     opkt.duration = av_rescale_q(pkt->duration, ist->st->time_base, ost->st->time_base);
1547     opkt.flags    = pkt->flags;
1548
1549     // FIXME remove the following 2 lines they shall be replaced by the bitstream filters
1550     if (  ost->st->codec->codec_id != AV_CODEC_ID_H264
1551        && ost->st->codec->codec_id != AV_CODEC_ID_MPEG1VIDEO
1552        && ost->st->codec->codec_id != AV_CODEC_ID_MPEG2VIDEO
1553        && ost->st->codec->codec_id != AV_CODEC_ID_VC1
1554        ) {
1555         if (av_parser_change(ost->parser, ost->st->codec,
1556                              &opkt.data, &opkt.size,
1557                              pkt->data, pkt->size,
1558                              pkt->flags & AV_PKT_FLAG_KEY)) {
1559             opkt.buf = av_buffer_create(opkt.data, opkt.size, av_buffer_default_free, NULL, 0);
1560             if (!opkt.buf)
1561                 exit_program(1);
1562         }
1563     } else {
1564         opkt.data = pkt->data;
1565         opkt.size = pkt->size;
1566     }
1567     av_copy_packet_side_data(&opkt, pkt);
1568
1569     if (ost->st->codec->codec_type == AVMEDIA_TYPE_VIDEO && (of->ctx->oformat->flags & AVFMT_RAWPICTURE)) {
1570         /* store AVPicture in AVPacket, as expected by the output format */
1571         avpicture_fill(&pict, opkt.data, ost->st->codec->pix_fmt, ost->st->codec->width, ost->st->codec->height);
1572         opkt.data = (uint8_t *)&pict;
1573         opkt.size = sizeof(AVPicture);
1574         opkt.flags |= AV_PKT_FLAG_KEY;
1575     }
1576
1577     write_frame(of->ctx, &opkt, ost);
1578     ost->st->codec->frame_number++;
1579 }
1580
1581 int guess_input_channel_layout(InputStream *ist)
1582 {
1583     AVCodecContext *dec = ist->st->codec;
1584
1585     if (!dec->channel_layout) {
1586         char layout_name[256];
1587
1588         if (dec->channels > ist->guess_layout_max)
1589             return 0;
1590         dec->channel_layout = av_get_default_channel_layout(dec->channels);
1591         if (!dec->channel_layout)
1592             return 0;
1593         av_get_channel_layout_string(layout_name, sizeof(layout_name),
1594                                      dec->channels, dec->channel_layout);
1595         av_log(NULL, AV_LOG_WARNING, "Guessed Channel Layout for  Input Stream "
1596                "#%d.%d : %s\n", ist->file_index, ist->st->index, layout_name);
1597     }
1598     return 1;
1599 }
1600
1601 static int decode_audio(InputStream *ist, AVPacket *pkt, int *got_output)
1602 {
1603     AVFrame *decoded_frame, *f;
1604     AVCodecContext *avctx = ist->st->codec;
1605     int i, ret, err = 0, resample_changed;
1606     AVRational decoded_frame_tb;
1607
1608     if (!ist->decoded_frame && !(ist->decoded_frame = av_frame_alloc()))
1609         return AVERROR(ENOMEM);
1610     if (!ist->filter_frame && !(ist->filter_frame = av_frame_alloc()))
1611         return AVERROR(ENOMEM);
1612     decoded_frame = ist->decoded_frame;
1613
1614     update_benchmark(NULL);
1615     ret = avcodec_decode_audio4(avctx, decoded_frame, got_output, pkt);
1616     update_benchmark("decode_audio %d.%d", ist->file_index, ist->st->index);
1617
1618     if (ret >= 0 && avctx->sample_rate <= 0) {
1619         av_log(avctx, AV_LOG_ERROR, "Sample rate %d invalid\n", avctx->sample_rate);
1620         ret = AVERROR_INVALIDDATA;
1621     }
1622
1623     if (*got_output || ret<0 || pkt->size)
1624         decode_error_stat[ret<0] ++;
1625
1626     if (!*got_output || ret < 0) {
1627         if (!pkt->size) {
1628             for (i = 0; i < ist->nb_filters; i++)
1629 #if 1
1630                 av_buffersrc_add_ref(ist->filters[i]->filter, NULL, 0);
1631 #else
1632                 av_buffersrc_add_frame(ist->filters[i]->filter, NULL);
1633 #endif
1634         }
1635         return ret;
1636     }
1637
1638 #if 1
1639     /* increment next_dts to use for the case where the input stream does not
1640        have timestamps or there are multiple frames in the packet */
1641     ist->next_pts += ((int64_t)AV_TIME_BASE * decoded_frame->nb_samples) /
1642                      avctx->sample_rate;
1643     ist->next_dts += ((int64_t)AV_TIME_BASE * decoded_frame->nb_samples) /
1644                      avctx->sample_rate;
1645 #endif
1646
1647     resample_changed = ist->resample_sample_fmt     != decoded_frame->format         ||
1648                        ist->resample_channels       != avctx->channels               ||
1649                        ist->resample_channel_layout != decoded_frame->channel_layout ||
1650                        ist->resample_sample_rate    != decoded_frame->sample_rate;
1651     if (resample_changed) {
1652         char layout1[64], layout2[64];
1653
1654         if (!guess_input_channel_layout(ist)) {
1655             av_log(NULL, AV_LOG_FATAL, "Unable to find default channel "
1656                    "layout for Input Stream #%d.%d\n", ist->file_index,
1657                    ist->st->index);
1658             exit_program(1);
1659         }
1660         decoded_frame->channel_layout = avctx->channel_layout;
1661
1662         av_get_channel_layout_string(layout1, sizeof(layout1), ist->resample_channels,
1663                                      ist->resample_channel_layout);
1664         av_get_channel_layout_string(layout2, sizeof(layout2), avctx->channels,
1665                                      decoded_frame->channel_layout);
1666
1667         av_log(NULL, AV_LOG_INFO,
1668                "Input stream #%d:%d frame changed from rate:%d fmt:%s ch:%d chl:%s to rate:%d fmt:%s ch:%d chl:%s\n",
1669                ist->file_index, ist->st->index,
1670                ist->resample_sample_rate,  av_get_sample_fmt_name(ist->resample_sample_fmt),
1671                ist->resample_channels, layout1,
1672                decoded_frame->sample_rate, av_get_sample_fmt_name(decoded_frame->format),
1673                avctx->channels, layout2);
1674
1675         ist->resample_sample_fmt     = decoded_frame->format;
1676         ist->resample_sample_rate    = decoded_frame->sample_rate;
1677         ist->resample_channel_layout = decoded_frame->channel_layout;
1678         ist->resample_channels       = avctx->channels;
1679
1680         for (i = 0; i < nb_filtergraphs; i++)
1681             if (ist_in_filtergraph(filtergraphs[i], ist)) {
1682                 FilterGraph *fg = filtergraphs[i];
1683                 int j;
1684                 if (configure_filtergraph(fg) < 0) {
1685                     av_log(NULL, AV_LOG_FATAL, "Error reinitializing filters!\n");
1686                     exit_program(1);
1687                 }
1688                 for (j = 0; j < fg->nb_outputs; j++) {
1689                     OutputStream *ost = fg->outputs[j]->ost;
1690                     if (ost->enc->type == AVMEDIA_TYPE_AUDIO &&
1691                         !(ost->enc->capabilities & CODEC_CAP_VARIABLE_FRAME_SIZE))
1692                         av_buffersink_set_frame_size(ost->filter->filter,
1693                                                      ost->st->codec->frame_size);
1694                 }
1695             }
1696     }
1697
1698     /* if the decoder provides a pts, use it instead of the last packet pts.
1699        the decoder could be delaying output by a packet or more. */
1700     if (decoded_frame->pts != AV_NOPTS_VALUE) {
1701         ist->dts = ist->next_dts = ist->pts = ist->next_pts = av_rescale_q(decoded_frame->pts, avctx->time_base, AV_TIME_BASE_Q);
1702         decoded_frame_tb   = avctx->time_base;
1703     } else if (decoded_frame->pkt_pts != AV_NOPTS_VALUE) {
1704         decoded_frame->pts = decoded_frame->pkt_pts;
1705         pkt->pts           = AV_NOPTS_VALUE;
1706         decoded_frame_tb   = ist->st->time_base;
1707     } else if (pkt->pts != AV_NOPTS_VALUE) {
1708         decoded_frame->pts = pkt->pts;
1709         pkt->pts           = AV_NOPTS_VALUE;
1710         decoded_frame_tb   = ist->st->time_base;
1711     }else {
1712         decoded_frame->pts = ist->dts;
1713         decoded_frame_tb   = AV_TIME_BASE_Q;
1714     }
1715     if (decoded_frame->pts != AV_NOPTS_VALUE)
1716         decoded_frame->pts = av_rescale_delta(decoded_frame_tb, decoded_frame->pts,
1717                                               (AVRational){1, ist->st->codec->sample_rate}, decoded_frame->nb_samples, &ist->filter_in_rescale_delta_last,
1718                                               (AVRational){1, ist->st->codec->sample_rate});
1719     for (i = 0; i < ist->nb_filters; i++) {
1720         if (i < ist->nb_filters - 1) {
1721             f = ist->filter_frame;
1722             err = av_frame_ref(f, decoded_frame);
1723             if (err < 0)
1724                 break;
1725         } else
1726             f = decoded_frame;
1727         err = av_buffersrc_add_frame_flags(ist->filters[i]->filter, f,
1728                                      AV_BUFFERSRC_FLAG_PUSH);
1729         if (err == AVERROR_EOF)
1730             err = 0; /* ignore */
1731         if (err < 0)
1732             break;
1733     }
1734     decoded_frame->pts = AV_NOPTS_VALUE;
1735
1736     av_frame_unref(ist->filter_frame);
1737     av_frame_unref(decoded_frame);
1738     return err < 0 ? err : ret;
1739 }
1740
1741 static int decode_video(InputStream *ist, AVPacket *pkt, int *got_output)
1742 {
1743     AVFrame *decoded_frame, *f;
1744     int i, ret = 0, err = 0, resample_changed;
1745     int64_t best_effort_timestamp;
1746     AVRational *frame_sample_aspect;
1747
1748     if (!ist->decoded_frame && !(ist->decoded_frame = av_frame_alloc()))
1749         return AVERROR(ENOMEM);
1750     if (!ist->filter_frame && !(ist->filter_frame = av_frame_alloc()))
1751         return AVERROR(ENOMEM);
1752     decoded_frame = ist->decoded_frame;
1753     pkt->dts  = av_rescale_q(ist->dts, AV_TIME_BASE_Q, ist->st->time_base);
1754
1755     update_benchmark(NULL);
1756     ret = avcodec_decode_video2(ist->st->codec,
1757                                 decoded_frame, got_output, pkt);
1758     update_benchmark("decode_video %d.%d", ist->file_index, ist->st->index);
1759
1760     if (*got_output || ret<0 || pkt->size)
1761         decode_error_stat[ret<0] ++;
1762
1763     if (!*got_output || ret < 0) {
1764         if (!pkt->size) {
1765             for (i = 0; i < ist->nb_filters; i++)
1766 #if 1
1767                 av_buffersrc_add_ref(ist->filters[i]->filter, NULL, 0);
1768 #else
1769                 av_buffersrc_add_frame(ist->filters[i]->filter, NULL);
1770 #endif
1771         }
1772         return ret;
1773     }
1774
1775     if(ist->top_field_first>=0)
1776         decoded_frame->top_field_first = ist->top_field_first;
1777
1778     if (ist->hwaccel_retrieve_data && decoded_frame->format == ist->hwaccel_pix_fmt) {
1779         err = ist->hwaccel_retrieve_data(ist->st->codec, decoded_frame);
1780         if (err < 0)
1781             goto fail;
1782     }
1783     ist->hwaccel_retrieved_pix_fmt = decoded_frame->format;
1784
1785     best_effort_timestamp= av_frame_get_best_effort_timestamp(decoded_frame);
1786     if(best_effort_timestamp != AV_NOPTS_VALUE)
1787         ist->next_pts = ist->pts = av_rescale_q(decoded_frame->pts = best_effort_timestamp, ist->st->time_base, AV_TIME_BASE_Q);
1788
1789     if (debug_ts) {
1790         av_log(NULL, AV_LOG_INFO, "decoder -> ist_index:%d type:video "
1791                "frame_pts:%s frame_pts_time:%s best_effort_ts:%"PRId64" best_effort_ts_time:%s keyframe:%d frame_type:%d time_base:%d/%d\n",
1792                ist->st->index, av_ts2str(decoded_frame->pts),
1793                av_ts2timestr(decoded_frame->pts, &ist->st->time_base),
1794                best_effort_timestamp,
1795                av_ts2timestr(best_effort_timestamp, &ist->st->time_base),
1796                decoded_frame->key_frame, decoded_frame->pict_type,
1797                ist->st->time_base.num, ist->st->time_base.den);
1798     }
1799
1800     pkt->size = 0;
1801
1802     if (ist->st->sample_aspect_ratio.num)
1803         decoded_frame->sample_aspect_ratio = ist->st->sample_aspect_ratio;
1804
1805     resample_changed = ist->resample_width   != decoded_frame->width  ||
1806                        ist->resample_height  != decoded_frame->height ||
1807                        ist->resample_pix_fmt != decoded_frame->format;
1808     if (resample_changed) {
1809         av_log(NULL, AV_LOG_INFO,
1810                "Input stream #%d:%d frame changed from size:%dx%d fmt:%s to size:%dx%d fmt:%s\n",
1811                ist->file_index, ist->st->index,
1812                ist->resample_width,  ist->resample_height,  av_get_pix_fmt_name(ist->resample_pix_fmt),
1813                decoded_frame->width, decoded_frame->height, av_get_pix_fmt_name(decoded_frame->format));
1814
1815         ist->resample_width   = decoded_frame->width;
1816         ist->resample_height  = decoded_frame->height;
1817         ist->resample_pix_fmt = decoded_frame->format;
1818
1819         for (i = 0; i < nb_filtergraphs; i++) {
1820             if (ist_in_filtergraph(filtergraphs[i], ist) && ist->reinit_filters &&
1821                 configure_filtergraph(filtergraphs[i]) < 0) {
1822                 av_log(NULL, AV_LOG_FATAL, "Error reinitializing filters!\n");
1823                 exit_program(1);
1824             }
1825         }
1826     }
1827
1828     frame_sample_aspect= av_opt_ptr(avcodec_get_frame_class(), decoded_frame, "sample_aspect_ratio");
1829     for (i = 0; i < ist->nb_filters; i++) {
1830         if (!frame_sample_aspect->num)
1831             *frame_sample_aspect = ist->st->sample_aspect_ratio;
1832
1833         if (i < ist->nb_filters - 1) {
1834             f = ist->filter_frame;
1835             err = av_frame_ref(f, decoded_frame);
1836             if (err < 0)
1837                 break;
1838         } else
1839             f = decoded_frame;
1840         ret = av_buffersrc_add_frame_flags(ist->filters[i]->filter, f, AV_BUFFERSRC_FLAG_PUSH);
1841         if (ret == AVERROR_EOF) {
1842             ret = 0; /* ignore */
1843         } else if (ret < 0) {
1844             av_log(NULL, AV_LOG_FATAL,
1845                    "Failed to inject frame into filter network: %s\n", av_err2str(ret));
1846             exit_program(1);
1847         }
1848     }
1849
1850 fail:
1851     av_frame_unref(ist->filter_frame);
1852     av_frame_unref(decoded_frame);
1853     return err < 0 ? err : ret;
1854 }
1855
1856 static int transcode_subtitles(InputStream *ist, AVPacket *pkt, int *got_output)
1857 {
1858     AVSubtitle subtitle;
1859     int i, ret = avcodec_decode_subtitle2(ist->st->codec,
1860                                           &subtitle, got_output, pkt);
1861
1862     if (*got_output || ret<0 || pkt->size)
1863         decode_error_stat[ret<0] ++;
1864
1865     if (ret < 0 || !*got_output) {
1866         if (!pkt->size)
1867             sub2video_flush(ist);
1868         return ret;
1869     }
1870
1871     if (ist->fix_sub_duration) {
1872         int end = 1;
1873         if (ist->prev_sub.got_output) {
1874             end = av_rescale(subtitle.pts - ist->prev_sub.subtitle.pts,
1875                              1000, AV_TIME_BASE);
1876             if (end < ist->prev_sub.subtitle.end_display_time) {
1877                 av_log(ist->st->codec, AV_LOG_DEBUG,
1878                        "Subtitle duration reduced from %d to %d%s\n",
1879                        ist->prev_sub.subtitle.end_display_time, end,
1880                        end <= 0 ? ", dropping it" : "");
1881                 ist->prev_sub.subtitle.end_display_time = end;
1882             }
1883         }
1884         FFSWAP(int,        *got_output, ist->prev_sub.got_output);
1885         FFSWAP(int,        ret,         ist->prev_sub.ret);
1886         FFSWAP(AVSubtitle, subtitle,    ist->prev_sub.subtitle);
1887         if (end <= 0)
1888             goto out;
1889     }
1890
1891     if (!*got_output)
1892         return ret;
1893
1894     sub2video_update(ist, &subtitle);
1895
1896     if (!subtitle.num_rects)
1897         goto out;
1898
1899     for (i = 0; i < nb_output_streams; i++) {
1900         OutputStream *ost = output_streams[i];
1901
1902         if (!check_output_constraints(ist, ost) || !ost->encoding_needed
1903             || ost->enc->type != AVMEDIA_TYPE_SUBTITLE)
1904             continue;
1905
1906         do_subtitle_out(output_files[ost->file_index]->ctx, ost, ist, &subtitle);
1907     }
1908
1909 out:
1910     avsubtitle_free(&subtitle);
1911     return ret;
1912 }
1913
1914 /* pkt = NULL means EOF (needed to flush decoder buffers) */
1915 static int output_packet(InputStream *ist, const AVPacket *pkt)
1916 {
1917     int ret = 0, i;
1918     int got_output = 0;
1919
1920     AVPacket avpkt;
1921     if (!ist->saw_first_ts) {
1922         ist->dts = ist->st->avg_frame_rate.num ? - ist->st->codec->has_b_frames * AV_TIME_BASE / av_q2d(ist->st->avg_frame_rate) : 0;
1923         ist->pts = 0;
1924         if (pkt != NULL && pkt->pts != AV_NOPTS_VALUE && !ist->decoding_needed) {
1925             ist->dts += av_rescale_q(pkt->pts, ist->st->time_base, AV_TIME_BASE_Q);
1926             ist->pts = ist->dts; //unused but better to set it to a value thats not totally wrong
1927         }
1928         ist->saw_first_ts = 1;
1929     }
1930
1931     if (ist->next_dts == AV_NOPTS_VALUE)
1932         ist->next_dts = ist->dts;
1933     if (ist->next_pts == AV_NOPTS_VALUE)
1934         ist->next_pts = ist->pts;
1935
1936     if (pkt == NULL) {
1937         /* EOF handling */
1938         av_init_packet(&avpkt);
1939         avpkt.data = NULL;
1940         avpkt.size = 0;
1941         goto handle_eof;
1942     } else {
1943         avpkt = *pkt;
1944     }
1945
1946     if (pkt->dts != AV_NOPTS_VALUE) {
1947         ist->next_dts = ist->dts = av_rescale_q(pkt->dts, ist->st->time_base, AV_TIME_BASE_Q);
1948         if (ist->st->codec->codec_type != AVMEDIA_TYPE_VIDEO || !ist->decoding_needed)
1949             ist->next_pts = ist->pts = ist->dts;
1950     }
1951
1952     // while we have more to decode or while the decoder did output something on EOF
1953     while (ist->decoding_needed && (avpkt.size > 0 || (!pkt && got_output))) {
1954         int duration;
1955     handle_eof:
1956
1957         ist->pts = ist->next_pts;
1958         ist->dts = ist->next_dts;
1959
1960         if (avpkt.size && avpkt.size != pkt->size) {
1961             av_log(NULL, ist->showed_multi_packet_warning ? AV_LOG_VERBOSE : AV_LOG_WARNING,
1962                    "Multiple frames in a packet from stream %d\n", pkt->stream_index);
1963             ist->showed_multi_packet_warning = 1;
1964         }
1965
1966         switch (ist->st->codec->codec_type) {
1967         case AVMEDIA_TYPE_AUDIO:
1968             ret = decode_audio    (ist, &avpkt, &got_output);
1969             break;
1970         case AVMEDIA_TYPE_VIDEO:
1971             ret = decode_video    (ist, &avpkt, &got_output);
1972             if (avpkt.duration) {
1973                 duration = av_rescale_q(avpkt.duration, ist->st->time_base, AV_TIME_BASE_Q);
1974             } else if(ist->st->codec->time_base.num != 0 && ist->st->codec->time_base.den != 0) {
1975                 int ticks= ist->st->parser ? ist->st->parser->repeat_pict+1 : ist->st->codec->ticks_per_frame;
1976                 duration = ((int64_t)AV_TIME_BASE *
1977                                 ist->st->codec->time_base.num * ticks) /
1978                                 ist->st->codec->time_base.den;
1979             } else
1980                 duration = 0;
1981
1982             if(ist->dts != AV_NOPTS_VALUE && duration) {
1983                 ist->next_dts += duration;
1984             }else
1985                 ist->next_dts = AV_NOPTS_VALUE;
1986
1987             if (got_output)
1988                 ist->next_pts += duration; //FIXME the duration is not correct in some cases
1989             break;
1990         case AVMEDIA_TYPE_SUBTITLE:
1991             ret = transcode_subtitles(ist, &avpkt, &got_output);
1992             break;
1993         default:
1994             return -1;
1995         }
1996
1997         if (ret < 0)
1998             return ret;
1999
2000         avpkt.dts=
2001         avpkt.pts= AV_NOPTS_VALUE;
2002
2003         // touch data and size only if not EOF
2004         if (pkt) {
2005             if(ist->st->codec->codec_type != AVMEDIA_TYPE_AUDIO)
2006                 ret = avpkt.size;
2007             avpkt.data += ret;
2008             avpkt.size -= ret;
2009         }
2010         if (!got_output) {
2011             continue;
2012         }
2013     }
2014
2015     /* handle stream copy */
2016     if (!ist->decoding_needed) {
2017         ist->dts = ist->next_dts;
2018         switch (ist->st->codec->codec_type) {
2019         case AVMEDIA_TYPE_AUDIO:
2020             ist->next_dts += ((int64_t)AV_TIME_BASE * ist->st->codec->frame_size) /
2021                              ist->st->codec->sample_rate;
2022             break;
2023         case AVMEDIA_TYPE_VIDEO:
2024             if (ist->framerate.num) {
2025                 // TODO: Remove work-around for c99-to-c89 issue 7
2026                 AVRational time_base_q = AV_TIME_BASE_Q;
2027                 int64_t next_dts = av_rescale_q(ist->next_dts, time_base_q, av_inv_q(ist->framerate));
2028                 ist->next_dts = av_rescale_q(next_dts + 1, av_inv_q(ist->framerate), time_base_q);
2029             } else if (pkt->duration) {
2030                 ist->next_dts += av_rescale_q(pkt->duration, ist->st->time_base, AV_TIME_BASE_Q);
2031             } else if(ist->st->codec->time_base.num != 0) {
2032                 int ticks= ist->st->parser ? ist->st->parser->repeat_pict + 1 : ist->st->codec->ticks_per_frame;
2033                 ist->next_dts += ((int64_t)AV_TIME_BASE *
2034                                   ist->st->codec->time_base.num * ticks) /
2035                                   ist->st->codec->time_base.den;
2036             }
2037             break;
2038         }
2039         ist->pts = ist->dts;
2040         ist->next_pts = ist->next_dts;
2041     }
2042     for (i = 0; pkt && i < nb_output_streams; i++) {
2043         OutputStream *ost = output_streams[i];
2044
2045         if (!check_output_constraints(ist, ost) || ost->encoding_needed)
2046             continue;
2047
2048         do_streamcopy(ist, ost, pkt);
2049     }
2050
2051     return 0;
2052 }
2053
2054 static void print_sdp(void)
2055 {
2056     char sdp[16384];
2057     int i;
2058     AVFormatContext **avc = av_malloc(sizeof(*avc) * nb_output_files);
2059
2060     if (!avc)
2061         exit_program(1);
2062     for (i = 0; i < nb_output_files; i++)
2063         avc[i] = output_files[i]->ctx;
2064
2065     av_sdp_create(avc, nb_output_files, sdp, sizeof(sdp));
2066     printf("SDP:\n%s\n", sdp);
2067     fflush(stdout);
2068     av_freep(&avc);
2069 }
2070
2071 static const HWAccel *get_hwaccel(enum AVPixelFormat pix_fmt)
2072 {
2073     int i;
2074     for (i = 0; hwaccels[i].name; i++)
2075         if (hwaccels[i].pix_fmt == pix_fmt)
2076             return &hwaccels[i];
2077     return NULL;
2078 }
2079
2080 static enum AVPixelFormat get_format(AVCodecContext *s, const enum AVPixelFormat *pix_fmts)
2081 {
2082     InputStream *ist = s->opaque;
2083     const enum AVPixelFormat *p;
2084     int ret;
2085
2086     for (p = pix_fmts; *p != -1; p++) {
2087         const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(*p);
2088         const HWAccel *hwaccel;
2089
2090         if (!(desc->flags & AV_PIX_FMT_FLAG_HWACCEL))
2091             break;
2092
2093         hwaccel = get_hwaccel(*p);
2094         if (!hwaccel ||
2095             (ist->active_hwaccel_id && ist->active_hwaccel_id != hwaccel->id) ||
2096             (ist->hwaccel_id != HWACCEL_AUTO && ist->hwaccel_id != hwaccel->id))
2097             continue;
2098
2099         ret = hwaccel->init(s);
2100         if (ret < 0) {
2101             if (ist->hwaccel_id == hwaccel->id) {
2102                 av_log(NULL, AV_LOG_FATAL,
2103                        "%s hwaccel requested for input stream #%d:%d, "
2104                        "but cannot be initialized.\n", hwaccel->name,
2105                        ist->file_index, ist->st->index);
2106                 exit_program(1);
2107             }
2108             continue;
2109         }
2110         ist->active_hwaccel_id = hwaccel->id;
2111         ist->hwaccel_pix_fmt   = *p;
2112         break;
2113     }
2114
2115     return *p;
2116 }
2117
2118 static int get_buffer(AVCodecContext *s, AVFrame *frame, int flags)
2119 {
2120     InputStream *ist = s->opaque;
2121
2122     if (ist->hwaccel_get_buffer && frame->format == ist->hwaccel_pix_fmt)
2123         return ist->hwaccel_get_buffer(s, frame, flags);
2124
2125     return avcodec_default_get_buffer2(s, frame, flags);
2126 }
2127
2128 static int init_input_stream(int ist_index, char *error, int error_len)
2129 {
2130     int ret;
2131     InputStream *ist = input_streams[ist_index];
2132
2133     if (ist->decoding_needed) {
2134         AVCodec *codec = ist->dec;
2135         if (!codec) {
2136             snprintf(error, error_len, "Decoder (codec %s) not found for input stream #%d:%d",
2137                     avcodec_get_name(ist->st->codec->codec_id), ist->file_index, ist->st->index);
2138             return AVERROR(EINVAL);
2139         }
2140
2141         ist->st->codec->opaque      = ist;
2142         ist->st->codec->get_format  = get_format;
2143         ist->st->codec->get_buffer2 = get_buffer;
2144         ist->st->codec->thread_safe_callbacks = 1;
2145
2146         av_opt_set_int(ist->st->codec, "refcounted_frames", 1, 0);
2147
2148         if (!av_dict_get(ist->opts, "threads", NULL, 0))
2149             av_dict_set(&ist->opts, "threads", "auto", 0);
2150         if ((ret = avcodec_open2(ist->st->codec, codec, &ist->opts)) < 0) {
2151             if (ret == AVERROR_EXPERIMENTAL)
2152                 abort_codec_experimental(codec, 0);
2153
2154             snprintf(error, error_len,
2155                      "Error while opening decoder for input stream "
2156                      "#%d:%d : %s",
2157                      ist->file_index, ist->st->index, av_err2str(ret));
2158             return ret;
2159         }
2160         assert_avoptions(ist->opts);
2161     }
2162
2163     ist->next_pts = AV_NOPTS_VALUE;
2164     ist->next_dts = AV_NOPTS_VALUE;
2165
2166     return 0;
2167 }
2168
2169 static InputStream *get_input_stream(OutputStream *ost)
2170 {
2171     if (ost->source_index >= 0)
2172         return input_streams[ost->source_index];
2173     return NULL;
2174 }
2175
2176 static int compare_int64(const void *a, const void *b)
2177 {
2178     int64_t va = *(int64_t *)a, vb = *(int64_t *)b;
2179     return va < vb ? -1 : va > vb ? +1 : 0;
2180 }
2181
2182 static void parse_forced_key_frames(char *kf, OutputStream *ost,
2183                                     AVCodecContext *avctx)
2184 {
2185     char *p;
2186     int n = 1, i, size, index = 0;
2187     int64_t t, *pts;
2188
2189     for (p = kf; *p; p++)
2190         if (*p == ',')
2191             n++;
2192     size = n;
2193     pts = av_malloc(sizeof(*pts) * size);
2194     if (!pts) {
2195         av_log(NULL, AV_LOG_FATAL, "Could not allocate forced key frames array.\n");
2196         exit_program(1);
2197     }
2198
2199     p = kf;
2200     for (i = 0; i < n; i++) {
2201         char *next = strchr(p, ',');
2202
2203         if (next)
2204             *next++ = 0;
2205
2206         if (!memcmp(p, "chapters", 8)) {
2207
2208             AVFormatContext *avf = output_files[ost->file_index]->ctx;
2209             int j;
2210
2211             if (avf->nb_chapters > INT_MAX - size ||
2212                 !(pts = av_realloc_f(pts, size += avf->nb_chapters - 1,
2213                                      sizeof(*pts)))) {
2214                 av_log(NULL, AV_LOG_FATAL,
2215                        "Could not allocate forced key frames array.\n");
2216                 exit_program(1);
2217             }
2218             t = p[8] ? parse_time_or_die("force_key_frames", p + 8, 1) : 0;
2219             t = av_rescale_q(t, AV_TIME_BASE_Q, avctx->time_base);
2220
2221             for (j = 0; j < avf->nb_chapters; j++) {
2222                 AVChapter *c = avf->chapters[j];
2223                 av_assert1(index < size);
2224                 pts[index++] = av_rescale_q(c->start, c->time_base,
2225                                             avctx->time_base) + t;
2226             }
2227
2228         } else {
2229
2230             t = parse_time_or_die("force_key_frames", p, 1);
2231             av_assert1(index < size);
2232             pts[index++] = av_rescale_q(t, AV_TIME_BASE_Q, avctx->time_base);
2233
2234         }
2235
2236         p = next;
2237     }
2238
2239     av_assert0(index == size);
2240     qsort(pts, size, sizeof(*pts), compare_int64);
2241     ost->forced_kf_count = size;
2242     ost->forced_kf_pts   = pts;
2243 }
2244
2245 static void report_new_stream(int input_index, AVPacket *pkt)
2246 {
2247     InputFile *file = input_files[input_index];
2248     AVStream *st = file->ctx->streams[pkt->stream_index];
2249
2250     if (pkt->stream_index < file->nb_streams_warn)
2251         return;
2252     av_log(file->ctx, AV_LOG_WARNING,
2253            "New %s stream %d:%d at pos:%"PRId64" and DTS:%ss\n",
2254            av_get_media_type_string(st->codec->codec_type),
2255            input_index, pkt->stream_index,
2256            pkt->pos, av_ts2timestr(pkt->dts, &st->time_base));
2257     file->nb_streams_warn = pkt->stream_index + 1;
2258 }
2259
2260 static int transcode_init(void)
2261 {
2262     int ret = 0, i, j, k;
2263     AVFormatContext *oc;
2264     AVCodecContext *codec;
2265     OutputStream *ost;
2266     InputStream *ist;
2267     char error[1024];
2268     int want_sdp = 1;
2269
2270     for (i = 0; i < nb_filtergraphs; i++) {
2271         FilterGraph *fg = filtergraphs[i];
2272         for (j = 0; j < fg->nb_outputs; j++) {
2273             OutputFilter *ofilter = fg->outputs[j];
2274             if (!ofilter->ost || ofilter->ost->source_index >= 0)
2275                 continue;
2276             if (fg->nb_inputs != 1)
2277                 continue;
2278             for (k = nb_input_streams-1; k >= 0 ; k--)
2279                 if (fg->inputs[0]->ist == input_streams[k])
2280                     break;
2281             ofilter->ost->source_index = k;
2282         }
2283     }
2284
2285     /* init framerate emulation */
2286     for (i = 0; i < nb_input_files; i++) {
2287         InputFile *ifile = input_files[i];
2288         if (ifile->rate_emu)
2289             for (j = 0; j < ifile->nb_streams; j++)
2290                 input_streams[j + ifile->ist_index]->start = av_gettime();
2291     }
2292
2293     /* output stream init */
2294     for (i = 0; i < nb_output_files; i++) {
2295         oc = output_files[i]->ctx;
2296         if (!oc->nb_streams && !(oc->oformat->flags & AVFMT_NOSTREAMS)) {
2297             av_dump_format(oc, i, oc->filename, 1);
2298             av_log(NULL, AV_LOG_ERROR, "Output file #%d does not contain any stream\n", i);
2299             return AVERROR(EINVAL);
2300         }
2301     }
2302
2303     /* init complex filtergraphs */
2304     for (i = 0; i < nb_filtergraphs; i++)
2305         if ((ret = avfilter_graph_config(filtergraphs[i]->graph, NULL)) < 0)
2306             return ret;
2307
2308     /* for each output stream, we compute the right encoding parameters */
2309     for (i = 0; i < nb_output_streams; i++) {
2310         AVCodecContext *icodec = NULL;
2311         ost = output_streams[i];
2312         oc  = output_files[ost->file_index]->ctx;
2313         ist = get_input_stream(ost);
2314
2315         if (ost->attachment_filename)
2316             continue;
2317
2318         codec  = ost->st->codec;
2319
2320         if (ist) {
2321             icodec = ist->st->codec;
2322
2323             ost->st->disposition          = ist->st->disposition;
2324             codec->bits_per_raw_sample    = icodec->bits_per_raw_sample;
2325             codec->chroma_sample_location = icodec->chroma_sample_location;
2326         } else {
2327             for (j=0; j<oc->nb_streams; j++) {
2328                 AVStream *st = oc->streams[j];
2329                 if (st != ost->st && st->codec->codec_type == codec->codec_type)
2330                     break;
2331             }
2332             if (j == oc->nb_streams)
2333                 if (codec->codec_type == AVMEDIA_TYPE_AUDIO || codec->codec_type == AVMEDIA_TYPE_VIDEO)
2334                     ost->st->disposition = AV_DISPOSITION_DEFAULT;
2335         }
2336
2337         if (ost->stream_copy) {
2338             AVRational sar;
2339             uint64_t extra_size;
2340
2341             av_assert0(ist && !ost->filter);
2342
2343             extra_size = (uint64_t)icodec->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE;
2344
2345             if (extra_size > INT_MAX) {
2346                 return AVERROR(EINVAL);
2347             }
2348
2349             /* if stream_copy is selected, no need to decode or encode */
2350             codec->codec_id   = icodec->codec_id;
2351             codec->codec_type = icodec->codec_type;
2352
2353             if (!codec->codec_tag) {
2354                 unsigned int codec_tag;
2355                 if (!oc->oformat->codec_tag ||
2356                      av_codec_get_id (oc->oformat->codec_tag, icodec->codec_tag) == codec->codec_id ||
2357                      !av_codec_get_tag2(oc->oformat->codec_tag, icodec->codec_id, &codec_tag))
2358                     codec->codec_tag = icodec->codec_tag;
2359             }
2360
2361             codec->bit_rate       = icodec->bit_rate;
2362             codec->rc_max_rate    = icodec->rc_max_rate;
2363             codec->rc_buffer_size = icodec->rc_buffer_size;
2364             codec->field_order    = icodec->field_order;
2365             codec->extradata      = av_mallocz(extra_size);
2366             if (!codec->extradata) {
2367                 return AVERROR(ENOMEM);
2368             }
2369             memcpy(codec->extradata, icodec->extradata, icodec->extradata_size);
2370             codec->extradata_size= icodec->extradata_size;
2371             codec->bits_per_coded_sample  = icodec->bits_per_coded_sample;
2372
2373             codec->time_base = ist->st->time_base;
2374             /*
2375              * Avi is a special case here because it supports variable fps but
2376              * having the fps and timebase differe significantly adds quite some
2377              * overhead
2378              */
2379             if(!strcmp(oc->oformat->name, "avi")) {
2380                 if ( copy_tb<0 && av_q2d(ist->st->r_frame_rate) >= av_q2d(ist->st->avg_frame_rate)
2381                                && 0.5/av_q2d(ist->st->r_frame_rate) > av_q2d(ist->st->time_base)
2382                                && 0.5/av_q2d(ist->st->r_frame_rate) > av_q2d(icodec->time_base)
2383                                && av_q2d(ist->st->time_base) < 1.0/500 && av_q2d(icodec->time_base) < 1.0/500
2384                      || copy_tb==2){
2385                     codec->time_base.num = ist->st->r_frame_rate.den;
2386                     codec->time_base.den = 2*ist->st->r_frame_rate.num;
2387                     codec->ticks_per_frame = 2;
2388                 } else if (   copy_tb<0 && av_q2d(icodec->time_base)*icodec->ticks_per_frame > 2*av_q2d(ist->st->time_base)
2389                                  && av_q2d(ist->st->time_base) < 1.0/500
2390                     || copy_tb==0){
2391                     codec->time_base = icodec->time_base;
2392                     codec->time_base.num *= icodec->ticks_per_frame;
2393                     codec->time_base.den *= 2;
2394                     codec->ticks_per_frame = 2;
2395                 }
2396             } else if(!(oc->oformat->flags & AVFMT_VARIABLE_FPS)
2397                       && strcmp(oc->oformat->name, "mov") && strcmp(oc->oformat->name, "mp4") && strcmp(oc->oformat->name, "3gp")
2398                       && strcmp(oc->oformat->name, "3g2") && strcmp(oc->oformat->name, "psp") && strcmp(oc->oformat->name, "ipod")
2399                       && strcmp(oc->oformat->name, "f4v")
2400             ) {
2401                 if(   copy_tb<0 && icodec->time_base.den
2402                                 && av_q2d(icodec->time_base)*icodec->ticks_per_frame > av_q2d(ist->st->time_base)
2403                                 && av_q2d(ist->st->time_base) < 1.0/500
2404                    || copy_tb==0){
2405                     codec->time_base = icodec->time_base;
2406                     codec->time_base.num *= icodec->ticks_per_frame;
2407                 }
2408             }
2409             if (   codec->codec_tag == AV_RL32("tmcd")
2410                 && icodec->time_base.num < icodec->time_base.den
2411                 && icodec->time_base.num > 0
2412                 && 121LL*icodec->time_base.num > icodec->time_base.den) {
2413                 codec->time_base = icodec->time_base;
2414             }
2415
2416             if (ist && !ost->frame_rate.num)
2417                 ost->frame_rate = ist->framerate;
2418             if(ost->frame_rate.num)
2419                 codec->time_base = av_inv_q(ost->frame_rate);
2420
2421             av_reduce(&codec->time_base.num, &codec->time_base.den,
2422                         codec->time_base.num, codec->time_base.den, INT_MAX);
2423
2424             ost->parser = av_parser_init(codec->codec_id);
2425
2426             switch (codec->codec_type) {
2427             case AVMEDIA_TYPE_AUDIO:
2428                 if (audio_volume != 256) {
2429                     av_log(NULL, AV_LOG_FATAL, "-acodec copy and -vol are incompatible (frames are not decoded)\n");
2430                     exit_program(1);
2431                 }
2432                 codec->channel_layout     = icodec->channel_layout;
2433                 codec->sample_rate        = icodec->sample_rate;
2434                 codec->channels           = icodec->channels;
2435                 codec->frame_size         = icodec->frame_size;
2436                 codec->audio_service_type = icodec->audio_service_type;
2437                 codec->block_align        = icodec->block_align;
2438                 codec->delay              = icodec->delay;
2439                 if((codec->block_align == 1 || codec->block_align == 1152 || codec->block_align == 576) && codec->codec_id == AV_CODEC_ID_MP3)
2440                     codec->block_align= 0;
2441                 if(codec->codec_id == AV_CODEC_ID_AC3)
2442                     codec->block_align= 0;
2443                 break;
2444             case AVMEDIA_TYPE_VIDEO:
2445                 codec->pix_fmt            = icodec->pix_fmt;
2446                 codec->width              = icodec->width;
2447                 codec->height             = icodec->height;
2448                 codec->has_b_frames       = icodec->has_b_frames;
2449                 if (ost->frame_aspect_ratio.num) { // overridden by the -aspect cli option
2450                     sar =
2451                         av_mul_q(ost->frame_aspect_ratio,
2452                                  (AVRational){ codec->height, codec->width });
2453                     av_log(NULL, AV_LOG_WARNING, "Overriding aspect ratio "
2454                            "with stream copy may produce invalid files\n");
2455                 }
2456                 else if (ist->st->sample_aspect_ratio.num)
2457                     sar = ist->st->sample_aspect_ratio;
2458                 else
2459                     sar = icodec->sample_aspect_ratio;
2460                 ost->st->sample_aspect_ratio = codec->sample_aspect_ratio = sar;
2461                 ost->st->avg_frame_rate = ist->st->avg_frame_rate;
2462                 break;
2463             case AVMEDIA_TYPE_SUBTITLE:
2464                 codec->width  = icodec->width;
2465                 codec->height = icodec->height;
2466                 break;
2467             case AVMEDIA_TYPE_DATA:
2468             case AVMEDIA_TYPE_ATTACHMENT:
2469                 break;
2470             default:
2471                 abort();
2472             }
2473         } else {
2474             if (!ost->enc)
2475                 ost->enc = avcodec_find_encoder(codec->codec_id);
2476             if (!ost->enc) {
2477                 /* should only happen when a default codec is not present. */
2478                 snprintf(error, sizeof(error), "Encoder (codec %s) not found for output stream #%d:%d",
2479                          avcodec_get_name(ost->st->codec->codec_id), ost->file_index, ost->index);
2480                 ret = AVERROR(EINVAL);
2481                 goto dump_format;
2482             }
2483
2484             if (ist)
2485                 ist->decoding_needed++;
2486             ost->encoding_needed = 1;
2487
2488             if (!ost->filter &&
2489                 (codec->codec_type == AVMEDIA_TYPE_VIDEO ||
2490                  codec->codec_type == AVMEDIA_TYPE_AUDIO)) {
2491                     FilterGraph *fg;
2492                     fg = init_simple_filtergraph(ist, ost);
2493                     if (configure_filtergraph(fg)) {
2494                         av_log(NULL, AV_LOG_FATAL, "Error opening filters!\n");
2495                         exit_program(1);
2496                     }
2497             }
2498
2499             if (codec->codec_type == AVMEDIA_TYPE_VIDEO) {
2500                 if (ost->filter && !ost->frame_rate.num)
2501                     ost->frame_rate = av_buffersink_get_frame_rate(ost->filter->filter);
2502                 if (ist && !ost->frame_rate.num)
2503                     ost->frame_rate = ist->framerate;
2504                 if (ist && !ost->frame_rate.num)
2505                     ost->frame_rate = ist->st->r_frame_rate;
2506                 if (ist && !ost->frame_rate.num) {
2507                     ost->frame_rate = (AVRational){25, 1};
2508                     av_log(NULL, AV_LOG_WARNING,
2509                            "No information "
2510                            "about the input framerate is available. Falling "
2511                            "back to a default value of 25fps for output stream #%d:%d. Use the -r option "
2512                            "if you want a different framerate.\n",
2513                            ost->file_index, ost->index);
2514                 }
2515 //                    ost->frame_rate = ist->st->avg_frame_rate.num ? ist->st->avg_frame_rate : (AVRational){25, 1};
2516                 if (ost->enc && ost->enc->supported_framerates && !ost->force_fps) {
2517                     int idx = av_find_nearest_q_idx(ost->frame_rate, ost->enc->supported_framerates);
2518                     ost->frame_rate = ost->enc->supported_framerates[idx];
2519                 }
2520                 if (codec->codec_id == AV_CODEC_ID_MPEG4) {
2521                     av_reduce(&ost->frame_rate.num, &ost->frame_rate.den,
2522                               ost->frame_rate.num, ost->frame_rate.den, 65535);
2523                 }
2524             }
2525
2526             switch (codec->codec_type) {
2527             case AVMEDIA_TYPE_AUDIO:
2528                 codec->sample_fmt     = ost->filter->filter->inputs[0]->format;
2529                 codec->sample_rate    = ost->filter->filter->inputs[0]->sample_rate;
2530                 codec->channel_layout = ost->filter->filter->inputs[0]->channel_layout;
2531                 codec->channels       = avfilter_link_get_channels(ost->filter->filter->inputs[0]);
2532                 codec->time_base      = (AVRational){ 1, codec->sample_rate };
2533                 break;
2534             case AVMEDIA_TYPE_VIDEO:
2535                 codec->time_base = av_inv_q(ost->frame_rate);
2536                 if (ost->filter && !(codec->time_base.num && codec->time_base.den))
2537                     codec->time_base = ost->filter->filter->inputs[0]->time_base;
2538                 if (   av_q2d(codec->time_base) < 0.001 && video_sync_method != VSYNC_PASSTHROUGH
2539                    && (video_sync_method == VSYNC_CFR || video_sync_method == VSYNC_VSCFR || (video_sync_method == VSYNC_AUTO && !(oc->oformat->flags & AVFMT_VARIABLE_FPS)))){
2540                     av_log(oc, AV_LOG_WARNING, "Frame rate very high for a muxer not efficiently supporting it.\n"
2541                                                "Please consider specifying a lower framerate, a different muxer or -vsync 2\n");
2542                 }
2543                 for (j = 0; j < ost->forced_kf_count; j++)
2544                     ost->forced_kf_pts[j] = av_rescale_q(ost->forced_kf_pts[j],
2545                                                          AV_TIME_BASE_Q,
2546                                                          codec->time_base);
2547
2548                 codec->width  = ost->filter->filter->inputs[0]->w;
2549                 codec->height = ost->filter->filter->inputs[0]->h;
2550                 codec->sample_aspect_ratio = ost->st->sample_aspect_ratio =
2551                     ost->frame_aspect_ratio.num ? // overridden by the -aspect cli option
2552                     av_mul_q(ost->frame_aspect_ratio, (AVRational){ codec->height, codec->width }) :
2553                     ost->filter->filter->inputs[0]->sample_aspect_ratio;
2554                 if (!strncmp(ost->enc->name, "libx264", 7) &&
2555                     codec->pix_fmt == AV_PIX_FMT_NONE &&
2556                     ost->filter->filter->inputs[0]->format != AV_PIX_FMT_YUV420P)
2557                     av_log(NULL, AV_LOG_WARNING,
2558                            "No pixel format specified, %s for H.264 encoding chosen.\n"
2559                            "Use -pix_fmt yuv420p for compatibility with outdated media players.\n",
2560                            av_get_pix_fmt_name(ost->filter->filter->inputs[0]->format));
2561                 if (!strncmp(ost->enc->name, "mpeg2video", 10) &&
2562                     codec->pix_fmt == AV_PIX_FMT_NONE &&
2563                     ost->filter->filter->inputs[0]->format != AV_PIX_FMT_YUV420P)
2564                     av_log(NULL, AV_LOG_WARNING,
2565                            "No pixel format specified, %s for MPEG-2 encoding chosen.\n"
2566                            "Use -pix_fmt yuv420p for compatibility with outdated media players.\n",
2567                            av_get_pix_fmt_name(ost->filter->filter->inputs[0]->format));
2568                 codec->pix_fmt = ost->filter->filter->inputs[0]->format;
2569
2570                 if (!icodec ||
2571                     codec->width   != icodec->width  ||
2572                     codec->height  != icodec->height ||
2573                     codec->pix_fmt != icodec->pix_fmt) {
2574                     codec->bits_per_raw_sample = frame_bits_per_raw_sample;
2575                 }
2576
2577                 if (ost->forced_keyframes) {
2578                     if (!strncmp(ost->forced_keyframes, "expr:", 5)) {
2579                         ret = av_expr_parse(&ost->forced_keyframes_pexpr, ost->forced_keyframes+5,
2580                                             forced_keyframes_const_names, NULL, NULL, NULL, NULL, 0, NULL);
2581                         if (ret < 0) {
2582                             av_log(NULL, AV_LOG_ERROR,
2583                                    "Invalid force_key_frames expression '%s'\n", ost->forced_keyframes+5);
2584                             return ret;
2585                         }
2586                         ost->forced_keyframes_expr_const_values[FKF_N] = 0;
2587                         ost->forced_keyframes_expr_const_values[FKF_N_FORCED] = 0;
2588                         ost->forced_keyframes_expr_const_values[FKF_PREV_FORCED_N] = NAN;
2589                         ost->forced_keyframes_expr_const_values[FKF_PREV_FORCED_T] = NAN;
2590                     } else {
2591                         parse_forced_key_frames(ost->forced_keyframes, ost, ost->st->codec);
2592                     }
2593                 }
2594                 break;
2595             case AVMEDIA_TYPE_SUBTITLE:
2596                 codec->time_base = (AVRational){1, 1000};
2597                 if (!codec->width) {
2598                     codec->width     = input_streams[ost->source_index]->st->codec->width;
2599                     codec->height    = input_streams[ost->source_index]->st->codec->height;
2600                 }
2601                 break;
2602             default:
2603                 abort();
2604                 break;
2605             }
2606             /* two pass mode */
2607             if (codec->flags & (CODEC_FLAG_PASS1 | CODEC_FLAG_PASS2)) {
2608                 char logfilename[1024];
2609                 FILE *f;
2610
2611                 snprintf(logfilename, sizeof(logfilename), "%s-%d.log",
2612                          ost->logfile_prefix ? ost->logfile_prefix :
2613                                                DEFAULT_PASS_LOGFILENAME_PREFIX,
2614                          i);
2615                 if (!strcmp(ost->enc->name, "libx264")) {
2616                     av_dict_set(&ost->opts, "stats", logfilename, AV_DICT_DONT_OVERWRITE);
2617                 } else {
2618                     if (codec->flags & CODEC_FLAG_PASS2) {
2619                         char  *logbuffer;
2620                         size_t logbuffer_size;
2621                         if (cmdutils_read_file(logfilename, &logbuffer, &logbuffer_size) < 0) {
2622                             av_log(NULL, AV_LOG_FATAL, "Error reading log file '%s' for pass-2 encoding\n",
2623                                    logfilename);
2624                             exit_program(1);
2625                         }
2626                         codec->stats_in = logbuffer;
2627                     }
2628                     if (codec->flags & CODEC_FLAG_PASS1) {
2629                         f = av_fopen_utf8(logfilename, "wb");
2630                         if (!f) {
2631                             av_log(NULL, AV_LOG_FATAL, "Cannot write log file '%s' for pass-1 encoding: %s\n",
2632                                 logfilename, strerror(errno));
2633                             exit_program(1);
2634                         }
2635                         ost->logfile = f;
2636                     }
2637                 }
2638             }
2639         }
2640     }
2641
2642     /* open each encoder */
2643     for (i = 0; i < nb_output_streams; i++) {
2644         ost = output_streams[i];
2645         if (ost->encoding_needed) {
2646             AVCodec      *codec = ost->enc;
2647             AVCodecContext *dec = NULL;
2648
2649             if ((ist = get_input_stream(ost)))
2650                 dec = ist->st->codec;
2651             if (dec && dec->subtitle_header) {
2652                 /* ASS code assumes this buffer is null terminated so add extra byte. */
2653                 ost->st->codec->subtitle_header = av_mallocz(dec->subtitle_header_size + 1);
2654                 if (!ost->st->codec->subtitle_header) {
2655                     ret = AVERROR(ENOMEM);
2656                     goto dump_format;
2657                 }
2658                 memcpy(ost->st->codec->subtitle_header, dec->subtitle_header, dec->subtitle_header_size);
2659                 ost->st->codec->subtitle_header_size = dec->subtitle_header_size;
2660             }
2661             if (!av_dict_get(ost->opts, "threads", NULL, 0))
2662                 av_dict_set(&ost->opts, "threads", "auto", 0);
2663             if ((ret = avcodec_open2(ost->st->codec, codec, &ost->opts)) < 0) {
2664                 if (ret == AVERROR_EXPERIMENTAL)
2665                     abort_codec_experimental(codec, 1);
2666                 snprintf(error, sizeof(error), "Error while opening encoder for output stream #%d:%d - maybe incorrect parameters such as bit_rate, rate, width or height",
2667                         ost->file_index, ost->index);
2668                 goto dump_format;
2669             }
2670             if (ost->enc->type == AVMEDIA_TYPE_AUDIO &&
2671                 !(ost->enc->capabilities & CODEC_CAP_VARIABLE_FRAME_SIZE))
2672                 av_buffersink_set_frame_size(ost->filter->filter,
2673                                              ost->st->codec->frame_size);
2674             assert_avoptions(ost->opts);
2675             if (ost->st->codec->bit_rate && ost->st->codec->bit_rate < 1000)
2676                 av_log(NULL, AV_LOG_WARNING, "The bitrate parameter is set too low."
2677                                              " It takes bits/s as argument, not kbits/s\n");
2678             extra_size += ost->st->codec->extradata_size;
2679         } else {
2680             av_opt_set_dict(ost->st->codec, &ost->opts);
2681         }
2682     }
2683
2684     /* init input streams */
2685     for (i = 0; i < nb_input_streams; i++)
2686         if ((ret = init_input_stream(i, error, sizeof(error))) < 0) {
2687             for (i = 0; i < nb_output_streams; i++) {
2688                 ost = output_streams[i];
2689                 avcodec_close(ost->st->codec);
2690             }
2691             goto dump_format;
2692         }
2693
2694     /* discard unused programs */
2695     for (i = 0; i < nb_input_files; i++) {
2696         InputFile *ifile = input_files[i];
2697         for (j = 0; j < ifile->ctx->nb_programs; j++) {
2698             AVProgram *p = ifile->ctx->programs[j];
2699             int discard  = AVDISCARD_ALL;
2700
2701             for (k = 0; k < p->nb_stream_indexes; k++)
2702                 if (!input_streams[ifile->ist_index + p->stream_index[k]]->discard) {
2703                     discard = AVDISCARD_DEFAULT;
2704                     break;
2705                 }
2706             p->discard = discard;
2707         }
2708     }
2709
2710     /* open files and write file headers */
2711     for (i = 0; i < nb_output_files; i++) {
2712         oc = output_files[i]->ctx;
2713         oc->interrupt_callback = int_cb;
2714         if ((ret = avformat_write_header(oc, &output_files[i]->opts)) < 0) {
2715             snprintf(error, sizeof(error),
2716                      "Could not write header for output file #%d "
2717                      "(incorrect codec parameters ?): %s",
2718                      i, av_err2str(ret));
2719             ret = AVERROR(EINVAL);
2720             goto dump_format;
2721         }
2722 //         assert_avoptions(output_files[i]->opts);
2723         if (strcmp(oc->oformat->name, "rtp")) {
2724             want_sdp = 0;
2725         }
2726     }
2727
2728  dump_format:
2729     /* dump the file output parameters - cannot be done before in case
2730        of stream copy */
2731     for (i = 0; i < nb_output_files; i++) {
2732         av_dump_format(output_files[i]->ctx, i, output_files[i]->ctx->filename, 1);
2733     }
2734
2735     /* dump the stream mapping */
2736     av_log(NULL, AV_LOG_INFO, "Stream mapping:\n");
2737     for (i = 0; i < nb_input_streams; i++) {
2738         ist = input_streams[i];
2739
2740         for (j = 0; j < ist->nb_filters; j++) {
2741             if (ist->filters[j]->graph->graph_desc) {
2742                 av_log(NULL, AV_LOG_INFO, "  Stream #%d:%d (%s) -> %s",
2743                        ist->file_index, ist->st->index, ist->dec ? ist->dec->name : "?",
2744                        ist->filters[j]->name);
2745                 if (nb_filtergraphs > 1)
2746                     av_log(NULL, AV_LOG_INFO, " (graph %d)", ist->filters[j]->graph->index);
2747                 av_log(NULL, AV_LOG_INFO, "\n");
2748             }
2749         }
2750     }
2751
2752     for (i = 0; i < nb_output_streams; i++) {
2753         ost = output_streams[i];
2754
2755         if (ost->attachment_filename) {
2756             /* an attached file */
2757             av_log(NULL, AV_LOG_INFO, "  File %s -> Stream #%d:%d\n",
2758                    ost->attachment_filename, ost->file_index, ost->index);
2759             continue;
2760         }
2761
2762         if (ost->filter && ost->filter->graph->graph_desc) {
2763             /* output from a complex graph */
2764             av_log(NULL, AV_LOG_INFO, "  %s", ost->filter->name);
2765             if (nb_filtergraphs > 1)
2766                 av_log(NULL, AV_LOG_INFO, " (graph %d)", ost->filter->graph->index);
2767
2768             av_log(NULL, AV_LOG_INFO, " -> Stream #%d:%d (%s)\n", ost->file_index,
2769                    ost->index, ost->enc ? ost->enc->name : "?");
2770             continue;
2771         }
2772
2773         av_log(NULL, AV_LOG_INFO, "  Stream #%d:%d -> #%d:%d",
2774                input_streams[ost->source_index]->file_index,
2775                input_streams[ost->source_index]->st->index,
2776                ost->file_index,
2777                ost->index);
2778         if (ost->sync_ist != input_streams[ost->source_index])
2779             av_log(NULL, AV_LOG_INFO, " [sync #%d:%d]",
2780                    ost->sync_ist->file_index,
2781                    ost->sync_ist->st->index);
2782         if (ost->stream_copy)
2783             av_log(NULL, AV_LOG_INFO, " (copy)");
2784         else
2785             av_log(NULL, AV_LOG_INFO, " (%s -> %s)", input_streams[ost->source_index]->dec ?
2786                    input_streams[ost->source_index]->dec->name : "?",
2787                    ost->enc ? ost->enc->name : "?");
2788         av_log(NULL, AV_LOG_INFO, "\n");
2789     }
2790
2791     if (ret) {
2792         av_log(NULL, AV_LOG_ERROR, "%s\n", error);
2793         return ret;
2794     }
2795
2796     if (want_sdp) {
2797         print_sdp();
2798     }
2799
2800     return 0;
2801 }
2802
2803 /* Return 1 if there remain streams where more output is wanted, 0 otherwise. */
2804 static int need_output(void)
2805 {
2806     int i;
2807
2808     for (i = 0; i < nb_output_streams; i++) {
2809         OutputStream *ost    = output_streams[i];
2810         OutputFile *of       = output_files[ost->file_index];
2811         AVFormatContext *os  = output_files[ost->file_index]->ctx;
2812
2813         if (ost->finished ||
2814             (os->pb && avio_tell(os->pb) >= of->limit_filesize))
2815             continue;
2816         if (ost->frame_number >= ost->max_frames) {
2817             int j;
2818             for (j = 0; j < of->ctx->nb_streams; j++)
2819                 close_output_stream(output_streams[of->ost_index + j]);
2820             continue;
2821         }
2822
2823         return 1;
2824     }
2825
2826     return 0;
2827 }
2828
2829 /**
2830  * Select the output stream to process.
2831  *
2832  * @return  selected output stream, or NULL if none available
2833  */
2834 static OutputStream *choose_output(void)
2835 {
2836     int i;
2837     int64_t opts_min = INT64_MAX;
2838     OutputStream *ost_min = NULL;
2839
2840     for (i = 0; i < nb_output_streams; i++) {
2841         OutputStream *ost = output_streams[i];
2842         int64_t opts = av_rescale_q(ost->st->cur_dts, ost->st->time_base,
2843                                     AV_TIME_BASE_Q);
2844         if (!ost->unavailable && !ost->finished && opts < opts_min) {
2845             opts_min = opts;
2846             ost_min  = ost;
2847         }
2848     }
2849     return ost_min;
2850 }
2851
2852 static int check_keyboard_interaction(int64_t cur_time)
2853 {
2854     int i, ret, key;
2855     static int64_t last_time;
2856     if (received_nb_signals)
2857         return AVERROR_EXIT;
2858     /* read_key() returns 0 on EOF */
2859     if(cur_time - last_time >= 100000 && !run_as_daemon){
2860         key =  read_key();
2861         last_time = cur_time;
2862     }else
2863         key = -1;
2864     if (key == 'q')
2865         return AVERROR_EXIT;
2866     if (key == '+') av_log_set_level(av_log_get_level()+10);
2867     if (key == '-') av_log_set_level(av_log_get_level()-10);
2868     if (key == 's') qp_hist     ^= 1;
2869     if (key == 'h'){
2870         if (do_hex_dump){
2871             do_hex_dump = do_pkt_dump = 0;
2872         } else if(do_pkt_dump){
2873             do_hex_dump = 1;
2874         } else
2875             do_pkt_dump = 1;
2876         av_log_set_level(AV_LOG_DEBUG);
2877     }
2878     if (key == 'c' || key == 'C'){
2879         char buf[4096], target[64], command[256], arg[256] = {0};
2880         double time;
2881         int k, n = 0;
2882         fprintf(stderr, "\nEnter command: <target>|all <time>|-1 <command>[ <argument>]\n");
2883         i = 0;
2884         while ((k = read_key()) != '\n' && k != '\r' && i < sizeof(buf)-1)
2885             if (k > 0)
2886                 buf[i++] = k;
2887         buf[i] = 0;
2888         if (k > 0 &&
2889             (n = sscanf(buf, "%63[^ ] %lf %255[^ ] %255[^\n]", target, &time, command, arg)) >= 3) {
2890             av_log(NULL, AV_LOG_DEBUG, "Processing command target:%s time:%f command:%s arg:%s",
2891                    target, time, command, arg);
2892             for (i = 0; i < nb_filtergraphs; i++) {
2893                 FilterGraph *fg = filtergraphs[i];
2894                 if (fg->graph) {
2895                     if (time < 0) {
2896                         ret = avfilter_graph_send_command(fg->graph, target, command, arg, buf, sizeof(buf),
2897                                                           key == 'c' ? AVFILTER_CMD_FLAG_ONE : 0);
2898                         fprintf(stderr, "Command reply for stream %d: ret:%d res:\n%s", i, ret, buf);
2899                     } else if (key == 'c') {
2900                         fprintf(stderr, "Queing commands only on filters supporting the specific command is unsupported\n");
2901                         ret = AVERROR_PATCHWELCOME;
2902                     } else {
2903                         ret = avfilter_graph_queue_command(fg->graph, target, command, arg, 0, time);
2904                     }
2905                 }
2906             }
2907         } else {
2908             av_log(NULL, AV_LOG_ERROR,
2909                    "Parse error, at least 3 arguments were expected, "
2910                    "only %d given in string '%s'\n", n, buf);
2911         }
2912     }
2913     if (key == 'd' || key == 'D'){
2914         int debug=0;
2915         if(key == 'D') {
2916             debug = input_streams[0]->st->codec->debug<<1;
2917             if(!debug) debug = 1;
2918             while(debug & (FF_DEBUG_DCT_COEFF|FF_DEBUG_VIS_QP|FF_DEBUG_VIS_MB_TYPE)) //unsupported, would just crash
2919                 debug += debug;
2920         }else
2921             if(scanf("%d", &debug)!=1)
2922                 fprintf(stderr,"error parsing debug value\n");
2923         for(i=0;i<nb_input_streams;i++) {
2924             input_streams[i]->st->codec->debug = debug;
2925         }
2926         for(i=0;i<nb_output_streams;i++) {
2927             OutputStream *ost = output_streams[i];
2928             ost->st->codec->debug = debug;
2929         }
2930         if(debug) av_log_set_level(AV_LOG_DEBUG);
2931         fprintf(stderr,"debug=%d\n", debug);
2932     }
2933     if (key == '?'){
2934         fprintf(stderr, "key    function\n"
2935                         "?      show this help\n"
2936                         "+      increase verbosity\n"
2937                         "-      decrease verbosity\n"
2938                         "c      Send command to first matching filter supporting it\n"
2939                         "C      Send/Que command to all matching filters\n"
2940                         "D      cycle through available debug modes\n"
2941                         "h      dump packets/hex press to cycle through the 3 states\n"
2942                         "q      quit\n"
2943                         "s      Show QP histogram\n"
2944         );
2945     }
2946     return 0;
2947 }
2948
2949 #if HAVE_PTHREADS
2950 static void *input_thread(void *arg)
2951 {
2952     InputFile *f = arg;
2953     int ret = 0;
2954
2955     while (!transcoding_finished && ret >= 0) {
2956         AVPacket pkt;
2957         ret = av_read_frame(f->ctx, &pkt);
2958
2959         if (ret == AVERROR(EAGAIN)) {
2960             av_usleep(10000);
2961             ret = 0;
2962             continue;
2963         } else if (ret < 0)
2964             break;
2965
2966         pthread_mutex_lock(&f->fifo_lock);
2967         while (!av_fifo_space(f->fifo))
2968             pthread_cond_wait(&f->fifo_cond, &f->fifo_lock);
2969
2970         av_dup_packet(&pkt);
2971         av_fifo_generic_write(f->fifo, &pkt, sizeof(pkt), NULL);
2972         pthread_cond_signal(&f->fifo_cond);
2973
2974         pthread_mutex_unlock(&f->fifo_lock);
2975     }
2976
2977     pthread_mutex_lock(&f->fifo_lock);
2978     f->finished = 1;
2979     pthread_cond_signal(&f->fifo_cond);
2980     pthread_mutex_unlock(&f->fifo_lock);
2981     return NULL;
2982 }
2983
2984 static void free_input_threads(void)
2985 {
2986     int i;
2987
2988     if (nb_input_files == 1)
2989         return;
2990
2991     transcoding_finished = 1;
2992
2993     for (i = 0; i < nb_input_files; i++) {
2994         InputFile *f = input_files[i];
2995         AVPacket pkt;
2996
2997         if (!f->fifo || f->joined)
2998             continue;
2999
3000         pthread_mutex_lock(&f->fifo_lock);
3001         while (av_fifo_size(f->fifo)) {
3002             av_fifo_generic_read(f->fifo, &pkt, sizeof(pkt), NULL);
3003             av_free_packet(&pkt);
3004         }
3005         pthread_cond_signal(&f->fifo_cond);
3006         pthread_mutex_unlock(&f->fifo_lock);
3007
3008         pthread_join(f->thread, NULL);
3009         f->joined = 1;
3010
3011         while (av_fifo_size(f->fifo)) {
3012             av_fifo_generic_read(f->fifo, &pkt, sizeof(pkt), NULL);
3013             av_free_packet(&pkt);
3014         }
3015         av_fifo_free(f->fifo);
3016     }
3017 }
3018
3019 static int init_input_threads(void)
3020 {
3021     int i, ret;
3022
3023     if (nb_input_files == 1)
3024         return 0;
3025
3026     for (i = 0; i < nb_input_files; i++) {
3027         InputFile *f = input_files[i];
3028
3029         if (!(f->fifo = av_fifo_alloc(8*sizeof(AVPacket))))
3030             return AVERROR(ENOMEM);
3031
3032         if (f->ctx->pb ? !f->ctx->pb->seekable :
3033             strcmp(f->ctx->iformat->name, "lavfi"))
3034             f->non_blocking = 1;
3035
3036         pthread_mutex_init(&f->fifo_lock, NULL);
3037         pthread_cond_init (&f->fifo_cond, NULL);
3038
3039         if ((ret = pthread_create(&f->thread, NULL, input_thread, f)))
3040             return AVERROR(ret);
3041     }
3042     return 0;
3043 }
3044
3045 static int get_input_packet_mt(InputFile *f, AVPacket *pkt)
3046 {
3047     int ret = 0;
3048
3049     pthread_mutex_lock(&f->fifo_lock);
3050
3051     while (1) {
3052     if (av_fifo_size(f->fifo)) {
3053         av_fifo_generic_read(f->fifo, pkt, sizeof(*pkt), NULL);
3054         pthread_cond_signal(&f->fifo_cond);
3055         break;
3056     } else {
3057         if (f->finished) {
3058             ret = AVERROR_EOF;
3059             break;
3060         }
3061         if (f->non_blocking) {
3062             ret = AVERROR(EAGAIN);
3063             break;
3064         }
3065         pthread_cond_wait(&f->fifo_cond, &f->fifo_lock);
3066     }
3067     }
3068
3069     pthread_mutex_unlock(&f->fifo_lock);
3070
3071     return ret;
3072 }
3073 #endif
3074
3075 static int get_input_packet(InputFile *f, AVPacket *pkt)
3076 {
3077     if (f->rate_emu) {
3078         int i;
3079         for (i = 0; i < f->nb_streams; i++) {
3080             InputStream *ist = input_streams[f->ist_index + i];
3081             int64_t pts = av_rescale(ist->dts, 1000000, AV_TIME_BASE);
3082             int64_t now = av_gettime() - ist->start;
3083             if (pts > now)
3084                 return AVERROR(EAGAIN);
3085         }
3086     }
3087
3088 #if HAVE_PTHREADS
3089     if (nb_input_files > 1)
3090         return get_input_packet_mt(f, pkt);
3091 #endif
3092     return av_read_frame(f->ctx, pkt);
3093 }
3094
3095 static int got_eagain(void)
3096 {
3097     int i;
3098     for (i = 0; i < nb_output_streams; i++)
3099         if (output_streams[i]->unavailable)
3100             return 1;
3101     return 0;
3102 }
3103
3104 static void reset_eagain(void)
3105 {
3106     int i;
3107     for (i = 0; i < nb_input_files; i++)
3108         input_files[i]->eagain = 0;
3109     for (i = 0; i < nb_output_streams; i++)
3110         output_streams[i]->unavailable = 0;
3111 }
3112
3113 /*
3114  * Return
3115  * - 0 -- one packet was read and processed
3116  * - AVERROR(EAGAIN) -- no packets were available for selected file,
3117  *   this function should be called again
3118  * - AVERROR_EOF -- this function should not be called again
3119  */
3120 static int process_input(int file_index)
3121 {
3122     InputFile *ifile = input_files[file_index];
3123     AVFormatContext *is;
3124     InputStream *ist;
3125     AVPacket pkt;
3126     int ret, i, j;
3127
3128     is  = ifile->ctx;
3129     ret = get_input_packet(ifile, &pkt);
3130
3131     if (ret == AVERROR(EAGAIN)) {
3132         ifile->eagain = 1;
3133         return ret;
3134     }
3135     if (ret < 0) {
3136         if (ret != AVERROR_EOF) {
3137             print_error(is->filename, ret);
3138             if (exit_on_error)
3139                 exit_program(1);
3140         }
3141         ifile->eof_reached = 1;
3142
3143         for (i = 0; i < ifile->nb_streams; i++) {
3144             ist = input_streams[ifile->ist_index + i];
3145             if (ist->decoding_needed)
3146                 output_packet(ist, NULL);
3147
3148             /* mark all outputs that don't go through lavfi as finished */
3149             for (j = 0; j < nb_output_streams; j++) {
3150                 OutputStream *ost = output_streams[j];
3151
3152                 if (ost->source_index == ifile->ist_index + i &&
3153                     (ost->stream_copy || ost->enc->type == AVMEDIA_TYPE_SUBTITLE))
3154                     close_output_stream(ost);
3155             }
3156         }
3157
3158         return AVERROR(EAGAIN);
3159     }
3160
3161     reset_eagain();
3162
3163     if (do_pkt_dump) {
3164         av_pkt_dump_log2(NULL, AV_LOG_DEBUG, &pkt, do_hex_dump,
3165                          is->streams[pkt.stream_index]);
3166     }
3167     /* the following test is needed in case new streams appear
3168        dynamically in stream : we ignore them */
3169     if (pkt.stream_index >= ifile->nb_streams) {
3170         report_new_stream(file_index, &pkt);
3171         goto discard_packet;
3172     }
3173
3174     ist = input_streams[ifile->ist_index + pkt.stream_index];
3175     if (ist->discard)
3176         goto discard_packet;
3177
3178     if (debug_ts) {
3179         av_log(NULL, AV_LOG_INFO, "demuxer -> ist_index:%d type:%s "
3180                "next_dts:%s next_dts_time:%s next_pts:%s next_pts_time:%s pkt_pts:%s pkt_pts_time:%s pkt_dts:%s pkt_dts_time:%s off:%s off_time:%s\n",
3181                ifile->ist_index + pkt.stream_index, av_get_media_type_string(ist->st->codec->codec_type),
3182                av_ts2str(ist->next_dts), av_ts2timestr(ist->next_dts, &AV_TIME_BASE_Q),
3183                av_ts2str(ist->next_pts), av_ts2timestr(ist->next_pts, &AV_TIME_BASE_Q),
3184                av_ts2str(pkt.pts), av_ts2timestr(pkt.pts, &ist->st->time_base),
3185                av_ts2str(pkt.dts), av_ts2timestr(pkt.dts, &ist->st->time_base),
3186                av_ts2str(input_files[ist->file_index]->ts_offset),
3187                av_ts2timestr(input_files[ist->file_index]->ts_offset, &AV_TIME_BASE_Q));
3188     }
3189
3190     if(!ist->wrap_correction_done && is->start_time != AV_NOPTS_VALUE && ist->st->pts_wrap_bits < 64){
3191         int64_t stime, stime2;
3192         // Correcting starttime based on the enabled streams
3193         // FIXME this ideally should be done before the first use of starttime but we do not know which are the enabled streams at that point.
3194         //       so we instead do it here as part of discontinuity handling
3195         if (   ist->next_dts == AV_NOPTS_VALUE
3196             && ifile->ts_offset == -is->start_time
3197             && (is->iformat->flags & AVFMT_TS_DISCONT)) {
3198             int64_t new_start_time = INT64_MAX;
3199             for (i=0; i<is->nb_streams; i++) {
3200                 AVStream *st = is->streams[i];
3201                 if(st->discard == AVDISCARD_ALL || st->start_time == AV_NOPTS_VALUE)
3202                     continue;
3203                 new_start_time = FFMIN(new_start_time, av_rescale_q(st->start_time, st->time_base, AV_TIME_BASE_Q));
3204             }
3205             if (new_start_time > is->start_time) {
3206                 av_log(is, AV_LOG_VERBOSE, "Correcting start time by %"PRId64"\n", new_start_time - is->start_time);
3207                 ifile->ts_offset = -new_start_time;
3208             }
3209         }
3210
3211         stime = av_rescale_q(is->start_time, AV_TIME_BASE_Q, ist->st->time_base);
3212         stime2= stime + (1ULL<<ist->st->pts_wrap_bits);
3213         ist->wrap_correction_done = 1;
3214
3215         if(stime2 > stime && pkt.dts != AV_NOPTS_VALUE && pkt.dts > stime + (1LL<<(ist->st->pts_wrap_bits-1))) {
3216             pkt.dts -= 1ULL<<ist->st->pts_wrap_bits;
3217             ist->wrap_correction_done = 0;
3218         }
3219         if(stime2 > stime && pkt.pts != AV_NOPTS_VALUE && pkt.pts > stime + (1LL<<(ist->st->pts_wrap_bits-1))) {
3220             pkt.pts -= 1ULL<<ist->st->pts_wrap_bits;
3221             ist->wrap_correction_done = 0;
3222         }
3223     }
3224
3225     if (pkt.dts != AV_NOPTS_VALUE)
3226         pkt.dts += av_rescale_q(ifile->ts_offset, AV_TIME_BASE_Q, ist->st->time_base);
3227     if (pkt.pts != AV_NOPTS_VALUE)
3228         pkt.pts += av_rescale_q(ifile->ts_offset, AV_TIME_BASE_Q, ist->st->time_base);
3229
3230     if (pkt.pts != AV_NOPTS_VALUE)
3231         pkt.pts *= ist->ts_scale;
3232     if (pkt.dts != AV_NOPTS_VALUE)
3233         pkt.dts *= ist->ts_scale;
3234
3235     if (pkt.dts != AV_NOPTS_VALUE && ist->next_dts == AV_NOPTS_VALUE && !copy_ts
3236         && (is->iformat->flags & AVFMT_TS_DISCONT) && ifile->last_ts != AV_NOPTS_VALUE) {
3237         int64_t pkt_dts = av_rescale_q(pkt.dts, ist->st->time_base, AV_TIME_BASE_Q);
3238         int64_t delta   = pkt_dts - ifile->last_ts;
3239         if(delta < -1LL*dts_delta_threshold*AV_TIME_BASE ||
3240             (delta > 1LL*dts_delta_threshold*AV_TIME_BASE &&
3241                 ist->st->codec->codec_type != AVMEDIA_TYPE_SUBTITLE)){
3242             ifile->ts_offset -= delta;
3243             av_log(NULL, AV_LOG_DEBUG,
3244                    "Inter stream timestamp discontinuity %"PRId64", new offset= %"PRId64"\n",
3245                    delta, ifile->ts_offset);
3246             pkt.dts -= av_rescale_q(delta, AV_TIME_BASE_Q, ist->st->time_base);
3247             if (pkt.pts != AV_NOPTS_VALUE)
3248                 pkt.pts -= av_rescale_q(delta, AV_TIME_BASE_Q, ist->st->time_base);
3249         }
3250     }
3251
3252     if (pkt.dts != AV_NOPTS_VALUE && ist->next_dts != AV_NOPTS_VALUE &&
3253         !copy_ts) {
3254         int64_t pkt_dts = av_rescale_q(pkt.dts, ist->st->time_base, AV_TIME_BASE_Q);
3255         int64_t delta   = pkt_dts - ist->next_dts;
3256         if (is->iformat->flags & AVFMT_TS_DISCONT) {
3257             if (delta < -1LL*dts_delta_threshold*AV_TIME_BASE ||
3258                 (delta > 1LL*dts_delta_threshold*AV_TIME_BASE &&
3259                  ist->st->codec->codec_type != AVMEDIA_TYPE_SUBTITLE) ||
3260                 pkt_dts + AV_TIME_BASE/10 < FFMAX(ist->pts, ist->dts)) {
3261                 ifile->ts_offset -= delta;
3262                 av_log(NULL, AV_LOG_DEBUG,
3263                        "timestamp discontinuity %"PRId64", new offset= %"PRId64"\n",
3264                        delta, ifile->ts_offset);
3265                 pkt.dts -= av_rescale_q(delta, AV_TIME_BASE_Q, ist->st->time_base);
3266                 if (pkt.pts != AV_NOPTS_VALUE)
3267                     pkt.pts -= av_rescale_q(delta, AV_TIME_BASE_Q, ist->st->time_base);
3268             }
3269         } else {
3270             if ( delta < -1LL*dts_error_threshold*AV_TIME_BASE ||
3271                 (delta > 1LL*dts_error_threshold*AV_TIME_BASE && ist->st->codec->codec_type != AVMEDIA_TYPE_SUBTITLE)) {
3272                 av_log(NULL, AV_LOG_WARNING, "DTS %"PRId64", next:%"PRId64" st:%d invalid dropping\n", pkt.dts, ist->next_dts, pkt.stream_index);
3273                 pkt.dts = AV_NOPTS_VALUE;
3274             }
3275             if (pkt.pts != AV_NOPTS_VALUE){
3276                 int64_t pkt_pts = av_rescale_q(pkt.pts, ist->st->time_base, AV_TIME_BASE_Q);
3277                 delta   = pkt_pts - ist->next_dts;
3278                 if ( delta < -1LL*dts_error_threshold*AV_TIME_BASE ||
3279                     (delta > 1LL*dts_error_threshold*AV_TIME_BASE && ist->st->codec->codec_type != AVMEDIA_TYPE_SUBTITLE)) {
3280                     av_log(NULL, AV_LOG_WARNING, "PTS %"PRId64", next:%"PRId64" invalid dropping st:%d\n", pkt.pts, ist->next_dts, pkt.stream_index);
3281                     pkt.pts = AV_NOPTS_VALUE;
3282                 }
3283             }
3284         }
3285     }
3286
3287     if (pkt.dts != AV_NOPTS_VALUE)
3288         ifile->last_ts = av_rescale_q(pkt.dts, ist->st->time_base, AV_TIME_BASE_Q);
3289
3290     if (debug_ts) {
3291         av_log(NULL, AV_LOG_INFO, "demuxer+ffmpeg -> ist_index:%d type:%s pkt_pts:%s pkt_pts_time:%s pkt_dts:%s pkt_dts_time:%s off:%s off_time:%s\n",
3292                ifile->ist_index + pkt.stream_index, av_get_media_type_string(ist->st->codec->codec_type),
3293                av_ts2str(pkt.pts), av_ts2timestr(pkt.pts, &ist->st->time_base),
3294                av_ts2str(pkt.dts), av_ts2timestr(pkt.dts, &ist->st->time_base),
3295                av_ts2str(input_files[ist->file_index]->ts_offset),
3296                av_ts2timestr(input_files[ist->file_index]->ts_offset, &AV_TIME_BASE_Q));
3297     }
3298
3299     sub2video_heartbeat(ist, pkt.pts);
3300
3301     ret = output_packet(ist, &pkt);
3302     if (ret < 0) {
3303         av_log(NULL, AV_LOG_ERROR, "Error while decoding stream #%d:%d: %s\n",
3304                ist->file_index, ist->st->index, av_err2str(ret));
3305         if (exit_on_error)
3306             exit_program(1);
3307     }
3308
3309 discard_packet:
3310     av_free_packet(&pkt);
3311
3312     return 0;
3313 }
3314
3315 /**
3316  * Perform a step of transcoding for the specified filter graph.
3317  *
3318  * @param[in]  graph     filter graph to consider
3319  * @param[out] best_ist  input stream where a frame would allow to continue
3320  * @return  0 for success, <0 for error
3321  */
3322 static int transcode_from_filter(FilterGraph *graph, InputStream **best_ist)
3323 {
3324     int i, ret;
3325     int nb_requests, nb_requests_max = 0;
3326     InputFilter *ifilter;
3327     InputStream *ist;
3328
3329     *best_ist = NULL;
3330     ret = avfilter_graph_request_oldest(graph->graph);
3331     if (ret >= 0)
3332         return reap_filters();
3333
3334     if (ret == AVERROR_EOF) {
3335         ret = reap_filters();
3336         for (i = 0; i < graph->nb_outputs; i++)
3337             close_output_stream(graph->outputs[i]->ost);
3338         return ret;
3339     }
3340     if (ret != AVERROR(EAGAIN))
3341         return ret;
3342
3343     for (i = 0; i < graph->nb_inputs; i++) {
3344         ifilter = graph->inputs[i];
3345         ist = ifilter->ist;
3346         if (input_files[ist->file_index]->eagain ||
3347             input_files[ist->file_index]->eof_reached)
3348             continue;
3349         nb_requests = av_buffersrc_get_nb_failed_requests(ifilter->filter);
3350         if (nb_requests > nb_requests_max) {
3351             nb_requests_max = nb_requests;
3352             *best_ist = ist;
3353         }
3354     }
3355
3356     if (!*best_ist)
3357         for (i = 0; i < graph->nb_outputs; i++)
3358             graph->outputs[i]->ost->unavailable = 1;
3359
3360     return 0;
3361 }
3362
3363 /**
3364  * Run a single step of transcoding.
3365  *
3366  * @return  0 for success, <0 for error
3367  */
3368 static int transcode_step(void)
3369 {
3370     OutputStream *ost;
3371     InputStream  *ist;
3372     int ret;
3373
3374     ost = choose_output();
3375     if (!ost) {
3376         if (got_eagain()) {
3377             reset_eagain();
3378             av_usleep(10000);
3379             return 0;
3380         }
3381         av_log(NULL, AV_LOG_VERBOSE, "No more inputs to read from, finishing.\n");
3382         return AVERROR_EOF;
3383     }
3384
3385     if (ost->filter) {
3386         if ((ret = transcode_from_filter(ost->filter->graph, &ist)) < 0)
3387             return ret;
3388         if (!ist)
3389             return 0;
3390     } else {
3391         av_assert0(ost->source_index >= 0);
3392         ist = input_streams[ost->source_index];
3393     }
3394
3395     ret = process_input(ist->file_index);
3396     if (ret == AVERROR(EAGAIN)) {
3397         if (input_files[ist->file_index]->eagain)
3398             ost->unavailable = 1;
3399         return 0;
3400     }
3401     if (ret < 0)
3402         return ret == AVERROR_EOF ? 0 : ret;
3403
3404     return reap_filters();
3405 }
3406
3407 /*
3408  * The following code is the main loop of the file converter
3409  */
3410 static int transcode(void)
3411 {
3412     int ret, i;
3413     AVFormatContext *os;
3414     OutputStream *ost;
3415     InputStream *ist;
3416     int64_t timer_start;
3417
3418     ret = transcode_init();
3419     if (ret < 0)
3420         goto fail;
3421
3422     if (stdin_interaction) {
3423         av_log(NULL, AV_LOG_INFO, "Press [q] to stop, [?] for help\n");
3424     }
3425
3426     timer_start = av_gettime();
3427
3428 #if HAVE_PTHREADS
3429     if ((ret = init_input_threads()) < 0)
3430         goto fail;
3431 #endif
3432
3433     while (!received_sigterm) {
3434         int64_t cur_time= av_gettime();
3435
3436         /* if 'q' pressed, exits */
3437         if (stdin_interaction)
3438             if (check_keyboard_interaction(cur_time) < 0)
3439                 break;
3440
3441         /* check if there's any stream where output is still needed */
3442         if (!need_output()) {
3443             av_log(NULL, AV_LOG_VERBOSE, "No more output streams to write to, finishing.\n");
3444             break;
3445         }
3446
3447         ret = transcode_step();
3448         if (ret < 0) {
3449             if (ret == AVERROR_EOF || ret == AVERROR(EAGAIN))
3450                 continue;
3451
3452             av_log(NULL, AV_LOG_ERROR, "Error while filtering.\n");
3453             break;
3454         }
3455
3456         /* dump report by using the output first video and audio streams */
3457         print_report(0, timer_start, cur_time);
3458     }
3459 #if HAVE_PTHREADS
3460     free_input_threads();
3461 #endif
3462
3463     /* at the end of stream, we must flush the decoder buffers */
3464     for (i = 0; i < nb_input_streams; i++) {
3465         ist = input_streams[i];
3466         if (!input_files[ist->file_index]->eof_reached && ist->decoding_needed) {
3467             output_packet(ist, NULL);
3468         }
3469     }
3470     flush_encoders();
3471
3472     term_exit();
3473
3474     /* write the trailer if needed and close file */
3475     for (i = 0; i < nb_output_files; i++) {
3476         os = output_files[i]->ctx;
3477         av_write_trailer(os);
3478     }
3479
3480     /* dump report by using the first video and audio streams */
3481     print_report(1, timer_start, av_gettime());
3482
3483     /* close each encoder */
3484     for (i = 0; i < nb_output_streams; i++) {
3485         ost = output_streams[i];
3486         if (ost->encoding_needed) {
3487             av_freep(&ost->st->codec->stats_in);
3488             avcodec_close(ost->st->codec);
3489         }
3490     }
3491
3492     /* close each decoder */
3493     for (i = 0; i < nb_input_streams; i++) {
3494         ist = input_streams[i];
3495         if (ist->decoding_needed) {
3496             avcodec_close(ist->st->codec);
3497             if (ist->hwaccel_uninit)
3498                 ist->hwaccel_uninit(ist->st->codec);
3499         }
3500     }
3501
3502     /* finished ! */
3503     ret = 0;
3504
3505  fail:
3506 #if HAVE_PTHREADS
3507     free_input_threads();
3508 #endif
3509
3510     if (output_streams) {
3511         for (i = 0; i < nb_output_streams; i++) {
3512             ost = output_streams[i];
3513             if (ost) {
3514                 if (ost->stream_copy)
3515                     av_freep(&ost->st->codec->extradata);
3516                 if (ost->logfile) {
3517                     fclose(ost->logfile);
3518                     ost->logfile = NULL;
3519                 }
3520                 av_freep(&ost->st->codec->subtitle_header);
3521                 av_freep(&ost->forced_kf_pts);
3522                 av_freep(&ost->apad);
3523                 av_dict_free(&ost->opts);
3524                 av_dict_free(&ost->swr_opts);
3525                 av_dict_free(&ost->resample_opts);
3526             }
3527         }
3528     }
3529     return ret;
3530 }
3531
3532
3533 static int64_t getutime(void)
3534 {
3535 #if HAVE_GETRUSAGE
3536     struct rusage rusage;
3537
3538     getrusage(RUSAGE_SELF, &rusage);
3539     return (rusage.ru_utime.tv_sec * 1000000LL) + rusage.ru_utime.tv_usec;
3540 #elif HAVE_GETPROCESSTIMES
3541     HANDLE proc;
3542     FILETIME c, e, k, u;
3543     proc = GetCurrentProcess();
3544     GetProcessTimes(proc, &c, &e, &k, &u);
3545     return ((int64_t) u.dwHighDateTime << 32 | u.dwLowDateTime) / 10;
3546 #else
3547     return av_gettime();
3548 #endif
3549 }
3550
3551 static int64_t getmaxrss(void)
3552 {
3553 #if HAVE_GETRUSAGE && HAVE_STRUCT_RUSAGE_RU_MAXRSS
3554     struct rusage rusage;
3555     getrusage(RUSAGE_SELF, &rusage);
3556     return (int64_t)rusage.ru_maxrss * 1024;
3557 #elif HAVE_GETPROCESSMEMORYINFO
3558     HANDLE proc;
3559     PROCESS_MEMORY_COUNTERS memcounters;
3560     proc = GetCurrentProcess();
3561     memcounters.cb = sizeof(memcounters);
3562     GetProcessMemoryInfo(proc, &memcounters, sizeof(memcounters));
3563     return memcounters.PeakPagefileUsage;
3564 #else
3565     return 0;
3566 #endif
3567 }
3568
3569 static void log_callback_null(void *ptr, int level, const char *fmt, va_list vl)
3570 {
3571 }
3572
3573 int main(int argc, char **argv)
3574 {
3575     int ret;
3576     int64_t ti;
3577
3578     register_exit(ffmpeg_cleanup);
3579
3580     setvbuf(stderr,NULL,_IONBF,0); /* win32 runtime needs this */
3581
3582     av_log_set_flags(AV_LOG_SKIP_REPEATED);
3583     parse_loglevel(argc, argv, options);
3584
3585     if(argc>1 && !strcmp(argv[1], "-d")){
3586         run_as_daemon=1;
3587         av_log_set_callback(log_callback_null);
3588         argc--;
3589         argv++;
3590     }
3591
3592     avcodec_register_all();
3593 #if CONFIG_AVDEVICE
3594     avdevice_register_all();
3595 #endif
3596     avfilter_register_all();
3597     av_register_all();
3598     avformat_network_init();
3599
3600     show_banner(argc, argv, options);
3601
3602     term_init();
3603
3604     /* parse options and open all input/output files */
3605     ret = ffmpeg_parse_options(argc, argv);
3606     if (ret < 0)
3607         exit_program(1);
3608
3609     if (nb_output_files <= 0 && nb_input_files == 0) {
3610         show_usage();
3611         av_log(NULL, AV_LOG_WARNING, "Use -h to get full help or, even better, run 'man %s'\n", program_name);
3612         exit_program(1);
3613     }
3614
3615     /* file converter / grab */
3616     if (nb_output_files <= 0) {
3617         av_log(NULL, AV_LOG_FATAL, "At least one output file must be specified\n");
3618         exit_program(1);
3619     }
3620
3621 //     if (nb_input_files == 0) {
3622 //         av_log(NULL, AV_LOG_FATAL, "At least one input file must be specified\n");
3623 //         exit_program(1);
3624 //     }
3625
3626     current_time = ti = getutime();
3627     if (transcode() < 0)
3628         exit_program(1);
3629     ti = getutime() - ti;
3630     if (do_benchmark) {
3631         printf("bench: utime=%0.3fs\n", ti / 1000000.0);
3632     }
3633     av_log(NULL, AV_LOG_DEBUG, "%"PRIu64" frames successfully decoded, %"PRIu64" decoding errors\n",
3634            decode_error_stat[0], decode_error_stat[1]);
3635     if ((decode_error_stat[0] + decode_error_stat[1]) * max_error_rate < decode_error_stat[1])
3636         exit_program(69);
3637
3638     exit_program(received_nb_signals ? 255 : main_return_code);
3639     return main_return_code;
3640 }