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