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