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