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