avconv: split the code for processing input packets out of transcode()
[platform/upstream/libav.git] / avconv.c
1 /*
2  * avconv main
3  * Copyright (c) 2000-2011 The libav developers.
4  *
5  * This file is part of Libav.
6  *
7  * Libav is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU Lesser General Public
9  * License as published by the Free Software Foundation; either
10  * version 2.1 of the License, or (at your option) any later version.
11  *
12  * Libav is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * Lesser General Public License for more details.
16  *
17  * You should have received a copy of the GNU Lesser General Public
18  * License along with Libav; if not, write to the Free Software
19  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20  */
21
22 #include "config.h"
23 #include <ctype.h>
24 #include <string.h>
25 #include <math.h>
26 #include <stdlib.h>
27 #include <errno.h>
28 #include <signal.h>
29 #include <limits.h>
30 #include "libavformat/avformat.h"
31 #include "libavdevice/avdevice.h"
32 #include "libswscale/swscale.h"
33 #include "libavresample/avresample.h"
34 #include "libavutil/opt.h"
35 #include "libavutil/audioconvert.h"
36 #include "libavutil/parseutils.h"
37 #include "libavutil/samplefmt.h"
38 #include "libavutil/colorspace.h"
39 #include "libavutil/fifo.h"
40 #include "libavutil/intreadwrite.h"
41 #include "libavutil/dict.h"
42 #include "libavutil/mathematics.h"
43 #include "libavutil/pixdesc.h"
44 #include "libavutil/avstring.h"
45 #include "libavutil/libm.h"
46 #include "libavutil/imgutils.h"
47 #include "libavutil/time.h"
48 #include "libavformat/os_support.h"
49
50 # include "libavfilter/avfilter.h"
51 # include "libavfilter/avfiltergraph.h"
52 # include "libavfilter/buffersrc.h"
53 # include "libavfilter/buffersink.h"
54
55 #if HAVE_SYS_RESOURCE_H
56 #include <sys/types.h>
57 #include <sys/resource.h>
58 #elif HAVE_GETPROCESSTIMES
59 #include <windows.h>
60 #endif
61 #if HAVE_GETPROCESSMEMORYINFO
62 #include <windows.h>
63 #include <psapi.h>
64 #endif
65
66 #if HAVE_SYS_SELECT_H
67 #include <sys/select.h>
68 #endif
69
70 #if HAVE_PTHREADS
71 #include <pthread.h>
72 #endif
73
74 #include <time.h>
75
76 #include "avconv.h"
77 #include "cmdutils.h"
78
79 #include "libavutil/avassert.h"
80
81 const char program_name[] = "avconv";
82 const int program_birth_year = 2000;
83
84 static FILE *vstats_file;
85
86 static int64_t video_size = 0;
87 static int64_t audio_size = 0;
88 static int64_t extra_size = 0;
89 static int nb_frames_dup = 0;
90 static int nb_frames_drop = 0;
91
92
93
94 #if HAVE_PTHREADS
95 /* signal to input threads that they should exit; set by the main thread */
96 static int transcoding_finished;
97 #endif
98
99 #define DEFAULT_PASS_LOGFILENAME_PREFIX "av2pass"
100
101 InputStream **input_streams = NULL;
102 int        nb_input_streams = 0;
103 InputFile   **input_files   = NULL;
104 int        nb_input_files   = 0;
105
106 OutputStream **output_streams = NULL;
107 int         nb_output_streams = 0;
108 OutputFile   **output_files   = NULL;
109 int         nb_output_files   = 0;
110
111 FilterGraph **filtergraphs;
112 int        nb_filtergraphs;
113
114 static void term_exit(void)
115 {
116     av_log(NULL, AV_LOG_QUIET, "");
117 }
118
119 static volatile int received_sigterm = 0;
120 static volatile int received_nb_signals = 0;
121
122 static void
123 sigterm_handler(int sig)
124 {
125     received_sigterm = sig;
126     received_nb_signals++;
127     term_exit();
128 }
129
130 static void term_init(void)
131 {
132     signal(SIGINT , sigterm_handler); /* Interrupt (ANSI).    */
133     signal(SIGTERM, sigterm_handler); /* Termination (ANSI).  */
134 #ifdef SIGXCPU
135     signal(SIGXCPU, sigterm_handler);
136 #endif
137 }
138
139 static int decode_interrupt_cb(void *ctx)
140 {
141     return received_nb_signals > 1;
142 }
143
144 const AVIOInterruptCB int_cb = { decode_interrupt_cb, NULL };
145
146 void exit_program(int ret)
147 {
148     int i, j;
149
150     for (i = 0; i < nb_filtergraphs; i++) {
151         avfilter_graph_free(&filtergraphs[i]->graph);
152         for (j = 0; j < filtergraphs[i]->nb_inputs; j++) {
153             av_freep(&filtergraphs[i]->inputs[j]->name);
154             av_freep(&filtergraphs[i]->inputs[j]);
155         }
156         av_freep(&filtergraphs[i]->inputs);
157         for (j = 0; j < filtergraphs[i]->nb_outputs; j++) {
158             av_freep(&filtergraphs[i]->outputs[j]->name);
159             av_freep(&filtergraphs[i]->outputs[j]);
160         }
161         av_freep(&filtergraphs[i]->outputs);
162         av_freep(&filtergraphs[i]);
163     }
164     av_freep(&filtergraphs);
165
166     /* close files */
167     for (i = 0; i < nb_output_files; i++) {
168         AVFormatContext *s = output_files[i]->ctx;
169         if (!(s->oformat->flags & AVFMT_NOFILE) && s->pb)
170             avio_close(s->pb);
171         avformat_free_context(s);
172         av_dict_free(&output_files[i]->opts);
173         av_freep(&output_files[i]);
174     }
175     for (i = 0; i < nb_output_streams; i++) {
176         AVBitStreamFilterContext *bsfc = output_streams[i]->bitstream_filters;
177         while (bsfc) {
178             AVBitStreamFilterContext *next = bsfc->next;
179             av_bitstream_filter_close(bsfc);
180             bsfc = next;
181         }
182         output_streams[i]->bitstream_filters = NULL;
183
184         av_freep(&output_streams[i]->forced_keyframes);
185         av_freep(&output_streams[i]->avfilter);
186         av_freep(&output_streams[i]->filtered_frame);
187         av_freep(&output_streams[i]);
188     }
189     for (i = 0; i < nb_input_files; i++) {
190         avformat_close_input(&input_files[i]->ctx);
191         av_freep(&input_files[i]);
192     }
193     for (i = 0; i < nb_input_streams; i++) {
194         av_freep(&input_streams[i]->decoded_frame);
195         av_dict_free(&input_streams[i]->opts);
196         free_buffer_pool(&input_streams[i]->buffer_pool);
197         av_freep(&input_streams[i]->filters);
198         av_freep(&input_streams[i]);
199     }
200
201     if (vstats_file)
202         fclose(vstats_file);
203     av_free(vstats_filename);
204
205     av_freep(&input_streams);
206     av_freep(&input_files);
207     av_freep(&output_streams);
208     av_freep(&output_files);
209
210     uninit_opts();
211
212     avfilter_uninit();
213     avformat_network_deinit();
214
215     if (received_sigterm) {
216         av_log(NULL, AV_LOG_INFO, "Received signal %d: terminating.\n",
217                (int) received_sigterm);
218         exit (255);
219     }
220
221     exit(ret);
222 }
223
224 void assert_avoptions(AVDictionary *m)
225 {
226     AVDictionaryEntry *t;
227     if ((t = av_dict_get(m, "", NULL, AV_DICT_IGNORE_SUFFIX))) {
228         av_log(NULL, AV_LOG_FATAL, "Option %s not found.\n", t->key);
229         exit_program(1);
230     }
231 }
232
233 static void assert_codec_experimental(AVCodecContext *c, int encoder)
234 {
235     const char *codec_string = encoder ? "encoder" : "decoder";
236     AVCodec *codec;
237     if (c->codec->capabilities & CODEC_CAP_EXPERIMENTAL &&
238         c->strict_std_compliance > FF_COMPLIANCE_EXPERIMENTAL) {
239         av_log(NULL, AV_LOG_FATAL, "%s '%s' is experimental and might produce bad "
240                 "results.\nAdd '-strict experimental' if you want to use it.\n",
241                 codec_string, c->codec->name);
242         codec = encoder ? avcodec_find_encoder(c->codec->id) : avcodec_find_decoder(c->codec->id);
243         if (!(codec->capabilities & CODEC_CAP_EXPERIMENTAL))
244             av_log(NULL, AV_LOG_FATAL, "Or use the non experimental %s '%s'.\n",
245                    codec_string, codec->name);
246         exit_program(1);
247     }
248 }
249
250 /**
251  * Update the requested input sample format based on the output sample format.
252  * This is currently only used to request float output from decoders which
253  * support multiple sample formats, one of which is AV_SAMPLE_FMT_FLT.
254  * Ideally this will be removed in the future when decoders do not do format
255  * conversion and only output in their native format.
256  */
257 static void update_sample_fmt(AVCodecContext *dec, AVCodec *dec_codec,
258                               AVCodecContext *enc)
259 {
260     /* if sample formats match or a decoder sample format has already been
261        requested, just return */
262     if (enc->sample_fmt == dec->sample_fmt ||
263         dec->request_sample_fmt > AV_SAMPLE_FMT_NONE)
264         return;
265
266     /* if decoder supports more than one output format */
267     if (dec_codec && dec_codec->sample_fmts &&
268         dec_codec->sample_fmts[0] != AV_SAMPLE_FMT_NONE &&
269         dec_codec->sample_fmts[1] != AV_SAMPLE_FMT_NONE) {
270         const enum AVSampleFormat *p;
271         int min_dec = -1, min_inc = -1;
272
273         /* find a matching sample format in the encoder */
274         for (p = dec_codec->sample_fmts; *p != AV_SAMPLE_FMT_NONE; p++) {
275             if (*p == enc->sample_fmt) {
276                 dec->request_sample_fmt = *p;
277                 return;
278             } else if (*p > enc->sample_fmt) {
279                 min_inc = FFMIN(min_inc, *p - enc->sample_fmt);
280             } else
281                 min_dec = FFMIN(min_dec, enc->sample_fmt - *p);
282         }
283
284         /* if none match, provide the one that matches quality closest */
285         dec->request_sample_fmt = min_inc > 0 ? enc->sample_fmt + min_inc :
286                                   enc->sample_fmt - min_dec;
287     }
288 }
289
290 static void write_frame(AVFormatContext *s, AVPacket *pkt, OutputStream *ost)
291 {
292     AVBitStreamFilterContext *bsfc = ost->bitstream_filters;
293     AVCodecContext          *avctx = ost->st->codec;
294     int ret;
295
296     /*
297      * Audio encoders may split the packets --  #frames in != #packets out.
298      * But there is no reordering, so we can limit the number of output packets
299      * by simply dropping them here.
300      * Counting encoded video frames needs to be done separately because of
301      * reordering, see do_video_out()
302      */
303     if (!(avctx->codec_type == AVMEDIA_TYPE_VIDEO && avctx->codec)) {
304         if (ost->frame_number >= ost->max_frames) {
305             av_free_packet(pkt);
306             return;
307         }
308         ost->frame_number++;
309     }
310
311     while (bsfc) {
312         AVPacket new_pkt = *pkt;
313         int a = av_bitstream_filter_filter(bsfc, avctx, NULL,
314                                            &new_pkt.data, &new_pkt.size,
315                                            pkt->data, pkt->size,
316                                            pkt->flags & AV_PKT_FLAG_KEY);
317         if (a > 0) {
318             av_free_packet(pkt);
319             new_pkt.destruct = av_destruct_packet;
320         } else if (a < 0) {
321             av_log(NULL, AV_LOG_ERROR, "%s failed for stream %d, codec %s",
322                    bsfc->filter->name, pkt->stream_index,
323                    avctx->codec ? avctx->codec->name : "copy");
324             print_error("", a);
325             if (exit_on_error)
326                 exit_program(1);
327         }
328         *pkt = new_pkt;
329
330         bsfc = bsfc->next;
331     }
332
333     pkt->stream_index = ost->index;
334     ret = av_interleaved_write_frame(s, pkt);
335     if (ret < 0) {
336         print_error("av_interleaved_write_frame()", ret);
337         exit_program(1);
338     }
339 }
340
341 static int check_recording_time(OutputStream *ost)
342 {
343     OutputFile *of = output_files[ost->file_index];
344
345     if (of->recording_time != INT64_MAX &&
346         av_compare_ts(ost->sync_opts - ost->first_pts, ost->st->codec->time_base, of->recording_time,
347                       AV_TIME_BASE_Q) >= 0) {
348         ost->is_past_recording_time = 1;
349         return 0;
350     }
351     return 1;
352 }
353
354 static void do_audio_out(AVFormatContext *s, OutputStream *ost,
355                          AVFrame *frame)
356 {
357     AVCodecContext *enc = ost->st->codec;
358     AVPacket pkt;
359     int got_packet = 0;
360
361     av_init_packet(&pkt);
362     pkt.data = NULL;
363     pkt.size = 0;
364
365     if (!check_recording_time(ost))
366         return;
367
368     if (frame->pts == AV_NOPTS_VALUE || audio_sync_method < 0)
369         frame->pts = ost->sync_opts;
370     ost->sync_opts = frame->pts + frame->nb_samples;
371
372     if (avcodec_encode_audio2(enc, &pkt, frame, &got_packet) < 0) {
373         av_log(NULL, AV_LOG_FATAL, "Audio encoding failed\n");
374         exit_program(1);
375     }
376
377     if (got_packet) {
378         if (pkt.pts != AV_NOPTS_VALUE)
379             pkt.pts      = av_rescale_q(pkt.pts,      enc->time_base, ost->st->time_base);
380         if (pkt.dts != AV_NOPTS_VALUE)
381             pkt.dts      = av_rescale_q(pkt.dts,      enc->time_base, ost->st->time_base);
382         if (pkt.duration > 0)
383             pkt.duration = av_rescale_q(pkt.duration, enc->time_base, ost->st->time_base);
384
385         write_frame(s, &pkt, ost);
386
387         audio_size += pkt.size;
388     }
389 }
390
391 static void pre_process_video_frame(InputStream *ist, AVPicture *picture, void **bufp)
392 {
393     AVCodecContext *dec;
394     AVPicture *picture2;
395     AVPicture picture_tmp;
396     uint8_t *buf = 0;
397
398     dec = ist->st->codec;
399
400     /* deinterlace : must be done before any resize */
401     if (do_deinterlace) {
402         int size;
403
404         /* create temporary picture */
405         size = avpicture_get_size(dec->pix_fmt, dec->width, dec->height);
406         buf  = av_malloc(size);
407         if (!buf)
408             return;
409
410         picture2 = &picture_tmp;
411         avpicture_fill(picture2, buf, dec->pix_fmt, dec->width, dec->height);
412
413         if (avpicture_deinterlace(picture2, picture,
414                                  dec->pix_fmt, dec->width, dec->height) < 0) {
415             /* if error, do not deinterlace */
416             av_log(NULL, AV_LOG_WARNING, "Deinterlacing failed\n");
417             av_free(buf);
418             buf = NULL;
419             picture2 = picture;
420         }
421     } else {
422         picture2 = picture;
423     }
424
425     if (picture != picture2)
426         *picture = *picture2;
427     *bufp = buf;
428 }
429
430 static void do_subtitle_out(AVFormatContext *s,
431                             OutputStream *ost,
432                             InputStream *ist,
433                             AVSubtitle *sub,
434                             int64_t pts)
435 {
436     static uint8_t *subtitle_out = NULL;
437     int subtitle_out_max_size = 1024 * 1024;
438     int subtitle_out_size, nb, i;
439     AVCodecContext *enc;
440     AVPacket pkt;
441
442     if (pts == AV_NOPTS_VALUE) {
443         av_log(NULL, AV_LOG_ERROR, "Subtitle packets must have a pts\n");
444         if (exit_on_error)
445             exit_program(1);
446         return;
447     }
448
449     enc = ost->st->codec;
450
451     if (!subtitle_out) {
452         subtitle_out = av_malloc(subtitle_out_max_size);
453     }
454
455     /* Note: DVB subtitle need one packet to draw them and one other
456        packet to clear them */
457     /* XXX: signal it in the codec context ? */
458     if (enc->codec_id == AV_CODEC_ID_DVB_SUBTITLE)
459         nb = 2;
460     else
461         nb = 1;
462
463     for (i = 0; i < nb; i++) {
464         ost->sync_opts = av_rescale_q(pts, ist->st->time_base, enc->time_base);
465         if (!check_recording_time(ost))
466             return;
467
468         sub->pts = av_rescale_q(pts, ist->st->time_base, AV_TIME_BASE_Q);
469         // start_display_time is required to be 0
470         sub->pts               += av_rescale_q(sub->start_display_time, (AVRational){ 1, 1000 }, AV_TIME_BASE_Q);
471         sub->end_display_time  -= sub->start_display_time;
472         sub->start_display_time = 0;
473         subtitle_out_size = avcodec_encode_subtitle(enc, subtitle_out,
474                                                     subtitle_out_max_size, sub);
475         if (subtitle_out_size < 0) {
476             av_log(NULL, AV_LOG_FATAL, "Subtitle encoding failed\n");
477             exit_program(1);
478         }
479
480         av_init_packet(&pkt);
481         pkt.data = subtitle_out;
482         pkt.size = subtitle_out_size;
483         pkt.pts  = av_rescale_q(sub->pts, AV_TIME_BASE_Q, ost->st->time_base);
484         if (enc->codec_id == AV_CODEC_ID_DVB_SUBTITLE) {
485             /* XXX: the pts correction is handled here. Maybe handling
486                it in the codec would be better */
487             if (i == 0)
488                 pkt.pts += 90 * sub->start_display_time;
489             else
490                 pkt.pts += 90 * sub->end_display_time;
491         }
492         write_frame(s, &pkt, ost);
493     }
494 }
495
496 static void do_video_out(AVFormatContext *s,
497                          OutputStream *ost,
498                          AVFrame *in_picture,
499                          int *frame_size, float quality)
500 {
501     int ret, format_video_sync;
502     AVPacket pkt;
503     AVCodecContext *enc = ost->st->codec;
504
505     *frame_size = 0;
506
507     format_video_sync = video_sync_method;
508     if (format_video_sync == VSYNC_AUTO)
509         format_video_sync = (s->oformat->flags & AVFMT_NOTIMESTAMPS) ? VSYNC_PASSTHROUGH :
510                             (s->oformat->flags & AVFMT_VARIABLE_FPS) ? VSYNC_VFR : VSYNC_CFR;
511     if (format_video_sync != VSYNC_PASSTHROUGH &&
512         ost->frame_number &&
513         in_picture->pts != AV_NOPTS_VALUE &&
514         in_picture->pts < ost->sync_opts) {
515         nb_frames_drop++;
516         av_log(NULL, AV_LOG_VERBOSE, "*** drop!\n");
517         return;
518     }
519
520     if (in_picture->pts == AV_NOPTS_VALUE)
521         in_picture->pts = ost->sync_opts;
522     ost->sync_opts = in_picture->pts;
523
524
525     if (!ost->frame_number)
526         ost->first_pts = in_picture->pts;
527
528     av_init_packet(&pkt);
529     pkt.data = NULL;
530     pkt.size = 0;
531
532     if (!check_recording_time(ost) ||
533         ost->frame_number >= ost->max_frames)
534         return;
535
536     if (s->oformat->flags & AVFMT_RAWPICTURE &&
537         enc->codec->id == AV_CODEC_ID_RAWVIDEO) {
538         /* raw pictures are written as AVPicture structure to
539            avoid any copies. We support temporarily the older
540            method. */
541         enc->coded_frame->interlaced_frame = in_picture->interlaced_frame;
542         enc->coded_frame->top_field_first  = in_picture->top_field_first;
543         pkt.data   = (uint8_t *)in_picture;
544         pkt.size   =  sizeof(AVPicture);
545         pkt.pts    = av_rescale_q(in_picture->pts, enc->time_base, ost->st->time_base);
546         pkt.flags |= AV_PKT_FLAG_KEY;
547
548         write_frame(s, &pkt, ost);
549     } else {
550         int got_packet;
551         AVFrame big_picture;
552
553         big_picture = *in_picture;
554         /* better than nothing: use input picture interlaced
555            settings */
556         big_picture.interlaced_frame = in_picture->interlaced_frame;
557         if (ost->st->codec->flags & (CODEC_FLAG_INTERLACED_DCT|CODEC_FLAG_INTERLACED_ME)) {
558             if (ost->top_field_first == -1)
559                 big_picture.top_field_first = in_picture->top_field_first;
560             else
561                 big_picture.top_field_first = !!ost->top_field_first;
562         }
563
564         /* handles same_quant here. This is not correct because it may
565            not be a global option */
566         big_picture.quality = quality;
567         if (!enc->me_threshold)
568             big_picture.pict_type = 0;
569         if (ost->forced_kf_index < ost->forced_kf_count &&
570             big_picture.pts >= ost->forced_kf_pts[ost->forced_kf_index]) {
571             big_picture.pict_type = AV_PICTURE_TYPE_I;
572             ost->forced_kf_index++;
573         }
574         ret = avcodec_encode_video2(enc, &pkt, &big_picture, &got_packet);
575         if (ret < 0) {
576             av_log(NULL, AV_LOG_FATAL, "Video encoding failed\n");
577             exit_program(1);
578         }
579
580         if (got_packet) {
581             if (pkt.pts != AV_NOPTS_VALUE)
582                 pkt.pts = av_rescale_q(pkt.pts, enc->time_base, ost->st->time_base);
583             if (pkt.dts != AV_NOPTS_VALUE)
584                 pkt.dts = av_rescale_q(pkt.dts, enc->time_base, ost->st->time_base);
585
586             write_frame(s, &pkt, ost);
587             *frame_size = pkt.size;
588             video_size += pkt.size;
589
590             /* if two pass, output log */
591             if (ost->logfile && enc->stats_out) {
592                 fprintf(ost->logfile, "%s", enc->stats_out);
593             }
594         }
595     }
596     ost->sync_opts++;
597     /*
598      * For video, number of frames in == number of packets out.
599      * But there may be reordering, so we can't throw away frames on encoder
600      * flush, we need to limit them here, before they go into encoder.
601      */
602     ost->frame_number++;
603 }
604
605 static double psnr(double d)
606 {
607     return -10.0 * log(d) / log(10.0);
608 }
609
610 static void do_video_stats(AVFormatContext *os, OutputStream *ost,
611                            int frame_size)
612 {
613     AVCodecContext *enc;
614     int frame_number;
615     double ti1, bitrate, avg_bitrate;
616
617     /* this is executed just the first time do_video_stats is called */
618     if (!vstats_file) {
619         vstats_file = fopen(vstats_filename, "w");
620         if (!vstats_file) {
621             perror("fopen");
622             exit_program(1);
623         }
624     }
625
626     enc = ost->st->codec;
627     if (enc->codec_type == AVMEDIA_TYPE_VIDEO) {
628         frame_number = ost->frame_number;
629         fprintf(vstats_file, "frame= %5d q= %2.1f ", frame_number, enc->coded_frame->quality / (float)FF_QP2LAMBDA);
630         if (enc->flags&CODEC_FLAG_PSNR)
631             fprintf(vstats_file, "PSNR= %6.2f ", psnr(enc->coded_frame->error[0] / (enc->width * enc->height * 255.0 * 255.0)));
632
633         fprintf(vstats_file,"f_size= %6d ", frame_size);
634         /* compute pts value */
635         ti1 = ost->sync_opts * av_q2d(enc->time_base);
636         if (ti1 < 0.01)
637             ti1 = 0.01;
638
639         bitrate     = (frame_size * 8) / av_q2d(enc->time_base) / 1000.0;
640         avg_bitrate = (double)(video_size * 8) / ti1 / 1000.0;
641         fprintf(vstats_file, "s_size= %8.0fkB time= %0.3f br= %7.1fkbits/s avg_br= %7.1fkbits/s ",
642                (double)video_size / 1024, ti1, bitrate, avg_bitrate);
643         fprintf(vstats_file, "type= %c\n", av_get_picture_type_char(enc->coded_frame->pict_type));
644     }
645 }
646
647 /**
648  * Read one frame for lavfi output for ost and encode it.
649  */
650 static int poll_filter(OutputStream *ost)
651 {
652     OutputFile    *of = output_files[ost->file_index];
653     AVFilterBufferRef *picref;
654     AVFrame *filtered_frame = NULL;
655     int frame_size, ret;
656
657     if (!ost->filtered_frame && !(ost->filtered_frame = avcodec_alloc_frame())) {
658         return AVERROR(ENOMEM);
659     } else
660         avcodec_get_frame_defaults(ost->filtered_frame);
661     filtered_frame = ost->filtered_frame;
662
663     if (ost->enc->type == AVMEDIA_TYPE_AUDIO &&
664         !(ost->enc->capabilities & CODEC_CAP_VARIABLE_FRAME_SIZE))
665         ret = av_buffersink_read_samples(ost->filter->filter, &picref,
666                                          ost->st->codec->frame_size);
667     else
668         ret = av_buffersink_read(ost->filter->filter, &picref);
669
670     if (ret < 0)
671         return ret;
672
673     avfilter_copy_buf_props(filtered_frame, picref);
674     if (picref->pts != AV_NOPTS_VALUE) {
675         filtered_frame->pts = av_rescale_q(picref->pts,
676                                            ost->filter->filter->inputs[0]->time_base,
677                                            ost->st->codec->time_base) -
678                               av_rescale_q(of->start_time,
679                                            AV_TIME_BASE_Q,
680                                            ost->st->codec->time_base);
681
682         if (of->start_time && filtered_frame->pts < 0) {
683             avfilter_unref_buffer(picref);
684             return 0;
685         }
686     }
687
688     switch (ost->filter->filter->inputs[0]->type) {
689     case AVMEDIA_TYPE_VIDEO:
690         if (!ost->frame_aspect_ratio)
691             ost->st->codec->sample_aspect_ratio = picref->video->pixel_aspect;
692
693         do_video_out(of->ctx, ost, filtered_frame, &frame_size,
694                      same_quant ? ost->last_quality :
695                                   ost->st->codec->global_quality);
696         if (vstats_filename && frame_size)
697             do_video_stats(of->ctx, ost, frame_size);
698         break;
699     case AVMEDIA_TYPE_AUDIO:
700         do_audio_out(of->ctx, ost, filtered_frame);
701         break;
702     default:
703         // TODO support subtitle filters
704         av_assert0(0);
705     }
706
707     avfilter_unref_buffer(picref);
708
709     return 0;
710 }
711
712 /**
713  * Read as many frames from possible from lavfi and encode them.
714  *
715  * Always read from the active stream with the lowest timestamp. If no frames
716  * are available for it then return EAGAIN and wait for more input. This way we
717  * can use lavfi sources that generate unlimited amount of frames without memory
718  * usage exploding.
719  */
720 static int poll_filters(void)
721 {
722     int i, ret = 0;
723
724     while (ret >= 0 && !received_sigterm) {
725         OutputStream *ost = NULL;
726         int64_t min_pts = INT64_MAX;
727
728         /* choose output stream with the lowest timestamp */
729         for (i = 0; i < nb_output_streams; i++) {
730             int64_t pts = output_streams[i]->sync_opts;
731
732             if (!output_streams[i]->filter ||
733                 output_streams[i]->is_past_recording_time)
734                 continue;
735
736             pts = av_rescale_q(pts, output_streams[i]->st->codec->time_base,
737                                AV_TIME_BASE_Q);
738             if (pts < min_pts) {
739                 min_pts = pts;
740                 ost = output_streams[i];
741             }
742         }
743
744         if (!ost)
745             break;
746
747         ret = poll_filter(ost);
748
749         if (ret == AVERROR_EOF) {
750             ost->is_past_recording_time = 1;
751
752             if (opt_shortest)
753                 return ret;
754
755             ret = 0;
756         } else if (ret == AVERROR(EAGAIN))
757             return 0;
758     }
759
760     return ret;
761 }
762
763 static void print_report(int is_last_report, int64_t timer_start)
764 {
765     char buf[1024];
766     OutputStream *ost;
767     AVFormatContext *oc;
768     int64_t total_size;
769     AVCodecContext *enc;
770     int frame_number, vid, i;
771     double bitrate, ti1, pts;
772     static int64_t last_time = -1;
773     static int qp_histogram[52];
774
775     if (!print_stats && !is_last_report)
776         return;
777
778     if (!is_last_report) {
779         int64_t cur_time;
780         /* display the report every 0.5 seconds */
781         cur_time = av_gettime();
782         if (last_time == -1) {
783             last_time = cur_time;
784             return;
785         }
786         if ((cur_time - last_time) < 500000)
787             return;
788         last_time = cur_time;
789     }
790
791
792     oc = output_files[0]->ctx;
793
794     total_size = avio_size(oc->pb);
795     if (total_size < 0) // FIXME improve avio_size() so it works with non seekable output too
796         total_size = avio_tell(oc->pb);
797
798     buf[0] = '\0';
799     ti1 = 1e10;
800     vid = 0;
801     for (i = 0; i < nb_output_streams; i++) {
802         float q = -1;
803         ost = output_streams[i];
804         enc = ost->st->codec;
805         if (!ost->stream_copy && enc->coded_frame)
806             q = enc->coded_frame->quality / (float)FF_QP2LAMBDA;
807         if (vid && enc->codec_type == AVMEDIA_TYPE_VIDEO) {
808             snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "q=%2.1f ", q);
809         }
810         if (!vid && enc->codec_type == AVMEDIA_TYPE_VIDEO) {
811             float t = (av_gettime() - timer_start) / 1000000.0;
812
813             frame_number = ost->frame_number;
814             snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "frame=%5d fps=%3d q=%3.1f ",
815                      frame_number, (t > 1) ? (int)(frame_number / t + 0.5) : 0, q);
816             if (is_last_report)
817                 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "L");
818             if (qp_hist) {
819                 int j;
820                 int qp = lrintf(q);
821                 if (qp >= 0 && qp < FF_ARRAY_ELEMS(qp_histogram))
822                     qp_histogram[qp]++;
823                 for (j = 0; j < 32; j++)
824                     snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "%X", (int)lrintf(log(qp_histogram[j] + 1) / log(2)));
825             }
826             if (enc->flags&CODEC_FLAG_PSNR) {
827                 int j;
828                 double error, error_sum = 0;
829                 double scale, scale_sum = 0;
830                 char type[3] = { 'Y','U','V' };
831                 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "PSNR=");
832                 for (j = 0; j < 3; j++) {
833                     if (is_last_report) {
834                         error = enc->error[j];
835                         scale = enc->width * enc->height * 255.0 * 255.0 * frame_number;
836                     } else {
837                         error = enc->coded_frame->error[j];
838                         scale = enc->width * enc->height * 255.0 * 255.0;
839                     }
840                     if (j)
841                         scale /= 4;
842                     error_sum += error;
843                     scale_sum += scale;
844                     snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "%c:%2.2f ", type[j], psnr(error / scale));
845                 }
846                 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "*:%2.2f ", psnr(error_sum / scale_sum));
847             }
848             vid = 1;
849         }
850         /* compute min output value */
851         pts = (double)ost->st->pts.val * av_q2d(ost->st->time_base);
852         if ((pts < ti1) && (pts > 0))
853             ti1 = pts;
854     }
855     if (ti1 < 0.01)
856         ti1 = 0.01;
857
858     bitrate = (double)(total_size * 8) / ti1 / 1000.0;
859
860     snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
861             "size=%8.0fkB time=%0.2f bitrate=%6.1fkbits/s",
862             (double)total_size / 1024, ti1, bitrate);
863
864     if (nb_frames_dup || nb_frames_drop)
865         snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), " dup=%d drop=%d",
866                 nb_frames_dup, nb_frames_drop);
867
868     av_log(NULL, AV_LOG_INFO, "%s    \r", buf);
869
870     fflush(stderr);
871
872     if (is_last_report) {
873         int64_t raw= audio_size + video_size + extra_size;
874         av_log(NULL, AV_LOG_INFO, "\n");
875         av_log(NULL, AV_LOG_INFO, "video:%1.0fkB audio:%1.0fkB global headers:%1.0fkB muxing overhead %f%%\n",
876                video_size / 1024.0,
877                audio_size / 1024.0,
878                extra_size / 1024.0,
879                100.0 * (total_size - raw) / raw
880         );
881     }
882 }
883
884 static void flush_encoders(void)
885 {
886     int i, ret;
887
888     for (i = 0; i < nb_output_streams; i++) {
889         OutputStream   *ost = output_streams[i];
890         AVCodecContext *enc = ost->st->codec;
891         AVFormatContext *os = output_files[ost->file_index]->ctx;
892         int stop_encoding = 0;
893
894         if (!ost->encoding_needed)
895             continue;
896
897         if (ost->st->codec->codec_type == AVMEDIA_TYPE_AUDIO && enc->frame_size <= 1)
898             continue;
899         if (ost->st->codec->codec_type == AVMEDIA_TYPE_VIDEO && (os->oformat->flags & AVFMT_RAWPICTURE) && enc->codec->id == AV_CODEC_ID_RAWVIDEO)
900             continue;
901
902         for (;;) {
903             int (*encode)(AVCodecContext*, AVPacket*, const AVFrame*, int*) = NULL;
904             const char *desc;
905             int64_t *size;
906
907             switch (ost->st->codec->codec_type) {
908             case AVMEDIA_TYPE_AUDIO:
909                 encode = avcodec_encode_audio2;
910                 desc   = "Audio";
911                 size   = &audio_size;
912                 break;
913             case AVMEDIA_TYPE_VIDEO:
914                 encode = avcodec_encode_video2;
915                 desc   = "Video";
916                 size   = &video_size;
917                 break;
918             default:
919                 stop_encoding = 1;
920             }
921
922             if (encode) {
923                 AVPacket pkt;
924                 int got_packet;
925                 av_init_packet(&pkt);
926                 pkt.data = NULL;
927                 pkt.size = 0;
928
929                 ret = encode(enc, &pkt, NULL, &got_packet);
930                 if (ret < 0) {
931                     av_log(NULL, AV_LOG_FATAL, "%s encoding failed\n", desc);
932                     exit_program(1);
933                 }
934                 *size += ret;
935                 if (ost->logfile && enc->stats_out) {
936                     fprintf(ost->logfile, "%s", enc->stats_out);
937                 }
938                 if (!got_packet) {
939                     stop_encoding = 1;
940                     break;
941                 }
942                 if (pkt.pts != AV_NOPTS_VALUE)
943                     pkt.pts = av_rescale_q(pkt.pts, enc->time_base, ost->st->time_base);
944                 if (pkt.dts != AV_NOPTS_VALUE)
945                     pkt.dts = av_rescale_q(pkt.dts, enc->time_base, ost->st->time_base);
946                 write_frame(os, &pkt, ost);
947             }
948
949             if (stop_encoding)
950                 break;
951         }
952     }
953 }
954
955 /*
956  * Check whether a packet from ist should be written into ost at this time
957  */
958 static int check_output_constraints(InputStream *ist, OutputStream *ost)
959 {
960     OutputFile *of = output_files[ost->file_index];
961     int ist_index  = input_files[ist->file_index]->ist_index + ist->st->index;
962
963     if (ost->source_index != ist_index)
964         return 0;
965
966     if (of->start_time && ist->last_dts < of->start_time)
967         return 0;
968
969     return 1;
970 }
971
972 static void do_streamcopy(InputStream *ist, OutputStream *ost, const AVPacket *pkt)
973 {
974     OutputFile *of = output_files[ost->file_index];
975     int64_t ost_tb_start_time = av_rescale_q(of->start_time, AV_TIME_BASE_Q, ost->st->time_base);
976     AVPacket opkt;
977
978     av_init_packet(&opkt);
979
980     if ((!ost->frame_number && !(pkt->flags & AV_PKT_FLAG_KEY)) &&
981         !ost->copy_initial_nonkeyframes)
982         return;
983
984     if (of->recording_time != INT64_MAX &&
985         ist->last_dts >= of->recording_time + of->start_time) {
986         ost->is_past_recording_time = 1;
987         return;
988     }
989
990     /* force the input stream PTS */
991     if (ost->st->codec->codec_type == AVMEDIA_TYPE_AUDIO)
992         audio_size += pkt->size;
993     else if (ost->st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
994         video_size += pkt->size;
995         ost->sync_opts++;
996     }
997
998     if (pkt->pts != AV_NOPTS_VALUE)
999         opkt.pts = av_rescale_q(pkt->pts, ist->st->time_base, ost->st->time_base) - ost_tb_start_time;
1000     else
1001         opkt.pts = AV_NOPTS_VALUE;
1002
1003     if (pkt->dts == AV_NOPTS_VALUE)
1004         opkt.dts = av_rescale_q(ist->last_dts, AV_TIME_BASE_Q, ost->st->time_base);
1005     else
1006         opkt.dts = av_rescale_q(pkt->dts, ist->st->time_base, ost->st->time_base);
1007     opkt.dts -= ost_tb_start_time;
1008
1009     opkt.duration = av_rescale_q(pkt->duration, ist->st->time_base, ost->st->time_base);
1010     opkt.flags    = pkt->flags;
1011
1012     // FIXME remove the following 2 lines they shall be replaced by the bitstream filters
1013     if (  ost->st->codec->codec_id != AV_CODEC_ID_H264
1014        && ost->st->codec->codec_id != AV_CODEC_ID_MPEG1VIDEO
1015        && ost->st->codec->codec_id != AV_CODEC_ID_MPEG2VIDEO
1016        && ost->st->codec->codec_id != AV_CODEC_ID_VC1
1017        ) {
1018         if (av_parser_change(ist->st->parser, ost->st->codec, &opkt.data, &opkt.size, pkt->data, pkt->size, pkt->flags & AV_PKT_FLAG_KEY))
1019             opkt.destruct = av_destruct_packet;
1020     } else {
1021         opkt.data = pkt->data;
1022         opkt.size = pkt->size;
1023     }
1024
1025     write_frame(of->ctx, &opkt, ost);
1026     ost->st->codec->frame_number++;
1027     av_free_packet(&opkt);
1028 }
1029
1030 static void rate_emu_sleep(InputStream *ist)
1031 {
1032     if (input_files[ist->file_index]->rate_emu) {
1033         int64_t pts = av_rescale(ist->last_dts, 1000000, AV_TIME_BASE);
1034         int64_t now = av_gettime() - ist->start;
1035         if (pts > now)
1036             av_usleep(pts - now);
1037     }
1038 }
1039
1040 int guess_input_channel_layout(InputStream *ist)
1041 {
1042     AVCodecContext *dec = ist->st->codec;
1043
1044     if (!dec->channel_layout) {
1045         char layout_name[256];
1046
1047         dec->channel_layout = av_get_default_channel_layout(dec->channels);
1048         if (!dec->channel_layout)
1049             return 0;
1050         av_get_channel_layout_string(layout_name, sizeof(layout_name),
1051                                      dec->channels, dec->channel_layout);
1052         av_log(NULL, AV_LOG_WARNING, "Guessed Channel Layout for  Input Stream "
1053                "#%d.%d : %s\n", ist->file_index, ist->st->index, layout_name);
1054     }
1055     return 1;
1056 }
1057
1058 static int decode_audio(InputStream *ist, AVPacket *pkt, int *got_output)
1059 {
1060     AVFrame *decoded_frame;
1061     AVCodecContext *avctx = ist->st->codec;
1062     int bps = av_get_bytes_per_sample(ist->st->codec->sample_fmt);
1063     int i, ret, resample_changed;
1064
1065     if (!ist->decoded_frame && !(ist->decoded_frame = avcodec_alloc_frame()))
1066         return AVERROR(ENOMEM);
1067     else
1068         avcodec_get_frame_defaults(ist->decoded_frame);
1069     decoded_frame = ist->decoded_frame;
1070
1071     ret = avcodec_decode_audio4(avctx, decoded_frame, got_output, pkt);
1072     if (!*got_output || ret < 0) {
1073         if (!pkt->size) {
1074             for (i = 0; i < ist->nb_filters; i++)
1075                 av_buffersrc_buffer(ist->filters[i]->filter, NULL);
1076         }
1077         return ret;
1078     }
1079
1080     /* if the decoder provides a pts, use it instead of the last packet pts.
1081        the decoder could be delaying output by a packet or more. */
1082     if (decoded_frame->pts != AV_NOPTS_VALUE)
1083         ist->next_dts = decoded_frame->pts;
1084     else if (pkt->pts != AV_NOPTS_VALUE) {
1085         decoded_frame->pts = pkt->pts;
1086         pkt->pts           = AV_NOPTS_VALUE;
1087     }
1088
1089     // preprocess audio (volume)
1090     if (audio_volume != 256) {
1091         int decoded_data_size = decoded_frame->nb_samples * avctx->channels * bps;
1092         void *samples = decoded_frame->data[0];
1093         switch (avctx->sample_fmt) {
1094         case AV_SAMPLE_FMT_U8:
1095         {
1096             uint8_t *volp = samples;
1097             for (i = 0; i < (decoded_data_size / sizeof(*volp)); i++) {
1098                 int v = (((*volp - 128) * audio_volume + 128) >> 8) + 128;
1099                 *volp++ = av_clip_uint8(v);
1100             }
1101             break;
1102         }
1103         case AV_SAMPLE_FMT_S16:
1104         {
1105             int16_t *volp = samples;
1106             for (i = 0; i < (decoded_data_size / sizeof(*volp)); i++) {
1107                 int v = ((*volp) * audio_volume + 128) >> 8;
1108                 *volp++ = av_clip_int16(v);
1109             }
1110             break;
1111         }
1112         case AV_SAMPLE_FMT_S32:
1113         {
1114             int32_t *volp = samples;
1115             for (i = 0; i < (decoded_data_size / sizeof(*volp)); i++) {
1116                 int64_t v = (((int64_t)*volp * audio_volume + 128) >> 8);
1117                 *volp++ = av_clipl_int32(v);
1118             }
1119             break;
1120         }
1121         case AV_SAMPLE_FMT_FLT:
1122         {
1123             float *volp = samples;
1124             float scale = audio_volume / 256.f;
1125             for (i = 0; i < (decoded_data_size / sizeof(*volp)); i++) {
1126                 *volp++ *= scale;
1127             }
1128             break;
1129         }
1130         case AV_SAMPLE_FMT_DBL:
1131         {
1132             double *volp = samples;
1133             double scale = audio_volume / 256.;
1134             for (i = 0; i < (decoded_data_size / sizeof(*volp)); i++) {
1135                 *volp++ *= scale;
1136             }
1137             break;
1138         }
1139         default:
1140             av_log(NULL, AV_LOG_FATAL,
1141                    "Audio volume adjustment on sample format %s is not supported.\n",
1142                    av_get_sample_fmt_name(ist->st->codec->sample_fmt));
1143             exit_program(1);
1144         }
1145     }
1146
1147     rate_emu_sleep(ist);
1148
1149     resample_changed = ist->resample_sample_fmt     != decoded_frame->format         ||
1150                        ist->resample_channels       != avctx->channels               ||
1151                        ist->resample_channel_layout != decoded_frame->channel_layout ||
1152                        ist->resample_sample_rate    != decoded_frame->sample_rate;
1153     if (resample_changed) {
1154         char layout1[64], layout2[64];
1155
1156         if (!guess_input_channel_layout(ist)) {
1157             av_log(NULL, AV_LOG_FATAL, "Unable to find default channel "
1158                    "layout for Input Stream #%d.%d\n", ist->file_index,
1159                    ist->st->index);
1160             exit_program(1);
1161         }
1162         decoded_frame->channel_layout = avctx->channel_layout;
1163
1164         av_get_channel_layout_string(layout1, sizeof(layout1), ist->resample_channels,
1165                                      ist->resample_channel_layout);
1166         av_get_channel_layout_string(layout2, sizeof(layout2), avctx->channels,
1167                                      decoded_frame->channel_layout);
1168
1169         av_log(NULL, AV_LOG_INFO,
1170                "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",
1171                ist->file_index, ist->st->index,
1172                ist->resample_sample_rate,  av_get_sample_fmt_name(ist->resample_sample_fmt),
1173                ist->resample_channels, layout1,
1174                decoded_frame->sample_rate, av_get_sample_fmt_name(decoded_frame->format),
1175                avctx->channels, layout2);
1176
1177         ist->resample_sample_fmt     = decoded_frame->format;
1178         ist->resample_sample_rate    = decoded_frame->sample_rate;
1179         ist->resample_channel_layout = decoded_frame->channel_layout;
1180         ist->resample_channels       = avctx->channels;
1181
1182         for (i = 0; i < nb_filtergraphs; i++)
1183             if (ist_in_filtergraph(filtergraphs[i], ist) &&
1184                 configure_filtergraph(filtergraphs[i]) < 0) {
1185                 av_log(NULL, AV_LOG_FATAL, "Error reinitializing filters!\n");
1186                 exit_program(1);
1187             }
1188     }
1189
1190     if (decoded_frame->pts != AV_NOPTS_VALUE)
1191         decoded_frame->pts = av_rescale_q(decoded_frame->pts,
1192                                           ist->st->time_base,
1193                                           (AVRational){1, ist->st->codec->sample_rate});
1194     for (i = 0; i < ist->nb_filters; i++)
1195         av_buffersrc_write_frame(ist->filters[i]->filter, decoded_frame);
1196
1197     return ret;
1198 }
1199
1200 static int decode_video(InputStream *ist, AVPacket *pkt, int *got_output)
1201 {
1202     AVFrame *decoded_frame;
1203     void *buffer_to_free = NULL;
1204     int i, ret = 0, resample_changed;
1205     float quality;
1206
1207     if (!ist->decoded_frame && !(ist->decoded_frame = avcodec_alloc_frame()))
1208         return AVERROR(ENOMEM);
1209     else
1210         avcodec_get_frame_defaults(ist->decoded_frame);
1211     decoded_frame = ist->decoded_frame;
1212
1213     ret = avcodec_decode_video2(ist->st->codec,
1214                                 decoded_frame, got_output, pkt);
1215     if (!*got_output || ret < 0) {
1216         if (!pkt->size) {
1217             for (i = 0; i < ist->nb_filters; i++)
1218                 av_buffersrc_buffer(ist->filters[i]->filter, NULL);
1219         }
1220         return ret;
1221     }
1222
1223     quality = same_quant ? decoded_frame->quality : 0;
1224     decoded_frame->pts = guess_correct_pts(&ist->pts_ctx, decoded_frame->pkt_pts,
1225                                            decoded_frame->pkt_dts);
1226     pkt->size = 0;
1227     pre_process_video_frame(ist, (AVPicture *)decoded_frame, &buffer_to_free);
1228
1229     rate_emu_sleep(ist);
1230
1231     if (ist->st->sample_aspect_ratio.num)
1232         decoded_frame->sample_aspect_ratio = ist->st->sample_aspect_ratio;
1233
1234     resample_changed = ist->resample_width   != decoded_frame->width  ||
1235                        ist->resample_height  != decoded_frame->height ||
1236                        ist->resample_pix_fmt != decoded_frame->format;
1237     if (resample_changed) {
1238         av_log(NULL, AV_LOG_INFO,
1239                "Input stream #%d:%d frame changed from size:%dx%d fmt:%s to size:%dx%d fmt:%s\n",
1240                ist->file_index, ist->st->index,
1241                ist->resample_width,  ist->resample_height,  av_get_pix_fmt_name(ist->resample_pix_fmt),
1242                decoded_frame->width, decoded_frame->height, av_get_pix_fmt_name(decoded_frame->format));
1243
1244         ist->resample_width   = decoded_frame->width;
1245         ist->resample_height  = decoded_frame->height;
1246         ist->resample_pix_fmt = decoded_frame->format;
1247
1248         for (i = 0; i < nb_filtergraphs; i++)
1249             if (ist_in_filtergraph(filtergraphs[i], ist) &&
1250                 configure_filtergraph(filtergraphs[i]) < 0) {
1251                 av_log(NULL, AV_LOG_FATAL, "Error reinitializing filters!\n");
1252                 exit_program(1);
1253             }
1254     }
1255
1256     for (i = 0; i < ist->nb_filters; i++) {
1257         // XXX what an ugly hack
1258         if (ist->filters[i]->graph->nb_outputs == 1)
1259             ist->filters[i]->graph->outputs[0]->ost->last_quality = quality;
1260
1261         if (ist->st->codec->codec->capabilities & CODEC_CAP_DR1) {
1262             FrameBuffer      *buf = decoded_frame->opaque;
1263             AVFilterBufferRef *fb = avfilter_get_video_buffer_ref_from_arrays(
1264                                         decoded_frame->data, decoded_frame->linesize,
1265                                         AV_PERM_READ | AV_PERM_PRESERVE,
1266                                         ist->st->codec->width, ist->st->codec->height,
1267                                         ist->st->codec->pix_fmt);
1268
1269             avfilter_copy_frame_props(fb, decoded_frame);
1270             fb->buf->priv           = buf;
1271             fb->buf->free           = filter_release_buffer;
1272
1273             buf->refcount++;
1274             av_buffersrc_buffer(ist->filters[i]->filter, fb);
1275         } else
1276             av_buffersrc_write_frame(ist->filters[i]->filter, decoded_frame);
1277     }
1278
1279     av_free(buffer_to_free);
1280     return ret;
1281 }
1282
1283 static int transcode_subtitles(InputStream *ist, AVPacket *pkt, int *got_output)
1284 {
1285     AVSubtitle subtitle;
1286     int i, ret = avcodec_decode_subtitle2(ist->st->codec,
1287                                           &subtitle, got_output, pkt);
1288     if (ret < 0)
1289         return ret;
1290     if (!*got_output)
1291         return ret;
1292
1293     rate_emu_sleep(ist);
1294
1295     for (i = 0; i < nb_output_streams; i++) {
1296         OutputStream *ost = output_streams[i];
1297
1298         if (!check_output_constraints(ist, ost) || !ost->encoding_needed)
1299             continue;
1300
1301         do_subtitle_out(output_files[ost->file_index]->ctx, ost, ist, &subtitle, pkt->pts);
1302     }
1303
1304     avsubtitle_free(&subtitle);
1305     return ret;
1306 }
1307
1308 /* pkt = NULL means EOF (needed to flush decoder buffers) */
1309 static int output_packet(InputStream *ist, const AVPacket *pkt)
1310 {
1311     int i;
1312     int got_output;
1313     AVPacket avpkt;
1314
1315     if (ist->next_dts == AV_NOPTS_VALUE)
1316         ist->next_dts = ist->last_dts;
1317
1318     if (pkt == NULL) {
1319         /* EOF handling */
1320         av_init_packet(&avpkt);
1321         avpkt.data = NULL;
1322         avpkt.size = 0;
1323         goto handle_eof;
1324     } else {
1325         avpkt = *pkt;
1326     }
1327
1328     if (pkt->dts != AV_NOPTS_VALUE)
1329         ist->next_dts = ist->last_dts = av_rescale_q(pkt->dts, ist->st->time_base, AV_TIME_BASE_Q);
1330
1331     // while we have more to decode or while the decoder did output something on EOF
1332     while (ist->decoding_needed && (avpkt.size > 0 || (!pkt && got_output))) {
1333         int ret = 0;
1334     handle_eof:
1335
1336         ist->last_dts = ist->next_dts;
1337
1338         if (avpkt.size && avpkt.size != pkt->size) {
1339             av_log(NULL, ist->showed_multi_packet_warning ? AV_LOG_VERBOSE : AV_LOG_WARNING,
1340                    "Multiple frames in a packet from stream %d\n", pkt->stream_index);
1341             ist->showed_multi_packet_warning = 1;
1342         }
1343
1344         switch (ist->st->codec->codec_type) {
1345         case AVMEDIA_TYPE_AUDIO:
1346             ret = decode_audio    (ist, &avpkt, &got_output);
1347             break;
1348         case AVMEDIA_TYPE_VIDEO:
1349             ret = decode_video    (ist, &avpkt, &got_output);
1350             if (avpkt.duration)
1351                 ist->next_dts += av_rescale_q(avpkt.duration, ist->st->time_base, AV_TIME_BASE_Q);
1352             else if (ist->st->avg_frame_rate.num)
1353                 ist->next_dts += av_rescale_q(1, av_inv_q(ist->st->avg_frame_rate),
1354                                               AV_TIME_BASE_Q);
1355             else if (ist->st->codec->time_base.num != 0) {
1356                 int ticks      = ist->st->parser ? ist->st->parser->repeat_pict + 1 :
1357                                                    ist->st->codec->ticks_per_frame;
1358                 ist->next_dts += av_rescale_q(ticks, ist->st->codec->time_base, AV_TIME_BASE_Q);
1359             }
1360             break;
1361         case AVMEDIA_TYPE_SUBTITLE:
1362             ret = transcode_subtitles(ist, &avpkt, &got_output);
1363             break;
1364         default:
1365             return -1;
1366         }
1367
1368         if (ret < 0)
1369             return ret;
1370         // touch data and size only if not EOF
1371         if (pkt) {
1372             avpkt.data += ret;
1373             avpkt.size -= ret;
1374         }
1375         if (!got_output) {
1376             continue;
1377         }
1378     }
1379
1380     /* handle stream copy */
1381     if (!ist->decoding_needed) {
1382         rate_emu_sleep(ist);
1383         ist->last_dts = ist->next_dts;
1384         switch (ist->st->codec->codec_type) {
1385         case AVMEDIA_TYPE_AUDIO:
1386             ist->next_dts += ((int64_t)AV_TIME_BASE * ist->st->codec->frame_size) /
1387                              ist->st->codec->sample_rate;
1388             break;
1389         case AVMEDIA_TYPE_VIDEO:
1390             if (ist->st->codec->time_base.num != 0) {
1391                 int ticks = ist->st->parser ? ist->st->parser->repeat_pict + 1 : ist->st->codec->ticks_per_frame;
1392                 ist->next_dts += ((int64_t)AV_TIME_BASE *
1393                                   ist->st->codec->time_base.num * ticks) /
1394                                   ist->st->codec->time_base.den;
1395             }
1396             break;
1397         }
1398     }
1399     for (i = 0; pkt && i < nb_output_streams; i++) {
1400         OutputStream *ost = output_streams[i];
1401
1402         if (!check_output_constraints(ist, ost) || ost->encoding_needed)
1403             continue;
1404
1405         do_streamcopy(ist, ost, pkt);
1406     }
1407
1408     return 0;
1409 }
1410
1411 static void print_sdp(void)
1412 {
1413     char sdp[2048];
1414     int i;
1415     AVFormatContext **avc = av_malloc(sizeof(*avc) * nb_output_files);
1416
1417     if (!avc)
1418         exit_program(1);
1419     for (i = 0; i < nb_output_files; i++)
1420         avc[i] = output_files[i]->ctx;
1421
1422     av_sdp_create(avc, nb_output_files, sdp, sizeof(sdp));
1423     printf("SDP:\n%s\n", sdp);
1424     fflush(stdout);
1425     av_freep(&avc);
1426 }
1427
1428 static int init_input_stream(int ist_index, char *error, int error_len)
1429 {
1430     int i;
1431     InputStream *ist = input_streams[ist_index];
1432     if (ist->decoding_needed) {
1433         AVCodec *codec = ist->dec;
1434         if (!codec) {
1435             snprintf(error, error_len, "Decoder (codec id %d) not found for input stream #%d:%d",
1436                     ist->st->codec->codec_id, ist->file_index, ist->st->index);
1437             return AVERROR(EINVAL);
1438         }
1439
1440         /* update requested sample format for the decoder based on the
1441            corresponding encoder sample format */
1442         for (i = 0; i < nb_output_streams; i++) {
1443             OutputStream *ost = output_streams[i];
1444             if (ost->source_index == ist_index) {
1445                 update_sample_fmt(ist->st->codec, codec, ost->st->codec);
1446                 break;
1447             }
1448         }
1449
1450         if (codec->type == AVMEDIA_TYPE_VIDEO && codec->capabilities & CODEC_CAP_DR1) {
1451             ist->st->codec->get_buffer     = codec_get_buffer;
1452             ist->st->codec->release_buffer = codec_release_buffer;
1453             ist->st->codec->opaque         = &ist->buffer_pool;
1454         }
1455
1456         if (!av_dict_get(ist->opts, "threads", NULL, 0))
1457             av_dict_set(&ist->opts, "threads", "auto", 0);
1458         if (avcodec_open2(ist->st->codec, codec, &ist->opts) < 0) {
1459             snprintf(error, error_len, "Error while opening decoder for input stream #%d:%d",
1460                     ist->file_index, ist->st->index);
1461             return AVERROR(EINVAL);
1462         }
1463         assert_codec_experimental(ist->st->codec, 0);
1464         assert_avoptions(ist->opts);
1465     }
1466
1467     ist->last_dts = ist->st->avg_frame_rate.num ? - ist->st->codec->has_b_frames * AV_TIME_BASE / av_q2d(ist->st->avg_frame_rate) : 0;
1468     ist->next_dts = AV_NOPTS_VALUE;
1469     init_pts_correction(&ist->pts_ctx);
1470     ist->is_start = 1;
1471
1472     return 0;
1473 }
1474
1475 static InputStream *get_input_stream(OutputStream *ost)
1476 {
1477     if (ost->source_index >= 0)
1478         return input_streams[ost->source_index];
1479
1480     if (ost->filter) {
1481         FilterGraph *fg = ost->filter->graph;
1482         int i;
1483
1484         for (i = 0; i < fg->nb_inputs; i++)
1485             if (fg->inputs[i]->ist->st->codec->codec_type == ost->st->codec->codec_type)
1486                 return fg->inputs[i]->ist;
1487     }
1488
1489     return NULL;
1490 }
1491
1492 static void parse_forced_key_frames(char *kf, OutputStream *ost,
1493                                     AVCodecContext *avctx)
1494 {
1495     char *p;
1496     int n = 1, i;
1497     int64_t t;
1498
1499     for (p = kf; *p; p++)
1500         if (*p == ',')
1501             n++;
1502     ost->forced_kf_count = n;
1503     ost->forced_kf_pts   = av_malloc(sizeof(*ost->forced_kf_pts) * n);
1504     if (!ost->forced_kf_pts) {
1505         av_log(NULL, AV_LOG_FATAL, "Could not allocate forced key frames array.\n");
1506         exit_program(1);
1507     }
1508
1509     p = kf;
1510     for (i = 0; i < n; i++) {
1511         char *next = strchr(p, ',');
1512
1513         if (next)
1514             *next++ = 0;
1515
1516         t = parse_time_or_die("force_key_frames", p, 1);
1517         ost->forced_kf_pts[i] = av_rescale_q(t, AV_TIME_BASE_Q, avctx->time_base);
1518
1519         p = next;
1520     }
1521 }
1522
1523 static int transcode_init(void)
1524 {
1525     int ret = 0, i, j, k;
1526     AVFormatContext *oc;
1527     AVCodecContext *codec, *icodec;
1528     OutputStream *ost;
1529     InputStream *ist;
1530     char error[1024];
1531     int want_sdp = 1;
1532
1533     /* init framerate emulation */
1534     for (i = 0; i < nb_input_files; i++) {
1535         InputFile *ifile = input_files[i];
1536         if (ifile->rate_emu)
1537             for (j = 0; j < ifile->nb_streams; j++)
1538                 input_streams[j + ifile->ist_index]->start = av_gettime();
1539     }
1540
1541     /* output stream init */
1542     for (i = 0; i < nb_output_files; i++) {
1543         oc = output_files[i]->ctx;
1544         if (!oc->nb_streams && !(oc->oformat->flags & AVFMT_NOSTREAMS)) {
1545             av_dump_format(oc, i, oc->filename, 1);
1546             av_log(NULL, AV_LOG_ERROR, "Output file #%d does not contain any stream\n", i);
1547             return AVERROR(EINVAL);
1548         }
1549     }
1550
1551     /* init complex filtergraphs */
1552     for (i = 0; i < nb_filtergraphs; i++)
1553         if ((ret = avfilter_graph_config(filtergraphs[i]->graph, NULL)) < 0)
1554             return ret;
1555
1556     /* for each output stream, we compute the right encoding parameters */
1557     for (i = 0; i < nb_output_streams; i++) {
1558         ost = output_streams[i];
1559         oc  = output_files[ost->file_index]->ctx;
1560         ist = get_input_stream(ost);
1561
1562         if (ost->attachment_filename)
1563             continue;
1564
1565         codec  = ost->st->codec;
1566
1567         if (ist) {
1568             icodec = ist->st->codec;
1569
1570             ost->st->disposition          = ist->st->disposition;
1571             codec->bits_per_raw_sample    = icodec->bits_per_raw_sample;
1572             codec->chroma_sample_location = icodec->chroma_sample_location;
1573         }
1574
1575         if (ost->stream_copy) {
1576             uint64_t extra_size;
1577
1578             av_assert0(ist && !ost->filter);
1579
1580             extra_size = (uint64_t)icodec->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE;
1581
1582             if (extra_size > INT_MAX) {
1583                 return AVERROR(EINVAL);
1584             }
1585
1586             /* if stream_copy is selected, no need to decode or encode */
1587             codec->codec_id   = icodec->codec_id;
1588             codec->codec_type = icodec->codec_type;
1589
1590             if (!codec->codec_tag) {
1591                 if (!oc->oformat->codec_tag ||
1592                      av_codec_get_id (oc->oformat->codec_tag, icodec->codec_tag) == codec->codec_id ||
1593                      av_codec_get_tag(oc->oformat->codec_tag, icodec->codec_id) <= 0)
1594                     codec->codec_tag = icodec->codec_tag;
1595             }
1596
1597             codec->bit_rate       = icodec->bit_rate;
1598             codec->rc_max_rate    = icodec->rc_max_rate;
1599             codec->rc_buffer_size = icodec->rc_buffer_size;
1600             codec->field_order    = icodec->field_order;
1601             codec->extradata      = av_mallocz(extra_size);
1602             if (!codec->extradata) {
1603                 return AVERROR(ENOMEM);
1604             }
1605             memcpy(codec->extradata, icodec->extradata, icodec->extradata_size);
1606             codec->extradata_size = icodec->extradata_size;
1607             if (!copy_tb) {
1608                 codec->time_base      = icodec->time_base;
1609                 codec->time_base.num *= icodec->ticks_per_frame;
1610                 av_reduce(&codec->time_base.num, &codec->time_base.den,
1611                           codec->time_base.num, codec->time_base.den, INT_MAX);
1612             } else
1613                 codec->time_base = ist->st->time_base;
1614
1615             switch (codec->codec_type) {
1616             case AVMEDIA_TYPE_AUDIO:
1617                 if (audio_volume != 256) {
1618                     av_log(NULL, AV_LOG_FATAL, "-acodec copy and -vol are incompatible (frames are not decoded)\n");
1619                     exit_program(1);
1620                 }
1621                 codec->channel_layout     = icodec->channel_layout;
1622                 codec->sample_rate        = icodec->sample_rate;
1623                 codec->channels           = icodec->channels;
1624                 codec->frame_size         = icodec->frame_size;
1625                 codec->audio_service_type = icodec->audio_service_type;
1626                 codec->block_align        = icodec->block_align;
1627                 break;
1628             case AVMEDIA_TYPE_VIDEO:
1629                 codec->pix_fmt            = icodec->pix_fmt;
1630                 codec->width              = icodec->width;
1631                 codec->height             = icodec->height;
1632                 codec->has_b_frames       = icodec->has_b_frames;
1633                 if (!codec->sample_aspect_ratio.num) {
1634                     codec->sample_aspect_ratio   =
1635                     ost->st->sample_aspect_ratio =
1636                         ist->st->sample_aspect_ratio.num ? ist->st->sample_aspect_ratio :
1637                         ist->st->codec->sample_aspect_ratio.num ?
1638                         ist->st->codec->sample_aspect_ratio : (AVRational){0, 1};
1639                 }
1640                 break;
1641             case AVMEDIA_TYPE_SUBTITLE:
1642                 codec->width  = icodec->width;
1643                 codec->height = icodec->height;
1644                 break;
1645             case AVMEDIA_TYPE_DATA:
1646             case AVMEDIA_TYPE_ATTACHMENT:
1647                 break;
1648             default:
1649                 abort();
1650             }
1651         } else {
1652             if (!ost->enc) {
1653                 /* should only happen when a default codec is not present. */
1654                 snprintf(error, sizeof(error), "Automatic encoder selection "
1655                          "failed for output stream #%d:%d. Default encoder for "
1656                          "format %s is probably disabled. Please choose an "
1657                          "encoder manually.\n", ost->file_index, ost->index,
1658                          oc->oformat->name);
1659                 ret = AVERROR(EINVAL);
1660                 goto dump_format;
1661             }
1662
1663             if (ist)
1664                 ist->decoding_needed = 1;
1665             ost->encoding_needed = 1;
1666
1667             /*
1668              * We want CFR output if and only if one of those is true:
1669              * 1) user specified output framerate with -r
1670              * 2) user specified -vsync cfr
1671              * 3) output format is CFR and the user didn't force vsync to
1672              *    something else than CFR
1673              *
1674              * in such a case, set ost->frame_rate
1675              */
1676             if (codec->codec_type == AVMEDIA_TYPE_VIDEO &&
1677                 !ost->frame_rate.num && ist &&
1678                 (video_sync_method ==  VSYNC_CFR ||
1679                  (video_sync_method ==  VSYNC_AUTO &&
1680                   !(oc->oformat->flags & (AVFMT_NOTIMESTAMPS | AVFMT_VARIABLE_FPS))))) {
1681                 ost->frame_rate = ist->st->avg_frame_rate.num ? ist->st->avg_frame_rate : (AVRational){25, 1};
1682                 if (ost->enc && ost->enc->supported_framerates && !ost->force_fps) {
1683                     int idx = av_find_nearest_q_idx(ost->frame_rate, ost->enc->supported_framerates);
1684                     ost->frame_rate = ost->enc->supported_framerates[idx];
1685                 }
1686             }
1687
1688             if (!ost->filter &&
1689                 (codec->codec_type == AVMEDIA_TYPE_VIDEO ||
1690                  codec->codec_type == AVMEDIA_TYPE_AUDIO)) {
1691                     FilterGraph *fg;
1692                     fg = init_simple_filtergraph(ist, ost);
1693                     if (configure_filtergraph(fg)) {
1694                         av_log(NULL, AV_LOG_FATAL, "Error opening filters!\n");
1695                         exit(1);
1696                     }
1697             }
1698
1699             switch (codec->codec_type) {
1700             case AVMEDIA_TYPE_AUDIO:
1701                 codec->sample_fmt     = ost->filter->filter->inputs[0]->format;
1702                 codec->sample_rate    = ost->filter->filter->inputs[0]->sample_rate;
1703                 codec->channel_layout = ost->filter->filter->inputs[0]->channel_layout;
1704                 codec->channels       = av_get_channel_layout_nb_channels(codec->channel_layout);
1705                 codec->time_base      = (AVRational){ 1, codec->sample_rate };
1706                 break;
1707             case AVMEDIA_TYPE_VIDEO:
1708                 codec->time_base = ost->filter->filter->inputs[0]->time_base;
1709
1710                 codec->width  = ost->filter->filter->inputs[0]->w;
1711                 codec->height = ost->filter->filter->inputs[0]->h;
1712                 codec->sample_aspect_ratio = ost->st->sample_aspect_ratio =
1713                     ost->frame_aspect_ratio ? // overridden by the -aspect cli option
1714                     av_d2q(ost->frame_aspect_ratio * codec->height/codec->width, 255) :
1715                     ost->filter->filter->inputs[0]->sample_aspect_ratio;
1716                 codec->pix_fmt = ost->filter->filter->inputs[0]->format;
1717
1718                 if (codec->width   != icodec->width  ||
1719                     codec->height  != icodec->height ||
1720                     codec->pix_fmt != icodec->pix_fmt) {
1721                     codec->bits_per_raw_sample = 0;
1722                 }
1723
1724                 if (ost->forced_keyframes)
1725                     parse_forced_key_frames(ost->forced_keyframes, ost,
1726                                             ost->st->codec);
1727                 break;
1728             case AVMEDIA_TYPE_SUBTITLE:
1729                 codec->time_base = (AVRational){1, 1000};
1730                 break;
1731             default:
1732                 abort();
1733                 break;
1734             }
1735             /* two pass mode */
1736             if ((codec->flags & (CODEC_FLAG_PASS1 | CODEC_FLAG_PASS2))) {
1737                 char logfilename[1024];
1738                 FILE *f;
1739
1740                 snprintf(logfilename, sizeof(logfilename), "%s-%d.log",
1741                          pass_logfilename_prefix ? pass_logfilename_prefix : DEFAULT_PASS_LOGFILENAME_PREFIX,
1742                          i);
1743                 if (!strcmp(ost->enc->name, "libx264")) {
1744                     av_dict_set(&ost->opts, "stats", logfilename, AV_DICT_DONT_OVERWRITE);
1745                 } else {
1746                     if (codec->flags & CODEC_FLAG_PASS1) {
1747                         f = fopen(logfilename, "wb");
1748                         if (!f) {
1749                             av_log(NULL, AV_LOG_FATAL, "Cannot write log file '%s' for pass-1 encoding: %s\n",
1750                                    logfilename, strerror(errno));
1751                             exit_program(1);
1752                         }
1753                         ost->logfile = f;
1754                     } else {
1755                         char  *logbuffer;
1756                         size_t logbuffer_size;
1757                         if (cmdutils_read_file(logfilename, &logbuffer, &logbuffer_size) < 0) {
1758                             av_log(NULL, AV_LOG_FATAL, "Error reading log file '%s' for pass-2 encoding\n",
1759                                    logfilename);
1760                             exit_program(1);
1761                         }
1762                         codec->stats_in = logbuffer;
1763                     }
1764                 }
1765             }
1766         }
1767     }
1768
1769     /* open each encoder */
1770     for (i = 0; i < nb_output_streams; i++) {
1771         ost = output_streams[i];
1772         if (ost->encoding_needed) {
1773             AVCodec      *codec = ost->enc;
1774             AVCodecContext *dec = NULL;
1775
1776             if ((ist = get_input_stream(ost)))
1777                 dec = ist->st->codec;
1778             if (dec && dec->subtitle_header) {
1779                 ost->st->codec->subtitle_header = av_malloc(dec->subtitle_header_size);
1780                 if (!ost->st->codec->subtitle_header) {
1781                     ret = AVERROR(ENOMEM);
1782                     goto dump_format;
1783                 }
1784                 memcpy(ost->st->codec->subtitle_header, dec->subtitle_header, dec->subtitle_header_size);
1785                 ost->st->codec->subtitle_header_size = dec->subtitle_header_size;
1786             }
1787             if (!av_dict_get(ost->opts, "threads", NULL, 0))
1788                 av_dict_set(&ost->opts, "threads", "auto", 0);
1789             if (avcodec_open2(ost->st->codec, codec, &ost->opts) < 0) {
1790                 snprintf(error, sizeof(error), "Error while opening encoder for output stream #%d:%d - maybe incorrect parameters such as bit_rate, rate, width or height",
1791                         ost->file_index, ost->index);
1792                 ret = AVERROR(EINVAL);
1793                 goto dump_format;
1794             }
1795             assert_codec_experimental(ost->st->codec, 1);
1796             assert_avoptions(ost->opts);
1797             if (ost->st->codec->bit_rate && ost->st->codec->bit_rate < 1000)
1798                 av_log(NULL, AV_LOG_WARNING, "The bitrate parameter is set too low."
1799                                              "It takes bits/s as argument, not kbits/s\n");
1800             extra_size += ost->st->codec->extradata_size;
1801
1802             if (ost->st->codec->me_threshold)
1803                 input_streams[ost->source_index]->st->codec->debug |= FF_DEBUG_MV;
1804         }
1805     }
1806
1807     /* init input streams */
1808     for (i = 0; i < nb_input_streams; i++)
1809         if ((ret = init_input_stream(i, error, sizeof(error))) < 0)
1810             goto dump_format;
1811
1812     /* discard unused programs */
1813     for (i = 0; i < nb_input_files; i++) {
1814         InputFile *ifile = input_files[i];
1815         for (j = 0; j < ifile->ctx->nb_programs; j++) {
1816             AVProgram *p = ifile->ctx->programs[j];
1817             int discard  = AVDISCARD_ALL;
1818
1819             for (k = 0; k < p->nb_stream_indexes; k++)
1820                 if (!input_streams[ifile->ist_index + p->stream_index[k]]->discard) {
1821                     discard = AVDISCARD_DEFAULT;
1822                     break;
1823                 }
1824             p->discard = discard;
1825         }
1826     }
1827
1828     /* open files and write file headers */
1829     for (i = 0; i < nb_output_files; i++) {
1830         oc = output_files[i]->ctx;
1831         oc->interrupt_callback = int_cb;
1832         if ((ret = avformat_write_header(oc, &output_files[i]->opts)) < 0) {
1833             char errbuf[128];
1834             const char *errbuf_ptr = errbuf;
1835             if (av_strerror(ret, errbuf, sizeof(errbuf)) < 0)
1836                 errbuf_ptr = strerror(AVUNERROR(ret));
1837             snprintf(error, sizeof(error), "Could not write header for output file #%d (incorrect codec parameters ?): %s", i, errbuf_ptr);
1838             ret = AVERROR(EINVAL);
1839             goto dump_format;
1840         }
1841         assert_avoptions(output_files[i]->opts);
1842         if (strcmp(oc->oformat->name, "rtp")) {
1843             want_sdp = 0;
1844         }
1845     }
1846
1847  dump_format:
1848     /* dump the file output parameters - cannot be done before in case
1849        of stream copy */
1850     for (i = 0; i < nb_output_files; i++) {
1851         av_dump_format(output_files[i]->ctx, i, output_files[i]->ctx->filename, 1);
1852     }
1853
1854     /* dump the stream mapping */
1855     av_log(NULL, AV_LOG_INFO, "Stream mapping:\n");
1856     for (i = 0; i < nb_input_streams; i++) {
1857         ist = input_streams[i];
1858
1859         for (j = 0; j < ist->nb_filters; j++) {
1860             if (ist->filters[j]->graph->graph_desc) {
1861                 av_log(NULL, AV_LOG_INFO, "  Stream #%d:%d (%s) -> %s",
1862                        ist->file_index, ist->st->index, ist->dec ? ist->dec->name : "?",
1863                        ist->filters[j]->name);
1864                 if (nb_filtergraphs > 1)
1865                     av_log(NULL, AV_LOG_INFO, " (graph %d)", ist->filters[j]->graph->index);
1866                 av_log(NULL, AV_LOG_INFO, "\n");
1867             }
1868         }
1869     }
1870
1871     for (i = 0; i < nb_output_streams; i++) {
1872         ost = output_streams[i];
1873
1874         if (ost->attachment_filename) {
1875             /* an attached file */
1876             av_log(NULL, AV_LOG_INFO, "  File %s -> Stream #%d:%d\n",
1877                    ost->attachment_filename, ost->file_index, ost->index);
1878             continue;
1879         }
1880
1881         if (ost->filter && ost->filter->graph->graph_desc) {
1882             /* output from a complex graph */
1883             av_log(NULL, AV_LOG_INFO, "  %s", ost->filter->name);
1884             if (nb_filtergraphs > 1)
1885                 av_log(NULL, AV_LOG_INFO, " (graph %d)", ost->filter->graph->index);
1886
1887             av_log(NULL, AV_LOG_INFO, " -> Stream #%d:%d (%s)\n", ost->file_index,
1888                    ost->index, ost->enc ? ost->enc->name : "?");
1889             continue;
1890         }
1891
1892         av_log(NULL, AV_LOG_INFO, "  Stream #%d:%d -> #%d:%d",
1893                input_streams[ost->source_index]->file_index,
1894                input_streams[ost->source_index]->st->index,
1895                ost->file_index,
1896                ost->index);
1897         if (ost->sync_ist != input_streams[ost->source_index])
1898             av_log(NULL, AV_LOG_INFO, " [sync #%d:%d]",
1899                    ost->sync_ist->file_index,
1900                    ost->sync_ist->st->index);
1901         if (ost->stream_copy)
1902             av_log(NULL, AV_LOG_INFO, " (copy)");
1903         else
1904             av_log(NULL, AV_LOG_INFO, " (%s -> %s)", input_streams[ost->source_index]->dec ?
1905                    input_streams[ost->source_index]->dec->name : "?",
1906                    ost->enc ? ost->enc->name : "?");
1907         av_log(NULL, AV_LOG_INFO, "\n");
1908     }
1909
1910     if (ret) {
1911         av_log(NULL, AV_LOG_ERROR, "%s\n", error);
1912         return ret;
1913     }
1914
1915     if (want_sdp) {
1916         print_sdp();
1917     }
1918
1919     return 0;
1920 }
1921
1922 /**
1923  * @return 1 if there are still streams where more output is wanted,
1924  *         0 otherwise
1925  */
1926 static int need_output(void)
1927 {
1928     int i;
1929
1930     for (i = 0; i < nb_output_streams; i++) {
1931         OutputStream *ost    = output_streams[i];
1932         OutputFile *of       = output_files[ost->file_index];
1933         AVFormatContext *os  = output_files[ost->file_index]->ctx;
1934
1935         if (ost->is_past_recording_time ||
1936             (os->pb && avio_tell(os->pb) >= of->limit_filesize))
1937             continue;
1938         if (ost->frame_number >= ost->max_frames) {
1939             int j;
1940             for (j = 0; j < of->ctx->nb_streams; j++)
1941                 output_streams[of->ost_index + j]->is_past_recording_time = 1;
1942             continue;
1943         }
1944
1945         return 1;
1946     }
1947
1948     return 0;
1949 }
1950
1951 static InputFile *select_input_file(void)
1952 {
1953     InputFile *ifile = NULL;
1954     int64_t ipts_min = INT64_MAX;
1955     int i;
1956
1957     for (i = 0; i < nb_input_streams; i++) {
1958         InputStream *ist = input_streams[i];
1959         int64_t ipts     = ist->last_dts;
1960
1961         if (ist->discard || input_files[ist->file_index]->eagain)
1962             continue;
1963         if (!input_files[ist->file_index]->eof_reached) {
1964             if (ipts < ipts_min) {
1965                 ipts_min = ipts;
1966                 ifile    = input_files[ist->file_index];
1967             }
1968         }
1969     }
1970
1971     return ifile;
1972 }
1973
1974 #if HAVE_PTHREADS
1975 static void *input_thread(void *arg)
1976 {
1977     InputFile *f = arg;
1978     int ret = 0;
1979
1980     while (!transcoding_finished && ret >= 0) {
1981         AVPacket pkt;
1982         ret = av_read_frame(f->ctx, &pkt);
1983
1984         if (ret == AVERROR(EAGAIN)) {
1985             av_usleep(10000);
1986             ret = 0;
1987             continue;
1988         } else if (ret < 0)
1989             break;
1990
1991         pthread_mutex_lock(&f->fifo_lock);
1992         while (!av_fifo_space(f->fifo))
1993             pthread_cond_wait(&f->fifo_cond, &f->fifo_lock);
1994
1995         av_dup_packet(&pkt);
1996         av_fifo_generic_write(f->fifo, &pkt, sizeof(pkt), NULL);
1997
1998         pthread_mutex_unlock(&f->fifo_lock);
1999     }
2000
2001     f->finished = 1;
2002     return NULL;
2003 }
2004
2005 static void free_input_threads(void)
2006 {
2007     int i;
2008
2009     if (nb_input_files == 1)
2010         return;
2011
2012     transcoding_finished = 1;
2013
2014     for (i = 0; i < nb_input_files; i++) {
2015         InputFile *f = input_files[i];
2016         AVPacket pkt;
2017
2018         if (!f->fifo || f->joined)
2019             continue;
2020
2021         pthread_mutex_lock(&f->fifo_lock);
2022         while (av_fifo_size(f->fifo)) {
2023             av_fifo_generic_read(f->fifo, &pkt, sizeof(pkt), NULL);
2024             av_free_packet(&pkt);
2025         }
2026         pthread_cond_signal(&f->fifo_cond);
2027         pthread_mutex_unlock(&f->fifo_lock);
2028
2029         pthread_join(f->thread, NULL);
2030         f->joined = 1;
2031
2032         while (av_fifo_size(f->fifo)) {
2033             av_fifo_generic_read(f->fifo, &pkt, sizeof(pkt), NULL);
2034             av_free_packet(&pkt);
2035         }
2036         av_fifo_free(f->fifo);
2037     }
2038 }
2039
2040 static int init_input_threads(void)
2041 {
2042     int i, ret;
2043
2044     if (nb_input_files == 1)
2045         return 0;
2046
2047     for (i = 0; i < nb_input_files; i++) {
2048         InputFile *f = input_files[i];
2049
2050         if (!(f->fifo = av_fifo_alloc(8*sizeof(AVPacket))))
2051             return AVERROR(ENOMEM);
2052
2053         pthread_mutex_init(&f->fifo_lock, NULL);
2054         pthread_cond_init (&f->fifo_cond, NULL);
2055
2056         if ((ret = pthread_create(&f->thread, NULL, input_thread, f)))
2057             return AVERROR(ret);
2058     }
2059     return 0;
2060 }
2061
2062 static int get_input_packet_mt(InputFile *f, AVPacket *pkt)
2063 {
2064     int ret = 0;
2065
2066     pthread_mutex_lock(&f->fifo_lock);
2067
2068     if (av_fifo_size(f->fifo)) {
2069         av_fifo_generic_read(f->fifo, pkt, sizeof(*pkt), NULL);
2070         pthread_cond_signal(&f->fifo_cond);
2071     } else {
2072         if (f->finished)
2073             ret = AVERROR_EOF;
2074         else
2075             ret = AVERROR(EAGAIN);
2076     }
2077
2078     pthread_mutex_unlock(&f->fifo_lock);
2079
2080     return ret;
2081 }
2082 #endif
2083
2084 static int get_input_packet(InputFile *f, AVPacket *pkt)
2085 {
2086 #if HAVE_PTHREADS
2087     if (nb_input_files > 1)
2088         return get_input_packet_mt(f, pkt);
2089 #endif
2090     return av_read_frame(f->ctx, pkt);
2091 }
2092
2093 static int got_eagain(void)
2094 {
2095     int i;
2096     for (i = 0; i < nb_input_files; i++)
2097         if (input_files[i]->eagain)
2098             return 1;
2099     return 0;
2100 }
2101
2102 static void reset_eagain(void)
2103 {
2104     int i;
2105     for (i = 0; i < nb_input_files; i++)
2106         input_files[i]->eagain = 0;
2107 }
2108
2109 /**
2110  * Read one packet from an input file and send it for
2111  * - decoding -> lavfi (audio/video)
2112  * - decoding -> encoding -> muxing (subtitles)
2113  * - muxing (streamcopy)
2114  *
2115  * @return
2116  * - 0 -- one packet was read and processed
2117  * - AVERROR(EAGAIN) -- no packets were available for selected file,
2118  *   this function should be called again
2119  * - AVERROR_EOF -- this function should not be called again
2120  */
2121 static int process_input(void)
2122 {
2123     InputFile *ifile;
2124     AVFormatContext *is;
2125     InputStream *ist;
2126     AVPacket pkt;
2127     int ret, i, j;
2128
2129     /* select the stream that we must read now */
2130     ifile = select_input_file();
2131     /* if none, if is finished */
2132     if (!ifile) {
2133         if (got_eagain()) {
2134             reset_eagain();
2135             av_usleep(10000);
2136             return AVERROR(EAGAIN);
2137         }
2138         av_log(NULL, AV_LOG_VERBOSE, "No more inputs to read from.\n");
2139         return AVERROR_EOF;
2140     }
2141
2142     is  = ifile->ctx;
2143     ret = get_input_packet(ifile, &pkt);
2144
2145     if (ret == AVERROR(EAGAIN)) {
2146         ifile->eagain = 1;
2147         return ret;
2148     }
2149     if (ret < 0) {
2150         if (ret != AVERROR_EOF) {
2151             print_error(is->filename, ret);
2152             if (exit_on_error)
2153                 exit_program(1);
2154         }
2155         ifile->eof_reached = 1;
2156
2157         for (i = 0; i < ifile->nb_streams; i++) {
2158             ist = input_streams[ifile->ist_index + i];
2159             if (ist->decoding_needed)
2160                 output_packet(ist, NULL);
2161
2162             /* mark all outputs that don't go through lavfi as finished */
2163             for (j = 0; j < nb_output_streams; j++) {
2164                 OutputStream *ost = output_streams[j];
2165
2166                 if (ost->source_index == ifile->ist_index + i &&
2167                     (ost->stream_copy || ost->enc->type == AVMEDIA_TYPE_SUBTITLE))
2168                     ost->is_past_recording_time = 1;
2169             }
2170         }
2171
2172         if (opt_shortest)
2173             return AVERROR_EOF;
2174         else
2175             return AVERROR(EAGAIN);
2176     }
2177
2178     reset_eagain();
2179
2180     if (do_pkt_dump) {
2181         av_pkt_dump_log2(NULL, AV_LOG_DEBUG, &pkt, do_hex_dump,
2182                          is->streams[pkt.stream_index]);
2183     }
2184     /* the following test is needed in case new streams appear
2185        dynamically in stream : we ignore them */
2186     if (pkt.stream_index >= ifile->nb_streams)
2187         goto discard_packet;
2188
2189     ist = input_streams[ifile->ist_index + pkt.stream_index];
2190     if (ist->discard)
2191         goto discard_packet;
2192
2193     if (pkt.dts != AV_NOPTS_VALUE)
2194         pkt.dts += av_rescale_q(ifile->ts_offset, AV_TIME_BASE_Q, ist->st->time_base);
2195     if (pkt.pts != AV_NOPTS_VALUE)
2196         pkt.pts += av_rescale_q(ifile->ts_offset, AV_TIME_BASE_Q, ist->st->time_base);
2197
2198     if (pkt.pts != AV_NOPTS_VALUE)
2199         pkt.pts *= ist->ts_scale;
2200     if (pkt.dts != AV_NOPTS_VALUE)
2201         pkt.dts *= ist->ts_scale;
2202
2203     if (pkt.dts != AV_NOPTS_VALUE && ist->next_dts != AV_NOPTS_VALUE &&
2204         (is->iformat->flags & AVFMT_TS_DISCONT)) {
2205         int64_t pkt_dts = av_rescale_q(pkt.dts, ist->st->time_base, AV_TIME_BASE_Q);
2206         int64_t delta   = pkt_dts - ist->next_dts;
2207
2208         if ((FFABS(delta) > 1LL * dts_delta_threshold * AV_TIME_BASE || pkt_dts + 1 < ist->last_dts) && !copy_ts) {
2209             ifile->ts_offset -= delta;
2210             av_log(NULL, AV_LOG_DEBUG,
2211                    "timestamp discontinuity %"PRId64", new offset= %"PRId64"\n",
2212                    delta, ifile->ts_offset);
2213             pkt.dts -= av_rescale_q(delta, AV_TIME_BASE_Q, ist->st->time_base);
2214             if (pkt.pts != AV_NOPTS_VALUE)
2215                 pkt.pts -= av_rescale_q(delta, AV_TIME_BASE_Q, ist->st->time_base);
2216         }
2217     }
2218
2219     ret = output_packet(ist, &pkt);
2220     if (ret < 0) {
2221         av_log(NULL, AV_LOG_ERROR, "Error while decoding stream #%d:%d\n",
2222                ist->file_index, ist->st->index);
2223         if (exit_on_error)
2224             exit_program(1);
2225     }
2226
2227 discard_packet:
2228     av_free_packet(&pkt);
2229
2230     return 0;
2231 }
2232
2233 /*
2234  * The following code is the main loop of the file converter
2235  */
2236 static int transcode(void)
2237 {
2238     int ret, i, need_input = 1;
2239     AVFormatContext *os;
2240     OutputStream *ost;
2241     InputStream *ist;
2242     int64_t timer_start;
2243
2244     ret = transcode_init();
2245     if (ret < 0)
2246         goto fail;
2247
2248     av_log(NULL, AV_LOG_INFO, "Press ctrl-c to stop encoding\n");
2249     term_init();
2250
2251     timer_start = av_gettime();
2252
2253 #if HAVE_PTHREADS
2254     if ((ret = init_input_threads()) < 0)
2255         goto fail;
2256 #endif
2257
2258     while (!received_sigterm) {
2259         /* check if there's any stream where output is still needed */
2260         if (!need_output()) {
2261             av_log(NULL, AV_LOG_VERBOSE, "No more output streams to write to, finishing.\n");
2262             break;
2263         }
2264
2265         /* read and process one input packet if needed */
2266         if (need_input) {
2267             ret = process_input();
2268             if (ret == AVERROR_EOF)
2269                 need_input = 0;
2270         }
2271
2272         ret = poll_filters();
2273         if (ret < 0) {
2274             if (ret == AVERROR_EOF || ret == AVERROR(EAGAIN))
2275                 continue;
2276
2277             av_log(NULL, AV_LOG_ERROR, "Error while filtering.\n");
2278             break;
2279         }
2280
2281         /* dump report by using the output first video and audio streams */
2282         print_report(0, timer_start);
2283     }
2284 #if HAVE_PTHREADS
2285     free_input_threads();
2286 #endif
2287
2288     /* at the end of stream, we must flush the decoder buffers */
2289     for (i = 0; i < nb_input_streams; i++) {
2290         ist = input_streams[i];
2291         if (!input_files[ist->file_index]->eof_reached && ist->decoding_needed) {
2292             output_packet(ist, NULL);
2293         }
2294     }
2295     poll_filters();
2296     flush_encoders();
2297
2298     term_exit();
2299
2300     /* write the trailer if needed and close file */
2301     for (i = 0; i < nb_output_files; i++) {
2302         os = output_files[i]->ctx;
2303         av_write_trailer(os);
2304     }
2305
2306     /* dump report by using the first video and audio streams */
2307     print_report(1, timer_start);
2308
2309     /* close each encoder */
2310     for (i = 0; i < nb_output_streams; i++) {
2311         ost = output_streams[i];
2312         if (ost->encoding_needed) {
2313             av_freep(&ost->st->codec->stats_in);
2314             avcodec_close(ost->st->codec);
2315         }
2316     }
2317
2318     /* close each decoder */
2319     for (i = 0; i < nb_input_streams; i++) {
2320         ist = input_streams[i];
2321         if (ist->decoding_needed) {
2322             avcodec_close(ist->st->codec);
2323         }
2324     }
2325
2326     /* finished ! */
2327     ret = 0;
2328
2329  fail:
2330 #if HAVE_PTHREADS
2331     free_input_threads();
2332 #endif
2333
2334     if (output_streams) {
2335         for (i = 0; i < nb_output_streams; i++) {
2336             ost = output_streams[i];
2337             if (ost) {
2338                 if (ost->stream_copy)
2339                     av_freep(&ost->st->codec->extradata);
2340                 if (ost->logfile) {
2341                     fclose(ost->logfile);
2342                     ost->logfile = NULL;
2343                 }
2344                 av_freep(&ost->st->codec->subtitle_header);
2345                 av_free(ost->forced_kf_pts);
2346                 av_dict_free(&ost->opts);
2347             }
2348         }
2349     }
2350     return ret;
2351 }
2352
2353 static int64_t getutime(void)
2354 {
2355 #if HAVE_GETRUSAGE
2356     struct rusage rusage;
2357
2358     getrusage(RUSAGE_SELF, &rusage);
2359     return (rusage.ru_utime.tv_sec * 1000000LL) + rusage.ru_utime.tv_usec;
2360 #elif HAVE_GETPROCESSTIMES
2361     HANDLE proc;
2362     FILETIME c, e, k, u;
2363     proc = GetCurrentProcess();
2364     GetProcessTimes(proc, &c, &e, &k, &u);
2365     return ((int64_t) u.dwHighDateTime << 32 | u.dwLowDateTime) / 10;
2366 #else
2367     return av_gettime();
2368 #endif
2369 }
2370
2371 static int64_t getmaxrss(void)
2372 {
2373 #if HAVE_GETRUSAGE && HAVE_STRUCT_RUSAGE_RU_MAXRSS
2374     struct rusage rusage;
2375     getrusage(RUSAGE_SELF, &rusage);
2376     return (int64_t)rusage.ru_maxrss * 1024;
2377 #elif HAVE_GETPROCESSMEMORYINFO
2378     HANDLE proc;
2379     PROCESS_MEMORY_COUNTERS memcounters;
2380     proc = GetCurrentProcess();
2381     memcounters.cb = sizeof(memcounters);
2382     GetProcessMemoryInfo(proc, &memcounters, sizeof(memcounters));
2383     return memcounters.PeakPagefileUsage;
2384 #else
2385     return 0;
2386 #endif
2387 }
2388
2389 static void parse_cpuflags(int argc, char **argv, const OptionDef *options)
2390 {
2391     int idx = locate_option(argc, argv, options, "cpuflags");
2392     if (idx && argv[idx + 1])
2393         opt_cpuflags("cpuflags", argv[idx + 1]);
2394 }
2395
2396 int main(int argc, char **argv)
2397 {
2398     OptionsContext o = { 0 };
2399     int64_t ti;
2400
2401     reset_options(&o);
2402
2403     av_log_set_flags(AV_LOG_SKIP_REPEATED);
2404     parse_loglevel(argc, argv, options);
2405
2406     avcodec_register_all();
2407 #if CONFIG_AVDEVICE
2408     avdevice_register_all();
2409 #endif
2410     avfilter_register_all();
2411     av_register_all();
2412     avformat_network_init();
2413
2414     show_banner();
2415
2416     parse_cpuflags(argc, argv, options);
2417
2418     /* parse options */
2419     parse_options(&o, argc, argv, options, opt_output_file);
2420
2421     if (nb_output_files <= 0 && nb_input_files == 0) {
2422         show_usage();
2423         av_log(NULL, AV_LOG_WARNING, "Use -h to get full help or, even better, run 'man %s'\n", program_name);
2424         exit_program(1);
2425     }
2426
2427     /* file converter / grab */
2428     if (nb_output_files <= 0) {
2429         fprintf(stderr, "At least one output file must be specified\n");
2430         exit_program(1);
2431     }
2432
2433     if (nb_input_files == 0) {
2434         av_log(NULL, AV_LOG_FATAL, "At least one input file must be specified\n");
2435         exit_program(1);
2436     }
2437
2438     ti = getutime();
2439     if (transcode() < 0)
2440         exit_program(1);
2441     ti = getutime() - ti;
2442     if (do_benchmark) {
2443         int maxrss = getmaxrss() / 1024;
2444         printf("bench: utime=%0.3fs maxrss=%ikB\n", ti / 1000000.0, maxrss);
2445     }
2446
2447     exit_program(0);
2448     return 0;
2449 }