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