]> git.sesse.net Git - ffmpeg/blob - ffmpeg.c
Merge commit '4d0d55cd623bcd504867f948849380f6b4060b4d'
[ffmpeg] / 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 #include <stdint.h>
34
35 #if HAVE_ISATTY
36 #if HAVE_IO_H
37 #include <io.h>
38 #endif
39 #if HAVE_UNISTD_H
40 #include <unistd.h>
41 #endif
42 #endif
43
44 #include "libavformat/avformat.h"
45 #include "libavdevice/avdevice.h"
46 #include "libswresample/swresample.h"
47 #include "libavutil/opt.h"
48 #include "libavutil/channel_layout.h"
49 #include "libavutil/parseutils.h"
50 #include "libavutil/samplefmt.h"
51 #include "libavutil/fifo.h"
52 #include "libavutil/internal.h"
53 #include "libavutil/intreadwrite.h"
54 #include "libavutil/dict.h"
55 #include "libavutil/mathematics.h"
56 #include "libavutil/pixdesc.h"
57 #include "libavutil/avstring.h"
58 #include "libavutil/libm.h"
59 #include "libavutil/imgutils.h"
60 #include "libavutil/timestamp.h"
61 #include "libavutil/bprint.h"
62 #include "libavutil/time.h"
63 #include "libavutil/threadmessage.h"
64 #include "libavcodec/mathops.h"
65 #include "libavformat/os_support.h"
66
67 # include "libavfilter/avcodec.h"
68 # include "libavfilter/avfilter.h"
69 # include "libavfilter/buffersrc.h"
70 # include "libavfilter/buffersink.h"
71
72 #if HAVE_SYS_RESOURCE_H
73 #include <sys/time.h>
74 #include <sys/types.h>
75 #include <sys/resource.h>
76 #elif HAVE_GETPROCESSTIMES
77 #include <windows.h>
78 #endif
79 #if HAVE_GETPROCESSMEMORYINFO
80 #include <windows.h>
81 #include <psapi.h>
82 #endif
83 #if HAVE_SETCONSOLECTRLHANDLER
84 #include <windows.h>
85 #endif
86
87
88 #if HAVE_SYS_SELECT_H
89 #include <sys/select.h>
90 #endif
91
92 #if HAVE_TERMIOS_H
93 #include <fcntl.h>
94 #include <sys/ioctl.h>
95 #include <sys/time.h>
96 #include <termios.h>
97 #elif HAVE_KBHIT
98 #include <conio.h>
99 #endif
100
101 #if HAVE_PTHREADS
102 #include <pthread.h>
103 #endif
104
105 #include <time.h>
106
107 #include "ffmpeg.h"
108 #include "cmdutils.h"
109
110 #include "libavutil/avassert.h"
111
112 const char program_name[] = "ffmpeg";
113 const int program_birth_year = 2000;
114
115 static FILE *vstats_file;
116
117 const char *const forced_keyframes_const_names[] = {
118     "n",
119     "n_forced",
120     "prev_forced_n",
121     "prev_forced_t",
122     "t",
123     NULL
124 };
125
126 static void do_video_stats(OutputStream *ost, int frame_size);
127 static int64_t getutime(void);
128 static int64_t getmaxrss(void);
129
130 static int run_as_daemon  = 0;
131 static int nb_frames_dup = 0;
132 static int nb_frames_drop = 0;
133 static int64_t decode_error_stat[2];
134
135 static int current_time;
136 AVIOContext *progress_avio = NULL;
137
138 static uint8_t *subtitle_out;
139
140 InputStream **input_streams = NULL;
141 int        nb_input_streams = 0;
142 InputFile   **input_files   = NULL;
143 int        nb_input_files   = 0;
144
145 OutputStream **output_streams = NULL;
146 int         nb_output_streams = 0;
147 OutputFile   **output_files   = NULL;
148 int         nb_output_files   = 0;
149
150 FilterGraph **filtergraphs;
151 int        nb_filtergraphs;
152
153 #if HAVE_TERMIOS_H
154
155 /* init terminal so that we can grab keys */
156 static struct termios oldtty;
157 static int restore_tty;
158 #endif
159
160 #if HAVE_PTHREADS
161 static void free_input_threads(void);
162 #endif
163
164 /* sub2video hack:
165    Convert subtitles to video with alpha to insert them in filter graphs.
166    This is a temporary solution until libavfilter gets real subtitles support.
167  */
168
169 static int sub2video_get_blank_frame(InputStream *ist)
170 {
171     int ret;
172     AVFrame *frame = ist->sub2video.frame;
173
174     av_frame_unref(frame);
175     ist->sub2video.frame->width  = ist->sub2video.w;
176     ist->sub2video.frame->height = ist->sub2video.h;
177     ist->sub2video.frame->format = AV_PIX_FMT_RGB32;
178     if ((ret = av_frame_get_buffer(frame, 32)) < 0)
179         return ret;
180     memset(frame->data[0], 0, frame->height * frame->linesize[0]);
181     return 0;
182 }
183
184 static void sub2video_copy_rect(uint8_t *dst, int dst_linesize, int w, int h,
185                                 AVSubtitleRect *r)
186 {
187     uint32_t *pal, *dst2;
188     uint8_t *src, *src2;
189     int x, y;
190
191     if (r->type != SUBTITLE_BITMAP) {
192         av_log(NULL, AV_LOG_WARNING, "sub2video: non-bitmap subtitle\n");
193         return;
194     }
195     if (r->x < 0 || r->x + r->w > w || r->y < 0 || r->y + r->h > h) {
196         av_log(NULL, AV_LOG_WARNING, "sub2video: rectangle overflowing\n");
197         return;
198     }
199
200     dst += r->y * dst_linesize + r->x * 4;
201     src = r->pict.data[0];
202     pal = (uint32_t *)r->pict.data[1];
203     for (y = 0; y < r->h; y++) {
204         dst2 = (uint32_t *)dst;
205         src2 = src;
206         for (x = 0; x < r->w; x++)
207             *(dst2++) = pal[*(src2++)];
208         dst += dst_linesize;
209         src += r->pict.linesize[0];
210     }
211 }
212
213 static void sub2video_push_ref(InputStream *ist, int64_t pts)
214 {
215     AVFrame *frame = ist->sub2video.frame;
216     int i;
217
218     av_assert1(frame->data[0]);
219     ist->sub2video.last_pts = frame->pts = pts;
220     for (i = 0; i < ist->nb_filters; i++)
221         av_buffersrc_add_frame_flags(ist->filters[i]->filter, frame,
222                                      AV_BUFFERSRC_FLAG_KEEP_REF |
223                                      AV_BUFFERSRC_FLAG_PUSH);
224 }
225
226 static void sub2video_update(InputStream *ist, AVSubtitle *sub)
227 {
228     int w = ist->sub2video.w, h = ist->sub2video.h;
229     AVFrame *frame = ist->sub2video.frame;
230     int8_t *dst;
231     int     dst_linesize;
232     int num_rects, i;
233     int64_t pts, end_pts;
234
235     if (!frame)
236         return;
237     if (sub) {
238         pts       = av_rescale_q(sub->pts + sub->start_display_time * 1000LL,
239                                  AV_TIME_BASE_Q, ist->st->time_base);
240         end_pts   = av_rescale_q(sub->pts + sub->end_display_time   * 1000LL,
241                                  AV_TIME_BASE_Q, ist->st->time_base);
242         num_rects = sub->num_rects;
243     } else {
244         pts       = ist->sub2video.end_pts;
245         end_pts   = INT64_MAX;
246         num_rects = 0;
247     }
248     if (sub2video_get_blank_frame(ist) < 0) {
249         av_log(ist->dec_ctx, AV_LOG_ERROR,
250                "Impossible to get a blank canvas.\n");
251         return;
252     }
253     dst          = frame->data    [0];
254     dst_linesize = frame->linesize[0];
255     for (i = 0; i < num_rects; i++)
256         sub2video_copy_rect(dst, dst_linesize, w, h, sub->rects[i]);
257     sub2video_push_ref(ist, pts);
258     ist->sub2video.end_pts = end_pts;
259 }
260
261 static void sub2video_heartbeat(InputStream *ist, int64_t pts)
262 {
263     InputFile *infile = input_files[ist->file_index];
264     int i, j, nb_reqs;
265     int64_t pts2;
266
267     /* When a frame is read from a file, examine all sub2video streams in
268        the same file and send the sub2video frame again. Otherwise, decoded
269        video frames could be accumulating in the filter graph while a filter
270        (possibly overlay) is desperately waiting for a subtitle frame. */
271     for (i = 0; i < infile->nb_streams; i++) {
272         InputStream *ist2 = input_streams[infile->ist_index + i];
273         if (!ist2->sub2video.frame)
274             continue;
275         /* subtitles seem to be usually muxed ahead of other streams;
276            if not, subtracting a larger time here is necessary */
277         pts2 = av_rescale_q(pts, ist->st->time_base, ist2->st->time_base) - 1;
278         /* do not send the heartbeat frame if the subtitle is already ahead */
279         if (pts2 <= ist2->sub2video.last_pts)
280             continue;
281         if (pts2 >= ist2->sub2video.end_pts || !ist2->sub2video.frame->data[0])
282             sub2video_update(ist2, NULL);
283         for (j = 0, nb_reqs = 0; j < ist2->nb_filters; j++)
284             nb_reqs += av_buffersrc_get_nb_failed_requests(ist2->filters[j]->filter);
285         if (nb_reqs)
286             sub2video_push_ref(ist2, pts2);
287     }
288 }
289
290 static void sub2video_flush(InputStream *ist)
291 {
292     int i;
293
294     if (ist->sub2video.end_pts < INT64_MAX)
295         sub2video_update(ist, NULL);
296     for (i = 0; i < ist->nb_filters; i++)
297         av_buffersrc_add_ref(ist->filters[i]->filter, NULL, 0);
298 }
299
300 /* end of sub2video hack */
301
302 static void term_exit_sigsafe(void)
303 {
304 #if HAVE_TERMIOS_H
305     if(restore_tty)
306         tcsetattr (0, TCSANOW, &oldtty);
307 #endif
308 }
309
310 void term_exit(void)
311 {
312     av_log(NULL, AV_LOG_QUIET, "%s", "");
313     term_exit_sigsafe();
314 }
315
316 static volatile int received_sigterm = 0;
317 static volatile int received_nb_signals = 0;
318 static volatile int transcode_init_done = 0;
319 static volatile int ffmpeg_exited = 0;
320 static int main_return_code = 0;
321
322 static void
323 sigterm_handler(int sig)
324 {
325     received_sigterm = sig;
326     received_nb_signals++;
327     term_exit_sigsafe();
328     if(received_nb_signals > 3) {
329         write(2/*STDERR_FILENO*/, "Received > 3 system signals, hard exiting\n",
330                            strlen("Received > 3 system signals, hard exiting\n"));
331
332         exit(123);
333     }
334 }
335
336 #if HAVE_SETCONSOLECTRLHANDLER
337 static BOOL WINAPI CtrlHandler(DWORD fdwCtrlType)
338 {
339     av_log(NULL, AV_LOG_DEBUG, "\nReceived windows signal %ld\n", fdwCtrlType);
340
341     switch (fdwCtrlType)
342     {
343     case CTRL_C_EVENT:
344     case CTRL_BREAK_EVENT:
345         sigterm_handler(SIGINT);
346         return TRUE;
347
348     case CTRL_CLOSE_EVENT:
349     case CTRL_LOGOFF_EVENT:
350     case CTRL_SHUTDOWN_EVENT:
351         sigterm_handler(SIGTERM);
352         /* Basically, with these 3 events, when we return from this method the
353            process is hard terminated, so stall as long as we need to
354            to try and let the main thread(s) clean up and gracefully terminate
355            (we have at most 5 seconds, but should be done far before that). */
356         while (!ffmpeg_exited) {
357             Sleep(0);
358         }
359         return TRUE;
360
361     default:
362         av_log(NULL, AV_LOG_ERROR, "Received unknown windows signal %ld\n", fdwCtrlType);
363         return FALSE;
364     }
365 }
366 #endif
367
368 void term_init(void)
369 {
370 #if HAVE_TERMIOS_H
371     if(!run_as_daemon){
372         struct termios tty;
373         int istty = 1;
374 #if HAVE_ISATTY
375         istty = isatty(0) && isatty(2);
376 #endif
377         if (istty && tcgetattr (0, &tty) == 0) {
378             oldtty = tty;
379             restore_tty = 1;
380
381             tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
382                              |INLCR|IGNCR|ICRNL|IXON);
383             tty.c_oflag |= OPOST;
384             tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
385             tty.c_cflag &= ~(CSIZE|PARENB);
386             tty.c_cflag |= CS8;
387             tty.c_cc[VMIN] = 1;
388             tty.c_cc[VTIME] = 0;
389
390             tcsetattr (0, TCSANOW, &tty);
391         }
392         signal(SIGQUIT, sigterm_handler); /* Quit (POSIX).  */
393     }
394 #endif
395
396     signal(SIGINT , sigterm_handler); /* Interrupt (ANSI).    */
397     signal(SIGTERM, sigterm_handler); /* Termination (ANSI).  */
398 #ifdef SIGXCPU
399     signal(SIGXCPU, sigterm_handler);
400 #endif
401 #if HAVE_SETCONSOLECTRLHANDLER
402     SetConsoleCtrlHandler((PHANDLER_ROUTINE) CtrlHandler, TRUE);
403 #endif
404 }
405
406 /* read a key without blocking */
407 static int read_key(void)
408 {
409     unsigned char ch;
410 #if HAVE_TERMIOS_H
411     int n = 1;
412     struct timeval tv;
413     fd_set rfds;
414
415     FD_ZERO(&rfds);
416     FD_SET(0, &rfds);
417     tv.tv_sec = 0;
418     tv.tv_usec = 0;
419     n = select(1, &rfds, NULL, NULL, &tv);
420     if (n > 0) {
421         n = read(0, &ch, 1);
422         if (n == 1)
423             return ch;
424
425         return n;
426     }
427 #elif HAVE_KBHIT
428 #    if HAVE_PEEKNAMEDPIPE
429     static int is_pipe;
430     static HANDLE input_handle;
431     DWORD dw, nchars;
432     if(!input_handle){
433         input_handle = GetStdHandle(STD_INPUT_HANDLE);
434         is_pipe = !GetConsoleMode(input_handle, &dw);
435     }
436
437     if (stdin->_cnt > 0) {
438         read(0, &ch, 1);
439         return ch;
440     }
441     if (is_pipe) {
442         /* When running under a GUI, you will end here. */
443         if (!PeekNamedPipe(input_handle, NULL, 0, NULL, &nchars, NULL)) {
444             // input pipe may have been closed by the program that ran ffmpeg
445             return -1;
446         }
447         //Read it
448         if(nchars != 0) {
449             read(0, &ch, 1);
450             return ch;
451         }else{
452             return -1;
453         }
454     }
455 #    endif
456     if(kbhit())
457         return(getch());
458 #endif
459     return -1;
460 }
461
462 static int decode_interrupt_cb(void *ctx)
463 {
464     return received_nb_signals > transcode_init_done;
465 }
466
467 const AVIOInterruptCB int_cb = { decode_interrupt_cb, NULL };
468
469 static void ffmpeg_cleanup(int ret)
470 {
471     int i, j;
472
473     if (do_benchmark) {
474         int maxrss = getmaxrss() / 1024;
475         av_log(NULL, AV_LOG_INFO, "bench: maxrss=%ikB\n", maxrss);
476     }
477
478     for (i = 0; i < nb_filtergraphs; i++) {
479         FilterGraph *fg = filtergraphs[i];
480         avfilter_graph_free(&fg->graph);
481         for (j = 0; j < fg->nb_inputs; j++) {
482             av_freep(&fg->inputs[j]->name);
483             av_freep(&fg->inputs[j]);
484         }
485         av_freep(&fg->inputs);
486         for (j = 0; j < fg->nb_outputs; j++) {
487             av_freep(&fg->outputs[j]->name);
488             av_freep(&fg->outputs[j]);
489         }
490         av_freep(&fg->outputs);
491         av_freep(&fg->graph_desc);
492
493         av_freep(&filtergraphs[i]);
494     }
495     av_freep(&filtergraphs);
496
497     av_freep(&subtitle_out);
498
499     /* close files */
500     for (i = 0; i < nb_output_files; i++) {
501         OutputFile *of = output_files[i];
502         AVFormatContext *s;
503         if (!of)
504             continue;
505         s = of->ctx;
506         if (s && s->oformat && !(s->oformat->flags & AVFMT_NOFILE))
507             avio_closep(&s->pb);
508         avformat_free_context(s);
509         av_dict_free(&of->opts);
510
511         av_freep(&output_files[i]);
512     }
513     for (i = 0; i < nb_output_streams; i++) {
514         OutputStream *ost = output_streams[i];
515         AVBitStreamFilterContext *bsfc;
516
517         if (!ost)
518             continue;
519
520         bsfc = ost->bitstream_filters;
521         while (bsfc) {
522             AVBitStreamFilterContext *next = bsfc->next;
523             av_bitstream_filter_close(bsfc);
524             bsfc = next;
525         }
526         ost->bitstream_filters = NULL;
527         av_frame_free(&ost->filtered_frame);
528         av_frame_free(&ost->last_frame);
529
530         av_parser_close(ost->parser);
531
532         av_freep(&ost->forced_keyframes);
533         av_expr_free(ost->forced_keyframes_pexpr);
534         av_freep(&ost->avfilter);
535         av_freep(&ost->logfile_prefix);
536
537         av_freep(&ost->audio_channels_map);
538         ost->audio_channels_mapped = 0;
539
540         avcodec_free_context(&ost->enc_ctx);
541
542         av_freep(&output_streams[i]);
543     }
544 #if HAVE_PTHREADS
545     free_input_threads();
546 #endif
547     for (i = 0; i < nb_input_files; i++) {
548         avformat_close_input(&input_files[i]->ctx);
549         av_freep(&input_files[i]);
550     }
551     for (i = 0; i < nb_input_streams; i++) {
552         InputStream *ist = input_streams[i];
553
554         av_frame_free(&ist->decoded_frame);
555         av_frame_free(&ist->filter_frame);
556         av_dict_free(&ist->decoder_opts);
557         avsubtitle_free(&ist->prev_sub.subtitle);
558         av_frame_free(&ist->sub2video.frame);
559         av_freep(&ist->filters);
560         av_freep(&ist->hwaccel_device);
561
562         avcodec_free_context(&ist->dec_ctx);
563
564         av_freep(&input_streams[i]);
565     }
566
567     if (vstats_file)
568         fclose(vstats_file);
569     av_freep(&vstats_filename);
570
571     av_freep(&input_streams);
572     av_freep(&input_files);
573     av_freep(&output_streams);
574     av_freep(&output_files);
575
576     uninit_opts();
577
578     avformat_network_deinit();
579
580     if (received_sigterm) {
581         av_log(NULL, AV_LOG_INFO, "Exiting normally, received signal %d.\n",
582                (int) received_sigterm);
583     } else if (ret && transcode_init_done) {
584         av_log(NULL, AV_LOG_INFO, "Conversion failed!\n");
585     }
586     term_exit();
587     ffmpeg_exited = 1;
588 }
589
590 void remove_avoptions(AVDictionary **a, AVDictionary *b)
591 {
592     AVDictionaryEntry *t = NULL;
593
594     while ((t = av_dict_get(b, "", t, AV_DICT_IGNORE_SUFFIX))) {
595         av_dict_set(a, t->key, NULL, AV_DICT_MATCH_CASE);
596     }
597 }
598
599 void assert_avoptions(AVDictionary *m)
600 {
601     AVDictionaryEntry *t;
602     if ((t = av_dict_get(m, "", NULL, AV_DICT_IGNORE_SUFFIX))) {
603         av_log(NULL, AV_LOG_FATAL, "Option %s not found.\n", t->key);
604         exit_program(1);
605     }
606 }
607
608 static void abort_codec_experimental(AVCodec *c, int encoder)
609 {
610     exit_program(1);
611 }
612
613 static void update_benchmark(const char *fmt, ...)
614 {
615     if (do_benchmark_all) {
616         int64_t t = getutime();
617         va_list va;
618         char buf[1024];
619
620         if (fmt) {
621             va_start(va, fmt);
622             vsnprintf(buf, sizeof(buf), fmt, va);
623             va_end(va);
624             av_log(NULL, AV_LOG_INFO, "bench: %8"PRIu64" %s \n", t - current_time, buf);
625         }
626         current_time = t;
627     }
628 }
629
630 static void close_all_output_streams(OutputStream *ost, OSTFinished this_stream, OSTFinished others)
631 {
632     int i;
633     for (i = 0; i < nb_output_streams; i++) {
634         OutputStream *ost2 = output_streams[i];
635         ost2->finished |= ost == ost2 ? this_stream : others;
636     }
637 }
638
639 static void write_frame(AVFormatContext *s, AVPacket *pkt, OutputStream *ost)
640 {
641     AVBitStreamFilterContext *bsfc = ost->bitstream_filters;
642     AVCodecContext          *avctx = ost->encoding_needed ? ost->enc_ctx : ost->st->codec;
643     int ret;
644
645     if (!ost->st->codec->extradata_size && ost->enc_ctx->extradata_size) {
646         ost->st->codec->extradata = av_mallocz(ost->enc_ctx->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE);
647         if (ost->st->codec->extradata) {
648             memcpy(ost->st->codec->extradata, ost->enc_ctx->extradata, ost->enc_ctx->extradata_size);
649             ost->st->codec->extradata_size = ost->enc_ctx->extradata_size;
650         }
651     }
652
653     if ((avctx->codec_type == AVMEDIA_TYPE_VIDEO && video_sync_method == VSYNC_DROP) ||
654         (avctx->codec_type == AVMEDIA_TYPE_AUDIO && audio_sync_method < 0))
655         pkt->pts = pkt->dts = AV_NOPTS_VALUE;
656
657     /*
658      * Audio encoders may split the packets --  #frames in != #packets out.
659      * But there is no reordering, so we can limit the number of output packets
660      * by simply dropping them here.
661      * Counting encoded video frames needs to be done separately because of
662      * reordering, see do_video_out()
663      */
664     if (!(avctx->codec_type == AVMEDIA_TYPE_VIDEO && avctx->codec)) {
665         if (ost->frame_number >= ost->max_frames) {
666             av_free_packet(pkt);
667             return;
668         }
669         ost->frame_number++;
670     }
671     if (avctx->codec_type == AVMEDIA_TYPE_VIDEO) {
672         uint8_t *sd = av_packet_get_side_data(pkt, AV_PKT_DATA_QUALITY_STATS,
673                                               NULL);
674         ost->quality = sd ? AV_RL32(sd) : -1;
675     }
676
677     if (bsfc)
678         av_packet_split_side_data(pkt);
679
680     while (bsfc) {
681         AVPacket new_pkt = *pkt;
682         AVDictionaryEntry *bsf_arg = av_dict_get(ost->bsf_args,
683                                                  bsfc->filter->name,
684                                                  NULL, 0);
685         int a = av_bitstream_filter_filter(bsfc, avctx,
686                                            bsf_arg ? bsf_arg->value : NULL,
687                                            &new_pkt.data, &new_pkt.size,
688                                            pkt->data, pkt->size,
689                                            pkt->flags & AV_PKT_FLAG_KEY);
690         if(a == 0 && new_pkt.data != pkt->data && new_pkt.destruct) {
691             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
692             if(t) {
693                 memcpy(t, new_pkt.data, new_pkt.size);
694                 memset(t + new_pkt.size, 0, FF_INPUT_BUFFER_PADDING_SIZE);
695                 new_pkt.data = t;
696                 new_pkt.buf = NULL;
697                 a = 1;
698             } else
699                 a = AVERROR(ENOMEM);
700         }
701         if (a > 0) {
702             pkt->side_data = NULL;
703             pkt->side_data_elems = 0;
704             av_free_packet(pkt);
705             new_pkt.buf = av_buffer_create(new_pkt.data, new_pkt.size,
706                                            av_buffer_default_free, NULL, 0);
707             if (!new_pkt.buf)
708                 exit_program(1);
709         } else if (a < 0) {
710             new_pkt = *pkt;
711             av_log(NULL, AV_LOG_ERROR, "Failed to open bitstream filter %s for stream %d with codec %s",
712                    bsfc->filter->name, pkt->stream_index,
713                    avctx->codec ? avctx->codec->name : "copy");
714             print_error("", a);
715             if (exit_on_error)
716                 exit_program(1);
717         }
718         *pkt = new_pkt;
719
720         bsfc = bsfc->next;
721     }
722
723     if (!(s->oformat->flags & AVFMT_NOTIMESTAMPS)) {
724         if (pkt->dts != AV_NOPTS_VALUE &&
725             pkt->pts != AV_NOPTS_VALUE &&
726             pkt->dts > pkt->pts) {
727             av_log(s, AV_LOG_WARNING, "Invalid DTS: %"PRId64" PTS: %"PRId64" in output stream %d:%d, replacing by guess\n",
728                    pkt->dts, pkt->pts,
729                    ost->file_index, ost->st->index);
730             pkt->pts =
731             pkt->dts = pkt->pts + pkt->dts + ost->last_mux_dts + 1
732                      - FFMIN3(pkt->pts, pkt->dts, ost->last_mux_dts + 1)
733                      - FFMAX3(pkt->pts, pkt->dts, ost->last_mux_dts + 1);
734         }
735      if(
736         (avctx->codec_type == AVMEDIA_TYPE_AUDIO || avctx->codec_type == AVMEDIA_TYPE_VIDEO) &&
737         pkt->dts != AV_NOPTS_VALUE &&
738         ost->last_mux_dts != AV_NOPTS_VALUE) {
739       int64_t max = ost->last_mux_dts + !(s->oformat->flags & AVFMT_TS_NONSTRICT);
740       if (pkt->dts < max) {
741         int loglevel = max - pkt->dts > 2 || avctx->codec_type == AVMEDIA_TYPE_VIDEO ? AV_LOG_WARNING : AV_LOG_DEBUG;
742         av_log(s, loglevel, "Non-monotonous DTS in output stream "
743                "%d:%d; previous: %"PRId64", current: %"PRId64"; ",
744                ost->file_index, ost->st->index, ost->last_mux_dts, pkt->dts);
745         if (exit_on_error) {
746             av_log(NULL, AV_LOG_FATAL, "aborting.\n");
747             exit_program(1);
748         }
749         av_log(s, loglevel, "changing to %"PRId64". This may result "
750                "in incorrect timestamps in the output file.\n",
751                max);
752         if(pkt->pts >= pkt->dts)
753             pkt->pts = FFMAX(pkt->pts, max);
754         pkt->dts = max;
755       }
756      }
757     }
758     ost->last_mux_dts = pkt->dts;
759
760     ost->data_size += pkt->size;
761     ost->packets_written++;
762
763     pkt->stream_index = ost->index;
764
765     if (debug_ts) {
766         av_log(NULL, AV_LOG_INFO, "muxer <- type:%s "
767                 "pkt_pts:%s pkt_pts_time:%s pkt_dts:%s pkt_dts_time:%s size:%d\n",
768                 av_get_media_type_string(ost->enc_ctx->codec_type),
769                 av_ts2str(pkt->pts), av_ts2timestr(pkt->pts, &ost->st->time_base),
770                 av_ts2str(pkt->dts), av_ts2timestr(pkt->dts, &ost->st->time_base),
771                 pkt->size
772               );
773     }
774
775     ret = av_interleaved_write_frame(s, pkt);
776     if (ret < 0) {
777         print_error("av_interleaved_write_frame()", ret);
778         main_return_code = 1;
779         close_all_output_streams(ost, MUXER_FINISHED | ENCODER_FINISHED, ENCODER_FINISHED);
780     }
781     av_free_packet(pkt);
782 }
783
784 static void close_output_stream(OutputStream *ost)
785 {
786     OutputFile *of = output_files[ost->file_index];
787
788     ost->finished |= ENCODER_FINISHED;
789     if (of->shortest) {
790         int64_t end = av_rescale_q(ost->sync_opts - ost->first_pts, ost->enc_ctx->time_base, AV_TIME_BASE_Q);
791         of->recording_time = FFMIN(of->recording_time, end);
792     }
793 }
794
795 static int check_recording_time(OutputStream *ost)
796 {
797     OutputFile *of = output_files[ost->file_index];
798
799     if (of->recording_time != INT64_MAX &&
800         av_compare_ts(ost->sync_opts - ost->first_pts, ost->enc_ctx->time_base, of->recording_time,
801                       AV_TIME_BASE_Q) >= 0) {
802         close_output_stream(ost);
803         return 0;
804     }
805     return 1;
806 }
807
808 static void do_audio_out(AVFormatContext *s, OutputStream *ost,
809                          AVFrame *frame)
810 {
811     AVCodecContext *enc = ost->enc_ctx;
812     AVPacket pkt;
813     int got_packet = 0;
814
815     av_init_packet(&pkt);
816     pkt.data = NULL;
817     pkt.size = 0;
818
819     if (!check_recording_time(ost))
820         return;
821
822     if (frame->pts == AV_NOPTS_VALUE || audio_sync_method < 0)
823         frame->pts = ost->sync_opts;
824     ost->sync_opts = frame->pts + frame->nb_samples;
825     ost->samples_encoded += frame->nb_samples;
826     ost->frames_encoded++;
827
828     av_assert0(pkt.size || !pkt.data);
829     update_benchmark(NULL);
830     if (debug_ts) {
831         av_log(NULL, AV_LOG_INFO, "encoder <- type:audio "
832                "frame_pts:%s frame_pts_time:%s time_base:%d/%d\n",
833                av_ts2str(frame->pts), av_ts2timestr(frame->pts, &enc->time_base),
834                enc->time_base.num, enc->time_base.den);
835     }
836
837     if (avcodec_encode_audio2(enc, &pkt, frame, &got_packet) < 0) {
838         av_log(NULL, AV_LOG_FATAL, "Audio encoding failed (avcodec_encode_audio2)\n");
839         exit_program(1);
840     }
841     update_benchmark("encode_audio %d.%d", ost->file_index, ost->index);
842
843     if (got_packet) {
844         av_packet_rescale_ts(&pkt, enc->time_base, ost->st->time_base);
845
846         if (debug_ts) {
847             av_log(NULL, AV_LOG_INFO, "encoder -> type:audio "
848                    "pkt_pts:%s pkt_pts_time:%s pkt_dts:%s pkt_dts_time:%s\n",
849                    av_ts2str(pkt.pts), av_ts2timestr(pkt.pts, &ost->st->time_base),
850                    av_ts2str(pkt.dts), av_ts2timestr(pkt.dts, &ost->st->time_base));
851         }
852
853         write_frame(s, &pkt, ost);
854     }
855 }
856
857 static void do_subtitle_out(AVFormatContext *s,
858                             OutputStream *ost,
859                             InputStream *ist,
860                             AVSubtitle *sub)
861 {
862     int subtitle_out_max_size = 1024 * 1024;
863     int subtitle_out_size, nb, i;
864     AVCodecContext *enc;
865     AVPacket pkt;
866     int64_t pts;
867
868     if (sub->pts == AV_NOPTS_VALUE) {
869         av_log(NULL, AV_LOG_ERROR, "Subtitle packets must have a pts\n");
870         if (exit_on_error)
871             exit_program(1);
872         return;
873     }
874
875     enc = ost->enc_ctx;
876
877     if (!subtitle_out) {
878         subtitle_out = av_malloc(subtitle_out_max_size);
879         if (!subtitle_out) {
880             av_log(NULL, AV_LOG_FATAL, "Failed to allocate subtitle_out\n");
881             exit_program(1);
882         }
883     }
884
885     /* Note: DVB subtitle need one packet to draw them and one other
886        packet to clear them */
887     /* XXX: signal it in the codec context ? */
888     if (enc->codec_id == AV_CODEC_ID_DVB_SUBTITLE)
889         nb = 2;
890     else
891         nb = 1;
892
893     /* shift timestamp to honor -ss and make check_recording_time() work with -t */
894     pts = sub->pts;
895     if (output_files[ost->file_index]->start_time != AV_NOPTS_VALUE)
896         pts -= output_files[ost->file_index]->start_time;
897     for (i = 0; i < nb; i++) {
898         unsigned save_num_rects = sub->num_rects;
899
900         ost->sync_opts = av_rescale_q(pts, AV_TIME_BASE_Q, enc->time_base);
901         if (!check_recording_time(ost))
902             return;
903
904         sub->pts = pts;
905         // start_display_time is required to be 0
906         sub->pts               += av_rescale_q(sub->start_display_time, (AVRational){ 1, 1000 }, AV_TIME_BASE_Q);
907         sub->end_display_time  -= sub->start_display_time;
908         sub->start_display_time = 0;
909         if (i == 1)
910             sub->num_rects = 0;
911
912         ost->frames_encoded++;
913
914         subtitle_out_size = avcodec_encode_subtitle(enc, subtitle_out,
915                                                     subtitle_out_max_size, sub);
916         if (i == 1)
917             sub->num_rects = save_num_rects;
918         if (subtitle_out_size < 0) {
919             av_log(NULL, AV_LOG_FATAL, "Subtitle encoding failed\n");
920             exit_program(1);
921         }
922
923         av_init_packet(&pkt);
924         pkt.data = subtitle_out;
925         pkt.size = subtitle_out_size;
926         pkt.pts  = av_rescale_q(sub->pts, AV_TIME_BASE_Q, ost->st->time_base);
927         pkt.duration = av_rescale_q(sub->end_display_time, (AVRational){ 1, 1000 }, ost->st->time_base);
928         if (enc->codec_id == AV_CODEC_ID_DVB_SUBTITLE) {
929             /* XXX: the pts correction is handled here. Maybe handling
930                it in the codec would be better */
931             if (i == 0)
932                 pkt.pts += 90 * sub->start_display_time;
933             else
934                 pkt.pts += 90 * sub->end_display_time;
935         }
936         pkt.dts = pkt.pts;
937         write_frame(s, &pkt, ost);
938     }
939 }
940
941 static void do_video_out(AVFormatContext *s,
942                          OutputStream *ost,
943                          AVFrame *next_picture,
944                          double sync_ipts)
945 {
946     int ret, format_video_sync;
947     AVPacket pkt;
948     AVCodecContext *enc = ost->enc_ctx;
949     AVCodecContext *mux_enc = ost->st->codec;
950     int nb_frames, nb0_frames, i;
951     double delta, delta0;
952     double duration = 0;
953     int frame_size = 0;
954     InputStream *ist = NULL;
955     AVFilterContext *filter = ost->filter->filter;
956
957     if (ost->source_index >= 0)
958         ist = input_streams[ost->source_index];
959
960     if (filter->inputs[0]->frame_rate.num > 0 &&
961         filter->inputs[0]->frame_rate.den > 0)
962         duration = 1/(av_q2d(filter->inputs[0]->frame_rate) * av_q2d(enc->time_base));
963
964     if(ist && ist->st->start_time != AV_NOPTS_VALUE && ist->st->first_dts != AV_NOPTS_VALUE && ost->frame_rate.num)
965         duration = FFMIN(duration, 1/(av_q2d(ost->frame_rate) * av_q2d(enc->time_base)));
966
967     if (!ost->filters_script &&
968         !ost->filters &&
969         next_picture &&
970         ist &&
971         lrintf(av_frame_get_pkt_duration(next_picture) * av_q2d(ist->st->time_base) / av_q2d(enc->time_base)) > 0) {
972         duration = lrintf(av_frame_get_pkt_duration(next_picture) * av_q2d(ist->st->time_base) / av_q2d(enc->time_base));
973     }
974
975     if (!next_picture) {
976         //end, flushing
977         nb0_frames = nb_frames = mid_pred(ost->last_nb0_frames[0],
978                                           ost->last_nb0_frames[1],
979                                           ost->last_nb0_frames[2]);
980     } else {
981         delta0 = sync_ipts - ost->sync_opts;
982         delta  = delta0 + duration;
983
984         /* by default, we output a single frame */
985         nb0_frames = 0;
986         nb_frames = 1;
987
988         format_video_sync = video_sync_method;
989         if (format_video_sync == VSYNC_AUTO) {
990             if(!strcmp(s->oformat->name, "avi")) {
991                 format_video_sync = VSYNC_VFR;
992             } else
993                 format_video_sync = (s->oformat->flags & AVFMT_VARIABLE_FPS) ? ((s->oformat->flags & AVFMT_NOTIMESTAMPS) ? VSYNC_PASSTHROUGH : VSYNC_VFR) : VSYNC_CFR;
994             if (   ist
995                 && format_video_sync == VSYNC_CFR
996                 && input_files[ist->file_index]->ctx->nb_streams == 1
997                 && input_files[ist->file_index]->input_ts_offset == 0) {
998                 format_video_sync = VSYNC_VSCFR;
999             }
1000             if (format_video_sync == VSYNC_CFR && copy_ts) {
1001                 format_video_sync = VSYNC_VSCFR;
1002             }
1003         }
1004
1005         if (delta0 < 0 &&
1006             delta > 0 &&
1007             format_video_sync != VSYNC_PASSTHROUGH &&
1008             format_video_sync != VSYNC_DROP) {
1009             double cor = FFMIN(-delta0, duration);
1010             if (delta0 < -0.6) {
1011                 av_log(NULL, AV_LOG_WARNING, "Past duration %f too large\n", -delta0);
1012             } else
1013                 av_log(NULL, AV_LOG_DEBUG, "Cliping frame in rate conversion by %f\n", -delta0);
1014             sync_ipts += cor;
1015             duration -= cor;
1016             delta0 += cor;
1017         }
1018
1019         switch (format_video_sync) {
1020         case VSYNC_VSCFR:
1021             if (ost->frame_number == 0 && delta - duration >= 0.5) {
1022                 av_log(NULL, AV_LOG_DEBUG, "Not duplicating %d initial frames\n", (int)lrintf(delta - duration));
1023                 delta = duration;
1024                 delta0 = 0;
1025                 ost->sync_opts = lrint(sync_ipts);
1026             }
1027         case VSYNC_CFR:
1028             // FIXME set to 0.5 after we fix some dts/pts bugs like in avidec.c
1029             if (frame_drop_threshold && delta < frame_drop_threshold && ost->frame_number) {
1030                 nb_frames = 0;
1031             } else if (delta < -1.1)
1032                 nb_frames = 0;
1033             else if (delta > 1.1) {
1034                 nb_frames = lrintf(delta);
1035                 if (delta0 > 1.1)
1036                     nb0_frames = lrintf(delta0 - 0.6);
1037             }
1038             break;
1039         case VSYNC_VFR:
1040             if (delta <= -0.6)
1041                 nb_frames = 0;
1042             else if (delta > 0.6)
1043                 ost->sync_opts = lrint(sync_ipts);
1044             break;
1045         case VSYNC_DROP:
1046         case VSYNC_PASSTHROUGH:
1047             ost->sync_opts = lrint(sync_ipts);
1048             break;
1049         default:
1050             av_assert0(0);
1051         }
1052     }
1053
1054     nb_frames = FFMIN(nb_frames, ost->max_frames - ost->frame_number);
1055     nb0_frames = FFMIN(nb0_frames, nb_frames);
1056
1057     memmove(ost->last_nb0_frames + 1,
1058             ost->last_nb0_frames,
1059             sizeof(ost->last_nb0_frames[0]) * (FF_ARRAY_ELEMS(ost->last_nb0_frames) - 1));
1060     ost->last_nb0_frames[0] = nb0_frames;
1061
1062     if (nb0_frames == 0 && ost->last_droped) {
1063         nb_frames_drop++;
1064         av_log(NULL, AV_LOG_VERBOSE,
1065                "*** dropping frame %d from stream %d at ts %"PRId64"\n",
1066                ost->frame_number, ost->st->index, ost->last_frame->pts);
1067     }
1068     if (nb_frames > (nb0_frames && ost->last_droped) + (nb_frames > nb0_frames)) {
1069         if (nb_frames > dts_error_threshold * 30) {
1070             av_log(NULL, AV_LOG_ERROR, "%d frame duplication too large, skipping\n", nb_frames - 1);
1071             nb_frames_drop++;
1072             return;
1073         }
1074         nb_frames_dup += nb_frames - (nb0_frames && ost->last_droped) - (nb_frames > nb0_frames);
1075         av_log(NULL, AV_LOG_VERBOSE, "*** %d dup!\n", nb_frames - 1);
1076     }
1077     ost->last_droped = nb_frames == nb0_frames && next_picture;
1078
1079   /* duplicates frame if needed */
1080   for (i = 0; i < nb_frames; i++) {
1081     AVFrame *in_picture;
1082     av_init_packet(&pkt);
1083     pkt.data = NULL;
1084     pkt.size = 0;
1085
1086     if (i < nb0_frames && ost->last_frame) {
1087         in_picture = ost->last_frame;
1088     } else
1089         in_picture = next_picture;
1090
1091     if (!in_picture)
1092         return;
1093
1094     in_picture->pts = ost->sync_opts;
1095
1096 #if 1
1097     if (!check_recording_time(ost))
1098 #else
1099     if (ost->frame_number >= ost->max_frames)
1100 #endif
1101         return;
1102
1103     if (s->oformat->flags & AVFMT_RAWPICTURE &&
1104         enc->codec->id == AV_CODEC_ID_RAWVIDEO) {
1105         /* raw pictures are written as AVPicture structure to
1106            avoid any copies. We support temporarily the older
1107            method. */
1108         if (in_picture->interlaced_frame)
1109             mux_enc->field_order = in_picture->top_field_first ? AV_FIELD_TB:AV_FIELD_BT;
1110         else
1111             mux_enc->field_order = AV_FIELD_PROGRESSIVE;
1112         pkt.data   = (uint8_t *)in_picture;
1113         pkt.size   =  sizeof(AVPicture);
1114         pkt.pts    = av_rescale_q(in_picture->pts, enc->time_base, ost->st->time_base);
1115         pkt.flags |= AV_PKT_FLAG_KEY;
1116
1117         write_frame(s, &pkt, ost);
1118     } else {
1119         int got_packet, forced_keyframe = 0;
1120         double pts_time;
1121
1122         if (enc->flags & (CODEC_FLAG_INTERLACED_DCT|CODEC_FLAG_INTERLACED_ME) &&
1123             ost->top_field_first >= 0)
1124             in_picture->top_field_first = !!ost->top_field_first;
1125
1126         if (in_picture->interlaced_frame) {
1127             if (enc->codec->id == AV_CODEC_ID_MJPEG)
1128                 mux_enc->field_order = in_picture->top_field_first ? AV_FIELD_TT:AV_FIELD_BB;
1129             else
1130                 mux_enc->field_order = in_picture->top_field_first ? AV_FIELD_TB:AV_FIELD_BT;
1131         } else
1132             mux_enc->field_order = AV_FIELD_PROGRESSIVE;
1133
1134         in_picture->quality = enc->global_quality;
1135         in_picture->pict_type = 0;
1136
1137         pts_time = in_picture->pts != AV_NOPTS_VALUE ?
1138             in_picture->pts * av_q2d(enc->time_base) : NAN;
1139         if (ost->forced_kf_index < ost->forced_kf_count &&
1140             in_picture->pts >= ost->forced_kf_pts[ost->forced_kf_index]) {
1141             ost->forced_kf_index++;
1142             forced_keyframe = 1;
1143         } else if (ost->forced_keyframes_pexpr) {
1144             double res;
1145             ost->forced_keyframes_expr_const_values[FKF_T] = pts_time;
1146             res = av_expr_eval(ost->forced_keyframes_pexpr,
1147                                ost->forced_keyframes_expr_const_values, NULL);
1148             av_dlog(NULL, "force_key_frame: n:%f n_forced:%f prev_forced_n:%f t:%f prev_forced_t:%f -> res:%f\n",
1149                     ost->forced_keyframes_expr_const_values[FKF_N],
1150                     ost->forced_keyframes_expr_const_values[FKF_N_FORCED],
1151                     ost->forced_keyframes_expr_const_values[FKF_PREV_FORCED_N],
1152                     ost->forced_keyframes_expr_const_values[FKF_T],
1153                     ost->forced_keyframes_expr_const_values[FKF_PREV_FORCED_T],
1154                     res);
1155             if (res) {
1156                 forced_keyframe = 1;
1157                 ost->forced_keyframes_expr_const_values[FKF_PREV_FORCED_N] =
1158                     ost->forced_keyframes_expr_const_values[FKF_N];
1159                 ost->forced_keyframes_expr_const_values[FKF_PREV_FORCED_T] =
1160                     ost->forced_keyframes_expr_const_values[FKF_T];
1161                 ost->forced_keyframes_expr_const_values[FKF_N_FORCED] += 1;
1162             }
1163
1164             ost->forced_keyframes_expr_const_values[FKF_N] += 1;
1165         } else if (   ost->forced_keyframes
1166                    && !strncmp(ost->forced_keyframes, "source", 6)
1167                    && in_picture->key_frame==1) {
1168             forced_keyframe = 1;
1169         }
1170
1171         if (forced_keyframe) {
1172             in_picture->pict_type = AV_PICTURE_TYPE_I;
1173             av_log(NULL, AV_LOG_DEBUG, "Forced keyframe at time %f\n", pts_time);
1174         }
1175
1176         update_benchmark(NULL);
1177         if (debug_ts) {
1178             av_log(NULL, AV_LOG_INFO, "encoder <- type:video "
1179                    "frame_pts:%s frame_pts_time:%s time_base:%d/%d\n",
1180                    av_ts2str(in_picture->pts), av_ts2timestr(in_picture->pts, &enc->time_base),
1181                    enc->time_base.num, enc->time_base.den);
1182         }
1183
1184         ost->frames_encoded++;
1185
1186         ret = avcodec_encode_video2(enc, &pkt, in_picture, &got_packet);
1187         update_benchmark("encode_video %d.%d", ost->file_index, ost->index);
1188         if (ret < 0) {
1189             av_log(NULL, AV_LOG_FATAL, "Video encoding failed\n");
1190             exit_program(1);
1191         }
1192
1193         if (got_packet) {
1194             if (debug_ts) {
1195                 av_log(NULL, AV_LOG_INFO, "encoder -> type:video "
1196                        "pkt_pts:%s pkt_pts_time:%s pkt_dts:%s pkt_dts_time:%s\n",
1197                        av_ts2str(pkt.pts), av_ts2timestr(pkt.pts, &enc->time_base),
1198                        av_ts2str(pkt.dts), av_ts2timestr(pkt.dts, &enc->time_base));
1199             }
1200
1201             if (pkt.pts == AV_NOPTS_VALUE && !(enc->codec->capabilities & CODEC_CAP_DELAY))
1202                 pkt.pts = ost->sync_opts;
1203
1204             av_packet_rescale_ts(&pkt, enc->time_base, ost->st->time_base);
1205
1206             if (debug_ts) {
1207                 av_log(NULL, AV_LOG_INFO, "encoder -> type:video "
1208                     "pkt_pts:%s pkt_pts_time:%s pkt_dts:%s pkt_dts_time:%s\n",
1209                     av_ts2str(pkt.pts), av_ts2timestr(pkt.pts, &ost->st->time_base),
1210                     av_ts2str(pkt.dts), av_ts2timestr(pkt.dts, &ost->st->time_base));
1211             }
1212
1213             frame_size = pkt.size;
1214             write_frame(s, &pkt, ost);
1215
1216             /* if two pass, output log */
1217             if (ost->logfile && enc->stats_out) {
1218                 fprintf(ost->logfile, "%s", enc->stats_out);
1219             }
1220         }
1221     }
1222     ost->sync_opts++;
1223     /*
1224      * For video, number of frames in == number of packets out.
1225      * But there may be reordering, so we can't throw away frames on encoder
1226      * flush, we need to limit them here, before they go into encoder.
1227      */
1228     ost->frame_number++;
1229
1230     if (vstats_filename && frame_size)
1231         do_video_stats(ost, frame_size);
1232   }
1233
1234     if (!ost->last_frame)
1235         ost->last_frame = av_frame_alloc();
1236     av_frame_unref(ost->last_frame);
1237     if (next_picture && ost->last_frame)
1238         av_frame_ref(ost->last_frame, next_picture);
1239     else
1240         av_frame_free(&ost->last_frame);
1241 }
1242
1243 static double psnr(double d)
1244 {
1245     return -10.0 * log(d) / log(10.0);
1246 }
1247
1248 static void do_video_stats(OutputStream *ost, int frame_size)
1249 {
1250     AVCodecContext *enc;
1251     int frame_number;
1252     double ti1, bitrate, avg_bitrate;
1253
1254     /* this is executed just the first time do_video_stats is called */
1255     if (!vstats_file) {
1256         vstats_file = fopen(vstats_filename, "w");
1257         if (!vstats_file) {
1258             perror("fopen");
1259             exit_program(1);
1260         }
1261     }
1262
1263     enc = ost->enc_ctx;
1264     if (enc->codec_type == AVMEDIA_TYPE_VIDEO) {
1265         frame_number = ost->st->nb_frames;
1266         fprintf(vstats_file, "frame= %5d q= %2.1f ", frame_number,
1267                 ost->quality / (float)FF_QP2LAMBDA);
1268
1269         if (enc->coded_frame && (enc->flags&CODEC_FLAG_PSNR))
1270             fprintf(vstats_file, "PSNR= %6.2f ", psnr(enc->coded_frame->error[0] / (enc->width * enc->height * 255.0 * 255.0)));
1271
1272         fprintf(vstats_file,"f_size= %6d ", frame_size);
1273         /* compute pts value */
1274         ti1 = av_stream_get_end_pts(ost->st) * av_q2d(ost->st->time_base);
1275         if (ti1 < 0.01)
1276             ti1 = 0.01;
1277
1278         bitrate     = (frame_size * 8) / av_q2d(enc->time_base) / 1000.0;
1279         avg_bitrate = (double)(ost->data_size * 8) / ti1 / 1000.0;
1280         fprintf(vstats_file, "s_size= %8.0fkB time= %0.3f br= %7.1fkbits/s avg_br= %7.1fkbits/s ",
1281                (double)ost->data_size / 1024, ti1, bitrate, avg_bitrate);
1282         fprintf(vstats_file, "type= %c\n", enc->coded_frame ? av_get_picture_type_char(enc->coded_frame->pict_type) : 'I');
1283     }
1284 }
1285
1286 static void finish_output_stream(OutputStream *ost)
1287 {
1288     OutputFile *of = output_files[ost->file_index];
1289     int i;
1290
1291     ost->finished = ENCODER_FINISHED | MUXER_FINISHED;
1292
1293     if (of->shortest) {
1294         for (i = 0; i < of->ctx->nb_streams; i++)
1295             output_streams[of->ost_index + i]->finished = ENCODER_FINISHED | MUXER_FINISHED;
1296     }
1297 }
1298
1299 /**
1300  * Get and encode new output from any of the filtergraphs, without causing
1301  * activity.
1302  *
1303  * @return  0 for success, <0 for severe errors
1304  */
1305 static int reap_filters(int flush)
1306 {
1307     AVFrame *filtered_frame = NULL;
1308     int i;
1309
1310     /* Reap all buffers present in the buffer sinks */
1311     for (i = 0; i < nb_output_streams; i++) {
1312         OutputStream *ost = output_streams[i];
1313         OutputFile    *of = output_files[ost->file_index];
1314         AVFilterContext *filter;
1315         AVCodecContext *enc = ost->enc_ctx;
1316         int ret = 0;
1317
1318         if (!ost->filter)
1319             continue;
1320         filter = ost->filter->filter;
1321
1322         if (!ost->filtered_frame && !(ost->filtered_frame = av_frame_alloc())) {
1323             return AVERROR(ENOMEM);
1324         }
1325         filtered_frame = ost->filtered_frame;
1326
1327         while (1) {
1328             double float_pts = AV_NOPTS_VALUE; // this is identical to filtered_frame.pts but with higher precision
1329             ret = av_buffersink_get_frame_flags(filter, filtered_frame,
1330                                                AV_BUFFERSINK_FLAG_NO_REQUEST);
1331             if (ret < 0) {
1332                 if (ret != AVERROR(EAGAIN) && ret != AVERROR_EOF) {
1333                     av_log(NULL, AV_LOG_WARNING,
1334                            "Error in av_buffersink_get_frame_flags(): %s\n", av_err2str(ret));
1335                 } else if (flush && ret == AVERROR_EOF) {
1336                     if (filter->inputs[0]->type == AVMEDIA_TYPE_VIDEO)
1337                         do_video_out(of->ctx, ost, NULL, AV_NOPTS_VALUE);
1338                 }
1339                 break;
1340             }
1341             if (ost->finished) {
1342                 av_frame_unref(filtered_frame);
1343                 continue;
1344             }
1345             if (filtered_frame->pts != AV_NOPTS_VALUE) {
1346                 int64_t start_time = (of->start_time == AV_NOPTS_VALUE) ? 0 : of->start_time;
1347                 AVRational tb = enc->time_base;
1348                 int extra_bits = av_clip(29 - av_log2(tb.den), 0, 16);
1349
1350                 tb.den <<= extra_bits;
1351                 float_pts =
1352                     av_rescale_q(filtered_frame->pts, filter->inputs[0]->time_base, tb) -
1353                     av_rescale_q(start_time, AV_TIME_BASE_Q, tb);
1354                 float_pts /= 1 << extra_bits;
1355                 // avoid exact midoints to reduce the chance of rounding differences, this can be removed in case the fps code is changed to work with integers
1356                 float_pts += FFSIGN(float_pts) * 1.0 / (1<<17);
1357
1358                 filtered_frame->pts =
1359                     av_rescale_q(filtered_frame->pts, filter->inputs[0]->time_base, enc->time_base) -
1360                     av_rescale_q(start_time, AV_TIME_BASE_Q, enc->time_base);
1361             }
1362             //if (ost->source_index >= 0)
1363             //    *filtered_frame= *input_streams[ost->source_index]->decoded_frame; //for me_threshold
1364
1365             switch (filter->inputs[0]->type) {
1366             case AVMEDIA_TYPE_VIDEO:
1367                 if (!ost->frame_aspect_ratio.num)
1368                     enc->sample_aspect_ratio = filtered_frame->sample_aspect_ratio;
1369
1370                 if (debug_ts) {
1371                     av_log(NULL, AV_LOG_INFO, "filter -> pts:%s pts_time:%s exact:%f time_base:%d/%d\n",
1372                             av_ts2str(filtered_frame->pts), av_ts2timestr(filtered_frame->pts, &enc->time_base),
1373                             float_pts,
1374                             enc->time_base.num, enc->time_base.den);
1375                 }
1376
1377                 do_video_out(of->ctx, ost, filtered_frame, float_pts);
1378                 break;
1379             case AVMEDIA_TYPE_AUDIO:
1380                 if (!(enc->codec->capabilities & CODEC_CAP_PARAM_CHANGE) &&
1381                     enc->channels != av_frame_get_channels(filtered_frame)) {
1382                     av_log(NULL, AV_LOG_ERROR,
1383                            "Audio filter graph output is not normalized and encoder does not support parameter changes\n");
1384                     break;
1385                 }
1386                 do_audio_out(of->ctx, ost, filtered_frame);
1387                 break;
1388             default:
1389                 // TODO support subtitle filters
1390                 av_assert0(0);
1391             }
1392
1393             av_frame_unref(filtered_frame);
1394         }
1395     }
1396
1397     return 0;
1398 }
1399
1400 static void print_final_stats(int64_t total_size)
1401 {
1402     uint64_t video_size = 0, audio_size = 0, extra_size = 0, other_size = 0;
1403     uint64_t subtitle_size = 0;
1404     uint64_t data_size = 0;
1405     float percent = -1.0;
1406     int i, j;
1407     int pass1_used = 1;
1408
1409     for (i = 0; i < nb_output_streams; i++) {
1410         OutputStream *ost = output_streams[i];
1411         switch (ost->enc_ctx->codec_type) {
1412             case AVMEDIA_TYPE_VIDEO: video_size += ost->data_size; break;
1413             case AVMEDIA_TYPE_AUDIO: audio_size += ost->data_size; break;
1414             case AVMEDIA_TYPE_SUBTITLE: subtitle_size += ost->data_size; break;
1415             default:                 other_size += ost->data_size; break;
1416         }
1417         extra_size += ost->enc_ctx->extradata_size;
1418         data_size  += ost->data_size;
1419         if (   (ost->enc_ctx->flags & (CODEC_FLAG_PASS1 | CODEC_FLAG_PASS2))
1420             != CODEC_FLAG_PASS1)
1421             pass1_used = 0;
1422     }
1423
1424     if (data_size && total_size>0 && total_size >= data_size)
1425         percent = 100.0 * (total_size - data_size) / data_size;
1426
1427     av_log(NULL, AV_LOG_INFO, "video:%1.0fkB audio:%1.0fkB subtitle:%1.0fkB other streams:%1.0fkB global headers:%1.0fkB muxing overhead: ",
1428            video_size / 1024.0,
1429            audio_size / 1024.0,
1430            subtitle_size / 1024.0,
1431            other_size / 1024.0,
1432            extra_size / 1024.0);
1433     if (percent >= 0.0)
1434         av_log(NULL, AV_LOG_INFO, "%f%%", percent);
1435     else
1436         av_log(NULL, AV_LOG_INFO, "unknown");
1437     av_log(NULL, AV_LOG_INFO, "\n");
1438
1439     /* print verbose per-stream stats */
1440     for (i = 0; i < nb_input_files; i++) {
1441         InputFile *f = input_files[i];
1442         uint64_t total_packets = 0, total_size = 0;
1443
1444         av_log(NULL, AV_LOG_VERBOSE, "Input file #%d (%s):\n",
1445                i, f->ctx->filename);
1446
1447         for (j = 0; j < f->nb_streams; j++) {
1448             InputStream *ist = input_streams[f->ist_index + j];
1449             enum AVMediaType type = ist->dec_ctx->codec_type;
1450
1451             total_size    += ist->data_size;
1452             total_packets += ist->nb_packets;
1453
1454             av_log(NULL, AV_LOG_VERBOSE, "  Input stream #%d:%d (%s): ",
1455                    i, j, media_type_string(type));
1456             av_log(NULL, AV_LOG_VERBOSE, "%"PRIu64" packets read (%"PRIu64" bytes); ",
1457                    ist->nb_packets, ist->data_size);
1458
1459             if (ist->decoding_needed) {
1460                 av_log(NULL, AV_LOG_VERBOSE, "%"PRIu64" frames decoded",
1461                        ist->frames_decoded);
1462                 if (type == AVMEDIA_TYPE_AUDIO)
1463                     av_log(NULL, AV_LOG_VERBOSE, " (%"PRIu64" samples)", ist->samples_decoded);
1464                 av_log(NULL, AV_LOG_VERBOSE, "; ");
1465             }
1466
1467             av_log(NULL, AV_LOG_VERBOSE, "\n");
1468         }
1469
1470         av_log(NULL, AV_LOG_VERBOSE, "  Total: %"PRIu64" packets (%"PRIu64" bytes) demuxed\n",
1471                total_packets, total_size);
1472     }
1473
1474     for (i = 0; i < nb_output_files; i++) {
1475         OutputFile *of = output_files[i];
1476         uint64_t total_packets = 0, total_size = 0;
1477
1478         av_log(NULL, AV_LOG_VERBOSE, "Output file #%d (%s):\n",
1479                i, of->ctx->filename);
1480
1481         for (j = 0; j < of->ctx->nb_streams; j++) {
1482             OutputStream *ost = output_streams[of->ost_index + j];
1483             enum AVMediaType type = ost->enc_ctx->codec_type;
1484
1485             total_size    += ost->data_size;
1486             total_packets += ost->packets_written;
1487
1488             av_log(NULL, AV_LOG_VERBOSE, "  Output stream #%d:%d (%s): ",
1489                    i, j, media_type_string(type));
1490             if (ost->encoding_needed) {
1491                 av_log(NULL, AV_LOG_VERBOSE, "%"PRIu64" frames encoded",
1492                        ost->frames_encoded);
1493                 if (type == AVMEDIA_TYPE_AUDIO)
1494                     av_log(NULL, AV_LOG_VERBOSE, " (%"PRIu64" samples)", ost->samples_encoded);
1495                 av_log(NULL, AV_LOG_VERBOSE, "; ");
1496             }
1497
1498             av_log(NULL, AV_LOG_VERBOSE, "%"PRIu64" packets muxed (%"PRIu64" bytes); ",
1499                    ost->packets_written, ost->data_size);
1500
1501             av_log(NULL, AV_LOG_VERBOSE, "\n");
1502         }
1503
1504         av_log(NULL, AV_LOG_VERBOSE, "  Total: %"PRIu64" packets (%"PRIu64" bytes) muxed\n",
1505                total_packets, total_size);
1506     }
1507     if(video_size + data_size + audio_size + subtitle_size + extra_size == 0){
1508         av_log(NULL, AV_LOG_WARNING, "Output file is empty, nothing was encoded ");
1509         if (pass1_used) {
1510             av_log(NULL, AV_LOG_WARNING, "\n");
1511         } else {
1512             av_log(NULL, AV_LOG_WARNING, "(check -ss / -t / -frames parameters if used)\n");
1513         }
1514     }
1515 }
1516
1517 static void print_report(int is_last_report, int64_t timer_start, int64_t cur_time)
1518 {
1519     char buf[1024];
1520     AVBPrint buf_script;
1521     OutputStream *ost;
1522     AVFormatContext *oc;
1523     int64_t total_size;
1524     AVCodecContext *enc;
1525     int frame_number, vid, i;
1526     double bitrate;
1527     int64_t pts = INT64_MIN;
1528     static int64_t last_time = -1;
1529     static int qp_histogram[52];
1530     int hours, mins, secs, us;
1531
1532     if (!print_stats && !is_last_report && !progress_avio)
1533         return;
1534
1535     if (!is_last_report) {
1536         if (last_time == -1) {
1537             last_time = cur_time;
1538             return;
1539         }
1540         if ((cur_time - last_time) < 500000)
1541             return;
1542         last_time = cur_time;
1543     }
1544
1545
1546     oc = output_files[0]->ctx;
1547
1548     total_size = avio_size(oc->pb);
1549     if (total_size <= 0) // FIXME improve avio_size() so it works with non seekable output too
1550         total_size = avio_tell(oc->pb);
1551
1552     buf[0] = '\0';
1553     vid = 0;
1554     av_bprint_init(&buf_script, 0, 1);
1555     for (i = 0; i < nb_output_streams; i++) {
1556         float q = -1;
1557         ost = output_streams[i];
1558         enc = ost->enc_ctx;
1559         if (!ost->stream_copy)
1560             q = ost->quality / (float) FF_QP2LAMBDA;
1561
1562         if (vid && enc->codec_type == AVMEDIA_TYPE_VIDEO) {
1563             snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "q=%2.1f ", q);
1564             av_bprintf(&buf_script, "stream_%d_%d_q=%.1f\n",
1565                        ost->file_index, ost->index, q);
1566         }
1567         if (!vid && enc->codec_type == AVMEDIA_TYPE_VIDEO) {
1568             float fps, t = (cur_time-timer_start) / 1000000.0;
1569
1570             frame_number = ost->frame_number;
1571             fps = t > 1 ? frame_number / t : 0;
1572             snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "frame=%5d fps=%3.*f q=%3.1f ",
1573                      frame_number, fps < 9.95, fps, q);
1574             av_bprintf(&buf_script, "frame=%d\n", frame_number);
1575             av_bprintf(&buf_script, "fps=%.1f\n", fps);
1576             av_bprintf(&buf_script, "stream_%d_%d_q=%.1f\n",
1577                        ost->file_index, ost->index, q);
1578             if (is_last_report)
1579                 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "L");
1580             if (qp_hist) {
1581                 int j;
1582                 int qp = lrintf(q);
1583                 if (qp >= 0 && qp < FF_ARRAY_ELEMS(qp_histogram))
1584                     qp_histogram[qp]++;
1585                 for (j = 0; j < 32; j++)
1586                     snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "%X", (int)lrintf(log2(qp_histogram[j] + 1)));
1587             }
1588
1589             if ((enc->flags&CODEC_FLAG_PSNR) && (enc->coded_frame || is_last_report)) {
1590                 int j;
1591                 double error, error_sum = 0;
1592                 double scale, scale_sum = 0;
1593                 double p;
1594                 char type[3] = { 'Y','U','V' };
1595                 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "PSNR=");
1596                 for (j = 0; j < 3; j++) {
1597                     if (is_last_report) {
1598                         error = enc->error[j];
1599                         scale = enc->width * enc->height * 255.0 * 255.0 * frame_number;
1600                     } else {
1601                         error = enc->coded_frame->error[j];
1602                         scale = enc->width * enc->height * 255.0 * 255.0;
1603                     }
1604                     if (j)
1605                         scale /= 4;
1606                     error_sum += error;
1607                     scale_sum += scale;
1608                     p = psnr(error / scale);
1609                     snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "%c:%2.2f ", type[j], p);
1610                     av_bprintf(&buf_script, "stream_%d_%d_psnr_%c=%2.2f\n",
1611                                ost->file_index, ost->index, type[j] | 32, p);
1612                 }
1613                 p = psnr(error_sum / scale_sum);
1614                 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "*:%2.2f ", psnr(error_sum / scale_sum));
1615                 av_bprintf(&buf_script, "stream_%d_%d_psnr_all=%2.2f\n",
1616                            ost->file_index, ost->index, p);
1617             }
1618             vid = 1;
1619         }
1620         /* compute min output value */
1621         if (av_stream_get_end_pts(ost->st) != AV_NOPTS_VALUE)
1622             pts = FFMAX(pts, av_rescale_q(av_stream_get_end_pts(ost->st),
1623                                           ost->st->time_base, AV_TIME_BASE_Q));
1624         if (is_last_report)
1625             nb_frames_drop += ost->last_droped;
1626     }
1627
1628     secs = FFABS(pts) / AV_TIME_BASE;
1629     us = FFABS(pts) % AV_TIME_BASE;
1630     mins = secs / 60;
1631     secs %= 60;
1632     hours = mins / 60;
1633     mins %= 60;
1634
1635     bitrate = pts && total_size >= 0 ? total_size * 8 / (pts / 1000.0) : -1;
1636
1637     if (total_size < 0) snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
1638                                  "size=N/A time=");
1639     else                snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
1640                                  "size=%8.0fkB time=", total_size / 1024.0);
1641     if (pts < 0)
1642         snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "-");
1643     snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
1644              "%02d:%02d:%02d.%02d ", hours, mins, secs,
1645              (100 * us) / AV_TIME_BASE);
1646
1647     if (bitrate < 0) {
1648         snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),"bitrate=N/A");
1649         av_bprintf(&buf_script, "bitrate=N/A\n");
1650     }else{
1651         snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),"bitrate=%6.1fkbits/s", bitrate);
1652         av_bprintf(&buf_script, "bitrate=%6.1fkbits/s\n", bitrate);
1653     }
1654
1655     if (total_size < 0) av_bprintf(&buf_script, "total_size=N/A\n");
1656     else                av_bprintf(&buf_script, "total_size=%"PRId64"\n", total_size);
1657     av_bprintf(&buf_script, "out_time_ms=%"PRId64"\n", pts);
1658     av_bprintf(&buf_script, "out_time=%02d:%02d:%02d.%06d\n",
1659                hours, mins, secs, us);
1660
1661     if (nb_frames_dup || nb_frames_drop)
1662         snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), " dup=%d drop=%d",
1663                 nb_frames_dup, nb_frames_drop);
1664     av_bprintf(&buf_script, "dup_frames=%d\n", nb_frames_dup);
1665     av_bprintf(&buf_script, "drop_frames=%d\n", nb_frames_drop);
1666
1667     if (print_stats || is_last_report) {
1668         const char end = is_last_report ? '\n' : '\r';
1669         if (print_stats==1 && AV_LOG_INFO > av_log_get_level()) {
1670             fprintf(stderr, "%s    %c", buf, end);
1671         } else
1672             av_log(NULL, AV_LOG_INFO, "%s    %c", buf, end);
1673
1674     fflush(stderr);
1675     }
1676
1677     if (progress_avio) {
1678         av_bprintf(&buf_script, "progress=%s\n",
1679                    is_last_report ? "end" : "continue");
1680         avio_write(progress_avio, buf_script.str,
1681                    FFMIN(buf_script.len, buf_script.size - 1));
1682         avio_flush(progress_avio);
1683         av_bprint_finalize(&buf_script, NULL);
1684         if (is_last_report) {
1685             avio_closep(&progress_avio);
1686         }
1687     }
1688
1689     if (is_last_report)
1690         print_final_stats(total_size);
1691 }
1692
1693 static void flush_encoders(void)
1694 {
1695     int i, ret;
1696
1697     for (i = 0; i < nb_output_streams; i++) {
1698         OutputStream   *ost = output_streams[i];
1699         AVCodecContext *enc = ost->enc_ctx;
1700         AVFormatContext *os = output_files[ost->file_index]->ctx;
1701         int stop_encoding = 0;
1702
1703         if (!ost->encoding_needed)
1704             continue;
1705
1706         if (enc->codec_type == AVMEDIA_TYPE_AUDIO && enc->frame_size <= 1)
1707             continue;
1708         if (enc->codec_type == AVMEDIA_TYPE_VIDEO && (os->oformat->flags & AVFMT_RAWPICTURE) && enc->codec->id == AV_CODEC_ID_RAWVIDEO)
1709             continue;
1710
1711         for (;;) {
1712             int (*encode)(AVCodecContext*, AVPacket*, const AVFrame*, int*) = NULL;
1713             const char *desc;
1714
1715             switch (enc->codec_type) {
1716             case AVMEDIA_TYPE_AUDIO:
1717                 encode = avcodec_encode_audio2;
1718                 desc   = "Audio";
1719                 break;
1720             case AVMEDIA_TYPE_VIDEO:
1721                 encode = avcodec_encode_video2;
1722                 desc   = "Video";
1723                 break;
1724             default:
1725                 stop_encoding = 1;
1726             }
1727
1728             if (encode) {
1729                 AVPacket pkt;
1730                 int pkt_size;
1731                 int got_packet;
1732                 av_init_packet(&pkt);
1733                 pkt.data = NULL;
1734                 pkt.size = 0;
1735
1736                 update_benchmark(NULL);
1737                 ret = encode(enc, &pkt, NULL, &got_packet);
1738                 update_benchmark("flush %s %d.%d", desc, ost->file_index, ost->index);
1739                 if (ret < 0) {
1740                     av_log(NULL, AV_LOG_FATAL, "%s encoding failed\n", desc);
1741                     exit_program(1);
1742                 }
1743                 if (ost->logfile && enc->stats_out) {
1744                     fprintf(ost->logfile, "%s", enc->stats_out);
1745                 }
1746                 if (!got_packet) {
1747                     stop_encoding = 1;
1748                     break;
1749                 }
1750                 if (ost->finished & MUXER_FINISHED) {
1751                     av_free_packet(&pkt);
1752                     continue;
1753                 }
1754                 av_packet_rescale_ts(&pkt, enc->time_base, ost->st->time_base);
1755                 pkt_size = pkt.size;
1756                 write_frame(os, &pkt, ost);
1757                 if (ost->enc_ctx->codec_type == AVMEDIA_TYPE_VIDEO && vstats_filename) {
1758                     do_video_stats(ost, pkt_size);
1759                 }
1760             }
1761
1762             if (stop_encoding)
1763                 break;
1764         }
1765     }
1766 }
1767
1768 /*
1769  * Check whether a packet from ist should be written into ost at this time
1770  */
1771 static int check_output_constraints(InputStream *ist, OutputStream *ost)
1772 {
1773     OutputFile *of = output_files[ost->file_index];
1774     int ist_index  = input_files[ist->file_index]->ist_index + ist->st->index;
1775
1776     if (ost->source_index != ist_index)
1777         return 0;
1778
1779     if (ost->finished)
1780         return 0;
1781
1782     if (of->start_time != AV_NOPTS_VALUE && ist->pts < of->start_time)
1783         return 0;
1784
1785     return 1;
1786 }
1787
1788 static void do_streamcopy(InputStream *ist, OutputStream *ost, const AVPacket *pkt)
1789 {
1790     OutputFile *of = output_files[ost->file_index];
1791     InputFile   *f = input_files [ist->file_index];
1792     int64_t start_time = (of->start_time == AV_NOPTS_VALUE) ? 0 : of->start_time;
1793     int64_t ost_tb_start_time = av_rescale_q(start_time, AV_TIME_BASE_Q, ost->st->time_base);
1794     int64_t ist_tb_start_time = av_rescale_q(start_time, AV_TIME_BASE_Q, ist->st->time_base);
1795     AVPicture pict;
1796     AVPacket opkt;
1797
1798     av_init_packet(&opkt);
1799
1800     if ((!ost->frame_number && !(pkt->flags & AV_PKT_FLAG_KEY)) &&
1801         !ost->copy_initial_nonkeyframes)
1802         return;
1803
1804     if (pkt->pts == AV_NOPTS_VALUE) {
1805         if (!ost->frame_number && ist->pts < start_time &&
1806             !ost->copy_prior_start)
1807             return;
1808     } else {
1809         if (!ost->frame_number && pkt->pts < ist_tb_start_time &&
1810             !ost->copy_prior_start)
1811             return;
1812     }
1813
1814     if (of->recording_time != INT64_MAX &&
1815         ist->pts >= of->recording_time + start_time) {
1816         close_output_stream(ost);
1817         return;
1818     }
1819
1820     if (f->recording_time != INT64_MAX) {
1821         start_time = f->ctx->start_time;
1822         if (f->start_time != AV_NOPTS_VALUE)
1823             start_time += f->start_time;
1824         if (ist->pts >= f->recording_time + start_time) {
1825             close_output_stream(ost);
1826             return;
1827         }
1828     }
1829
1830     /* force the input stream PTS */
1831     if (ost->enc_ctx->codec_type == AVMEDIA_TYPE_VIDEO)
1832         ost->sync_opts++;
1833
1834     if (pkt->pts != AV_NOPTS_VALUE)
1835         opkt.pts = av_rescale_q(pkt->pts, ist->st->time_base, ost->st->time_base) - ost_tb_start_time;
1836     else
1837         opkt.pts = AV_NOPTS_VALUE;
1838
1839     if (pkt->dts == AV_NOPTS_VALUE)
1840         opkt.dts = av_rescale_q(ist->dts, AV_TIME_BASE_Q, ost->st->time_base);
1841     else
1842         opkt.dts = av_rescale_q(pkt->dts, ist->st->time_base, ost->st->time_base);
1843     opkt.dts -= ost_tb_start_time;
1844
1845     if (ost->st->codec->codec_type == AVMEDIA_TYPE_AUDIO && pkt->dts != AV_NOPTS_VALUE) {
1846         int duration = av_get_audio_frame_duration(ist->dec_ctx, pkt->size);
1847         if(!duration)
1848             duration = ist->dec_ctx->frame_size;
1849         opkt.dts = opkt.pts = av_rescale_delta(ist->st->time_base, pkt->dts,
1850                                                (AVRational){1, ist->dec_ctx->sample_rate}, duration, &ist->filter_in_rescale_delta_last,
1851                                                ost->st->time_base) - ost_tb_start_time;
1852     }
1853
1854     opkt.duration = av_rescale_q(pkt->duration, ist->st->time_base, ost->st->time_base);
1855     opkt.flags    = pkt->flags;
1856
1857     // FIXME remove the following 2 lines they shall be replaced by the bitstream filters
1858     if (  ost->enc_ctx->codec_id != AV_CODEC_ID_H264
1859        && ost->enc_ctx->codec_id != AV_CODEC_ID_MPEG1VIDEO
1860        && ost->enc_ctx->codec_id != AV_CODEC_ID_MPEG2VIDEO
1861        && ost->enc_ctx->codec_id != AV_CODEC_ID_VC1
1862        ) {
1863         if (av_parser_change(ost->parser, ost->st->codec,
1864                              &opkt.data, &opkt.size,
1865                              pkt->data, pkt->size,
1866                              pkt->flags & AV_PKT_FLAG_KEY)) {
1867             opkt.buf = av_buffer_create(opkt.data, opkt.size, av_buffer_default_free, NULL, 0);
1868             if (!opkt.buf)
1869                 exit_program(1);
1870         }
1871     } else {
1872         opkt.data = pkt->data;
1873         opkt.size = pkt->size;
1874     }
1875     av_copy_packet_side_data(&opkt, pkt);
1876
1877     if (ost->st->codec->codec_type == AVMEDIA_TYPE_VIDEO && (of->ctx->oformat->flags & AVFMT_RAWPICTURE)) {
1878         /* store AVPicture in AVPacket, as expected by the output format */
1879         avpicture_fill(&pict, opkt.data, ost->st->codec->pix_fmt, ost->st->codec->width, ost->st->codec->height);
1880         opkt.data = (uint8_t *)&pict;
1881         opkt.size = sizeof(AVPicture);
1882         opkt.flags |= AV_PKT_FLAG_KEY;
1883     }
1884
1885     write_frame(of->ctx, &opkt, ost);
1886 }
1887
1888 int guess_input_channel_layout(InputStream *ist)
1889 {
1890     AVCodecContext *dec = ist->dec_ctx;
1891
1892     if (!dec->channel_layout) {
1893         char layout_name[256];
1894
1895         if (dec->channels > ist->guess_layout_max)
1896             return 0;
1897         dec->channel_layout = av_get_default_channel_layout(dec->channels);
1898         if (!dec->channel_layout)
1899             return 0;
1900         av_get_channel_layout_string(layout_name, sizeof(layout_name),
1901                                      dec->channels, dec->channel_layout);
1902         av_log(NULL, AV_LOG_WARNING, "Guessed Channel Layout for  Input Stream "
1903                "#%d.%d : %s\n", ist->file_index, ist->st->index, layout_name);
1904     }
1905     return 1;
1906 }
1907
1908 static int decode_audio(InputStream *ist, AVPacket *pkt, int *got_output)
1909 {
1910     AVFrame *decoded_frame, *f;
1911     AVCodecContext *avctx = ist->dec_ctx;
1912     int i, ret, err = 0, resample_changed;
1913     AVRational decoded_frame_tb;
1914
1915     if (!ist->decoded_frame && !(ist->decoded_frame = av_frame_alloc()))
1916         return AVERROR(ENOMEM);
1917     if (!ist->filter_frame && !(ist->filter_frame = av_frame_alloc()))
1918         return AVERROR(ENOMEM);
1919     decoded_frame = ist->decoded_frame;
1920
1921     update_benchmark(NULL);
1922     ret = avcodec_decode_audio4(avctx, decoded_frame, got_output, pkt);
1923     update_benchmark("decode_audio %d.%d", ist->file_index, ist->st->index);
1924
1925     if (ret >= 0 && avctx->sample_rate <= 0) {
1926         av_log(avctx, AV_LOG_ERROR, "Sample rate %d invalid\n", avctx->sample_rate);
1927         ret = AVERROR_INVALIDDATA;
1928     }
1929
1930     if (*got_output || ret<0)
1931         decode_error_stat[ret<0] ++;
1932
1933     if (ret < 0 && exit_on_error)
1934         exit_program(1);
1935
1936     if (!*got_output || ret < 0)
1937         return ret;
1938
1939     ist->samples_decoded += decoded_frame->nb_samples;
1940     ist->frames_decoded++;
1941
1942 #if 1
1943     /* increment next_dts to use for the case where the input stream does not
1944        have timestamps or there are multiple frames in the packet */
1945     ist->next_pts += ((int64_t)AV_TIME_BASE * decoded_frame->nb_samples) /
1946                      avctx->sample_rate;
1947     ist->next_dts += ((int64_t)AV_TIME_BASE * decoded_frame->nb_samples) /
1948                      avctx->sample_rate;
1949 #endif
1950
1951     resample_changed = ist->resample_sample_fmt     != decoded_frame->format         ||
1952                        ist->resample_channels       != avctx->channels               ||
1953                        ist->resample_channel_layout != decoded_frame->channel_layout ||
1954                        ist->resample_sample_rate    != decoded_frame->sample_rate;
1955     if (resample_changed) {
1956         char layout1[64], layout2[64];
1957
1958         if (!guess_input_channel_layout(ist)) {
1959             av_log(NULL, AV_LOG_FATAL, "Unable to find default channel "
1960                    "layout for Input Stream #%d.%d\n", ist->file_index,
1961                    ist->st->index);
1962             exit_program(1);
1963         }
1964         decoded_frame->channel_layout = avctx->channel_layout;
1965
1966         av_get_channel_layout_string(layout1, sizeof(layout1), ist->resample_channels,
1967                                      ist->resample_channel_layout);
1968         av_get_channel_layout_string(layout2, sizeof(layout2), avctx->channels,
1969                                      decoded_frame->channel_layout);
1970
1971         av_log(NULL, AV_LOG_INFO,
1972                "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",
1973                ist->file_index, ist->st->index,
1974                ist->resample_sample_rate,  av_get_sample_fmt_name(ist->resample_sample_fmt),
1975                ist->resample_channels, layout1,
1976                decoded_frame->sample_rate, av_get_sample_fmt_name(decoded_frame->format),
1977                avctx->channels, layout2);
1978
1979         ist->resample_sample_fmt     = decoded_frame->format;
1980         ist->resample_sample_rate    = decoded_frame->sample_rate;
1981         ist->resample_channel_layout = decoded_frame->channel_layout;
1982         ist->resample_channels       = avctx->channels;
1983
1984         for (i = 0; i < nb_filtergraphs; i++)
1985             if (ist_in_filtergraph(filtergraphs[i], ist)) {
1986                 FilterGraph *fg = filtergraphs[i];
1987                 if (configure_filtergraph(fg) < 0) {
1988                     av_log(NULL, AV_LOG_FATAL, "Error reinitializing filters!\n");
1989                     exit_program(1);
1990                 }
1991             }
1992     }
1993
1994     /* if the decoder provides a pts, use it instead of the last packet pts.
1995        the decoder could be delaying output by a packet or more. */
1996     if (decoded_frame->pts != AV_NOPTS_VALUE) {
1997         ist->dts = ist->next_dts = ist->pts = ist->next_pts = av_rescale_q(decoded_frame->pts, avctx->time_base, AV_TIME_BASE_Q);
1998         decoded_frame_tb   = avctx->time_base;
1999     } else if (decoded_frame->pkt_pts != AV_NOPTS_VALUE) {
2000         decoded_frame->pts = decoded_frame->pkt_pts;
2001         decoded_frame_tb   = ist->st->time_base;
2002     } else if (pkt->pts != AV_NOPTS_VALUE) {
2003         decoded_frame->pts = pkt->pts;
2004         decoded_frame_tb   = ist->st->time_base;
2005     }else {
2006         decoded_frame->pts = ist->dts;
2007         decoded_frame_tb   = AV_TIME_BASE_Q;
2008     }
2009     pkt->pts           = AV_NOPTS_VALUE;
2010     if (decoded_frame->pts != AV_NOPTS_VALUE)
2011         decoded_frame->pts = av_rescale_delta(decoded_frame_tb, decoded_frame->pts,
2012                                               (AVRational){1, avctx->sample_rate}, decoded_frame->nb_samples, &ist->filter_in_rescale_delta_last,
2013                                               (AVRational){1, avctx->sample_rate});
2014     for (i = 0; i < ist->nb_filters; i++) {
2015         if (i < ist->nb_filters - 1) {
2016             f = ist->filter_frame;
2017             err = av_frame_ref(f, decoded_frame);
2018             if (err < 0)
2019                 break;
2020         } else
2021             f = decoded_frame;
2022         err = av_buffersrc_add_frame_flags(ist->filters[i]->filter, f,
2023                                      AV_BUFFERSRC_FLAG_PUSH);
2024         if (err == AVERROR_EOF)
2025             err = 0; /* ignore */
2026         if (err < 0)
2027             break;
2028     }
2029     decoded_frame->pts = AV_NOPTS_VALUE;
2030
2031     av_frame_unref(ist->filter_frame);
2032     av_frame_unref(decoded_frame);
2033     return err < 0 ? err : ret;
2034 }
2035
2036 static int decode_video(InputStream *ist, AVPacket *pkt, int *got_output)
2037 {
2038     AVFrame *decoded_frame, *f;
2039     int i, ret = 0, err = 0, resample_changed;
2040     int64_t best_effort_timestamp;
2041     AVRational *frame_sample_aspect;
2042
2043     if (!ist->decoded_frame && !(ist->decoded_frame = av_frame_alloc()))
2044         return AVERROR(ENOMEM);
2045     if (!ist->filter_frame && !(ist->filter_frame = av_frame_alloc()))
2046         return AVERROR(ENOMEM);
2047     decoded_frame = ist->decoded_frame;
2048     pkt->dts  = av_rescale_q(ist->dts, AV_TIME_BASE_Q, ist->st->time_base);
2049
2050     update_benchmark(NULL);
2051     ret = avcodec_decode_video2(ist->dec_ctx,
2052                                 decoded_frame, got_output, pkt);
2053     update_benchmark("decode_video %d.%d", ist->file_index, ist->st->index);
2054
2055     // The following line may be required in some cases where there is no parser
2056     // or the parser does not has_b_frames correctly
2057     if (ist->st->codec->has_b_frames < ist->dec_ctx->has_b_frames) {
2058         if (ist->dec_ctx->codec_id == AV_CODEC_ID_H264) {
2059             ist->st->codec->has_b_frames = ist->dec_ctx->has_b_frames;
2060         } else
2061             av_log_ask_for_sample(
2062                 ist->dec_ctx,
2063                 "has_b_frames is larger in decoder than demuxer %d > %d ",
2064                 ist->dec_ctx->has_b_frames,
2065                 ist->st->codec->has_b_frames
2066             );
2067     }
2068
2069     if (*got_output || ret<0)
2070         decode_error_stat[ret<0] ++;
2071
2072     if (ret < 0 && exit_on_error)
2073         exit_program(1);
2074
2075     if (*got_output && ret >= 0) {
2076         if (ist->dec_ctx->width  != decoded_frame->width ||
2077             ist->dec_ctx->height != decoded_frame->height ||
2078             ist->dec_ctx->pix_fmt != decoded_frame->format) {
2079             av_log(NULL, AV_LOG_DEBUG, "Frame parameters mismatch context %d,%d,%d != %d,%d,%d\n",
2080                 decoded_frame->width,
2081                 decoded_frame->height,
2082                 decoded_frame->format,
2083                 ist->dec_ctx->width,
2084                 ist->dec_ctx->height,
2085                 ist->dec_ctx->pix_fmt);
2086         }
2087     }
2088
2089     if (!*got_output || ret < 0)
2090         return ret;
2091
2092     if(ist->top_field_first>=0)
2093         decoded_frame->top_field_first = ist->top_field_first;
2094
2095     ist->frames_decoded++;
2096
2097     if (ist->hwaccel_retrieve_data && decoded_frame->format == ist->hwaccel_pix_fmt) {
2098         err = ist->hwaccel_retrieve_data(ist->dec_ctx, decoded_frame);
2099         if (err < 0)
2100             goto fail;
2101     }
2102     ist->hwaccel_retrieved_pix_fmt = decoded_frame->format;
2103
2104     best_effort_timestamp= av_frame_get_best_effort_timestamp(decoded_frame);
2105     if(best_effort_timestamp != AV_NOPTS_VALUE)
2106         ist->next_pts = ist->pts = av_rescale_q(decoded_frame->pts = best_effort_timestamp, ist->st->time_base, AV_TIME_BASE_Q);
2107
2108     if (debug_ts) {
2109         av_log(NULL, AV_LOG_INFO, "decoder -> ist_index:%d type:video "
2110                "frame_pts:%s frame_pts_time:%s best_effort_ts:%"PRId64" best_effort_ts_time:%s keyframe:%d frame_type:%d time_base:%d/%d\n",
2111                ist->st->index, av_ts2str(decoded_frame->pts),
2112                av_ts2timestr(decoded_frame->pts, &ist->st->time_base),
2113                best_effort_timestamp,
2114                av_ts2timestr(best_effort_timestamp, &ist->st->time_base),
2115                decoded_frame->key_frame, decoded_frame->pict_type,
2116                ist->st->time_base.num, ist->st->time_base.den);
2117     }
2118
2119     pkt->size = 0;
2120
2121     if (ist->st->sample_aspect_ratio.num)
2122         decoded_frame->sample_aspect_ratio = ist->st->sample_aspect_ratio;
2123
2124     resample_changed = ist->resample_width   != decoded_frame->width  ||
2125                        ist->resample_height  != decoded_frame->height ||
2126                        ist->resample_pix_fmt != decoded_frame->format;
2127     if (resample_changed) {
2128         av_log(NULL, AV_LOG_INFO,
2129                "Input stream #%d:%d frame changed from size:%dx%d fmt:%s to size:%dx%d fmt:%s\n",
2130                ist->file_index, ist->st->index,
2131                ist->resample_width,  ist->resample_height,  av_get_pix_fmt_name(ist->resample_pix_fmt),
2132                decoded_frame->width, decoded_frame->height, av_get_pix_fmt_name(decoded_frame->format));
2133
2134         ist->resample_width   = decoded_frame->width;
2135         ist->resample_height  = decoded_frame->height;
2136         ist->resample_pix_fmt = decoded_frame->format;
2137
2138         for (i = 0; i < nb_filtergraphs; i++) {
2139             if (ist_in_filtergraph(filtergraphs[i], ist) && ist->reinit_filters &&
2140                 configure_filtergraph(filtergraphs[i]) < 0) {
2141                 av_log(NULL, AV_LOG_FATAL, "Error reinitializing filters!\n");
2142                 exit_program(1);
2143             }
2144         }
2145     }
2146
2147     frame_sample_aspect= av_opt_ptr(avcodec_get_frame_class(), decoded_frame, "sample_aspect_ratio");
2148     for (i = 0; i < ist->nb_filters; i++) {
2149         if (!frame_sample_aspect->num)
2150             *frame_sample_aspect = ist->st->sample_aspect_ratio;
2151
2152         if (i < ist->nb_filters - 1) {
2153             f = ist->filter_frame;
2154             err = av_frame_ref(f, decoded_frame);
2155             if (err < 0)
2156                 break;
2157         } else
2158             f = decoded_frame;
2159         ret = av_buffersrc_add_frame_flags(ist->filters[i]->filter, f, AV_BUFFERSRC_FLAG_PUSH);
2160         if (ret == AVERROR_EOF) {
2161             ret = 0; /* ignore */
2162         } else if (ret < 0) {
2163             av_log(NULL, AV_LOG_FATAL,
2164                    "Failed to inject frame into filter network: %s\n", av_err2str(ret));
2165             exit_program(1);
2166         }
2167     }
2168
2169 fail:
2170     av_frame_unref(ist->filter_frame);
2171     av_frame_unref(decoded_frame);
2172     return err < 0 ? err : ret;
2173 }
2174
2175 static int transcode_subtitles(InputStream *ist, AVPacket *pkt, int *got_output)
2176 {
2177     AVSubtitle subtitle;
2178     int i, ret = avcodec_decode_subtitle2(ist->dec_ctx,
2179                                           &subtitle, got_output, pkt);
2180
2181     if (*got_output || ret<0)
2182         decode_error_stat[ret<0] ++;
2183
2184     if (ret < 0 && exit_on_error)
2185         exit_program(1);
2186
2187     if (ret < 0 || !*got_output) {
2188         if (!pkt->size)
2189             sub2video_flush(ist);
2190         return ret;
2191     }
2192
2193     if (ist->fix_sub_duration) {
2194         int end = 1;
2195         if (ist->prev_sub.got_output) {
2196             end = av_rescale(subtitle.pts - ist->prev_sub.subtitle.pts,
2197                              1000, AV_TIME_BASE);
2198             if (end < ist->prev_sub.subtitle.end_display_time) {
2199                 av_log(ist->dec_ctx, AV_LOG_DEBUG,
2200                        "Subtitle duration reduced from %d to %d%s\n",
2201                        ist->prev_sub.subtitle.end_display_time, end,
2202                        end <= 0 ? ", dropping it" : "");
2203                 ist->prev_sub.subtitle.end_display_time = end;
2204             }
2205         }
2206         FFSWAP(int,        *got_output, ist->prev_sub.got_output);
2207         FFSWAP(int,        ret,         ist->prev_sub.ret);
2208         FFSWAP(AVSubtitle, subtitle,    ist->prev_sub.subtitle);
2209         if (end <= 0)
2210             goto out;
2211     }
2212
2213     if (!*got_output)
2214         return ret;
2215
2216     sub2video_update(ist, &subtitle);
2217
2218     if (!subtitle.num_rects)
2219         goto out;
2220
2221     ist->frames_decoded++;
2222
2223     for (i = 0; i < nb_output_streams; i++) {
2224         OutputStream *ost = output_streams[i];
2225
2226         if (!check_output_constraints(ist, ost) || !ost->encoding_needed
2227             || ost->enc->type != AVMEDIA_TYPE_SUBTITLE)
2228             continue;
2229
2230         do_subtitle_out(output_files[ost->file_index]->ctx, ost, ist, &subtitle);
2231     }
2232
2233 out:
2234     avsubtitle_free(&subtitle);
2235     return ret;
2236 }
2237
2238 static int send_filter_eof(InputStream *ist)
2239 {
2240     int i, ret;
2241     for (i = 0; i < ist->nb_filters; i++) {
2242 #if 1
2243         ret = av_buffersrc_add_ref(ist->filters[i]->filter, NULL, 0);
2244 #else
2245         ret = av_buffersrc_add_frame(ist->filters[i]->filter, NULL);
2246 #endif
2247         if (ret < 0)
2248             return ret;
2249     }
2250     return 0;
2251 }
2252
2253 /* pkt = NULL means EOF (needed to flush decoder buffers) */
2254 static int process_input_packet(InputStream *ist, const AVPacket *pkt)
2255 {
2256     int ret = 0, i;
2257     int got_output = 0;
2258
2259     AVPacket avpkt;
2260     if (!ist->saw_first_ts) {
2261         ist->dts = ist->st->avg_frame_rate.num ? - ist->dec_ctx->has_b_frames * AV_TIME_BASE / av_q2d(ist->st->avg_frame_rate) : 0;
2262         ist->pts = 0;
2263         if (pkt && pkt->pts != AV_NOPTS_VALUE && !ist->decoding_needed) {
2264             ist->dts += av_rescale_q(pkt->pts, ist->st->time_base, AV_TIME_BASE_Q);
2265             ist->pts = ist->dts; //unused but better to set it to a value thats not totally wrong
2266         }
2267         ist->saw_first_ts = 1;
2268     }
2269
2270     if (ist->next_dts == AV_NOPTS_VALUE)
2271         ist->next_dts = ist->dts;
2272     if (ist->next_pts == AV_NOPTS_VALUE)
2273         ist->next_pts = ist->pts;
2274
2275     if (!pkt) {
2276         /* EOF handling */
2277         av_init_packet(&avpkt);
2278         avpkt.data = NULL;
2279         avpkt.size = 0;
2280         goto handle_eof;
2281     } else {
2282         avpkt = *pkt;
2283     }
2284
2285     if (pkt->dts != AV_NOPTS_VALUE) {
2286         ist->next_dts = ist->dts = av_rescale_q(pkt->dts, ist->st->time_base, AV_TIME_BASE_Q);
2287         if (ist->dec_ctx->codec_type != AVMEDIA_TYPE_VIDEO || !ist->decoding_needed)
2288             ist->next_pts = ist->pts = ist->dts;
2289     }
2290
2291     // while we have more to decode or while the decoder did output something on EOF
2292     while (ist->decoding_needed && (avpkt.size > 0 || (!pkt && got_output))) {
2293         int duration;
2294     handle_eof:
2295
2296         ist->pts = ist->next_pts;
2297         ist->dts = ist->next_dts;
2298
2299         if (avpkt.size && avpkt.size != pkt->size &&
2300             !(ist->dec->capabilities & CODEC_CAP_SUBFRAMES)) {
2301             av_log(NULL, ist->showed_multi_packet_warning ? AV_LOG_VERBOSE : AV_LOG_WARNING,
2302                    "Multiple frames in a packet from stream %d\n", pkt->stream_index);
2303             ist->showed_multi_packet_warning = 1;
2304         }
2305
2306         switch (ist->dec_ctx->codec_type) {
2307         case AVMEDIA_TYPE_AUDIO:
2308             ret = decode_audio    (ist, &avpkt, &got_output);
2309             break;
2310         case AVMEDIA_TYPE_VIDEO:
2311             ret = decode_video    (ist, &avpkt, &got_output);
2312             if (avpkt.duration) {
2313                 duration = av_rescale_q(avpkt.duration, ist->st->time_base, AV_TIME_BASE_Q);
2314             } else if(ist->dec_ctx->framerate.num != 0 && ist->dec_ctx->framerate.den != 0) {
2315                 int ticks= av_stream_get_parser(ist->st) ? av_stream_get_parser(ist->st)->repeat_pict+1 : ist->dec_ctx->ticks_per_frame;
2316                 duration = ((int64_t)AV_TIME_BASE *
2317                                 ist->dec_ctx->framerate.den * ticks) /
2318                                 ist->dec_ctx->framerate.num / ist->dec_ctx->ticks_per_frame;
2319             } else
2320                 duration = 0;
2321
2322             if(ist->dts != AV_NOPTS_VALUE && duration) {
2323                 ist->next_dts += duration;
2324             }else
2325                 ist->next_dts = AV_NOPTS_VALUE;
2326
2327             if (got_output)
2328                 ist->next_pts += duration; //FIXME the duration is not correct in some cases
2329             break;
2330         case AVMEDIA_TYPE_SUBTITLE:
2331             ret = transcode_subtitles(ist, &avpkt, &got_output);
2332             break;
2333         default:
2334             return -1;
2335         }
2336
2337         if (ret < 0) {
2338             av_log(NULL, AV_LOG_ERROR, "Error while decoding stream #%d:%d: %s\n",
2339                    ist->file_index, ist->st->index, av_err2str(ret));
2340             if (exit_on_error)
2341                 exit_program(1);
2342             break;
2343         }
2344
2345         avpkt.dts=
2346         avpkt.pts= AV_NOPTS_VALUE;
2347
2348         // touch data and size only if not EOF
2349         if (pkt) {
2350             if(ist->dec_ctx->codec_type != AVMEDIA_TYPE_AUDIO)
2351                 ret = avpkt.size;
2352             avpkt.data += ret;
2353             avpkt.size -= ret;
2354         }
2355         if (!got_output) {
2356             continue;
2357         }
2358         if (got_output && !pkt)
2359             break;
2360     }
2361
2362     /* after flushing, send an EOF on all the filter inputs attached to the stream */
2363     if (!pkt && ist->decoding_needed && !got_output) {
2364         int ret = send_filter_eof(ist);
2365         if (ret < 0) {
2366             av_log(NULL, AV_LOG_FATAL, "Error marking filters as finished\n");
2367             exit_program(1);
2368         }
2369     }
2370
2371     /* handle stream copy */
2372     if (!ist->decoding_needed) {
2373         ist->dts = ist->next_dts;
2374         switch (ist->dec_ctx->codec_type) {
2375         case AVMEDIA_TYPE_AUDIO:
2376             ist->next_dts += ((int64_t)AV_TIME_BASE * ist->dec_ctx->frame_size) /
2377                              ist->dec_ctx->sample_rate;
2378             break;
2379         case AVMEDIA_TYPE_VIDEO:
2380             if (ist->framerate.num) {
2381                 // TODO: Remove work-around for c99-to-c89 issue 7
2382                 AVRational time_base_q = AV_TIME_BASE_Q;
2383                 int64_t next_dts = av_rescale_q(ist->next_dts, time_base_q, av_inv_q(ist->framerate));
2384                 ist->next_dts = av_rescale_q(next_dts + 1, av_inv_q(ist->framerate), time_base_q);
2385             } else if (pkt->duration) {
2386                 ist->next_dts += av_rescale_q(pkt->duration, ist->st->time_base, AV_TIME_BASE_Q);
2387             } else if(ist->dec_ctx->framerate.num != 0) {
2388                 int ticks= av_stream_get_parser(ist->st) ? av_stream_get_parser(ist->st)->repeat_pict + 1 : ist->dec_ctx->ticks_per_frame;
2389                 ist->next_dts += ((int64_t)AV_TIME_BASE *
2390                                   ist->dec_ctx->framerate.den * ticks) /
2391                                   ist->dec_ctx->framerate.num / ist->dec_ctx->ticks_per_frame;
2392             }
2393             break;
2394         }
2395         ist->pts = ist->dts;
2396         ist->next_pts = ist->next_dts;
2397     }
2398     for (i = 0; pkt && i < nb_output_streams; i++) {
2399         OutputStream *ost = output_streams[i];
2400
2401         if (!check_output_constraints(ist, ost) || ost->encoding_needed)
2402             continue;
2403
2404         do_streamcopy(ist, ost, pkt);
2405     }
2406
2407     return got_output;
2408 }
2409
2410 static void print_sdp(void)
2411 {
2412     char sdp[16384];
2413     int i;
2414     int j;
2415     AVIOContext *sdp_pb;
2416     AVFormatContext **avc = av_malloc_array(nb_output_files, sizeof(*avc));
2417
2418     if (!avc)
2419         exit_program(1);
2420     for (i = 0, j = 0; i < nb_output_files; i++) {
2421         if (!strcmp(output_files[i]->ctx->oformat->name, "rtp")) {
2422             avc[j] = output_files[i]->ctx;
2423             j++;
2424         }
2425     }
2426
2427     av_sdp_create(avc, j, sdp, sizeof(sdp));
2428
2429     if (!sdp_filename) {
2430         printf("SDP:\n%s\n", sdp);
2431         fflush(stdout);
2432     } else {
2433         if (avio_open2(&sdp_pb, sdp_filename, AVIO_FLAG_WRITE, &int_cb, NULL) < 0) {
2434             av_log(NULL, AV_LOG_ERROR, "Failed to open sdp file '%s'\n", sdp_filename);
2435         } else {
2436             avio_printf(sdp_pb, "SDP:\n%s", sdp);
2437             avio_closep(&sdp_pb);
2438             av_freep(&sdp_filename);
2439         }
2440     }
2441
2442     av_freep(&avc);
2443 }
2444
2445 static const HWAccel *get_hwaccel(enum AVPixelFormat pix_fmt)
2446 {
2447     int i;
2448     for (i = 0; hwaccels[i].name; i++)
2449         if (hwaccels[i].pix_fmt == pix_fmt)
2450             return &hwaccels[i];
2451     return NULL;
2452 }
2453
2454 static enum AVPixelFormat get_format(AVCodecContext *s, const enum AVPixelFormat *pix_fmts)
2455 {
2456     InputStream *ist = s->opaque;
2457     const enum AVPixelFormat *p;
2458     int ret;
2459
2460     for (p = pix_fmts; *p != -1; p++) {
2461         const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(*p);
2462         const HWAccel *hwaccel;
2463
2464         if (!(desc->flags & AV_PIX_FMT_FLAG_HWACCEL))
2465             break;
2466
2467         hwaccel = get_hwaccel(*p);
2468         if (!hwaccel ||
2469             (ist->active_hwaccel_id && ist->active_hwaccel_id != hwaccel->id) ||
2470             (ist->hwaccel_id != HWACCEL_AUTO && ist->hwaccel_id != hwaccel->id))
2471             continue;
2472
2473         ret = hwaccel->init(s);
2474         if (ret < 0) {
2475             if (ist->hwaccel_id == hwaccel->id) {
2476                 av_log(NULL, AV_LOG_FATAL,
2477                        "%s hwaccel requested for input stream #%d:%d, "
2478                        "but cannot be initialized.\n", hwaccel->name,
2479                        ist->file_index, ist->st->index);
2480                 return AV_PIX_FMT_NONE;
2481             }
2482             continue;
2483         }
2484         ist->active_hwaccel_id = hwaccel->id;
2485         ist->hwaccel_pix_fmt   = *p;
2486         break;
2487     }
2488
2489     return *p;
2490 }
2491
2492 static int get_buffer(AVCodecContext *s, AVFrame *frame, int flags)
2493 {
2494     InputStream *ist = s->opaque;
2495
2496     if (ist->hwaccel_get_buffer && frame->format == ist->hwaccel_pix_fmt)
2497         return ist->hwaccel_get_buffer(s, frame, flags);
2498
2499     return avcodec_default_get_buffer2(s, frame, flags);
2500 }
2501
2502 static int init_input_stream(int ist_index, char *error, int error_len)
2503 {
2504     int ret;
2505     InputStream *ist = input_streams[ist_index];
2506
2507     if (ist->decoding_needed) {
2508         AVCodec *codec = ist->dec;
2509         if (!codec) {
2510             snprintf(error, error_len, "Decoder (codec %s) not found for input stream #%d:%d",
2511                     avcodec_get_name(ist->dec_ctx->codec_id), ist->file_index, ist->st->index);
2512             return AVERROR(EINVAL);
2513         }
2514
2515         ist->dec_ctx->opaque                = ist;
2516         ist->dec_ctx->get_format            = get_format;
2517         ist->dec_ctx->get_buffer2           = get_buffer;
2518         ist->dec_ctx->thread_safe_callbacks = 1;
2519
2520         av_opt_set_int(ist->dec_ctx, "refcounted_frames", 1, 0);
2521         if (ist->dec_ctx->codec_id == AV_CODEC_ID_DVB_SUBTITLE &&
2522            (ist->decoding_needed & DECODING_FOR_OST)) {
2523             av_dict_set(&ist->decoder_opts, "compute_edt", "1", AV_DICT_DONT_OVERWRITE);
2524             if (ist->decoding_needed & DECODING_FOR_FILTER)
2525                 av_log(NULL, AV_LOG_WARNING, "Warning using DVB subtitles for filtering and output at the same time is not fully supported, also see -compute_edt [0|1]\n");
2526         }
2527
2528         if (!av_dict_get(ist->decoder_opts, "threads", NULL, 0))
2529             av_dict_set(&ist->decoder_opts, "threads", "auto", 0);
2530         if ((ret = avcodec_open2(ist->dec_ctx, codec, &ist->decoder_opts)) < 0) {
2531             if (ret == AVERROR_EXPERIMENTAL)
2532                 abort_codec_experimental(codec, 0);
2533
2534             snprintf(error, error_len,
2535                      "Error while opening decoder for input stream "
2536                      "#%d:%d : %s",
2537                      ist->file_index, ist->st->index, av_err2str(ret));
2538             return ret;
2539         }
2540         assert_avoptions(ist->decoder_opts);
2541     }
2542
2543     ist->next_pts = AV_NOPTS_VALUE;
2544     ist->next_dts = AV_NOPTS_VALUE;
2545
2546     return 0;
2547 }
2548
2549 static InputStream *get_input_stream(OutputStream *ost)
2550 {
2551     if (ost->source_index >= 0)
2552         return input_streams[ost->source_index];
2553     return NULL;
2554 }
2555
2556 static int compare_int64(const void *a, const void *b)
2557 {
2558     int64_t va = *(int64_t *)a, vb = *(int64_t *)b;
2559     return va < vb ? -1 : va > vb ? +1 : 0;
2560 }
2561
2562 static int init_output_stream(OutputStream *ost, char *error, int error_len)
2563 {
2564     int ret = 0;
2565
2566     if (ost->encoding_needed) {
2567         AVCodec      *codec = ost->enc;
2568         AVCodecContext *dec = NULL;
2569         InputStream *ist;
2570
2571         if ((ist = get_input_stream(ost)))
2572             dec = ist->dec_ctx;
2573         if (dec && dec->subtitle_header) {
2574             /* ASS code assumes this buffer is null terminated so add extra byte. */
2575             ost->enc_ctx->subtitle_header = av_mallocz(dec->subtitle_header_size + 1);
2576             if (!ost->enc_ctx->subtitle_header)
2577                 return AVERROR(ENOMEM);
2578             memcpy(ost->enc_ctx->subtitle_header, dec->subtitle_header, dec->subtitle_header_size);
2579             ost->enc_ctx->subtitle_header_size = dec->subtitle_header_size;
2580         }
2581         if (!av_dict_get(ost->encoder_opts, "threads", NULL, 0))
2582             av_dict_set(&ost->encoder_opts, "threads", "auto", 0);
2583         av_dict_set(&ost->encoder_opts, "side_data_only_packets", "1", 0);
2584
2585         if ((ret = avcodec_open2(ost->enc_ctx, codec, &ost->encoder_opts)) < 0) {
2586             if (ret == AVERROR_EXPERIMENTAL)
2587                 abort_codec_experimental(codec, 1);
2588             snprintf(error, error_len,
2589                      "Error while opening encoder for output stream #%d:%d - "
2590                      "maybe incorrect parameters such as bit_rate, rate, width or height",
2591                     ost->file_index, ost->index);
2592             return ret;
2593         }
2594         if (ost->enc->type == AVMEDIA_TYPE_AUDIO &&
2595             !(ost->enc->capabilities & CODEC_CAP_VARIABLE_FRAME_SIZE))
2596             av_buffersink_set_frame_size(ost->filter->filter,
2597                                             ost->enc_ctx->frame_size);
2598         assert_avoptions(ost->encoder_opts);
2599         if (ost->enc_ctx->bit_rate && ost->enc_ctx->bit_rate < 1000)
2600             av_log(NULL, AV_LOG_WARNING, "The bitrate parameter is set too low."
2601                                          " It takes bits/s as argument, not kbits/s\n");
2602
2603         ret = avcodec_copy_context(ost->st->codec, ost->enc_ctx);
2604         if (ret < 0) {
2605             av_log(NULL, AV_LOG_FATAL,
2606                    "Error initializing the output stream codec context.\n");
2607             exit_program(1);
2608         }
2609
2610         // copy timebase while removing common factors
2611         ost->st->time_base = av_add_q(ost->enc_ctx->time_base, (AVRational){0, 1});
2612         ost->st->codec->codec= ost->enc_ctx->codec;
2613     } else {
2614         ret = av_opt_set_dict(ost->enc_ctx, &ost->encoder_opts);
2615         if (ret < 0) {
2616            av_log(NULL, AV_LOG_FATAL,
2617                   "Error setting up codec context options.\n");
2618            return ret;
2619         }
2620         // copy timebase while removing common factors
2621         ost->st->time_base = av_add_q(ost->st->codec->time_base, (AVRational){0, 1});
2622     }
2623
2624     return ret;
2625 }
2626
2627 static void parse_forced_key_frames(char *kf, OutputStream *ost,
2628                                     AVCodecContext *avctx)
2629 {
2630     char *p;
2631     int n = 1, i, size, index = 0;
2632     int64_t t, *pts;
2633
2634     for (p = kf; *p; p++)
2635         if (*p == ',')
2636             n++;
2637     size = n;
2638     pts = av_malloc_array(size, sizeof(*pts));
2639     if (!pts) {
2640         av_log(NULL, AV_LOG_FATAL, "Could not allocate forced key frames array.\n");
2641         exit_program(1);
2642     }
2643
2644     p = kf;
2645     for (i = 0; i < n; i++) {
2646         char *next = strchr(p, ',');
2647
2648         if (next)
2649             *next++ = 0;
2650
2651         if (!memcmp(p, "chapters", 8)) {
2652
2653             AVFormatContext *avf = output_files[ost->file_index]->ctx;
2654             int j;
2655
2656             if (avf->nb_chapters > INT_MAX - size ||
2657                 !(pts = av_realloc_f(pts, size += avf->nb_chapters - 1,
2658                                      sizeof(*pts)))) {
2659                 av_log(NULL, AV_LOG_FATAL,
2660                        "Could not allocate forced key frames array.\n");
2661                 exit_program(1);
2662             }
2663             t = p[8] ? parse_time_or_die("force_key_frames", p + 8, 1) : 0;
2664             t = av_rescale_q(t, AV_TIME_BASE_Q, avctx->time_base);
2665
2666             for (j = 0; j < avf->nb_chapters; j++) {
2667                 AVChapter *c = avf->chapters[j];
2668                 av_assert1(index < size);
2669                 pts[index++] = av_rescale_q(c->start, c->time_base,
2670                                             avctx->time_base) + t;
2671             }
2672
2673         } else {
2674
2675             t = parse_time_or_die("force_key_frames", p, 1);
2676             av_assert1(index < size);
2677             pts[index++] = av_rescale_q(t, AV_TIME_BASE_Q, avctx->time_base);
2678
2679         }
2680
2681         p = next;
2682     }
2683
2684     av_assert0(index == size);
2685     qsort(pts, size, sizeof(*pts), compare_int64);
2686     ost->forced_kf_count = size;
2687     ost->forced_kf_pts   = pts;
2688 }
2689
2690 static void report_new_stream(int input_index, AVPacket *pkt)
2691 {
2692     InputFile *file = input_files[input_index];
2693     AVStream *st = file->ctx->streams[pkt->stream_index];
2694
2695     if (pkt->stream_index < file->nb_streams_warn)
2696         return;
2697     av_log(file->ctx, AV_LOG_WARNING,
2698            "New %s stream %d:%d at pos:%"PRId64" and DTS:%ss\n",
2699            av_get_media_type_string(st->codec->codec_type),
2700            input_index, pkt->stream_index,
2701            pkt->pos, av_ts2timestr(pkt->dts, &st->time_base));
2702     file->nb_streams_warn = pkt->stream_index + 1;
2703 }
2704
2705 static void set_encoder_id(OutputFile *of, OutputStream *ost)
2706 {
2707     AVDictionaryEntry *e;
2708
2709     uint8_t *encoder_string;
2710     int encoder_string_len;
2711     int format_flags = 0;
2712     int codec_flags = 0;
2713
2714     if (av_dict_get(ost->st->metadata, "encoder",  NULL, 0))
2715         return;
2716
2717     e = av_dict_get(of->opts, "fflags", NULL, 0);
2718     if (e) {
2719         const AVOption *o = av_opt_find(of->ctx, "fflags", NULL, 0, 0);
2720         if (!o)
2721             return;
2722         av_opt_eval_flags(of->ctx, o, e->value, &format_flags);
2723     }
2724     e = av_dict_get(ost->encoder_opts, "flags", NULL, 0);
2725     if (e) {
2726         const AVOption *o = av_opt_find(ost->enc_ctx, "flags", NULL, 0, 0);
2727         if (!o)
2728             return;
2729         av_opt_eval_flags(ost->enc_ctx, o, e->value, &codec_flags);
2730     }
2731
2732     encoder_string_len = sizeof(LIBAVCODEC_IDENT) + strlen(ost->enc->name) + 2;
2733     encoder_string     = av_mallocz(encoder_string_len);
2734     if (!encoder_string)
2735         exit_program(1);
2736
2737     if (!(format_flags & AVFMT_FLAG_BITEXACT) && !(codec_flags & CODEC_FLAG_BITEXACT))
2738         av_strlcpy(encoder_string, LIBAVCODEC_IDENT " ", encoder_string_len);
2739     else
2740         av_strlcpy(encoder_string, "Lavc ", encoder_string_len);
2741     av_strlcat(encoder_string, ost->enc->name, encoder_string_len);
2742     av_dict_set(&ost->st->metadata, "encoder",  encoder_string,
2743                 AV_DICT_DONT_STRDUP_VAL | AV_DICT_DONT_OVERWRITE);
2744 }
2745
2746 static int transcode_init(void)
2747 {
2748     int ret = 0, i, j, k;
2749     AVFormatContext *oc;
2750     OutputStream *ost;
2751     InputStream *ist;
2752     char error[1024] = {0};
2753     int want_sdp = 1;
2754
2755     for (i = 0; i < nb_filtergraphs; i++) {
2756         FilterGraph *fg = filtergraphs[i];
2757         for (j = 0; j < fg->nb_outputs; j++) {
2758             OutputFilter *ofilter = fg->outputs[j];
2759             if (!ofilter->ost || ofilter->ost->source_index >= 0)
2760                 continue;
2761             if (fg->nb_inputs != 1)
2762                 continue;
2763             for (k = nb_input_streams-1; k >= 0 ; k--)
2764                 if (fg->inputs[0]->ist == input_streams[k])
2765                     break;
2766             ofilter->ost->source_index = k;
2767         }
2768     }
2769
2770     /* init framerate emulation */
2771     for (i = 0; i < nb_input_files; i++) {
2772         InputFile *ifile = input_files[i];
2773         if (ifile->rate_emu)
2774             for (j = 0; j < ifile->nb_streams; j++)
2775                 input_streams[j + ifile->ist_index]->start = av_gettime_relative();
2776     }
2777
2778     /* for each output stream, we compute the right encoding parameters */
2779     for (i = 0; i < nb_output_streams; i++) {
2780         AVCodecContext *enc_ctx;
2781         AVCodecContext *dec_ctx = NULL;
2782         ost = output_streams[i];
2783         oc  = output_files[ost->file_index]->ctx;
2784         ist = get_input_stream(ost);
2785
2786         if (ost->attachment_filename)
2787             continue;
2788
2789         enc_ctx = ost->stream_copy ? ost->st->codec : ost->enc_ctx;
2790
2791         if (ist) {
2792             dec_ctx = ist->dec_ctx;
2793
2794             ost->st->disposition          = ist->st->disposition;
2795             enc_ctx->bits_per_raw_sample    = dec_ctx->bits_per_raw_sample;
2796             enc_ctx->chroma_sample_location = dec_ctx->chroma_sample_location;
2797         } else {
2798             for (j=0; j<oc->nb_streams; j++) {
2799                 AVStream *st = oc->streams[j];
2800                 if (st != ost->st && st->codec->codec_type == enc_ctx->codec_type)
2801                     break;
2802             }
2803             if (j == oc->nb_streams)
2804                 if (enc_ctx->codec_type == AVMEDIA_TYPE_AUDIO || enc_ctx->codec_type == AVMEDIA_TYPE_VIDEO)
2805                     ost->st->disposition = AV_DISPOSITION_DEFAULT;
2806         }
2807
2808         if (ost->stream_copy) {
2809             AVRational sar;
2810             uint64_t extra_size;
2811
2812             av_assert0(ist && !ost->filter);
2813
2814             extra_size = (uint64_t)dec_ctx->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE;
2815
2816             if (extra_size > INT_MAX) {
2817                 return AVERROR(EINVAL);
2818             }
2819
2820             /* if stream_copy is selected, no need to decode or encode */
2821             enc_ctx->codec_id   = dec_ctx->codec_id;
2822             enc_ctx->codec_type = dec_ctx->codec_type;
2823
2824             if (!enc_ctx->codec_tag) {
2825                 unsigned int codec_tag;
2826                 if (!oc->oformat->codec_tag ||
2827                      av_codec_get_id (oc->oformat->codec_tag, dec_ctx->codec_tag) == enc_ctx->codec_id ||
2828                      !av_codec_get_tag2(oc->oformat->codec_tag, dec_ctx->codec_id, &codec_tag))
2829                     enc_ctx->codec_tag = dec_ctx->codec_tag;
2830             }
2831
2832             enc_ctx->bit_rate       = dec_ctx->bit_rate;
2833             enc_ctx->rc_max_rate    = dec_ctx->rc_max_rate;
2834             enc_ctx->rc_buffer_size = dec_ctx->rc_buffer_size;
2835             enc_ctx->field_order    = dec_ctx->field_order;
2836             if (dec_ctx->extradata_size) {
2837                 enc_ctx->extradata      = av_mallocz(extra_size);
2838                 if (!enc_ctx->extradata) {
2839                     return AVERROR(ENOMEM);
2840                 }
2841                 memcpy(enc_ctx->extradata, dec_ctx->extradata, dec_ctx->extradata_size);
2842             }
2843             enc_ctx->extradata_size= dec_ctx->extradata_size;
2844             enc_ctx->bits_per_coded_sample  = dec_ctx->bits_per_coded_sample;
2845
2846             enc_ctx->time_base = ist->st->time_base;
2847             /*
2848              * Avi is a special case here because it supports variable fps but
2849              * having the fps and timebase differe significantly adds quite some
2850              * overhead
2851              */
2852             if(!strcmp(oc->oformat->name, "avi")) {
2853                 if ( copy_tb<0 && av_q2d(ist->st->r_frame_rate) >= av_q2d(ist->st->avg_frame_rate)
2854                                && 0.5/av_q2d(ist->st->r_frame_rate) > av_q2d(ist->st->time_base)
2855                                && 0.5/av_q2d(ist->st->r_frame_rate) > av_q2d(dec_ctx->time_base)
2856                                && av_q2d(ist->st->time_base) < 1.0/500 && av_q2d(dec_ctx->time_base) < 1.0/500
2857                      || copy_tb==2){
2858                     enc_ctx->time_base.num = ist->st->r_frame_rate.den;
2859                     enc_ctx->time_base.den = 2*ist->st->r_frame_rate.num;
2860                     enc_ctx->ticks_per_frame = 2;
2861                 } else if (   copy_tb<0 && av_q2d(dec_ctx->time_base)*dec_ctx->ticks_per_frame > 2*av_q2d(ist->st->time_base)
2862                                  && av_q2d(ist->st->time_base) < 1.0/500
2863                     || copy_tb==0){
2864                     enc_ctx->time_base = dec_ctx->time_base;
2865                     enc_ctx->time_base.num *= dec_ctx->ticks_per_frame;
2866                     enc_ctx->time_base.den *= 2;
2867                     enc_ctx->ticks_per_frame = 2;
2868                 }
2869             } else if(!(oc->oformat->flags & AVFMT_VARIABLE_FPS)
2870                       && strcmp(oc->oformat->name, "mov") && strcmp(oc->oformat->name, "mp4") && strcmp(oc->oformat->name, "3gp")
2871                       && strcmp(oc->oformat->name, "3g2") && strcmp(oc->oformat->name, "psp") && strcmp(oc->oformat->name, "ipod")
2872                       && strcmp(oc->oformat->name, "f4v")
2873             ) {
2874                 if(   copy_tb<0 && dec_ctx->time_base.den
2875                                 && av_q2d(dec_ctx->time_base)*dec_ctx->ticks_per_frame > av_q2d(ist->st->time_base)
2876                                 && av_q2d(ist->st->time_base) < 1.0/500
2877                    || copy_tb==0){
2878                     enc_ctx->time_base = dec_ctx->time_base;
2879                     enc_ctx->time_base.num *= dec_ctx->ticks_per_frame;
2880                 }
2881             }
2882             if (   enc_ctx->codec_tag == AV_RL32("tmcd")
2883                 && dec_ctx->time_base.num < dec_ctx->time_base.den
2884                 && dec_ctx->time_base.num > 0
2885                 && 121LL*dec_ctx->time_base.num > dec_ctx->time_base.den) {
2886                 enc_ctx->time_base = dec_ctx->time_base;
2887             }
2888
2889             if (ist && !ost->frame_rate.num)
2890                 ost->frame_rate = ist->framerate;
2891             if(ost->frame_rate.num)
2892                 enc_ctx->time_base = av_inv_q(ost->frame_rate);
2893
2894             av_reduce(&enc_ctx->time_base.num, &enc_ctx->time_base.den,
2895                         enc_ctx->time_base.num, enc_ctx->time_base.den, INT_MAX);
2896
2897             if (ist->st->nb_side_data) {
2898                 ost->st->side_data = av_realloc_array(NULL, ist->st->nb_side_data,
2899                                                       sizeof(*ist->st->side_data));
2900                 if (!ost->st->side_data)
2901                     return AVERROR(ENOMEM);
2902
2903                 ost->st->nb_side_data = 0;
2904                 for (j = 0; j < ist->st->nb_side_data; j++) {
2905                     const AVPacketSideData *sd_src = &ist->st->side_data[j];
2906                     AVPacketSideData *sd_dst = &ost->st->side_data[ost->st->nb_side_data];
2907
2908                     if (ost->rotate_overridden && sd_src->type == AV_PKT_DATA_DISPLAYMATRIX)
2909                         continue;
2910
2911                     sd_dst->data = av_malloc(sd_src->size);
2912                     if (!sd_dst->data)
2913                         return AVERROR(ENOMEM);
2914                     memcpy(sd_dst->data, sd_src->data, sd_src->size);
2915                     sd_dst->size = sd_src->size;
2916                     sd_dst->type = sd_src->type;
2917                     ost->st->nb_side_data++;
2918                 }
2919             }
2920
2921             ost->parser = av_parser_init(enc_ctx->codec_id);
2922
2923             switch (enc_ctx->codec_type) {
2924             case AVMEDIA_TYPE_AUDIO:
2925                 if (audio_volume != 256) {
2926                     av_log(NULL, AV_LOG_FATAL, "-acodec copy and -vol are incompatible (frames are not decoded)\n");
2927                     exit_program(1);
2928                 }
2929                 enc_ctx->channel_layout     = dec_ctx->channel_layout;
2930                 enc_ctx->sample_rate        = dec_ctx->sample_rate;
2931                 enc_ctx->channels           = dec_ctx->channels;
2932                 enc_ctx->frame_size         = dec_ctx->frame_size;
2933                 enc_ctx->audio_service_type = dec_ctx->audio_service_type;
2934                 enc_ctx->block_align        = dec_ctx->block_align;
2935                 enc_ctx->initial_padding    = dec_ctx->delay;
2936 #if FF_API_AUDIOENC_DELAY
2937                 enc_ctx->delay              = dec_ctx->delay;
2938 #endif
2939                 if((enc_ctx->block_align == 1 || enc_ctx->block_align == 1152 || enc_ctx->block_align == 576) && enc_ctx->codec_id == AV_CODEC_ID_MP3)
2940                     enc_ctx->block_align= 0;
2941                 if(enc_ctx->codec_id == AV_CODEC_ID_AC3)
2942                     enc_ctx->block_align= 0;
2943                 break;
2944             case AVMEDIA_TYPE_VIDEO:
2945                 enc_ctx->pix_fmt            = dec_ctx->pix_fmt;
2946                 enc_ctx->width              = dec_ctx->width;
2947                 enc_ctx->height             = dec_ctx->height;
2948                 enc_ctx->has_b_frames       = dec_ctx->has_b_frames;
2949                 if (ost->frame_aspect_ratio.num) { // overridden by the -aspect cli option
2950                     sar =
2951                         av_mul_q(ost->frame_aspect_ratio,
2952                                  (AVRational){ enc_ctx->height, enc_ctx->width });
2953                     av_log(NULL, AV_LOG_WARNING, "Overriding aspect ratio "
2954                            "with stream copy may produce invalid files\n");
2955                 }
2956                 else if (ist->st->sample_aspect_ratio.num)
2957                     sar = ist->st->sample_aspect_ratio;
2958                 else
2959                     sar = dec_ctx->sample_aspect_ratio;
2960                 ost->st->sample_aspect_ratio = enc_ctx->sample_aspect_ratio = sar;
2961                 ost->st->avg_frame_rate = ist->st->avg_frame_rate;
2962                 ost->st->r_frame_rate = ist->st->r_frame_rate;
2963                 break;
2964             case AVMEDIA_TYPE_SUBTITLE:
2965                 enc_ctx->width  = dec_ctx->width;
2966                 enc_ctx->height = dec_ctx->height;
2967                 break;
2968             case AVMEDIA_TYPE_UNKNOWN:
2969             case AVMEDIA_TYPE_DATA:
2970             case AVMEDIA_TYPE_ATTACHMENT:
2971                 break;
2972             default:
2973                 abort();
2974             }
2975         } else {
2976             if (!ost->enc)
2977                 ost->enc = avcodec_find_encoder(enc_ctx->codec_id);
2978             if (!ost->enc) {
2979                 /* should only happen when a default codec is not present. */
2980                 snprintf(error, sizeof(error), "Encoder (codec %s) not found for output stream #%d:%d",
2981                          avcodec_get_name(ost->st->codec->codec_id), ost->file_index, ost->index);
2982                 ret = AVERROR(EINVAL);
2983                 goto dump_format;
2984             }
2985
2986             set_encoder_id(output_files[ost->file_index], ost);
2987
2988             if (!ost->filter &&
2989                 (enc_ctx->codec_type == AVMEDIA_TYPE_VIDEO ||
2990                  enc_ctx->codec_type == AVMEDIA_TYPE_AUDIO)) {
2991                     FilterGraph *fg;
2992                     fg = init_simple_filtergraph(ist, ost);
2993                     if (configure_filtergraph(fg)) {
2994                         av_log(NULL, AV_LOG_FATAL, "Error opening filters!\n");
2995                         exit_program(1);
2996                     }
2997             }
2998
2999             if (enc_ctx->codec_type == AVMEDIA_TYPE_VIDEO) {
3000                 if (!ost->frame_rate.num)
3001                     ost->frame_rate = av_buffersink_get_frame_rate(ost->filter->filter);
3002                 if (ist && !ost->frame_rate.num)
3003                     ost->frame_rate = ist->framerate;
3004                 if (ist && !ost->frame_rate.num)
3005                     ost->frame_rate = ist->st->r_frame_rate;
3006                 if (ist && !ost->frame_rate.num) {
3007                     ost->frame_rate = (AVRational){25, 1};
3008                     av_log(NULL, AV_LOG_WARNING,
3009                            "No information "
3010                            "about the input framerate is available. Falling "
3011                            "back to a default value of 25fps for output stream #%d:%d. Use the -r option "
3012                            "if you want a different framerate.\n",
3013                            ost->file_index, ost->index);
3014                 }
3015 //                    ost->frame_rate = ist->st->avg_frame_rate.num ? ist->st->avg_frame_rate : (AVRational){25, 1};
3016                 if (ost->enc && ost->enc->supported_framerates && !ost->force_fps) {
3017                     int idx = av_find_nearest_q_idx(ost->frame_rate, ost->enc->supported_framerates);
3018                     ost->frame_rate = ost->enc->supported_framerates[idx];
3019                 }
3020                 // reduce frame rate for mpeg4 to be within the spec limits
3021                 if (enc_ctx->codec_id == AV_CODEC_ID_MPEG4) {
3022                     av_reduce(&ost->frame_rate.num, &ost->frame_rate.den,
3023                               ost->frame_rate.num, ost->frame_rate.den, 65535);
3024                 }
3025             }
3026
3027             switch (enc_ctx->codec_type) {
3028             case AVMEDIA_TYPE_AUDIO:
3029                 enc_ctx->sample_fmt     = ost->filter->filter->inputs[0]->format;
3030                 enc_ctx->sample_rate    = ost->filter->filter->inputs[0]->sample_rate;
3031                 enc_ctx->channel_layout = ost->filter->filter->inputs[0]->channel_layout;
3032                 enc_ctx->channels       = avfilter_link_get_channels(ost->filter->filter->inputs[0]);
3033                 enc_ctx->time_base      = (AVRational){ 1, enc_ctx->sample_rate };
3034                 break;
3035             case AVMEDIA_TYPE_VIDEO:
3036                 enc_ctx->time_base = av_inv_q(ost->frame_rate);
3037                 if (!(enc_ctx->time_base.num && enc_ctx->time_base.den))
3038                     enc_ctx->time_base = ost->filter->filter->inputs[0]->time_base;
3039                 if (   av_q2d(enc_ctx->time_base) < 0.001 && video_sync_method != VSYNC_PASSTHROUGH
3040                    && (video_sync_method == VSYNC_CFR || video_sync_method == VSYNC_VSCFR || (video_sync_method == VSYNC_AUTO && !(oc->oformat->flags & AVFMT_VARIABLE_FPS)))){
3041                     av_log(oc, AV_LOG_WARNING, "Frame rate very high for a muxer not efficiently supporting it.\n"
3042                                                "Please consider specifying a lower framerate, a different muxer or -vsync 2\n");
3043                 }
3044                 for (j = 0; j < ost->forced_kf_count; j++)
3045                     ost->forced_kf_pts[j] = av_rescale_q(ost->forced_kf_pts[j],
3046                                                          AV_TIME_BASE_Q,
3047                                                          enc_ctx->time_base);
3048
3049                 enc_ctx->width  = ost->filter->filter->inputs[0]->w;
3050                 enc_ctx->height = ost->filter->filter->inputs[0]->h;
3051                 enc_ctx->sample_aspect_ratio = ost->st->sample_aspect_ratio =
3052                     ost->frame_aspect_ratio.num ? // overridden by the -aspect cli option
3053                     av_mul_q(ost->frame_aspect_ratio, (AVRational){ enc_ctx->height, enc_ctx->width }) :
3054                     ost->filter->filter->inputs[0]->sample_aspect_ratio;
3055                 if (!strncmp(ost->enc->name, "libx264", 7) &&
3056                     enc_ctx->pix_fmt == AV_PIX_FMT_NONE &&
3057                     ost->filter->filter->inputs[0]->format != AV_PIX_FMT_YUV420P)
3058                     av_log(NULL, AV_LOG_WARNING,
3059                            "No pixel format specified, %s for H.264 encoding chosen.\n"
3060                            "Use -pix_fmt yuv420p for compatibility with outdated media players.\n",
3061                            av_get_pix_fmt_name(ost->filter->filter->inputs[0]->format));
3062                 if (!strncmp(ost->enc->name, "mpeg2video", 10) &&
3063                     enc_ctx->pix_fmt == AV_PIX_FMT_NONE &&
3064                     ost->filter->filter->inputs[0]->format != AV_PIX_FMT_YUV420P)
3065                     av_log(NULL, AV_LOG_WARNING,
3066                            "No pixel format specified, %s for MPEG-2 encoding chosen.\n"
3067                            "Use -pix_fmt yuv420p for compatibility with outdated media players.\n",
3068                            av_get_pix_fmt_name(ost->filter->filter->inputs[0]->format));
3069                 enc_ctx->pix_fmt = ost->filter->filter->inputs[0]->format;
3070
3071                 ost->st->avg_frame_rate = ost->frame_rate;
3072
3073                 if (!dec_ctx ||
3074                     enc_ctx->width   != dec_ctx->width  ||
3075                     enc_ctx->height  != dec_ctx->height ||
3076                     enc_ctx->pix_fmt != dec_ctx->pix_fmt) {
3077                     enc_ctx->bits_per_raw_sample = frame_bits_per_raw_sample;
3078                 }
3079
3080                 if (ost->forced_keyframes) {
3081                     if (!strncmp(ost->forced_keyframes, "expr:", 5)) {
3082                         ret = av_expr_parse(&ost->forced_keyframes_pexpr, ost->forced_keyframes+5,
3083                                             forced_keyframes_const_names, NULL, NULL, NULL, NULL, 0, NULL);
3084                         if (ret < 0) {
3085                             av_log(NULL, AV_LOG_ERROR,
3086                                    "Invalid force_key_frames expression '%s'\n", ost->forced_keyframes+5);
3087                             return ret;
3088                         }
3089                         ost->forced_keyframes_expr_const_values[FKF_N] = 0;
3090                         ost->forced_keyframes_expr_const_values[FKF_N_FORCED] = 0;
3091                         ost->forced_keyframes_expr_const_values[FKF_PREV_FORCED_N] = NAN;
3092                         ost->forced_keyframes_expr_const_values[FKF_PREV_FORCED_T] = NAN;
3093
3094                         // Don't parse the 'forced_keyframes' in case of 'keep-source-keyframes',
3095                         // parse it only for static kf timings
3096                     } else if(strncmp(ost->forced_keyframes, "source", 6)) {
3097                         parse_forced_key_frames(ost->forced_keyframes, ost, ost->enc_ctx);
3098                     }
3099                 }
3100                 break;
3101             case AVMEDIA_TYPE_SUBTITLE:
3102                 enc_ctx->time_base = (AVRational){1, 1000};
3103                 if (!enc_ctx->width) {
3104                     enc_ctx->width     = input_streams[ost->source_index]->st->codec->width;
3105                     enc_ctx->height    = input_streams[ost->source_index]->st->codec->height;
3106                 }
3107                 break;
3108             case AVMEDIA_TYPE_DATA:
3109                 break;
3110             default:
3111                 abort();
3112                 break;
3113             }
3114         }
3115
3116         if (ost->disposition) {
3117             static const AVOption opts[] = {
3118                 { "disposition"         , NULL, 0, AV_OPT_TYPE_FLAGS, { .i64 = 0 }, INT64_MIN, INT64_MAX, .unit = "flags" },
3119                 { "default"             , NULL, 0, AV_OPT_TYPE_CONST, { .i64 = AV_DISPOSITION_DEFAULT           },    .unit = "flags" },
3120                 { "dub"                 , NULL, 0, AV_OPT_TYPE_CONST, { .i64 = AV_DISPOSITION_DUB               },    .unit = "flags" },
3121                 { "original"            , NULL, 0, AV_OPT_TYPE_CONST, { .i64 = AV_DISPOSITION_ORIGINAL          },    .unit = "flags" },
3122                 { "comment"             , NULL, 0, AV_OPT_TYPE_CONST, { .i64 = AV_DISPOSITION_COMMENT           },    .unit = "flags" },
3123                 { "lyrics"              , NULL, 0, AV_OPT_TYPE_CONST, { .i64 = AV_DISPOSITION_LYRICS            },    .unit = "flags" },
3124                 { "karaoke"             , NULL, 0, AV_OPT_TYPE_CONST, { .i64 = AV_DISPOSITION_KARAOKE           },    .unit = "flags" },
3125                 { "forced"              , NULL, 0, AV_OPT_TYPE_CONST, { .i64 = AV_DISPOSITION_FORCED            },    .unit = "flags" },
3126                 { "hearing_impaired"    , NULL, 0, AV_OPT_TYPE_CONST, { .i64 = AV_DISPOSITION_HEARING_IMPAIRED  },    .unit = "flags" },
3127                 { "visual_impaired"     , NULL, 0, AV_OPT_TYPE_CONST, { .i64 = AV_DISPOSITION_VISUAL_IMPAIRED   },    .unit = "flags" },
3128                 { "clean_effects"       , NULL, 0, AV_OPT_TYPE_CONST, { .i64 = AV_DISPOSITION_CLEAN_EFFECTS     },    .unit = "flags" },
3129                 { "captions"            , NULL, 0, AV_OPT_TYPE_CONST, { .i64 = AV_DISPOSITION_CAPTIONS          },    .unit = "flags" },
3130                 { "descriptions"        , NULL, 0, AV_OPT_TYPE_CONST, { .i64 = AV_DISPOSITION_DESCRIPTIONS      },    .unit = "flags" },
3131                 { "metadata"            , NULL, 0, AV_OPT_TYPE_CONST, { .i64 = AV_DISPOSITION_METADATA          },    .unit = "flags" },
3132                 { NULL },
3133             };
3134             static const AVClass class = {
3135                 .class_name = "",
3136                 .item_name  = av_default_item_name,
3137                 .option     = opts,
3138                 .version    = LIBAVUTIL_VERSION_INT,
3139             };
3140             const AVClass *pclass = &class;
3141
3142             ret = av_opt_eval_flags(&pclass, &opts[0], ost->disposition, &ost->st->disposition);
3143             if (ret < 0)
3144                 goto dump_format;
3145         }
3146     }
3147
3148     /* open each encoder */
3149     for (i = 0; i < nb_output_streams; i++) {
3150         ret = init_output_stream(output_streams[i], error, sizeof(error));
3151         if (ret < 0)
3152             goto dump_format;
3153     }
3154
3155     /* init input streams */
3156     for (i = 0; i < nb_input_streams; i++)
3157         if ((ret = init_input_stream(i, error, sizeof(error))) < 0) {
3158             for (i = 0; i < nb_output_streams; i++) {
3159                 ost = output_streams[i];
3160                 avcodec_close(ost->enc_ctx);
3161             }
3162             goto dump_format;
3163         }
3164
3165     /* discard unused programs */
3166     for (i = 0; i < nb_input_files; i++) {
3167         InputFile *ifile = input_files[i];
3168         for (j = 0; j < ifile->ctx->nb_programs; j++) {
3169             AVProgram *p = ifile->ctx->programs[j];
3170             int discard  = AVDISCARD_ALL;
3171
3172             for (k = 0; k < p->nb_stream_indexes; k++)
3173                 if (!input_streams[ifile->ist_index + p->stream_index[k]]->discard) {
3174                     discard = AVDISCARD_DEFAULT;
3175                     break;
3176                 }
3177             p->discard = discard;
3178         }
3179     }
3180
3181     /* open files and write file headers */
3182     for (i = 0; i < nb_output_files; i++) {
3183         oc = output_files[i]->ctx;
3184         oc->interrupt_callback = int_cb;
3185         if ((ret = avformat_write_header(oc, &output_files[i]->opts)) < 0) {
3186             snprintf(error, sizeof(error),
3187                      "Could not write header for output file #%d "
3188                      "(incorrect codec parameters ?): %s",
3189                      i, av_err2str(ret));
3190             ret = AVERROR(EINVAL);
3191             goto dump_format;
3192         }
3193 //         assert_avoptions(output_files[i]->opts);
3194         if (strcmp(oc->oformat->name, "rtp")) {
3195             want_sdp = 0;
3196         }
3197     }
3198
3199  dump_format:
3200     /* dump the file output parameters - cannot be done before in case
3201        of stream copy */
3202     for (i = 0; i < nb_output_files; i++) {
3203         av_dump_format(output_files[i]->ctx, i, output_files[i]->ctx->filename, 1);
3204     }
3205
3206     /* dump the stream mapping */
3207     av_log(NULL, AV_LOG_INFO, "Stream mapping:\n");
3208     for (i = 0; i < nb_input_streams; i++) {
3209         ist = input_streams[i];
3210
3211         for (j = 0; j < ist->nb_filters; j++) {
3212             if (ist->filters[j]->graph->graph_desc) {
3213                 av_log(NULL, AV_LOG_INFO, "  Stream #%d:%d (%s) -> %s",
3214                        ist->file_index, ist->st->index, ist->dec ? ist->dec->name : "?",
3215                        ist->filters[j]->name);
3216                 if (nb_filtergraphs > 1)
3217                     av_log(NULL, AV_LOG_INFO, " (graph %d)", ist->filters[j]->graph->index);
3218                 av_log(NULL, AV_LOG_INFO, "\n");
3219             }
3220         }
3221     }
3222
3223     for (i = 0; i < nb_output_streams; i++) {
3224         ost = output_streams[i];
3225
3226         if (ost->attachment_filename) {
3227             /* an attached file */
3228             av_log(NULL, AV_LOG_INFO, "  File %s -> Stream #%d:%d\n",
3229                    ost->attachment_filename, ost->file_index, ost->index);
3230             continue;
3231         }
3232
3233         if (ost->filter && ost->filter->graph->graph_desc) {
3234             /* output from a complex graph */
3235             av_log(NULL, AV_LOG_INFO, "  %s", ost->filter->name);
3236             if (nb_filtergraphs > 1)
3237                 av_log(NULL, AV_LOG_INFO, " (graph %d)", ost->filter->graph->index);
3238
3239             av_log(NULL, AV_LOG_INFO, " -> Stream #%d:%d (%s)\n", ost->file_index,
3240                    ost->index, ost->enc ? ost->enc->name : "?");
3241             continue;
3242         }
3243
3244         av_log(NULL, AV_LOG_INFO, "  Stream #%d:%d -> #%d:%d",
3245                input_streams[ost->source_index]->file_index,
3246                input_streams[ost->source_index]->st->index,
3247                ost->file_index,
3248                ost->index);
3249         if (ost->sync_ist != input_streams[ost->source_index])
3250             av_log(NULL, AV_LOG_INFO, " [sync #%d:%d]",
3251                    ost->sync_ist->file_index,
3252                    ost->sync_ist->st->index);
3253         if (ost->stream_copy)
3254             av_log(NULL, AV_LOG_INFO, " (copy)");
3255         else {
3256             const AVCodec *in_codec    = input_streams[ost->source_index]->dec;
3257             const AVCodec *out_codec   = ost->enc;
3258             const char *decoder_name   = "?";
3259             const char *in_codec_name  = "?";
3260             const char *encoder_name   = "?";
3261             const char *out_codec_name = "?";
3262             const AVCodecDescriptor *desc;
3263
3264             if (in_codec) {
3265                 decoder_name  = in_codec->name;
3266                 desc = avcodec_descriptor_get(in_codec->id);
3267                 if (desc)
3268                     in_codec_name = desc->name;
3269                 if (!strcmp(decoder_name, in_codec_name))
3270                     decoder_name = "native";
3271             }
3272
3273             if (out_codec) {
3274                 encoder_name   = out_codec->name;
3275                 desc = avcodec_descriptor_get(out_codec->id);
3276                 if (desc)
3277                     out_codec_name = desc->name;
3278                 if (!strcmp(encoder_name, out_codec_name))
3279                     encoder_name = "native";
3280             }
3281
3282             av_log(NULL, AV_LOG_INFO, " (%s (%s) -> %s (%s))",
3283                    in_codec_name, decoder_name,
3284                    out_codec_name, encoder_name);
3285         }
3286         av_log(NULL, AV_LOG_INFO, "\n");
3287     }
3288
3289     if (ret) {
3290         av_log(NULL, AV_LOG_ERROR, "%s\n", error);
3291         return ret;
3292     }
3293
3294     if (sdp_filename || want_sdp) {
3295         print_sdp();
3296     }
3297
3298     transcode_init_done = 1;
3299
3300     return 0;
3301 }
3302
3303 /* Return 1 if there remain streams where more output is wanted, 0 otherwise. */
3304 static int need_output(void)
3305 {
3306     int i;
3307
3308     for (i = 0; i < nb_output_streams; i++) {
3309         OutputStream *ost    = output_streams[i];
3310         OutputFile *of       = output_files[ost->file_index];
3311         AVFormatContext *os  = output_files[ost->file_index]->ctx;
3312
3313         if (ost->finished ||
3314             (os->pb && avio_tell(os->pb) >= of->limit_filesize))
3315             continue;
3316         if (ost->frame_number >= ost->max_frames) {
3317             int j;
3318             for (j = 0; j < of->ctx->nb_streams; j++)
3319                 close_output_stream(output_streams[of->ost_index + j]);
3320             continue;
3321         }
3322
3323         return 1;
3324     }
3325
3326     return 0;
3327 }
3328
3329 /**
3330  * Select the output stream to process.
3331  *
3332  * @return  selected output stream, or NULL if none available
3333  */
3334 static OutputStream *choose_output(void)
3335 {
3336     int i;
3337     int64_t opts_min = INT64_MAX;
3338     OutputStream *ost_min = NULL;
3339
3340     for (i = 0; i < nb_output_streams; i++) {
3341         OutputStream *ost = output_streams[i];
3342         int64_t opts = av_rescale_q(ost->st->cur_dts, ost->st->time_base,
3343                                     AV_TIME_BASE_Q);
3344         if (!ost->finished && opts < opts_min) {
3345             opts_min = opts;
3346             ost_min  = ost->unavailable ? NULL : ost;
3347         }
3348     }
3349     return ost_min;
3350 }
3351
3352 static int check_keyboard_interaction(int64_t cur_time)
3353 {
3354     int i, ret, key;
3355     static int64_t last_time;
3356     if (received_nb_signals)
3357         return AVERROR_EXIT;
3358     /* read_key() returns 0 on EOF */
3359     if(cur_time - last_time >= 100000 && !run_as_daemon){
3360         key =  read_key();
3361         last_time = cur_time;
3362     }else
3363         key = -1;
3364     if (key == 'q')
3365         return AVERROR_EXIT;
3366     if (key == '+') av_log_set_level(av_log_get_level()+10);
3367     if (key == '-') av_log_set_level(av_log_get_level()-10);
3368     if (key == 's') qp_hist     ^= 1;
3369     if (key == 'h'){
3370         if (do_hex_dump){
3371             do_hex_dump = do_pkt_dump = 0;
3372         } else if(do_pkt_dump){
3373             do_hex_dump = 1;
3374         } else
3375             do_pkt_dump = 1;
3376         av_log_set_level(AV_LOG_DEBUG);
3377     }
3378     if (key == 'c' || key == 'C'){
3379         char buf[4096], target[64], command[256], arg[256] = {0};
3380         double time;
3381         int k, n = 0;
3382         fprintf(stderr, "\nEnter command: <target>|all <time>|-1 <command>[ <argument>]\n");
3383         i = 0;
3384         while ((k = read_key()) != '\n' && k != '\r' && i < sizeof(buf)-1)
3385             if (k > 0)
3386                 buf[i++] = k;
3387         buf[i] = 0;
3388         if (k > 0 &&
3389             (n = sscanf(buf, "%63[^ ] %lf %255[^ ] %255[^\n]", target, &time, command, arg)) >= 3) {
3390             av_log(NULL, AV_LOG_DEBUG, "Processing command target:%s time:%f command:%s arg:%s",
3391                    target, time, command, arg);
3392             for (i = 0; i < nb_filtergraphs; i++) {
3393                 FilterGraph *fg = filtergraphs[i];
3394                 if (fg->graph) {
3395                     if (time < 0) {
3396                         ret = avfilter_graph_send_command(fg->graph, target, command, arg, buf, sizeof(buf),
3397                                                           key == 'c' ? AVFILTER_CMD_FLAG_ONE : 0);
3398                         fprintf(stderr, "Command reply for stream %d: ret:%d res:\n%s", i, ret, buf);
3399                     } else if (key == 'c') {
3400                         fprintf(stderr, "Queing commands only on filters supporting the specific command is unsupported\n");
3401                         ret = AVERROR_PATCHWELCOME;
3402                     } else {
3403                         ret = avfilter_graph_queue_command(fg->graph, target, command, arg, 0, time);
3404                         if (ret < 0)
3405                             fprintf(stderr, "Queing command failed with error %s\n", av_err2str(ret));
3406                     }
3407                 }
3408             }
3409         } else {
3410             av_log(NULL, AV_LOG_ERROR,
3411                    "Parse error, at least 3 arguments were expected, "
3412                    "only %d given in string '%s'\n", n, buf);
3413         }
3414     }
3415     if (key == 'd' || key == 'D'){
3416         int debug=0;
3417         if(key == 'D') {
3418             debug = input_streams[0]->st->codec->debug<<1;
3419             if(!debug) debug = 1;
3420             while(debug & (FF_DEBUG_DCT_COEFF|FF_DEBUG_VIS_QP|FF_DEBUG_VIS_MB_TYPE)) //unsupported, would just crash
3421                 debug += debug;
3422         }else
3423             if(scanf("%d", &debug)!=1)
3424                 fprintf(stderr,"error parsing debug value\n");
3425         for(i=0;i<nb_input_streams;i++) {
3426             input_streams[i]->st->codec->debug = debug;
3427         }
3428         for(i=0;i<nb_output_streams;i++) {
3429             OutputStream *ost = output_streams[i];
3430             ost->enc_ctx->debug = debug;
3431         }
3432         if(debug) av_log_set_level(AV_LOG_DEBUG);
3433         fprintf(stderr,"debug=%d\n", debug);
3434     }
3435     if (key == '?'){
3436         fprintf(stderr, "key    function\n"
3437                         "?      show this help\n"
3438                         "+      increase verbosity\n"
3439                         "-      decrease verbosity\n"
3440                         "c      Send command to first matching filter supporting it\n"
3441                         "C      Send/Que command to all matching filters\n"
3442                         "D      cycle through available debug modes\n"
3443                         "h      dump packets/hex press to cycle through the 3 states\n"
3444                         "q      quit\n"
3445                         "s      Show QP histogram\n"
3446         );
3447     }
3448     return 0;
3449 }
3450
3451 #if HAVE_PTHREADS
3452 static void *input_thread(void *arg)
3453 {
3454     InputFile *f = arg;
3455     unsigned flags = f->non_blocking ? AV_THREAD_MESSAGE_NONBLOCK : 0;
3456     int ret = 0;
3457
3458     while (1) {
3459         AVPacket pkt;
3460         ret = av_read_frame(f->ctx, &pkt);
3461
3462         if (ret == AVERROR(EAGAIN)) {
3463             av_usleep(10000);
3464             continue;
3465         }
3466         if (ret < 0) {
3467             av_thread_message_queue_set_err_recv(f->in_thread_queue, ret);
3468             break;
3469         }
3470         av_dup_packet(&pkt);
3471         ret = av_thread_message_queue_send(f->in_thread_queue, &pkt, flags);
3472         if (flags && ret == AVERROR(EAGAIN)) {
3473             flags = 0;
3474             ret = av_thread_message_queue_send(f->in_thread_queue, &pkt, flags);
3475             av_log(f->ctx, AV_LOG_WARNING,
3476                    "Thread message queue blocking; consider raising the "
3477                    "thread_queue_size option (current value: %d)\n",
3478                    f->thread_queue_size);
3479         }
3480         if (ret < 0) {
3481             if (ret != AVERROR_EOF)
3482                 av_log(f->ctx, AV_LOG_ERROR,
3483                        "Unable to send packet to main thread: %s\n",
3484                        av_err2str(ret));
3485             av_free_packet(&pkt);
3486             av_thread_message_queue_set_err_recv(f->in_thread_queue, ret);
3487             break;
3488         }
3489     }
3490
3491     return NULL;
3492 }
3493
3494 static void free_input_threads(void)
3495 {
3496     int i;
3497
3498     for (i = 0; i < nb_input_files; i++) {
3499         InputFile *f = input_files[i];
3500         AVPacket pkt;
3501
3502         if (!f || !f->in_thread_queue)
3503             continue;
3504         av_thread_message_queue_set_err_send(f->in_thread_queue, AVERROR_EOF);
3505         while (av_thread_message_queue_recv(f->in_thread_queue, &pkt, 0) >= 0)
3506             av_free_packet(&pkt);
3507
3508         pthread_join(f->thread, NULL);
3509         f->joined = 1;
3510         av_thread_message_queue_free(&f->in_thread_queue);
3511     }
3512 }
3513
3514 static int init_input_threads(void)
3515 {
3516     int i, ret;
3517
3518     if (nb_input_files == 1)
3519         return 0;
3520
3521     for (i = 0; i < nb_input_files; i++) {
3522         InputFile *f = input_files[i];
3523
3524         if (f->ctx->pb ? !f->ctx->pb->seekable :
3525             strcmp(f->ctx->iformat->name, "lavfi"))
3526             f->non_blocking = 1;
3527         ret = av_thread_message_queue_alloc(&f->in_thread_queue,
3528                                             f->thread_queue_size, sizeof(AVPacket));
3529         if (ret < 0)
3530             return ret;
3531
3532         if ((ret = pthread_create(&f->thread, NULL, input_thread, f))) {
3533             av_log(NULL, AV_LOG_ERROR, "pthread_create failed: %s. Try to increase `ulimit -v` or decrease `ulimit -s`.\n", strerror(ret));
3534             av_thread_message_queue_free(&f->in_thread_queue);
3535             return AVERROR(ret);
3536         }
3537     }
3538     return 0;
3539 }
3540
3541 static int get_input_packet_mt(InputFile *f, AVPacket *pkt)
3542 {
3543     return av_thread_message_queue_recv(f->in_thread_queue, pkt,
3544                                         f->non_blocking ?
3545                                         AV_THREAD_MESSAGE_NONBLOCK : 0);
3546 }
3547 #endif
3548
3549 static int get_input_packet(InputFile *f, AVPacket *pkt)
3550 {
3551     if (f->rate_emu) {
3552         int i;
3553         for (i = 0; i < f->nb_streams; i++) {
3554             InputStream *ist = input_streams[f->ist_index + i];
3555             int64_t pts = av_rescale(ist->dts, 1000000, AV_TIME_BASE);
3556             int64_t now = av_gettime_relative() - ist->start;
3557             if (pts > now)
3558                 return AVERROR(EAGAIN);
3559         }
3560     }
3561
3562 #if HAVE_PTHREADS
3563     if (nb_input_files > 1)
3564         return get_input_packet_mt(f, pkt);
3565 #endif
3566     return av_read_frame(f->ctx, pkt);
3567 }
3568
3569 static int got_eagain(void)
3570 {
3571     int i;
3572     for (i = 0; i < nb_output_streams; i++)
3573         if (output_streams[i]->unavailable)
3574             return 1;
3575     return 0;
3576 }
3577
3578 static void reset_eagain(void)
3579 {
3580     int i;
3581     for (i = 0; i < nb_input_files; i++)
3582         input_files[i]->eagain = 0;
3583     for (i = 0; i < nb_output_streams; i++)
3584         output_streams[i]->unavailable = 0;
3585 }
3586
3587 /*
3588  * Return
3589  * - 0 -- one packet was read and processed
3590  * - AVERROR(EAGAIN) -- no packets were available for selected file,
3591  *   this function should be called again
3592  * - AVERROR_EOF -- this function should not be called again
3593  */
3594 static int process_input(int file_index)
3595 {
3596     InputFile *ifile = input_files[file_index];
3597     AVFormatContext *is;
3598     InputStream *ist;
3599     AVPacket pkt;
3600     int ret, i, j;
3601
3602     is  = ifile->ctx;
3603     ret = get_input_packet(ifile, &pkt);
3604
3605     if (ret == AVERROR(EAGAIN)) {
3606         ifile->eagain = 1;
3607         return ret;
3608     }
3609     if (ret < 0) {
3610         if (ret != AVERROR_EOF) {
3611             print_error(is->filename, ret);
3612             if (exit_on_error)
3613                 exit_program(1);
3614         }
3615
3616         for (i = 0; i < ifile->nb_streams; i++) {
3617             ist = input_streams[ifile->ist_index + i];
3618             if (ist->decoding_needed) {
3619                 ret = process_input_packet(ist, NULL);
3620                 if (ret>0)
3621                     return 0;
3622             }
3623
3624             /* mark all outputs that don't go through lavfi as finished */
3625             for (j = 0; j < nb_output_streams; j++) {
3626                 OutputStream *ost = output_streams[j];
3627
3628                 if (ost->source_index == ifile->ist_index + i &&
3629                     (ost->stream_copy || ost->enc->type == AVMEDIA_TYPE_SUBTITLE))
3630                     finish_output_stream(ost);
3631             }
3632         }
3633
3634         ifile->eof_reached = 1;
3635         return AVERROR(EAGAIN);
3636     }
3637
3638     reset_eagain();
3639
3640     if (do_pkt_dump) {
3641         av_pkt_dump_log2(NULL, AV_LOG_DEBUG, &pkt, do_hex_dump,
3642                          is->streams[pkt.stream_index]);
3643     }
3644     /* the following test is needed in case new streams appear
3645        dynamically in stream : we ignore them */
3646     if (pkt.stream_index >= ifile->nb_streams) {
3647         report_new_stream(file_index, &pkt);
3648         goto discard_packet;
3649     }
3650
3651     ist = input_streams[ifile->ist_index + pkt.stream_index];
3652
3653     ist->data_size += pkt.size;
3654     ist->nb_packets++;
3655
3656     if (ist->discard)
3657         goto discard_packet;
3658
3659     if (debug_ts) {
3660         av_log(NULL, AV_LOG_INFO, "demuxer -> ist_index:%d type:%s "
3661                "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",
3662                ifile->ist_index + pkt.stream_index, av_get_media_type_string(ist->dec_ctx->codec_type),
3663                av_ts2str(ist->next_dts), av_ts2timestr(ist->next_dts, &AV_TIME_BASE_Q),
3664                av_ts2str(ist->next_pts), av_ts2timestr(ist->next_pts, &AV_TIME_BASE_Q),
3665                av_ts2str(pkt.pts), av_ts2timestr(pkt.pts, &ist->st->time_base),
3666                av_ts2str(pkt.dts), av_ts2timestr(pkt.dts, &ist->st->time_base),
3667                av_ts2str(input_files[ist->file_index]->ts_offset),
3668                av_ts2timestr(input_files[ist->file_index]->ts_offset, &AV_TIME_BASE_Q));
3669     }
3670
3671     if(!ist->wrap_correction_done && is->start_time != AV_NOPTS_VALUE && ist->st->pts_wrap_bits < 64){
3672         int64_t stime, stime2;
3673         // Correcting starttime based on the enabled streams
3674         // 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.
3675         //       so we instead do it here as part of discontinuity handling
3676         if (   ist->next_dts == AV_NOPTS_VALUE
3677             && ifile->ts_offset == -is->start_time
3678             && (is->iformat->flags & AVFMT_TS_DISCONT)) {
3679             int64_t new_start_time = INT64_MAX;
3680             for (i=0; i<is->nb_streams; i++) {
3681                 AVStream *st = is->streams[i];
3682                 if(st->discard == AVDISCARD_ALL || st->start_time == AV_NOPTS_VALUE)
3683                     continue;
3684                 new_start_time = FFMIN(new_start_time, av_rescale_q(st->start_time, st->time_base, AV_TIME_BASE_Q));
3685             }
3686             if (new_start_time > is->start_time) {
3687                 av_log(is, AV_LOG_VERBOSE, "Correcting start time by %"PRId64"\n", new_start_time - is->start_time);
3688                 ifile->ts_offset = -new_start_time;
3689             }
3690         }
3691
3692         stime = av_rescale_q(is->start_time, AV_TIME_BASE_Q, ist->st->time_base);
3693         stime2= stime + (1ULL<<ist->st->pts_wrap_bits);
3694         ist->wrap_correction_done = 1;
3695
3696         if(stime2 > stime && pkt.dts != AV_NOPTS_VALUE && pkt.dts > stime + (1LL<<(ist->st->pts_wrap_bits-1))) {
3697             pkt.dts -= 1ULL<<ist->st->pts_wrap_bits;
3698             ist->wrap_correction_done = 0;
3699         }
3700         if(stime2 > stime && pkt.pts != AV_NOPTS_VALUE && pkt.pts > stime + (1LL<<(ist->st->pts_wrap_bits-1))) {
3701             pkt.pts -= 1ULL<<ist->st->pts_wrap_bits;
3702             ist->wrap_correction_done = 0;
3703         }
3704     }
3705
3706     /* add the stream-global side data to the first packet */
3707     if (ist->nb_packets == 1) {
3708         if (ist->st->nb_side_data)
3709             av_packet_split_side_data(&pkt);
3710         for (i = 0; i < ist->st->nb_side_data; i++) {
3711             AVPacketSideData *src_sd = &ist->st->side_data[i];
3712             uint8_t *dst_data;
3713
3714             if (av_packet_get_side_data(&pkt, src_sd->type, NULL))
3715                 continue;
3716             if (ist->autorotate && src_sd->type == AV_PKT_DATA_DISPLAYMATRIX)
3717                 continue;
3718
3719             dst_data = av_packet_new_side_data(&pkt, src_sd->type, src_sd->size);
3720             if (!dst_data)
3721                 exit_program(1);
3722
3723             memcpy(dst_data, src_sd->data, src_sd->size);
3724         }
3725     }
3726
3727     if (pkt.dts != AV_NOPTS_VALUE)
3728         pkt.dts += av_rescale_q(ifile->ts_offset, AV_TIME_BASE_Q, ist->st->time_base);
3729     if (pkt.pts != AV_NOPTS_VALUE)
3730         pkt.pts += av_rescale_q(ifile->ts_offset, AV_TIME_BASE_Q, ist->st->time_base);
3731
3732     if (pkt.pts != AV_NOPTS_VALUE)
3733         pkt.pts *= ist->ts_scale;
3734     if (pkt.dts != AV_NOPTS_VALUE)
3735         pkt.dts *= ist->ts_scale;
3736
3737     if ((ist->dec_ctx->codec_type == AVMEDIA_TYPE_VIDEO ||
3738          ist->dec_ctx->codec_type == AVMEDIA_TYPE_AUDIO) &&
3739         pkt.dts != AV_NOPTS_VALUE && ist->next_dts == AV_NOPTS_VALUE && !copy_ts
3740         && (is->iformat->flags & AVFMT_TS_DISCONT) && ifile->last_ts != AV_NOPTS_VALUE) {
3741         int64_t pkt_dts = av_rescale_q(pkt.dts, ist->st->time_base, AV_TIME_BASE_Q);
3742         int64_t delta   = pkt_dts - ifile->last_ts;
3743         if (delta < -1LL*dts_delta_threshold*AV_TIME_BASE ||
3744             delta >  1LL*dts_delta_threshold*AV_TIME_BASE){
3745             ifile->ts_offset -= delta;
3746             av_log(NULL, AV_LOG_DEBUG,
3747                    "Inter stream timestamp discontinuity %"PRId64", new offset= %"PRId64"\n",
3748                    delta, ifile->ts_offset);
3749             pkt.dts -= av_rescale_q(delta, AV_TIME_BASE_Q, ist->st->time_base);
3750             if (pkt.pts != AV_NOPTS_VALUE)
3751                 pkt.pts -= av_rescale_q(delta, AV_TIME_BASE_Q, ist->st->time_base);
3752         }
3753     }
3754
3755     if ((ist->dec_ctx->codec_type == AVMEDIA_TYPE_VIDEO ||
3756          ist->dec_ctx->codec_type == AVMEDIA_TYPE_AUDIO) &&
3757          pkt.dts != AV_NOPTS_VALUE && ist->next_dts != AV_NOPTS_VALUE &&
3758         !copy_ts) {
3759         int64_t pkt_dts = av_rescale_q(pkt.dts, ist->st->time_base, AV_TIME_BASE_Q);
3760         int64_t delta   = pkt_dts - ist->next_dts;
3761         if (is->iformat->flags & AVFMT_TS_DISCONT) {
3762             if (delta < -1LL*dts_delta_threshold*AV_TIME_BASE ||
3763                 delta >  1LL*dts_delta_threshold*AV_TIME_BASE ||
3764                 pkt_dts + AV_TIME_BASE/10 < FFMAX(ist->pts, ist->dts)) {
3765                 ifile->ts_offset -= delta;
3766                 av_log(NULL, AV_LOG_DEBUG,
3767                        "timestamp discontinuity %"PRId64", new offset= %"PRId64"\n",
3768                        delta, ifile->ts_offset);
3769                 pkt.dts -= av_rescale_q(delta, AV_TIME_BASE_Q, ist->st->time_base);
3770                 if (pkt.pts != AV_NOPTS_VALUE)
3771                     pkt.pts -= av_rescale_q(delta, AV_TIME_BASE_Q, ist->st->time_base);
3772             }
3773         } else {
3774             if ( delta < -1LL*dts_error_threshold*AV_TIME_BASE ||
3775                  delta >  1LL*dts_error_threshold*AV_TIME_BASE) {
3776                 av_log(NULL, AV_LOG_WARNING, "DTS %"PRId64", next:%"PRId64" st:%d invalid dropping\n", pkt.dts, ist->next_dts, pkt.stream_index);
3777                 pkt.dts = AV_NOPTS_VALUE;
3778             }
3779             if (pkt.pts != AV_NOPTS_VALUE){
3780                 int64_t pkt_pts = av_rescale_q(pkt.pts, ist->st->time_base, AV_TIME_BASE_Q);
3781                 delta   = pkt_pts - ist->next_dts;
3782                 if ( delta < -1LL*dts_error_threshold*AV_TIME_BASE ||
3783                      delta >  1LL*dts_error_threshold*AV_TIME_BASE) {
3784                     av_log(NULL, AV_LOG_WARNING, "PTS %"PRId64", next:%"PRId64" invalid dropping st:%d\n", pkt.pts, ist->next_dts, pkt.stream_index);
3785                     pkt.pts = AV_NOPTS_VALUE;
3786                 }
3787             }
3788         }
3789     }
3790
3791     if (pkt.dts != AV_NOPTS_VALUE)
3792         ifile->last_ts = av_rescale_q(pkt.dts, ist->st->time_base, AV_TIME_BASE_Q);
3793
3794     if (debug_ts) {
3795         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",
3796                ifile->ist_index + pkt.stream_index, av_get_media_type_string(ist->dec_ctx->codec_type),
3797                av_ts2str(pkt.pts), av_ts2timestr(pkt.pts, &ist->st->time_base),
3798                av_ts2str(pkt.dts), av_ts2timestr(pkt.dts, &ist->st->time_base),
3799                av_ts2str(input_files[ist->file_index]->ts_offset),
3800                av_ts2timestr(input_files[ist->file_index]->ts_offset, &AV_TIME_BASE_Q));
3801     }
3802
3803     sub2video_heartbeat(ist, pkt.pts);
3804
3805     process_input_packet(ist, &pkt);
3806
3807 discard_packet:
3808     av_free_packet(&pkt);
3809
3810     return 0;
3811 }
3812
3813 /**
3814  * Perform a step of transcoding for the specified filter graph.
3815  *
3816  * @param[in]  graph     filter graph to consider
3817  * @param[out] best_ist  input stream where a frame would allow to continue
3818  * @return  0 for success, <0 for error
3819  */
3820 static int transcode_from_filter(FilterGraph *graph, InputStream **best_ist)
3821 {
3822     int i, ret;
3823     int nb_requests, nb_requests_max = 0;
3824     InputFilter *ifilter;
3825     InputStream *ist;
3826
3827     *best_ist = NULL;
3828     ret = avfilter_graph_request_oldest(graph->graph);
3829     if (ret >= 0)
3830         return reap_filters(0);
3831
3832     if (ret == AVERROR_EOF) {
3833         ret = reap_filters(1);
3834         for (i = 0; i < graph->nb_outputs; i++)
3835             close_output_stream(graph->outputs[i]->ost);
3836         return ret;
3837     }
3838     if (ret != AVERROR(EAGAIN))
3839         return ret;
3840
3841     for (i = 0; i < graph->nb_inputs; i++) {
3842         ifilter = graph->inputs[i];
3843         ist = ifilter->ist;
3844         if (input_files[ist->file_index]->eagain ||
3845             input_files[ist->file_index]->eof_reached)
3846             continue;
3847         nb_requests = av_buffersrc_get_nb_failed_requests(ifilter->filter);
3848         if (nb_requests > nb_requests_max) {
3849             nb_requests_max = nb_requests;
3850             *best_ist = ist;
3851         }
3852     }
3853
3854     if (!*best_ist)
3855         for (i = 0; i < graph->nb_outputs; i++)
3856             graph->outputs[i]->ost->unavailable = 1;
3857
3858     return 0;
3859 }
3860
3861 /**
3862  * Run a single step of transcoding.
3863  *
3864  * @return  0 for success, <0 for error
3865  */
3866 static int transcode_step(void)
3867 {
3868     OutputStream *ost;
3869     InputStream  *ist;
3870     int ret;
3871
3872     ost = choose_output();
3873     if (!ost) {
3874         if (got_eagain()) {
3875             reset_eagain();
3876             av_usleep(10000);
3877             return 0;
3878         }
3879         av_log(NULL, AV_LOG_VERBOSE, "No more inputs to read from, finishing.\n");
3880         return AVERROR_EOF;
3881     }
3882
3883     if (ost->filter) {
3884         if ((ret = transcode_from_filter(ost->filter->graph, &ist)) < 0)
3885             return ret;
3886         if (!ist)
3887             return 0;
3888     } else {
3889         av_assert0(ost->source_index >= 0);
3890         ist = input_streams[ost->source_index];
3891     }
3892
3893     ret = process_input(ist->file_index);
3894     if (ret == AVERROR(EAGAIN)) {
3895         if (input_files[ist->file_index]->eagain)
3896             ost->unavailable = 1;
3897         return 0;
3898     }
3899
3900     if (ret < 0)
3901         return ret == AVERROR_EOF ? 0 : ret;
3902
3903     return reap_filters(0);
3904 }
3905
3906 /*
3907  * The following code is the main loop of the file converter
3908  */
3909 static int transcode(void)
3910 {
3911     int ret, i;
3912     AVFormatContext *os;
3913     OutputStream *ost;
3914     InputStream *ist;
3915     int64_t timer_start;
3916
3917     ret = transcode_init();
3918     if (ret < 0)
3919         goto fail;
3920
3921     if (stdin_interaction) {
3922         av_log(NULL, AV_LOG_INFO, "Press [q] to stop, [?] for help\n");
3923     }
3924
3925     timer_start = av_gettime_relative();
3926
3927 #if HAVE_PTHREADS
3928     if ((ret = init_input_threads()) < 0)
3929         goto fail;
3930 #endif
3931
3932     while (!received_sigterm) {
3933         int64_t cur_time= av_gettime_relative();
3934
3935         /* if 'q' pressed, exits */
3936         if (stdin_interaction)
3937             if (check_keyboard_interaction(cur_time) < 0)
3938                 break;
3939
3940         /* check if there's any stream where output is still needed */
3941         if (!need_output()) {
3942             av_log(NULL, AV_LOG_VERBOSE, "No more output streams to write to, finishing.\n");
3943             break;
3944         }
3945
3946         ret = transcode_step();
3947         if (ret < 0) {
3948             if (ret == AVERROR_EOF || ret == AVERROR(EAGAIN)) {
3949                 continue;
3950             } else {
3951                 char errbuf[128];
3952                 av_strerror(ret, errbuf, sizeof(errbuf));
3953
3954                 av_log(NULL, AV_LOG_ERROR, "Error while filtering: %s\n", errbuf);
3955                 break;
3956             }
3957         }
3958
3959         /* dump report by using the output first video and audio streams */
3960         print_report(0, timer_start, cur_time);
3961     }
3962 #if HAVE_PTHREADS
3963     free_input_threads();
3964 #endif
3965
3966     /* at the end of stream, we must flush the decoder buffers */
3967     for (i = 0; i < nb_input_streams; i++) {
3968         ist = input_streams[i];
3969         if (!input_files[ist->file_index]->eof_reached && ist->decoding_needed) {
3970             process_input_packet(ist, NULL);
3971         }
3972     }
3973     flush_encoders();
3974
3975     term_exit();
3976
3977     /* write the trailer if needed and close file */
3978     for (i = 0; i < nb_output_files; i++) {
3979         os = output_files[i]->ctx;
3980         av_write_trailer(os);
3981     }
3982
3983     /* dump report by using the first video and audio streams */
3984     print_report(1, timer_start, av_gettime_relative());
3985
3986     /* close each encoder */
3987     for (i = 0; i < nb_output_streams; i++) {
3988         ost = output_streams[i];
3989         if (ost->encoding_needed) {
3990             av_freep(&ost->enc_ctx->stats_in);
3991         }
3992     }
3993
3994     /* close each decoder */
3995     for (i = 0; i < nb_input_streams; i++) {
3996         ist = input_streams[i];
3997         if (ist->decoding_needed) {
3998             avcodec_close(ist->dec_ctx);
3999             if (ist->hwaccel_uninit)
4000                 ist->hwaccel_uninit(ist->dec_ctx);
4001         }
4002     }
4003
4004     /* finished ! */
4005     ret = 0;
4006
4007  fail:
4008 #if HAVE_PTHREADS
4009     free_input_threads();
4010 #endif
4011
4012     if (output_streams) {
4013         for (i = 0; i < nb_output_streams; i++) {
4014             ost = output_streams[i];
4015             if (ost) {
4016                 if (ost->logfile) {
4017                     fclose(ost->logfile);
4018                     ost->logfile = NULL;
4019                 }
4020                 av_freep(&ost->forced_kf_pts);
4021                 av_freep(&ost->apad);
4022                 av_freep(&ost->disposition);
4023                 av_dict_free(&ost->encoder_opts);
4024                 av_dict_free(&ost->swr_opts);
4025                 av_dict_free(&ost->resample_opts);
4026                 av_dict_free(&ost->bsf_args);
4027             }
4028         }
4029     }
4030     return ret;
4031 }
4032
4033
4034 static int64_t getutime(void)
4035 {
4036 #if HAVE_GETRUSAGE
4037     struct rusage rusage;
4038
4039     getrusage(RUSAGE_SELF, &rusage);
4040     return (rusage.ru_utime.tv_sec * 1000000LL) + rusage.ru_utime.tv_usec;
4041 #elif HAVE_GETPROCESSTIMES
4042     HANDLE proc;
4043     FILETIME c, e, k, u;
4044     proc = GetCurrentProcess();
4045     GetProcessTimes(proc, &c, &e, &k, &u);
4046     return ((int64_t) u.dwHighDateTime << 32 | u.dwLowDateTime) / 10;
4047 #else
4048     return av_gettime_relative();
4049 #endif
4050 }
4051
4052 static int64_t getmaxrss(void)
4053 {
4054 #if HAVE_GETRUSAGE && HAVE_STRUCT_RUSAGE_RU_MAXRSS
4055     struct rusage rusage;
4056     getrusage(RUSAGE_SELF, &rusage);
4057     return (int64_t)rusage.ru_maxrss * 1024;
4058 #elif HAVE_GETPROCESSMEMORYINFO
4059     HANDLE proc;
4060     PROCESS_MEMORY_COUNTERS memcounters;
4061     proc = GetCurrentProcess();
4062     memcounters.cb = sizeof(memcounters);
4063     GetProcessMemoryInfo(proc, &memcounters, sizeof(memcounters));
4064     return memcounters.PeakPagefileUsage;
4065 #else
4066     return 0;
4067 #endif
4068 }
4069
4070 static void log_callback_null(void *ptr, int level, const char *fmt, va_list vl)
4071 {
4072 }
4073
4074 int main(int argc, char **argv)
4075 {
4076     int ret;
4077     int64_t ti;
4078
4079     register_exit(ffmpeg_cleanup);
4080
4081     setvbuf(stderr,NULL,_IONBF,0); /* win32 runtime needs this */
4082
4083     av_log_set_flags(AV_LOG_SKIP_REPEATED);
4084     parse_loglevel(argc, argv, options);
4085
4086     if(argc>1 && !strcmp(argv[1], "-d")){
4087         run_as_daemon=1;
4088         av_log_set_callback(log_callback_null);
4089         argc--;
4090         argv++;
4091     }
4092
4093     avcodec_register_all();
4094 #if CONFIG_AVDEVICE
4095     avdevice_register_all();
4096 #endif
4097     avfilter_register_all();
4098     av_register_all();
4099     avformat_network_init();
4100
4101     show_banner(argc, argv, options);
4102
4103     term_init();
4104
4105     /* parse options and open all input/output files */
4106     ret = ffmpeg_parse_options(argc, argv);
4107     if (ret < 0)
4108         exit_program(1);
4109
4110     if (nb_output_files <= 0 && nb_input_files == 0) {
4111         show_usage();
4112         av_log(NULL, AV_LOG_WARNING, "Use -h to get full help or, even better, run 'man %s'\n", program_name);
4113         exit_program(1);
4114     }
4115
4116     /* file converter / grab */
4117     if (nb_output_files <= 0) {
4118         av_log(NULL, AV_LOG_FATAL, "At least one output file must be specified\n");
4119         exit_program(1);
4120     }
4121
4122 //     if (nb_input_files == 0) {
4123 //         av_log(NULL, AV_LOG_FATAL, "At least one input file must be specified\n");
4124 //         exit_program(1);
4125 //     }
4126
4127     current_time = ti = getutime();
4128     if (transcode() < 0)
4129         exit_program(1);
4130     ti = getutime() - ti;
4131     if (do_benchmark) {
4132         av_log(NULL, AV_LOG_INFO, "bench: utime=%0.3fs\n", ti / 1000000.0);
4133     }
4134     av_log(NULL, AV_LOG_DEBUG, "%"PRIu64" frames successfully decoded, %"PRIu64" decoding errors\n",
4135            decode_error_stat[0], decode_error_stat[1]);
4136     if ((decode_error_stat[0] + decode_error_stat[1]) * max_error_rate < decode_error_stat[1])
4137         exit_program(69);
4138
4139     exit_program(received_nb_signals ? 255 : main_return_code);
4140     return main_return_code;
4141 }