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