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