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