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