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