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