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