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