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