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