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