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