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