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