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