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