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