aarch64: Add assembly support for -fsanitize=hwaddress tagged globals.
[libav.git] / avtools / avconv.c
blob3abb7f872f37376c7b66a0a8e1c9769130a9e976
1 /*
2 * avconv main
3 * Copyright (c) 2000-2011 The Libav developers
5 * This file is part of Libav.
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.
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.
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
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>
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"
53 # include "libavfilter/avfilter.h"
54 # include "libavfilter/buffersrc.h"
55 # include "libavfilter/buffersink.h"
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
69 #if HAVE_SYS_SELECT_H
70 #include <sys/select.h>
71 #endif
73 #if HAVE_PTHREADS
74 #include <pthread.h>
75 #endif
77 #include <time.h>
79 #include "avconv.h"
80 #include "cmdutils.h"
82 #include "libavutil/avassert.h"
84 const char program_name[] = "avconv";
85 const int program_birth_year = 2000;
87 static FILE *vstats_file;
89 static int nb_frames_drop = 0;
91 static int want_sdp = 1;
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
98 InputStream **input_streams = NULL;
99 int nb_input_streams = 0;
100 InputFile **input_files = NULL;
101 int nb_input_files = 0;
103 OutputStream **output_streams = NULL;
104 int nb_output_streams = 0;
105 OutputFile **output_files = NULL;
106 int nb_output_files = 0;
108 FilterGraph **filtergraphs;
109 int nb_filtergraphs;
111 static void term_exit(void)
113 av_log(NULL, AV_LOG_QUIET, "");
116 static volatile int received_sigterm = 0;
117 static volatile int received_nb_signals = 0;
119 static void
120 sigterm_handler(int sig)
122 received_sigterm = sig;
123 received_nb_signals++;
124 term_exit();
127 static void term_init(void)
129 signal(SIGINT , sigterm_handler); /* Interrupt (ANSI). */
130 signal(SIGTERM, sigterm_handler); /* Termination (ANSI). */
131 #ifdef SIGXCPU
132 signal(SIGXCPU, sigterm_handler);
133 #endif
136 static int decode_interrupt_cb(void *ctx)
138 return received_nb_signals > 1;
141 const AVIOInterruptCB int_cb = { decode_interrupt_cb, NULL };
143 static void avconv_cleanup(int ret)
145 int i, j;
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);
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]);
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]);
170 av_freep(&fg->outputs);
171 av_freep(&fg->graph_desc);
173 av_freep(&filtergraphs[i]);
175 av_freep(&filtergraphs);
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);
186 av_freep(&output_files[i]);
188 for (i = 0; i < nb_output_streams; i++) {
189 OutputStream *ost = output_streams[i];
191 for (j = 0; j < ost->nb_bitstream_filters; j++)
192 av_bsf_free(&ost->bsf_ctx[j]);
193 av_freep(&ost->bsf_ctx);
195 av_frame_free(&ost->filtered_frame);
197 av_parser_close(ost->parser);
198 avcodec_free_context(&ost->parser_avctx);
200 av_freep(&ost->forced_keyframes);
201 av_freep(&ost->avfilter);
202 av_freep(&ost->logfile_prefix);
204 avcodec_free_context(&ost->enc_ctx);
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);
212 av_fifo_free(ost->muxing_queue);
214 av_freep(&output_streams[i]);
216 for (i = 0; i < nb_input_files; i++) {
217 avformat_close_input(&input_files[i]->ctx);
218 av_freep(&input_files[i]);
220 for (i = 0; i < nb_input_streams; i++) {
221 InputStream *ist = input_streams[i];
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);
229 avcodec_free_context(&ist->dec_ctx);
231 av_freep(&input_streams[i]);
234 if (vstats_file)
235 fclose(vstats_file);
236 av_free(vstats_filename);
238 av_freep(&input_streams);
239 av_freep(&input_files);
240 av_freep(&output_streams);
241 av_freep(&output_files);
243 uninit_opts();
245 avformat_network_deinit();
247 if (received_sigterm) {
248 av_log(NULL, AV_LOG_INFO, "Received signal %d: terminating.\n",
249 (int) received_sigterm);
250 exit (255);
254 void assert_avoptions(AVDictionary *m)
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);
263 static void abort_codec_experimental(AVCodec *c, int encoder)
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);
277 static void write_packet(OutputFile *of, AVPacket *pkt, OutputStream *ost)
279 AVFormatContext *s = of->ctx;
280 AVStream *st = ost->st;
281 int ret;
283 if (!of->header_written) {
284 AVPacket tmp_pkt = {0};
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);
295 ret = av_fifo_realloc2(ost->muxing_queue, new_size);
296 if (ret < 0)
297 exit_program(1);
299 ret = av_packet_ref(&tmp_pkt, pkt);
300 if (ret < 0)
301 exit_program(1);
302 av_fifo_generic_write(ost->muxing_queue, &tmp_pkt, sizeof(tmp_pkt), NULL);
303 av_packet_unref(pkt);
304 return;
308 * Audio encoders may split the packets -- #frames in != #packets out.
309 * But there is no reordering, so we can limit the number of output packets
310 * by simply dropping them here.
311 * Counting encoded video frames needs to be done separately because of
312 * reordering, see do_video_out()
314 if (!(st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO && ost->encoding_needed)) {
315 if (ost->frame_number >= ost->max_frames) {
316 av_packet_unref(pkt);
317 return;
319 ost->frame_number++;
321 if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
322 uint8_t *sd = av_packet_get_side_data(pkt, AV_PKT_DATA_QUALITY_FACTOR,
323 NULL);
324 ost->quality = sd ? *(int *)sd : -1;
326 if (ost->frame_rate.num) {
327 pkt->duration = av_rescale_q(1, av_inv_q(ost->frame_rate),
328 ost->mux_timebase);
332 av_packet_rescale_ts(pkt, ost->mux_timebase, ost->st->time_base);
334 if (!(s->oformat->flags & AVFMT_NOTIMESTAMPS) &&
335 ost->last_mux_dts != AV_NOPTS_VALUE &&
336 pkt->dts < ost->last_mux_dts + !(s->oformat->flags & AVFMT_TS_NONSTRICT)) {
337 av_log(NULL, AV_LOG_WARNING, "Non-monotonous DTS in output stream "
338 "%d:%d; previous: %"PRId64", current: %"PRId64"; ",
339 ost->file_index, ost->st->index, ost->last_mux_dts, pkt->dts);
340 if (exit_on_error) {
341 av_log(NULL, AV_LOG_FATAL, "aborting.\n");
342 exit_program(1);
344 av_log(NULL, AV_LOG_WARNING, "changing to %"PRId64". This may result "
345 "in incorrect timestamps in the output file.\n",
346 ost->last_mux_dts + 1);
347 pkt->dts = ost->last_mux_dts + 1;
348 if (pkt->pts != AV_NOPTS_VALUE)
349 pkt->pts = FFMAX(pkt->pts, pkt->dts);
351 ost->last_mux_dts = pkt->dts;
353 ost->data_size += pkt->size;
354 ost->packets_written++;
356 pkt->stream_index = ost->index;
358 ret = av_interleaved_write_frame(s, pkt);
359 if (ret < 0) {
360 print_error("av_interleaved_write_frame()", ret);
361 exit_program(1);
365 static void output_packet(OutputFile *of, AVPacket *pkt,
366 OutputStream *ost, int eof)
368 int ret = 0;
370 /* apply the output bitstream filters, if any */
371 if (ost->nb_bitstream_filters) {
372 int idx;
374 ret = av_bsf_send_packet(ost->bsf_ctx[0], eof ? NULL : pkt);
375 if (ret < 0)
376 goto finish;
378 eof = 0;
379 idx = 1;
380 while (idx) {
381 /* get a packet from the previous filter up the chain */
382 ret = av_bsf_receive_packet(ost->bsf_ctx[idx - 1], pkt);
383 if (ret == AVERROR(EAGAIN)) {
384 ret = 0;
385 idx--;
386 continue;
387 } else if (ret == AVERROR_EOF) {
388 eof = 1;
389 } else if (ret < 0)
390 goto finish;
392 /* send it to the next filter down the chain or to the muxer */
393 if (idx < ost->nb_bitstream_filters) {
394 ret = av_bsf_send_packet(ost->bsf_ctx[idx], eof ? NULL : pkt);
395 if (ret < 0)
396 goto finish;
397 idx++;
398 eof = 0;
399 } else if (eof)
400 goto finish;
401 else
402 write_packet(of, pkt, ost);
404 } else if (!eof)
405 write_packet(of, pkt, ost);
407 finish:
408 if (ret < 0 && ret != AVERROR_EOF) {
409 av_log(NULL, AV_LOG_FATAL, "Error applying bitstream filters to an output "
410 "packet for stream #%d:%d.\n", ost->file_index, ost->index);
411 exit_program(1);
415 static int check_recording_time(OutputStream *ost)
417 OutputFile *of = output_files[ost->file_index];
419 if (of->recording_time != INT64_MAX &&
420 av_compare_ts(ost->sync_opts - ost->first_pts, ost->enc_ctx->time_base, of->recording_time,
421 AV_TIME_BASE_Q) >= 0) {
422 ost->finished = 1;
423 return 0;
425 return 1;
428 static void do_audio_out(OutputFile *of, OutputStream *ost,
429 AVFrame *frame)
431 AVCodecContext *enc = ost->enc_ctx;
432 AVPacket pkt;
433 int ret;
435 av_init_packet(&pkt);
436 pkt.data = NULL;
437 pkt.size = 0;
439 if (frame->pts == AV_NOPTS_VALUE || audio_sync_method < 0)
440 frame->pts = ost->sync_opts;
441 ost->sync_opts = frame->pts + frame->nb_samples;
443 ost->samples_encoded += frame->nb_samples;
444 ost->frames_encoded++;
446 ret = avcodec_send_frame(enc, frame);
447 if (ret < 0)
448 goto error;
450 while (1) {
451 ret = avcodec_receive_packet(enc, &pkt);
452 if (ret == AVERROR(EAGAIN))
453 break;
454 if (ret < 0)
455 goto error;
457 output_packet(of, &pkt, ost, 0);
460 return;
461 error:
462 av_log(NULL, AV_LOG_FATAL, "Audio encoding failed\n");
463 exit_program(1);
466 static void do_subtitle_out(OutputFile *of,
467 OutputStream *ost,
468 InputStream *ist,
469 AVSubtitle *sub,
470 int64_t pts)
472 static uint8_t *subtitle_out = NULL;
473 int subtitle_out_max_size = 1024 * 1024;
474 int subtitle_out_size, nb, i;
475 AVCodecContext *enc;
476 AVPacket pkt;
478 if (pts == AV_NOPTS_VALUE) {
479 av_log(NULL, AV_LOG_ERROR, "Subtitle packets must have a pts\n");
480 if (exit_on_error)
481 exit_program(1);
482 return;
485 enc = ost->enc_ctx;
487 if (!subtitle_out) {
488 subtitle_out = av_malloc(subtitle_out_max_size);
491 /* Note: DVB subtitle need one packet to draw them and one other
492 packet to clear them */
493 /* XXX: signal it in the codec context ? */
494 if (enc->codec_id == AV_CODEC_ID_DVB_SUBTITLE)
495 nb = 2;
496 else
497 nb = 1;
499 for (i = 0; i < nb; i++) {
500 ost->sync_opts = av_rescale_q(pts, ist->st->time_base, enc->time_base);
501 if (!check_recording_time(ost))
502 return;
504 sub->pts = av_rescale_q(pts, ist->st->time_base, AV_TIME_BASE_Q);
505 // start_display_time is required to be 0
506 sub->pts += av_rescale_q(sub->start_display_time, (AVRational){ 1, 1000 }, AV_TIME_BASE_Q);
507 sub->end_display_time -= sub->start_display_time;
508 sub->start_display_time = 0;
510 ost->frames_encoded++;
512 subtitle_out_size = avcodec_encode_subtitle(enc, subtitle_out,
513 subtitle_out_max_size, sub);
514 if (subtitle_out_size < 0) {
515 av_log(NULL, AV_LOG_FATAL, "Subtitle encoding failed\n");
516 exit_program(1);
519 av_init_packet(&pkt);
520 pkt.data = subtitle_out;
521 pkt.size = subtitle_out_size;
522 pkt.pts = av_rescale_q(sub->pts, AV_TIME_BASE_Q, ost->mux_timebase);
523 if (enc->codec_id == AV_CODEC_ID_DVB_SUBTITLE) {
524 /* XXX: the pts correction is handled here. Maybe handling
525 it in the codec would be better */
526 if (i == 0)
527 pkt.pts += 90 * sub->start_display_time;
528 else
529 pkt.pts += 90 * sub->end_display_time;
531 output_packet(of, &pkt, ost, 0);
535 static void do_video_out(OutputFile *of,
536 OutputStream *ost,
537 AVFrame *in_picture,
538 int *frame_size)
540 int ret, format_video_sync;
541 AVPacket pkt;
542 AVCodecContext *enc = ost->enc_ctx;
544 *frame_size = 0;
546 format_video_sync = video_sync_method;
547 if (format_video_sync == VSYNC_AUTO)
548 format_video_sync = (of->ctx->oformat->flags & AVFMT_NOTIMESTAMPS) ? VSYNC_PASSTHROUGH :
549 (of->ctx->oformat->flags & AVFMT_VARIABLE_FPS) ? VSYNC_VFR : VSYNC_CFR;
550 if (format_video_sync != VSYNC_PASSTHROUGH &&
551 ost->frame_number &&
552 in_picture->pts != AV_NOPTS_VALUE &&
553 in_picture->pts < ost->sync_opts) {
554 nb_frames_drop++;
555 av_log(NULL, AV_LOG_WARNING,
556 "*** dropping frame %d from stream %d at ts %"PRId64"\n",
557 ost->frame_number, ost->st->index, in_picture->pts);
558 return;
561 if (in_picture->pts == AV_NOPTS_VALUE)
562 in_picture->pts = ost->sync_opts;
563 ost->sync_opts = in_picture->pts;
566 if (!ost->frame_number)
567 ost->first_pts = in_picture->pts;
569 av_init_packet(&pkt);
570 pkt.data = NULL;
571 pkt.size = 0;
573 if (ost->frame_number >= ost->max_frames)
574 return;
576 if (enc->flags & (AV_CODEC_FLAG_INTERLACED_DCT | AV_CODEC_FLAG_INTERLACED_ME) &&
577 ost->top_field_first >= 0)
578 in_picture->top_field_first = !!ost->top_field_first;
580 in_picture->quality = enc->global_quality;
581 in_picture->pict_type = 0;
582 if (ost->forced_kf_index < ost->forced_kf_count &&
583 in_picture->pts >= ost->forced_kf_pts[ost->forced_kf_index]) {
584 in_picture->pict_type = AV_PICTURE_TYPE_I;
585 ost->forced_kf_index++;
588 ost->frames_encoded++;
590 ret = avcodec_send_frame(enc, in_picture);
591 if (ret < 0)
592 goto error;
595 * For video, there may be reordering, so we can't throw away frames on
596 * encoder flush, we need to limit them here, before they go into encoder.
598 ost->frame_number++;
600 while (1) {
601 ret = avcodec_receive_packet(enc, &pkt);
602 if (ret == AVERROR(EAGAIN))
603 break;
604 if (ret < 0)
605 goto error;
607 output_packet(of, &pkt, ost, 0);
608 *frame_size = pkt.size;
610 /* if two pass, output log */
611 if (ost->logfile && enc->stats_out) {
612 fprintf(ost->logfile, "%s", enc->stats_out);
615 ost->sync_opts++;
618 return;
619 error:
620 av_assert0(ret != AVERROR(EAGAIN) && ret != AVERROR_EOF);
621 av_log(NULL, AV_LOG_FATAL, "Video encoding failed\n");
622 exit_program(1);
625 #if FF_API_CODED_FRAME && FF_API_ERROR_FRAME
626 static double psnr(double d)
628 return -10.0 * log(d) / log(10.0);
630 #endif
632 static void do_video_stats(OutputStream *ost, int frame_size)
634 AVCodecContext *enc;
635 int frame_number;
636 double ti1, bitrate, avg_bitrate;
638 /* this is executed just the first time do_video_stats is called */
639 if (!vstats_file) {
640 vstats_file = fopen(vstats_filename, "w");
641 if (!vstats_file) {
642 perror("fopen");
643 exit_program(1);
647 enc = ost->enc_ctx;
648 if (enc->codec_type == AVMEDIA_TYPE_VIDEO) {
649 frame_number = ost->frame_number;
650 fprintf(vstats_file, "frame= %5d q= %2.1f ", frame_number,
651 ost->quality / (float)FF_QP2LAMBDA);
653 #if FF_API_CODED_FRAME && FF_API_ERROR_FRAME
654 FF_DISABLE_DEPRECATION_WARNINGS
655 if (enc->flags & AV_CODEC_FLAG_PSNR)
656 fprintf(vstats_file, "PSNR= %6.2f ", psnr(enc->coded_frame->error[0] / (enc->width * enc->height * 255.0 * 255.0)));
657 FF_ENABLE_DEPRECATION_WARNINGS
658 #endif
660 fprintf(vstats_file,"f_size= %6d ", frame_size);
661 /* compute pts value */
662 ti1 = ost->sync_opts * av_q2d(enc->time_base);
663 if (ti1 < 0.01)
664 ti1 = 0.01;
666 bitrate = (frame_size * 8) / av_q2d(enc->time_base) / 1000.0;
667 avg_bitrate = (double)(ost->data_size * 8) / ti1 / 1000.0;
668 fprintf(vstats_file, "s_size= %8.0fkB time= %0.3f br= %7.1fkbits/s avg_br= %7.1fkbits/s ",
669 (double)ost->data_size / 1024, ti1, bitrate, avg_bitrate);
670 #if FF_API_CODED_FRAME
671 FF_DISABLE_DEPRECATION_WARNINGS
672 fprintf(vstats_file, "type= %c\n", av_get_picture_type_char(enc->coded_frame->pict_type));
673 FF_ENABLE_DEPRECATION_WARNINGS
674 #endif
678 static int init_output_stream(OutputStream *ost, char *error, int error_len);
681 * Read one frame for lavfi output for ost and encode it.
683 static int poll_filter(OutputStream *ost)
685 OutputFile *of = output_files[ost->file_index];
686 AVFrame *filtered_frame = NULL;
687 int frame_size, ret;
689 if (!ost->filtered_frame && !(ost->filtered_frame = av_frame_alloc())) {
690 return AVERROR(ENOMEM);
692 filtered_frame = ost->filtered_frame;
694 if (!ost->initialized) {
695 char error[1024];
696 ret = init_output_stream(ost, error, sizeof(error));
697 if (ret < 0) {
698 av_log(NULL, AV_LOG_ERROR, "Error initializing output stream %d:%d -- %s\n",
699 ost->file_index, ost->index, error);
700 exit_program(1);
704 if (ost->enc->type == AVMEDIA_TYPE_AUDIO &&
705 !(ost->enc->capabilities & AV_CODEC_CAP_VARIABLE_FRAME_SIZE))
706 ret = av_buffersink_get_samples(ost->filter->filter, filtered_frame,
707 ost->enc_ctx->frame_size);
708 else
709 ret = av_buffersink_get_frame(ost->filter->filter, filtered_frame);
711 if (ret < 0)
712 return ret;
714 if (filtered_frame->pts != AV_NOPTS_VALUE) {
715 int64_t start_time = (of->start_time == AV_NOPTS_VALUE) ? 0 : of->start_time;
716 filtered_frame->pts = av_rescale_q(filtered_frame->pts,
717 ost->filter->filter->inputs[0]->time_base,
718 ost->enc_ctx->time_base) -
719 av_rescale_q(start_time,
720 AV_TIME_BASE_Q,
721 ost->enc_ctx->time_base);
724 switch (ost->filter->filter->inputs[0]->type) {
725 case AVMEDIA_TYPE_VIDEO:
726 if (!ost->frame_aspect_ratio)
727 ost->enc_ctx->sample_aspect_ratio = filtered_frame->sample_aspect_ratio;
729 do_video_out(of, ost, filtered_frame, &frame_size);
730 if (vstats_filename && frame_size)
731 do_video_stats(ost, frame_size);
732 break;
733 case AVMEDIA_TYPE_AUDIO:
734 do_audio_out(of, ost, filtered_frame);
735 break;
736 default:
737 // TODO support subtitle filters
738 av_assert0(0);
741 av_frame_unref(filtered_frame);
743 return 0;
746 static void finish_output_stream(OutputStream *ost)
748 OutputFile *of = output_files[ost->file_index];
749 int i;
751 ost->finished = 1;
753 if (of->shortest) {
754 for (i = 0; i < of->ctx->nb_streams; i++)
755 output_streams[of->ost_index + i]->finished = 1;
760 * Read as many frames from possible from lavfi and encode them.
762 * Always read from the active stream with the lowest timestamp. If no frames
763 * are available for it then return EAGAIN and wait for more input. This way we
764 * can use lavfi sources that generate unlimited amount of frames without memory
765 * usage exploding.
767 static int poll_filters(void)
769 int i, ret = 0;
771 while (ret >= 0 && !received_sigterm) {
772 OutputStream *ost = NULL;
773 int64_t min_pts = INT64_MAX;
775 /* choose output stream with the lowest timestamp */
776 for (i = 0; i < nb_output_streams; i++) {
777 int64_t pts = output_streams[i]->sync_opts;
779 if (output_streams[i]->filter && !output_streams[i]->filter->graph->graph &&
780 !output_streams[i]->filter->graph->nb_inputs) {
781 ret = configure_filtergraph(output_streams[i]->filter->graph);
782 if (ret < 0) {
783 av_log(NULL, AV_LOG_ERROR, "Error reinitializing filters!\n");
784 return ret;
788 if (!output_streams[i]->filter || output_streams[i]->finished ||
789 !output_streams[i]->filter->graph->graph)
790 continue;
792 pts = av_rescale_q(pts, output_streams[i]->enc_ctx->time_base,
793 AV_TIME_BASE_Q);
794 if (pts < min_pts) {
795 min_pts = pts;
796 ost = output_streams[i];
800 if (!ost)
801 break;
803 ret = poll_filter(ost);
805 if (ret == AVERROR_EOF) {
806 finish_output_stream(ost);
807 ret = 0;
808 } else if (ret == AVERROR(EAGAIN))
809 return 0;
812 return ret;
815 static void print_final_stats(int64_t total_size)
817 uint64_t video_size = 0, audio_size = 0, extra_size = 0, other_size = 0;
818 uint64_t data_size = 0;
819 float percent = -1.0;
820 int i, j;
822 for (i = 0; i < nb_output_streams; i++) {
823 OutputStream *ost = output_streams[i];
824 switch (ost->enc_ctx->codec_type) {
825 case AVMEDIA_TYPE_VIDEO: video_size += ost->data_size; break;
826 case AVMEDIA_TYPE_AUDIO: audio_size += ost->data_size; break;
827 default: other_size += ost->data_size; break;
829 extra_size += ost->enc_ctx->extradata_size;
830 data_size += ost->data_size;
833 if (data_size && total_size >= data_size)
834 percent = 100.0 * (total_size - data_size) / data_size;
836 av_log(NULL, AV_LOG_INFO, "\n");
837 av_log(NULL, AV_LOG_INFO, "video:%1.0fkB audio:%1.0fkB other streams:%1.0fkB global headers:%1.0fkB muxing overhead: ",
838 video_size / 1024.0,
839 audio_size / 1024.0,
840 other_size / 1024.0,
841 extra_size / 1024.0);
842 if (percent >= 0.0)
843 av_log(NULL, AV_LOG_INFO, "%f%%", percent);
844 else
845 av_log(NULL, AV_LOG_INFO, "unknown");
846 av_log(NULL, AV_LOG_INFO, "\n");
848 /* print verbose per-stream stats */
849 for (i = 0; i < nb_input_files; i++) {
850 InputFile *f = input_files[i];
851 uint64_t total_packets = 0, total_size = 0;
853 av_log(NULL, AV_LOG_VERBOSE, "Input file #%d (%s):\n",
854 i, f->ctx->filename);
856 for (j = 0; j < f->nb_streams; j++) {
857 InputStream *ist = input_streams[f->ist_index + j];
858 enum AVMediaType type = ist->dec_ctx->codec_type;
860 total_size += ist->data_size;
861 total_packets += ist->nb_packets;
863 av_log(NULL, AV_LOG_VERBOSE, " Input stream #%d:%d (%s): ",
864 i, j, media_type_string(type));
865 av_log(NULL, AV_LOG_VERBOSE, "%"PRIu64" packets read (%"PRIu64" bytes); ",
866 ist->nb_packets, ist->data_size);
868 if (ist->decoding_needed) {
869 av_log(NULL, AV_LOG_VERBOSE, "%"PRIu64" frames decoded",
870 ist->frames_decoded);
871 if (type == AVMEDIA_TYPE_AUDIO)
872 av_log(NULL, AV_LOG_VERBOSE, " (%"PRIu64" samples)", ist->samples_decoded);
873 av_log(NULL, AV_LOG_VERBOSE, "; ");
876 av_log(NULL, AV_LOG_VERBOSE, "\n");
879 av_log(NULL, AV_LOG_VERBOSE, " Total: %"PRIu64" packets (%"PRIu64" bytes) demuxed\n",
880 total_packets, total_size);
883 for (i = 0; i < nb_output_files; i++) {
884 OutputFile *of = output_files[i];
885 uint64_t total_packets = 0, total_size = 0;
887 av_log(NULL, AV_LOG_VERBOSE, "Output file #%d (%s):\n",
888 i, of->ctx->filename);
890 for (j = 0; j < of->ctx->nb_streams; j++) {
891 OutputStream *ost = output_streams[of->ost_index + j];
892 enum AVMediaType type = ost->enc_ctx->codec_type;
894 total_size += ost->data_size;
895 total_packets += ost->packets_written;
897 av_log(NULL, AV_LOG_VERBOSE, " Output stream #%d:%d (%s): ",
898 i, j, media_type_string(type));
899 if (ost->encoding_needed) {
900 av_log(NULL, AV_LOG_VERBOSE, "%"PRIu64" frames encoded",
901 ost->frames_encoded);
902 if (type == AVMEDIA_TYPE_AUDIO)
903 av_log(NULL, AV_LOG_VERBOSE, " (%"PRIu64" samples)", ost->samples_encoded);
904 av_log(NULL, AV_LOG_VERBOSE, "; ");
907 av_log(NULL, AV_LOG_VERBOSE, "%"PRIu64" packets muxed (%"PRIu64" bytes); ",
908 ost->packets_written, ost->data_size);
910 av_log(NULL, AV_LOG_VERBOSE, "\n");
913 av_log(NULL, AV_LOG_VERBOSE, " Total: %"PRIu64" packets (%"PRIu64" bytes) muxed\n",
914 total_packets, total_size);
918 static void print_report(int is_last_report, int64_t timer_start)
920 char buf[1024];
921 OutputStream *ost;
922 AVFormatContext *oc;
923 int64_t total_size = 0;
924 AVCodecContext *enc;
925 int frame_number, vid, i;
926 double bitrate, ti1, pts;
927 static int64_t last_time = -1;
928 static int qp_histogram[52];
930 if (!print_stats && !is_last_report)
931 return;
933 if (!is_last_report) {
934 int64_t cur_time;
935 /* display the report every 0.5 seconds */
936 cur_time = av_gettime_relative();
937 if (last_time == -1) {
938 last_time = cur_time;
939 return;
941 if ((cur_time - last_time) < 500000)
942 return;
943 last_time = cur_time;
947 oc = output_files[0]->ctx;
948 if (oc->pb) {
949 total_size = avio_size(oc->pb);
950 if (total_size <= 0) // FIXME improve avio_size() so it works with non seekable output too
951 total_size = avio_tell(oc->pb);
952 if (total_size < 0) {
953 char errbuf[128];
954 av_strerror(total_size, errbuf, sizeof(errbuf));
955 av_log(NULL, AV_LOG_VERBOSE, "Bitrate not available, "
956 "avio_tell() failed: %s\n", errbuf);
957 total_size = 0;
961 buf[0] = '\0';
962 ti1 = 1e10;
963 vid = 0;
964 for (i = 0; i < nb_output_streams; i++) {
965 float q = -1;
966 ost = output_streams[i];
967 enc = ost->enc_ctx;
968 if (!ost->stream_copy)
969 q = ost->quality / (float) FF_QP2LAMBDA;
971 if (vid && enc->codec_type == AVMEDIA_TYPE_VIDEO) {
972 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "q=%2.1f ", q);
974 if (!vid && enc->codec_type == AVMEDIA_TYPE_VIDEO) {
975 float t = (av_gettime_relative() - timer_start) / 1000000.0;
977 frame_number = ost->frame_number;
978 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "frame=%5d fps=%3d q=%3.1f ",
979 frame_number, (t > 1) ? (int)(frame_number / t + 0.5) : 0, q);
980 if (is_last_report)
981 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "L");
982 if (qp_hist) {
983 int j;
984 int qp = lrintf(q);
985 if (qp >= 0 && qp < FF_ARRAY_ELEMS(qp_histogram))
986 qp_histogram[qp]++;
987 for (j = 0; j < 32; j++)
988 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "%X", (int)lrintf(log2(qp_histogram[j] + 1)));
991 #if FF_API_CODED_FRAME && FF_API_ERROR_FRAME
992 FF_DISABLE_DEPRECATION_WARNINGS
993 if (enc->flags & AV_CODEC_FLAG_PSNR) {
994 int j;
995 double error, error_sum = 0;
996 double scale, scale_sum = 0;
997 char type[3] = { 'Y','U','V' };
998 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "PSNR=");
999 for (j = 0; j < 3; j++) {
1000 if (is_last_report) {
1001 error = enc->error[j];
1002 scale = enc->width * enc->height * 255.0 * 255.0 * frame_number;
1003 } else {
1004 error = enc->coded_frame->error[j];
1005 scale = enc->width * enc->height * 255.0 * 255.0;
1007 if (j)
1008 scale /= 4;
1009 error_sum += error;
1010 scale_sum += scale;
1011 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "%c:%2.2f ", type[j], psnr(error / scale));
1013 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "*:%2.2f ", psnr(error_sum / scale_sum));
1015 FF_ENABLE_DEPRECATION_WARNINGS
1016 #endif
1017 vid = 1;
1019 /* compute min output value */
1020 pts = (double)ost->last_mux_dts * av_q2d(ost->st->time_base);
1021 if ((pts < ti1) && (pts > 0))
1022 ti1 = pts;
1024 if (ti1 < 0.01)
1025 ti1 = 0.01;
1027 bitrate = (double)(total_size * 8) / ti1 / 1000.0;
1029 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
1030 "size=%8.0fkB time=%0.2f bitrate=%6.1fkbits/s",
1031 (double)total_size / 1024, ti1, bitrate);
1033 if (nb_frames_drop)
1034 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), " drop=%d",
1035 nb_frames_drop);
1037 av_log(NULL, AV_LOG_INFO, "%s \r", buf);
1039 fflush(stderr);
1041 if (is_last_report)
1042 print_final_stats(total_size);
1046 static void flush_encoders(void)
1048 int i, ret;
1050 for (i = 0; i < nb_output_streams; i++) {
1051 OutputStream *ost = output_streams[i];
1052 AVCodecContext *enc = ost->enc_ctx;
1053 OutputFile *of = output_files[ost->file_index];
1054 int stop_encoding = 0;
1056 if (!ost->encoding_needed)
1057 continue;
1059 if (enc->codec_type == AVMEDIA_TYPE_AUDIO && enc->frame_size <= 1)
1060 continue;
1062 if (enc->codec_type != AVMEDIA_TYPE_VIDEO && enc->codec_type != AVMEDIA_TYPE_AUDIO)
1063 continue;
1065 avcodec_send_frame(enc, NULL);
1067 for (;;) {
1068 const char *desc = NULL;
1070 switch (enc->codec_type) {
1071 case AVMEDIA_TYPE_AUDIO:
1072 desc = "Audio";
1073 break;
1074 case AVMEDIA_TYPE_VIDEO:
1075 desc = "Video";
1076 break;
1077 default:
1078 av_assert0(0);
1081 if (1) {
1082 AVPacket pkt;
1083 av_init_packet(&pkt);
1084 pkt.data = NULL;
1085 pkt.size = 0;
1087 ret = avcodec_receive_packet(enc, &pkt);
1088 if (ret < 0 && ret != AVERROR_EOF) {
1089 av_log(NULL, AV_LOG_FATAL, "%s encoding failed\n", desc);
1090 exit_program(1);
1092 if (ost->logfile && enc->stats_out) {
1093 fprintf(ost->logfile, "%s", enc->stats_out);
1095 output_packet(of, &pkt, ost, ret == AVERROR_EOF);
1096 if (ret == AVERROR_EOF) {
1097 stop_encoding = 1;
1098 break;
1102 if (stop_encoding)
1103 break;
1109 * Check whether a packet from ist should be written into ost at this time
1111 static int check_output_constraints(InputStream *ist, OutputStream *ost)
1113 OutputFile *of = output_files[ost->file_index];
1114 int ist_index = input_files[ist->file_index]->ist_index + ist->st->index;
1116 if (ost->source_index != ist_index)
1117 return 0;
1119 if (of->start_time != AV_NOPTS_VALUE && ist->last_dts < of->start_time)
1120 return 0;
1122 return 1;
1125 static void do_streamcopy(InputStream *ist, OutputStream *ost, const AVPacket *pkt)
1127 OutputFile *of = output_files[ost->file_index];
1128 InputFile *f = input_files [ist->file_index];
1129 int64_t start_time = (of->start_time == AV_NOPTS_VALUE) ? 0 : of->start_time;
1130 int64_t ost_tb_start_time = av_rescale_q(start_time, AV_TIME_BASE_Q, ost->mux_timebase);
1131 AVPacket opkt = { 0 };
1133 av_init_packet(&opkt);
1135 // EOF: flush output bitstream filters.
1136 if (!pkt) {
1137 output_packet(of, &opkt, ost, 1);
1138 return;
1141 if ((!ost->frame_number && !(pkt->flags & AV_PKT_FLAG_KEY)) &&
1142 !ost->copy_initial_nonkeyframes)
1143 return;
1145 if (of->recording_time != INT64_MAX &&
1146 ist->last_dts >= of->recording_time + start_time) {
1147 ost->finished = 1;
1148 return;
1151 if (f->recording_time != INT64_MAX) {
1152 start_time = f->ctx->start_time;
1153 if (f->start_time != AV_NOPTS_VALUE)
1154 start_time += f->start_time;
1155 if (ist->last_dts >= f->recording_time + start_time) {
1156 ost->finished = 1;
1157 return;
1161 /* force the input stream PTS */
1162 if (ost->enc_ctx->codec_type == AVMEDIA_TYPE_VIDEO)
1163 ost->sync_opts++;
1165 if (pkt->pts != AV_NOPTS_VALUE)
1166 opkt.pts = av_rescale_q(pkt->pts, ist->st->time_base, ost->mux_timebase) - ost_tb_start_time;
1167 else
1168 opkt.pts = AV_NOPTS_VALUE;
1170 if (pkt->dts == AV_NOPTS_VALUE)
1171 opkt.dts = av_rescale_q(ist->last_dts, AV_TIME_BASE_Q, ost->mux_timebase);
1172 else
1173 opkt.dts = av_rescale_q(pkt->dts, ist->st->time_base, ost->mux_timebase);
1174 opkt.dts -= ost_tb_start_time;
1176 opkt.duration = av_rescale_q(pkt->duration, ist->st->time_base, ost->mux_timebase);
1177 opkt.flags = pkt->flags;
1179 // FIXME remove the following 2 lines they shall be replaced by the bitstream filters
1180 if ( ost->enc_ctx->codec_id != AV_CODEC_ID_H264
1181 && ost->enc_ctx->codec_id != AV_CODEC_ID_MPEG1VIDEO
1182 && ost->enc_ctx->codec_id != AV_CODEC_ID_MPEG2VIDEO
1183 && ost->enc_ctx->codec_id != AV_CODEC_ID_VC1
1185 if (av_parser_change(ost->parser, ost->parser_avctx,
1186 &opkt.data, &opkt.size,
1187 pkt->data, pkt->size,
1188 pkt->flags & AV_PKT_FLAG_KEY)) {
1189 opkt.buf = av_buffer_create(opkt.data, opkt.size, av_buffer_default_free, NULL, 0);
1190 if (!opkt.buf)
1191 exit_program(1);
1193 } else {
1194 opkt.data = pkt->data;
1195 opkt.size = pkt->size;
1198 output_packet(of, &opkt, ost, 0);
1201 static int ifilter_send_frame(InputFilter *ifilter, AVFrame *frame)
1203 FilterGraph *fg = ifilter->graph;
1204 int need_reinit, ret, i;
1206 /* determine if the parameters for this input changed */
1207 need_reinit = ifilter->format != frame->format;
1208 if (!!ifilter->hw_frames_ctx != !!frame->hw_frames_ctx ||
1209 (ifilter->hw_frames_ctx && ifilter->hw_frames_ctx->data != frame->hw_frames_ctx->data))
1210 need_reinit = 1;
1212 switch (ifilter->ist->st->codecpar->codec_type) {
1213 case AVMEDIA_TYPE_AUDIO:
1214 need_reinit |= ifilter->sample_rate != frame->sample_rate ||
1215 ifilter->channel_layout != frame->channel_layout;
1216 break;
1217 case AVMEDIA_TYPE_VIDEO:
1218 need_reinit |= ifilter->width != frame->width ||
1219 ifilter->height != frame->height;
1220 break;
1223 if (need_reinit) {
1224 ret = ifilter_parameters_from_frame(ifilter, frame);
1225 if (ret < 0)
1226 return ret;
1229 /* (re)init the graph if possible, otherwise buffer the frame and return */
1230 if (need_reinit || !fg->graph) {
1231 for (i = 0; i < fg->nb_inputs; i++) {
1232 if (fg->inputs[i]->format < 0) {
1233 AVFrame *tmp = av_frame_clone(frame);
1234 if (!tmp)
1235 return AVERROR(ENOMEM);
1236 av_frame_unref(frame);
1238 if (!av_fifo_space(ifilter->frame_queue)) {
1239 ret = av_fifo_realloc2(ifilter->frame_queue, 2 * av_fifo_size(ifilter->frame_queue));
1240 if (ret < 0)
1241 return ret;
1243 av_fifo_generic_write(ifilter->frame_queue, &tmp, sizeof(tmp), NULL);
1244 return 0;
1248 ret = poll_filters();
1249 if (ret < 0 && ret != AVERROR_EOF) {
1250 char errbuf[128];
1251 av_strerror(ret, errbuf, sizeof(errbuf));
1253 av_log(NULL, AV_LOG_ERROR, "Error while filtering: %s\n", errbuf);
1254 return ret;
1257 ret = configure_filtergraph(fg);
1258 if (ret < 0) {
1259 av_log(NULL, AV_LOG_ERROR, "Error reinitializing filters!\n");
1260 return ret;
1264 ret = av_buffersrc_add_frame(ifilter->filter, frame);
1265 if (ret < 0) {
1266 av_log(NULL, AV_LOG_ERROR, "Error while filtering\n");
1267 return ret;
1270 return 0;
1273 static int ifilter_send_eof(InputFilter *ifilter)
1275 int i, j, ret;
1277 ifilter->eof = 1;
1279 if (ifilter->filter) {
1280 ret = av_buffersrc_add_frame(ifilter->filter, NULL);
1281 if (ret < 0)
1282 return ret;
1283 } else {
1284 // the filtergraph was never configured
1285 FilterGraph *fg = ifilter->graph;
1286 for (i = 0; i < fg->nb_inputs; i++)
1287 if (!fg->inputs[i]->eof)
1288 break;
1289 if (i == fg->nb_inputs) {
1290 // All the input streams have finished without the filtergraph
1291 // ever being configured.
1292 // Mark the output streams as finished.
1293 for (j = 0; j < fg->nb_outputs; j++)
1294 finish_output_stream(fg->outputs[j]->ost);
1298 return 0;
1301 // This does not quite work like avcodec_decode_audio4/avcodec_decode_video2.
1302 // There is the following difference: if you got a frame, you must call
1303 // it again with pkt=NULL. pkt==NULL is treated differently from pkt.size==0
1304 // (pkt==NULL means get more output, pkt.size==0 is a flush/drain packet)
1305 static int decode(AVCodecContext *avctx, AVFrame *frame, int *got_frame, AVPacket *pkt)
1307 int ret;
1309 *got_frame = 0;
1311 if (pkt) {
1312 ret = avcodec_send_packet(avctx, pkt);
1313 // In particular, we don't expect AVERROR(EAGAIN), because we read all
1314 // decoded frames with avcodec_receive_frame() until done.
1315 if (ret < 0)
1316 return ret == AVERROR_EOF ? 0 : ret;
1319 ret = avcodec_receive_frame(avctx, frame);
1320 if (ret < 0 && ret != AVERROR(EAGAIN) && ret != AVERROR_EOF)
1321 return ret;
1322 if (ret >= 0)
1323 *got_frame = 1;
1325 return 0;
1328 int guess_input_channel_layout(InputStream *ist)
1330 AVCodecContext *dec = ist->dec_ctx;
1332 if (!dec->channel_layout) {
1333 char layout_name[256];
1335 dec->channel_layout = av_get_default_channel_layout(dec->channels);
1336 if (!dec->channel_layout)
1337 return 0;
1338 av_get_channel_layout_string(layout_name, sizeof(layout_name),
1339 dec->channels, dec->channel_layout);
1340 av_log(NULL, AV_LOG_WARNING, "Guessed Channel Layout for Input Stream "
1341 "#%d.%d : %s\n", ist->file_index, ist->st->index, layout_name);
1343 return 1;
1346 static int decode_audio(InputStream *ist, AVPacket *pkt, int *got_output,
1347 int *decode_failed)
1349 AVFrame *decoded_frame, *f;
1350 AVCodecContext *avctx = ist->dec_ctx;
1351 int i, ret, err = 0;
1353 if (!ist->decoded_frame && !(ist->decoded_frame = av_frame_alloc()))
1354 return AVERROR(ENOMEM);
1355 if (!ist->filter_frame && !(ist->filter_frame = av_frame_alloc()))
1356 return AVERROR(ENOMEM);
1357 decoded_frame = ist->decoded_frame;
1359 ret = decode(avctx, decoded_frame, got_output, pkt);
1360 if (ret < 0)
1361 *decode_failed = 1;
1362 if (!*got_output || ret < 0)
1363 return ret;
1365 ist->samples_decoded += decoded_frame->nb_samples;
1366 ist->frames_decoded++;
1368 /* if the decoder provides a pts, use it instead of the last packet pts.
1369 the decoder could be delaying output by a packet or more. */
1370 if (decoded_frame->pts != AV_NOPTS_VALUE)
1371 ist->next_dts = av_rescale_q(decoded_frame->pts, ist->st->time_base, AV_TIME_BASE_Q);
1372 else if (pkt && pkt->pts != AV_NOPTS_VALUE) {
1373 decoded_frame->pts = pkt->pts;
1376 if (decoded_frame->pts != AV_NOPTS_VALUE)
1377 decoded_frame->pts = av_rescale_q(decoded_frame->pts,
1378 ist->st->time_base,
1379 (AVRational){1, avctx->sample_rate});
1380 ist->nb_samples = decoded_frame->nb_samples;
1381 for (i = 0; i < ist->nb_filters; i++) {
1382 if (i < ist->nb_filters - 1) {
1383 f = ist->filter_frame;
1384 err = av_frame_ref(f, decoded_frame);
1385 if (err < 0)
1386 break;
1387 } else
1388 f = decoded_frame;
1390 err = ifilter_send_frame(ist->filters[i], f);
1391 if (err < 0)
1392 break;
1395 av_frame_unref(ist->filter_frame);
1396 av_frame_unref(decoded_frame);
1397 return err < 0 ? err : ret;
1400 static int decode_video(InputStream *ist, AVPacket *pkt, int *got_output,
1401 int *decode_failed)
1403 AVFrame *decoded_frame, *f;
1404 int i, ret = 0, err = 0;
1406 if (!ist->decoded_frame && !(ist->decoded_frame = av_frame_alloc()))
1407 return AVERROR(ENOMEM);
1408 if (!ist->filter_frame && !(ist->filter_frame = av_frame_alloc()))
1409 return AVERROR(ENOMEM);
1410 decoded_frame = ist->decoded_frame;
1412 ret = decode(ist->dec_ctx, decoded_frame, got_output, pkt);
1413 if (ret < 0)
1414 *decode_failed = 1;
1415 if (!*got_output || ret < 0)
1416 return ret;
1418 ist->frames_decoded++;
1420 if (ist->hwaccel_retrieve_data && decoded_frame->format == ist->hwaccel_pix_fmt) {
1421 err = ist->hwaccel_retrieve_data(ist->dec_ctx, decoded_frame);
1422 if (err < 0)
1423 goto fail;
1425 ist->hwaccel_retrieved_pix_fmt = decoded_frame->format;
1427 decoded_frame->pts = guess_correct_pts(&ist->pts_ctx, decoded_frame->pts,
1428 decoded_frame->pkt_dts);
1429 if (ist->framerate.num)
1430 decoded_frame->pts = ist->cfr_next_pts++;
1432 if (ist->st->sample_aspect_ratio.num)
1433 decoded_frame->sample_aspect_ratio = ist->st->sample_aspect_ratio;
1435 for (i = 0; i < ist->nb_filters; i++) {
1436 if (i < ist->nb_filters - 1) {
1437 f = ist->filter_frame;
1438 err = av_frame_ref(f, decoded_frame);
1439 if (err < 0)
1440 break;
1441 } else
1442 f = decoded_frame;
1444 err = ifilter_send_frame(ist->filters[i], f);
1445 if (err < 0)
1446 break;
1449 fail:
1450 av_frame_unref(ist->filter_frame);
1451 av_frame_unref(decoded_frame);
1452 return err < 0 ? err : ret;
1455 static int transcode_subtitles(InputStream *ist, AVPacket *pkt, int *got_output,
1456 int *decode_failed)
1458 AVSubtitle subtitle;
1459 int i, ret = avcodec_decode_subtitle2(ist->dec_ctx,
1460 &subtitle, got_output, pkt);
1461 if (ret < 0) {
1462 *decode_failed = 1;
1463 return ret;
1465 if (!*got_output)
1466 return ret;
1468 ist->frames_decoded++;
1470 for (i = 0; i < nb_output_streams; i++) {
1471 OutputStream *ost = output_streams[i];
1473 if (!check_output_constraints(ist, ost) || !ost->encoding_needed)
1474 continue;
1476 do_subtitle_out(output_files[ost->file_index], ost, ist, &subtitle, pkt->pts);
1479 avsubtitle_free(&subtitle);
1480 return ret;
1483 static int send_filter_eof(InputStream *ist)
1485 int i, ret;
1486 for (i = 0; i < ist->nb_filters; i++) {
1487 ret = ifilter_send_eof(ist->filters[i]);
1488 if (ret < 0)
1489 return ret;
1491 return 0;
1494 /* pkt = NULL means EOF (needed to flush decoder buffers) */
1495 static void process_input_packet(InputStream *ist, const AVPacket *pkt, int no_eof)
1497 int i;
1498 int repeating = 0;
1499 AVPacket avpkt;
1501 if (ist->next_dts == AV_NOPTS_VALUE)
1502 ist->next_dts = ist->last_dts;
1504 if (!pkt) {
1505 /* EOF handling */
1506 av_init_packet(&avpkt);
1507 avpkt.data = NULL;
1508 avpkt.size = 0;
1509 } else {
1510 avpkt = *pkt;
1513 if (pkt && pkt->dts != AV_NOPTS_VALUE)
1514 ist->next_dts = ist->last_dts = av_rescale_q(pkt->dts, ist->st->time_base, AV_TIME_BASE_Q);
1516 // while we have more to decode or while the decoder did output something on EOF
1517 while (ist->decoding_needed && (!pkt || avpkt.size > 0)) {
1518 int ret = 0;
1519 int got_output = 0;
1520 int decode_failed = 0;
1522 if (!repeating)
1523 ist->last_dts = ist->next_dts;
1525 switch (ist->dec_ctx->codec_type) {
1526 case AVMEDIA_TYPE_AUDIO:
1527 ret = decode_audio (ist, repeating ? NULL : &avpkt, &got_output,
1528 &decode_failed);
1529 break;
1530 case AVMEDIA_TYPE_VIDEO:
1531 ret = decode_video (ist, repeating ? NULL : &avpkt, &got_output,
1532 &decode_failed);
1533 if (repeating && !got_output)
1535 else if (pkt && pkt->duration)
1536 ist->next_dts += av_rescale_q(pkt->duration, ist->st->time_base, AV_TIME_BASE_Q);
1537 else if (ist->st->avg_frame_rate.num)
1538 ist->next_dts += av_rescale_q(1, av_inv_q(ist->st->avg_frame_rate),
1539 AV_TIME_BASE_Q);
1540 else if (ist->dec_ctx->framerate.num != 0) {
1541 int ticks = ist->st->parser ? ist->st->parser->repeat_pict + 1 :
1542 ist->dec_ctx->ticks_per_frame;
1543 ist->next_dts += av_rescale_q(ticks, ist->dec_ctx->framerate, AV_TIME_BASE_Q);
1545 break;
1546 case AVMEDIA_TYPE_SUBTITLE:
1547 if (repeating)
1548 break;
1549 ret = transcode_subtitles(ist, &avpkt, &got_output, &decode_failed);
1550 break;
1551 default:
1552 return;
1555 if (ret < 0) {
1556 if (decode_failed) {
1557 av_log(NULL, AV_LOG_ERROR, "Error while decoding stream #%d:%d\n",
1558 ist->file_index, ist->st->index);
1559 } else {
1560 av_log(NULL, AV_LOG_FATAL, "Error while processing the decoded "
1561 "data for stream #%d:%d\n", ist->file_index, ist->st->index);
1563 if (!decode_failed || exit_on_error)
1564 exit_program(1);
1565 break;
1568 if (!got_output)
1569 break;
1571 repeating = 1;
1574 /* after flushing, send an EOF on all the filter inputs attached to the stream */
1575 /* except when looping we need to flush but not to send an EOF */
1576 if (!pkt && ist->decoding_needed && !no_eof) {
1577 int ret = send_filter_eof(ist);
1578 if (ret < 0) {
1579 av_log(NULL, AV_LOG_FATAL, "Error marking filters as finished\n");
1580 exit_program(1);
1584 /* handle stream copy */
1585 if (!ist->decoding_needed) {
1586 ist->last_dts = ist->next_dts;
1587 switch (ist->dec_ctx->codec_type) {
1588 case AVMEDIA_TYPE_AUDIO:
1589 ist->next_dts += ((int64_t)AV_TIME_BASE * ist->dec_ctx->frame_size) /
1590 ist->dec_ctx->sample_rate;
1591 break;
1592 case AVMEDIA_TYPE_VIDEO:
1593 if (ist->dec_ctx->framerate.num != 0) {
1594 int ticks = ist->st->parser ? ist->st->parser->repeat_pict + 1 : ist->dec_ctx->ticks_per_frame;
1595 ist->next_dts += ((int64_t)AV_TIME_BASE *
1596 ist->dec_ctx->framerate.den * ticks) /
1597 ist->dec_ctx->framerate.num;
1599 break;
1602 for (i = 0; i < nb_output_streams; i++) {
1603 OutputStream *ost = output_streams[i];
1605 if (!check_output_constraints(ist, ost) || ost->encoding_needed)
1606 continue;
1608 do_streamcopy(ist, ost, pkt);
1611 return;
1614 static void print_sdp(void)
1616 char sdp[16384];
1617 int i;
1618 AVFormatContext **avc;
1620 for (i = 0; i < nb_output_files; i++) {
1621 if (!output_files[i]->header_written)
1622 return;
1625 avc = av_malloc(sizeof(*avc) * nb_output_files);
1626 if (!avc)
1627 exit_program(1);
1628 for (i = 0; i < nb_output_files; i++)
1629 avc[i] = output_files[i]->ctx;
1631 av_sdp_create(avc, nb_output_files, sdp, sizeof(sdp));
1632 printf("SDP:\n%s\n", sdp);
1633 fflush(stdout);
1634 av_freep(&avc);
1637 static enum AVPixelFormat get_format(AVCodecContext *s, const enum AVPixelFormat *pix_fmts)
1639 InputStream *ist = s->opaque;
1640 const enum AVPixelFormat *p;
1641 int ret;
1643 for (p = pix_fmts; *p != AV_PIX_FMT_NONE; p++) {
1644 const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(*p);
1645 const AVCodecHWConfig *config = NULL;
1646 int i;
1648 if (!(desc->flags & AV_PIX_FMT_FLAG_HWACCEL))
1649 break;
1651 if (ist->hwaccel_id == HWACCEL_GENERIC ||
1652 ist->hwaccel_id == HWACCEL_AUTO) {
1653 for (i = 0;; i++) {
1654 config = avcodec_get_hw_config(s->codec, i);
1655 if (!config)
1656 break;
1657 if (!(config->methods &
1658 AV_CODEC_HW_CONFIG_METHOD_HW_DEVICE_CTX))
1659 continue;
1660 if (config->pix_fmt == *p)
1661 break;
1664 if (config) {
1665 if (config->device_type != ist->hwaccel_device_type) {
1666 // Different hwaccel offered, ignore.
1667 continue;
1670 ret = hwaccel_decode_init(s);
1671 if (ret < 0) {
1672 if (ist->hwaccel_id == HWACCEL_GENERIC) {
1673 av_log(NULL, AV_LOG_FATAL,
1674 "%s hwaccel requested for input stream #%d:%d, "
1675 "but cannot be initialized.\n",
1676 av_hwdevice_get_type_name(config->device_type),
1677 ist->file_index, ist->st->index);
1678 return AV_PIX_FMT_NONE;
1680 continue;
1682 } else {
1683 const HWAccel *hwaccel = NULL;
1684 int i;
1685 for (i = 0; hwaccels[i].name; i++) {
1686 if (hwaccels[i].pix_fmt == *p) {
1687 hwaccel = &hwaccels[i];
1688 break;
1691 if (!hwaccel) {
1692 // No hwaccel supporting this pixfmt.
1693 continue;
1695 if (hwaccel->id != ist->hwaccel_id) {
1696 // Does not match requested hwaccel.
1697 continue;
1700 ret = hwaccel->init(s);
1701 if (ret < 0) {
1702 av_log(NULL, AV_LOG_FATAL,
1703 "%s hwaccel requested for input stream #%d:%d, "
1704 "but cannot be initialized.\n", hwaccel->name,
1705 ist->file_index, ist->st->index);
1706 return AV_PIX_FMT_NONE;
1710 if (ist->hw_frames_ctx) {
1711 s->hw_frames_ctx = av_buffer_ref(ist->hw_frames_ctx);
1712 if (!s->hw_frames_ctx)
1713 return AV_PIX_FMT_NONE;
1716 ist->hwaccel_pix_fmt = *p;
1717 break;
1720 return *p;
1723 static int get_buffer(AVCodecContext *s, AVFrame *frame, int flags)
1725 InputStream *ist = s->opaque;
1727 if (ist->hwaccel_get_buffer && frame->format == ist->hwaccel_pix_fmt)
1728 return ist->hwaccel_get_buffer(s, frame, flags);
1730 return avcodec_default_get_buffer2(s, frame, flags);
1733 static int init_input_stream(int ist_index, char *error, int error_len)
1735 int ret;
1736 InputStream *ist = input_streams[ist_index];
1738 if (ist->decoding_needed) {
1739 AVCodec *codec = ist->dec;
1740 if (!codec) {
1741 snprintf(error, error_len, "Decoder (codec id %d) not found for input stream #%d:%d",
1742 ist->dec_ctx->codec_id, ist->file_index, ist->st->index);
1743 return AVERROR(EINVAL);
1746 ist->dec_ctx->opaque = ist;
1747 ist->dec_ctx->get_format = get_format;
1748 ist->dec_ctx->get_buffer2 = get_buffer;
1749 ist->dec_ctx->thread_safe_callbacks = 1;
1751 av_opt_set_int(ist->dec_ctx, "refcounted_frames", 1, 0);
1753 if (!av_dict_get(ist->decoder_opts, "threads", NULL, 0))
1754 av_dict_set(&ist->decoder_opts, "threads", "auto", 0);
1756 ret = hw_device_setup_for_decode(ist);
1757 if (ret < 0) {
1758 char errbuf[128];
1759 av_strerror(ret, errbuf, sizeof(errbuf));
1760 snprintf(error, error_len, "Device setup failed for "
1761 "decoder on input stream #%d:%d : %s",
1762 ist->file_index, ist->st->index, errbuf);
1763 return ret;
1766 if ((ret = avcodec_open2(ist->dec_ctx, codec, &ist->decoder_opts)) < 0) {
1767 char errbuf[128];
1768 if (ret == AVERROR_EXPERIMENTAL)
1769 abort_codec_experimental(codec, 0);
1771 av_strerror(ret, errbuf, sizeof(errbuf));
1773 snprintf(error, error_len,
1774 "Error while opening decoder for input stream "
1775 "#%d:%d : %s",
1776 ist->file_index, ist->st->index, errbuf);
1777 return ret;
1779 assert_avoptions(ist->decoder_opts);
1782 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;
1783 ist->next_dts = AV_NOPTS_VALUE;
1784 init_pts_correction(&ist->pts_ctx);
1786 return 0;
1789 static InputStream *get_input_stream(OutputStream *ost)
1791 if (ost->source_index >= 0)
1792 return input_streams[ost->source_index];
1794 if (ost->filter) {
1795 FilterGraph *fg = ost->filter->graph;
1796 int i;
1798 for (i = 0; i < fg->nb_inputs; i++)
1799 if (fg->inputs[i]->ist->dec_ctx->codec_type == ost->enc_ctx->codec_type)
1800 return fg->inputs[i]->ist;
1803 return NULL;
1806 /* open the muxer when all the streams are initialized */
1807 static int check_init_output_file(OutputFile *of, int file_index)
1809 int ret, i;
1811 for (i = 0; i < of->ctx->nb_streams; i++) {
1812 OutputStream *ost = output_streams[of->ost_index + i];
1813 if (!ost->initialized)
1814 return 0;
1817 of->ctx->interrupt_callback = int_cb;
1819 ret = avformat_write_header(of->ctx, &of->opts);
1820 if (ret < 0) {
1821 char errbuf[128];
1823 av_strerror(ret, errbuf, sizeof(errbuf));
1825 av_log(NULL, AV_LOG_ERROR,
1826 "Could not write header for output file #%d "
1827 "(incorrect codec parameters ?): %s",
1828 file_index, errbuf);
1829 return ret;
1831 assert_avoptions(of->opts);
1832 of->header_written = 1;
1834 av_dump_format(of->ctx, file_index, of->ctx->filename, 1);
1836 if (want_sdp)
1837 print_sdp();
1839 /* flush the muxing queues */
1840 for (i = 0; i < of->ctx->nb_streams; i++) {
1841 OutputStream *ost = output_streams[of->ost_index + i];
1843 while (av_fifo_size(ost->muxing_queue)) {
1844 AVPacket pkt;
1845 av_fifo_generic_read(ost->muxing_queue, &pkt, sizeof(pkt), NULL);
1846 write_packet(of, &pkt, ost);
1850 return 0;
1853 static int init_output_bsfs(OutputStream *ost)
1855 AVBSFContext *ctx;
1856 int i, ret;
1858 if (!ost->nb_bitstream_filters)
1859 return 0;
1861 for (i = 0; i < ost->nb_bitstream_filters; i++) {
1862 ctx = ost->bsf_ctx[i];
1864 ret = avcodec_parameters_copy(ctx->par_in,
1865 i ? ost->bsf_ctx[i - 1]->par_out : ost->st->codecpar);
1866 if (ret < 0)
1867 return ret;
1869 ctx->time_base_in = i ? ost->bsf_ctx[i - 1]->time_base_out : ost->st->time_base;
1871 ret = av_bsf_init(ctx);
1872 if (ret < 0) {
1873 av_log(NULL, AV_LOG_ERROR, "Error initializing bitstream filter: %s\n",
1874 ctx->filter->name);
1875 return ret;
1879 ret = avcodec_parameters_copy(ost->st->codecpar, ctx->par_out);
1880 if (ret < 0)
1881 return ret;
1883 ost->st->time_base = ctx->time_base_out;
1885 return 0;
1888 static int init_output_stream_streamcopy(OutputStream *ost)
1890 OutputFile *of = output_files[ost->file_index];
1891 InputStream *ist = get_input_stream(ost);
1892 AVCodecParameters *par_dst = ost->st->codecpar;
1893 AVCodecParameters *par_src = ist->st->codecpar;
1894 AVRational sar;
1895 uint32_t codec_tag = par_dst->codec_tag;
1896 int i, ret;
1898 if (!codec_tag) {
1899 if (!of->ctx->oformat->codec_tag ||
1900 av_codec_get_id (of->ctx->oformat->codec_tag, par_src->codec_tag) == par_src->codec_id ||
1901 av_codec_get_tag(of->ctx->oformat->codec_tag, par_src->codec_id) <= 0)
1902 codec_tag = par_src->codec_tag;
1905 ret = avcodec_parameters_copy(par_dst, par_src);
1906 if (ret < 0)
1907 return ret;
1909 par_dst->codec_tag = codec_tag;
1911 ost->st->disposition = ist->st->disposition;
1913 ost->st->time_base = ist->st->time_base;
1915 if (ost->bitrate_override)
1916 par_dst->bit_rate = ost->bitrate_override;
1918 if (ist->st->nb_side_data) {
1919 ost->st->side_data = av_realloc_array(NULL, ist->st->nb_side_data,
1920 sizeof(*ist->st->side_data));
1921 if (!ost->st->side_data)
1922 return AVERROR(ENOMEM);
1924 for (i = 0; i < ist->st->nb_side_data; i++) {
1925 const AVPacketSideData *sd_src = &ist->st->side_data[i];
1926 AVPacketSideData *sd_dst = &ost->st->side_data[i];
1928 sd_dst->data = av_malloc(sd_src->size);
1929 if (!sd_dst->data)
1930 return AVERROR(ENOMEM);
1931 memcpy(sd_dst->data, sd_src->data, sd_src->size);
1932 sd_dst->size = sd_src->size;
1933 sd_dst->type = sd_src->type;
1934 ost->st->nb_side_data++;
1938 ost->parser = av_parser_init(par_dst->codec_id);
1939 ost->parser_avctx = avcodec_alloc_context3(NULL);
1940 if (!ost->parser_avctx)
1941 return AVERROR(ENOMEM);
1943 if (par_dst->codec_type == AVMEDIA_TYPE_VIDEO) {
1944 if (ost->frame_aspect_ratio)
1945 sar = av_d2q(ost->frame_aspect_ratio * par_dst->height / par_dst->width, 255);
1946 else if (ist->st->sample_aspect_ratio.num)
1947 sar = ist->st->sample_aspect_ratio;
1948 else
1949 sar = par_src->sample_aspect_ratio;
1950 ost->st->sample_aspect_ratio = par_dst->sample_aspect_ratio = sar;
1953 return 0;
1956 static void set_encoder_id(OutputFile *of, OutputStream *ost)
1958 AVDictionaryEntry *e;
1960 uint8_t *encoder_string;
1961 int encoder_string_len;
1962 int format_flags = 0;
1964 e = av_dict_get(of->opts, "fflags", NULL, 0);
1965 if (e) {
1966 const AVOption *o = av_opt_find(of->ctx, "fflags", NULL, 0, 0);
1967 if (!o)
1968 return;
1969 av_opt_eval_flags(of->ctx, o, e->value, &format_flags);
1972 encoder_string_len = sizeof(LIBAVCODEC_IDENT) + strlen(ost->enc->name) + 2;
1973 encoder_string = av_mallocz(encoder_string_len);
1974 if (!encoder_string)
1975 exit_program(1);
1977 if (!(format_flags & AVFMT_FLAG_BITEXACT))
1978 av_strlcpy(encoder_string, LIBAVCODEC_IDENT " ", encoder_string_len);
1979 av_strlcat(encoder_string, ost->enc->name, encoder_string_len);
1980 av_dict_set(&ost->st->metadata, "encoder", encoder_string,
1981 AV_DICT_DONT_STRDUP_VAL | AV_DICT_DONT_OVERWRITE);
1984 static void parse_forced_key_frames(char *kf, OutputStream *ost,
1985 AVCodecContext *avctx)
1987 char *p;
1988 int n = 1, i;
1989 int64_t t;
1991 for (p = kf; *p; p++)
1992 if (*p == ',')
1993 n++;
1994 ost->forced_kf_count = n;
1995 ost->forced_kf_pts = av_malloc(sizeof(*ost->forced_kf_pts) * n);
1996 if (!ost->forced_kf_pts) {
1997 av_log(NULL, AV_LOG_FATAL, "Could not allocate forced key frames array.\n");
1998 exit_program(1);
2001 p = kf;
2002 for (i = 0; i < n; i++) {
2003 char *next = strchr(p, ',');
2005 if (next)
2006 *next++ = 0;
2008 t = parse_time_or_die("force_key_frames", p, 1);
2009 ost->forced_kf_pts[i] = av_rescale_q(t, AV_TIME_BASE_Q, avctx->time_base);
2011 p = next;
2015 static int init_output_stream_encode(OutputStream *ost)
2017 InputStream *ist = get_input_stream(ost);
2018 AVCodecContext *enc_ctx = ost->enc_ctx;
2019 AVCodecContext *dec_ctx = NULL;
2021 set_encoder_id(output_files[ost->file_index], ost);
2023 if (ist) {
2024 ost->st->disposition = ist->st->disposition;
2026 dec_ctx = ist->dec_ctx;
2028 enc_ctx->bits_per_raw_sample = dec_ctx->bits_per_raw_sample;
2029 enc_ctx->chroma_sample_location = dec_ctx->chroma_sample_location;
2032 switch (enc_ctx->codec_type) {
2033 case AVMEDIA_TYPE_AUDIO:
2034 enc_ctx->sample_fmt = ost->filter->filter->inputs[0]->format;
2035 enc_ctx->sample_rate = ost->filter->filter->inputs[0]->sample_rate;
2036 enc_ctx->channel_layout = ost->filter->filter->inputs[0]->channel_layout;
2037 enc_ctx->channels = av_get_channel_layout_nb_channels(enc_ctx->channel_layout);
2038 enc_ctx->time_base = (AVRational){ 1, enc_ctx->sample_rate };
2039 break;
2040 case AVMEDIA_TYPE_VIDEO:
2041 enc_ctx->time_base = ost->filter->filter->inputs[0]->time_base;
2043 enc_ctx->width = ost->filter->filter->inputs[0]->w;
2044 enc_ctx->height = ost->filter->filter->inputs[0]->h;
2045 enc_ctx->sample_aspect_ratio = ost->st->sample_aspect_ratio =
2046 ost->frame_aspect_ratio ? // overridden by the -aspect cli option
2047 av_d2q(ost->frame_aspect_ratio * enc_ctx->height/enc_ctx->width, 255) :
2048 ost->filter->filter->inputs[0]->sample_aspect_ratio;
2049 enc_ctx->pix_fmt = ost->filter->filter->inputs[0]->format;
2051 enc_ctx->framerate = ost->frame_rate;
2053 ost->st->avg_frame_rate = ost->frame_rate;
2055 if (dec_ctx &&
2056 (enc_ctx->width != dec_ctx->width ||
2057 enc_ctx->height != dec_ctx->height ||
2058 enc_ctx->pix_fmt != dec_ctx->pix_fmt)) {
2059 enc_ctx->bits_per_raw_sample = 0;
2062 if (ost->forced_keyframes)
2063 parse_forced_key_frames(ost->forced_keyframes, ost,
2064 ost->enc_ctx);
2065 break;
2066 case AVMEDIA_TYPE_SUBTITLE:
2067 enc_ctx->time_base = (AVRational){1, 1000};
2068 break;
2069 default:
2070 abort();
2071 break;
2074 return 0;
2077 static int init_output_stream(OutputStream *ost, char *error, int error_len)
2079 int ret = 0;
2081 if (ost->encoding_needed) {
2082 AVCodec *codec = ost->enc;
2083 AVCodecContext *dec = NULL;
2084 InputStream *ist;
2086 ret = init_output_stream_encode(ost);
2087 if (ret < 0)
2088 return ret;
2090 if ((ist = get_input_stream(ost)))
2091 dec = ist->dec_ctx;
2092 if (dec && dec->subtitle_header) {
2093 ost->enc_ctx->subtitle_header = av_malloc(dec->subtitle_header_size);
2094 if (!ost->enc_ctx->subtitle_header)
2095 return AVERROR(ENOMEM);
2096 memcpy(ost->enc_ctx->subtitle_header, dec->subtitle_header, dec->subtitle_header_size);
2097 ost->enc_ctx->subtitle_header_size = dec->subtitle_header_size;
2099 if (!av_dict_get(ost->encoder_opts, "threads", NULL, 0))
2100 av_dict_set(&ost->encoder_opts, "threads", "auto", 0);
2102 if (ost->filter && ost->filter->filter->inputs[0]->hw_frames_ctx &&
2103 ((AVHWFramesContext*)ost->filter->filter->inputs[0]->hw_frames_ctx->data)->format ==
2104 ost->filter->filter->inputs[0]->format) {
2105 ost->enc_ctx->hw_frames_ctx = av_buffer_ref(ost->filter->filter->inputs[0]->hw_frames_ctx);
2106 if (!ost->enc_ctx->hw_frames_ctx)
2107 return AVERROR(ENOMEM);
2108 } else {
2109 ret = hw_device_setup_for_encode(ost);
2110 if (ret < 0) {
2111 char errbuf[128];
2112 av_strerror(ret, errbuf, sizeof(errbuf));
2113 snprintf(error, error_len, "Device setup failed for "
2114 "encoder on output stream #%d:%d : %s",
2115 ost->file_index, ost->index, errbuf);
2116 return ret;
2120 if ((ret = avcodec_open2(ost->enc_ctx, codec, &ost->encoder_opts)) < 0) {
2121 if (ret == AVERROR_EXPERIMENTAL)
2122 abort_codec_experimental(codec, 1);
2123 snprintf(error, error_len,
2124 "Error while opening encoder for output stream #%d:%d - "
2125 "maybe incorrect parameters such as bit_rate, rate, width or height",
2126 ost->file_index, ost->index);
2127 return ret;
2129 assert_avoptions(ost->encoder_opts);
2130 if (ost->enc_ctx->bit_rate && ost->enc_ctx->bit_rate < 1000)
2131 av_log(NULL, AV_LOG_WARNING, "The bitrate parameter is set too low."
2132 "It takes bits/s as argument, not kbits/s\n");
2134 ret = avcodec_parameters_from_context(ost->st->codecpar, ost->enc_ctx);
2135 if (ret < 0) {
2136 av_log(NULL, AV_LOG_FATAL,
2137 "Error initializing the output stream codec context.\n");
2138 exit_program(1);
2141 if (ost->enc_ctx->nb_coded_side_data) {
2142 int i;
2144 ost->st->side_data = av_realloc_array(NULL, ost->enc_ctx->nb_coded_side_data,
2145 sizeof(*ost->st->side_data));
2146 if (!ost->st->side_data)
2147 return AVERROR(ENOMEM);
2149 for (i = 0; i < ost->enc_ctx->nb_coded_side_data; i++) {
2150 const AVPacketSideData *sd_src = &ost->enc_ctx->coded_side_data[i];
2151 AVPacketSideData *sd_dst = &ost->st->side_data[i];
2153 sd_dst->data = av_malloc(sd_src->size);
2154 if (!sd_dst->data)
2155 return AVERROR(ENOMEM);
2156 memcpy(sd_dst->data, sd_src->data, sd_src->size);
2157 sd_dst->size = sd_src->size;
2158 sd_dst->type = sd_src->type;
2159 ost->st->nb_side_data++;
2163 ost->st->time_base = ost->enc_ctx->time_base;
2164 } else if (ost->stream_copy) {
2165 ret = init_output_stream_streamcopy(ost);
2166 if (ret < 0)
2167 return ret;
2170 * FIXME: will the codec context used by the parser during streamcopy
2171 * This should go away with the new parser API.
2173 ret = avcodec_parameters_to_context(ost->parser_avctx, ost->st->codecpar);
2174 if (ret < 0)
2175 return ret;
2178 /* initialize bitstream filters for the output stream
2179 * needs to be done here, because the codec id for streamcopy is not
2180 * known until now */
2181 ret = init_output_bsfs(ost);
2182 if (ret < 0)
2183 return ret;
2185 ost->mux_timebase = ost->st->time_base;
2187 ost->initialized = 1;
2189 ret = check_init_output_file(output_files[ost->file_index], ost->file_index);
2190 if (ret < 0)
2191 return ret;
2193 return ret;
2196 static int transcode_init(void)
2198 int ret = 0, i, j, k;
2199 OutputStream *ost;
2200 InputStream *ist;
2201 char error[1024];
2203 /* init framerate emulation */
2204 for (i = 0; i < nb_input_files; i++) {
2205 InputFile *ifile = input_files[i];
2206 if (ifile->rate_emu)
2207 for (j = 0; j < ifile->nb_streams; j++)
2208 input_streams[j + ifile->ist_index]->start = av_gettime_relative();
2211 /* init input streams */
2212 for (i = 0; i < nb_input_streams; i++)
2213 if ((ret = init_input_stream(i, error, sizeof(error))) < 0)
2214 goto dump_format;
2216 /* open each encoder */
2217 for (i = 0; i < nb_output_streams; i++) {
2218 // skip streams fed from filtergraphs until we have a frame for them
2219 if (output_streams[i]->filter)
2220 continue;
2222 ret = init_output_stream(output_streams[i], error, sizeof(error));
2223 if (ret < 0)
2224 goto dump_format;
2228 /* discard unused programs */
2229 for (i = 0; i < nb_input_files; i++) {
2230 InputFile *ifile = input_files[i];
2231 for (j = 0; j < ifile->ctx->nb_programs; j++) {
2232 AVProgram *p = ifile->ctx->programs[j];
2233 int discard = AVDISCARD_ALL;
2235 for (k = 0; k < p->nb_stream_indexes; k++)
2236 if (!input_streams[ifile->ist_index + p->stream_index[k]]->discard) {
2237 discard = AVDISCARD_DEFAULT;
2238 break;
2240 p->discard = discard;
2244 dump_format:
2245 /* dump the stream mapping */
2246 av_log(NULL, AV_LOG_INFO, "Stream mapping:\n");
2247 for (i = 0; i < nb_input_streams; i++) {
2248 ist = input_streams[i];
2250 for (j = 0; j < ist->nb_filters; j++) {
2251 if (!filtergraph_is_simple(ist->filters[j]->graph)) {
2252 av_log(NULL, AV_LOG_INFO, " Stream #%d:%d (%s) -> %s",
2253 ist->file_index, ist->st->index, ist->dec ? ist->dec->name : "?",
2254 ist->filters[j]->name);
2255 if (nb_filtergraphs > 1)
2256 av_log(NULL, AV_LOG_INFO, " (graph %d)", ist->filters[j]->graph->index);
2257 av_log(NULL, AV_LOG_INFO, "\n");
2262 for (i = 0; i < nb_output_streams; i++) {
2263 ost = output_streams[i];
2265 if (ost->attachment_filename) {
2266 /* an attached file */
2267 av_log(NULL, AV_LOG_INFO, " File %s -> Stream #%d:%d\n",
2268 ost->attachment_filename, ost->file_index, ost->index);
2269 continue;
2272 if (ost->filter && !filtergraph_is_simple(ost->filter->graph)) {
2273 /* output from a complex graph */
2274 av_log(NULL, AV_LOG_INFO, " %s", ost->filter->name);
2275 if (nb_filtergraphs > 1)
2276 av_log(NULL, AV_LOG_INFO, " (graph %d)", ost->filter->graph->index);
2278 av_log(NULL, AV_LOG_INFO, " -> Stream #%d:%d (%s)\n", ost->file_index,
2279 ost->index, ost->enc ? ost->enc->name : "?");
2280 continue;
2283 av_log(NULL, AV_LOG_INFO, " Stream #%d:%d -> #%d:%d",
2284 input_streams[ost->source_index]->file_index,
2285 input_streams[ost->source_index]->st->index,
2286 ost->file_index,
2287 ost->index);
2288 if (ost->sync_ist != input_streams[ost->source_index])
2289 av_log(NULL, AV_LOG_INFO, " [sync #%d:%d]",
2290 ost->sync_ist->file_index,
2291 ost->sync_ist->st->index);
2292 if (ost->stream_copy)
2293 av_log(NULL, AV_LOG_INFO, " (copy)");
2294 else {
2295 const AVCodec *in_codec = input_streams[ost->source_index]->dec;
2296 const AVCodec *out_codec = ost->enc;
2297 const char *decoder_name = "?";
2298 const char *in_codec_name = "?";
2299 const char *encoder_name = "?";
2300 const char *out_codec_name = "?";
2301 const AVCodecDescriptor *desc;
2303 if (in_codec) {
2304 decoder_name = in_codec->name;
2305 desc = avcodec_descriptor_get(in_codec->id);
2306 if (desc)
2307 in_codec_name = desc->name;
2308 if (!strcmp(decoder_name, in_codec_name))
2309 decoder_name = "native";
2312 if (out_codec) {
2313 encoder_name = out_codec->name;
2314 desc = avcodec_descriptor_get(out_codec->id);
2315 if (desc)
2316 out_codec_name = desc->name;
2317 if (!strcmp(encoder_name, out_codec_name))
2318 encoder_name = "native";
2321 av_log(NULL, AV_LOG_INFO, " (%s (%s) -> %s (%s))",
2322 in_codec_name, decoder_name,
2323 out_codec_name, encoder_name);
2325 av_log(NULL, AV_LOG_INFO, "\n");
2328 if (ret) {
2329 av_log(NULL, AV_LOG_ERROR, "%s\n", error);
2330 return ret;
2333 return 0;
2336 /* Return 1 if there remain streams where more output is wanted, 0 otherwise. */
2337 static int need_output(void)
2339 int i;
2341 for (i = 0; i < nb_output_streams; i++) {
2342 OutputStream *ost = output_streams[i];
2343 OutputFile *of = output_files[ost->file_index];
2344 AVFormatContext *os = output_files[ost->file_index]->ctx;
2346 if (ost->finished ||
2347 (os->pb && avio_tell(os->pb) >= of->limit_filesize))
2348 continue;
2349 if (ost->frame_number >= ost->max_frames) {
2350 int j;
2351 for (j = 0; j < of->ctx->nb_streams; j++)
2352 output_streams[of->ost_index + j]->finished = 1;
2353 continue;
2356 return 1;
2359 return 0;
2362 static InputFile *select_input_file(void)
2364 InputFile *ifile = NULL;
2365 int64_t ipts_min = INT64_MAX;
2366 int i;
2368 for (i = 0; i < nb_input_streams; i++) {
2369 InputStream *ist = input_streams[i];
2370 int64_t ipts = ist->last_dts;
2372 if (ist->discard || input_files[ist->file_index]->eagain)
2373 continue;
2374 if (!input_files[ist->file_index]->eof_reached) {
2375 if (ipts < ipts_min) {
2376 ipts_min = ipts;
2377 ifile = input_files[ist->file_index];
2382 return ifile;
2385 #if HAVE_PTHREADS
2386 static void *input_thread(void *arg)
2388 InputFile *f = arg;
2389 int ret = 0;
2391 while (!transcoding_finished && ret >= 0) {
2392 AVPacket pkt;
2393 ret = av_read_frame(f->ctx, &pkt);
2395 if (ret == AVERROR(EAGAIN)) {
2396 av_usleep(10000);
2397 ret = 0;
2398 continue;
2399 } else if (ret < 0)
2400 break;
2402 pthread_mutex_lock(&f->fifo_lock);
2403 while (!av_fifo_space(f->fifo))
2404 pthread_cond_wait(&f->fifo_cond, &f->fifo_lock);
2406 av_fifo_generic_write(f->fifo, &pkt, sizeof(pkt), NULL);
2408 pthread_mutex_unlock(&f->fifo_lock);
2411 f->finished = 1;
2412 return NULL;
2415 static void free_input_threads(void)
2417 int i;
2419 if (nb_input_files == 1)
2420 return;
2422 transcoding_finished = 1;
2424 for (i = 0; i < nb_input_files; i++) {
2425 InputFile *f = input_files[i];
2426 AVPacket pkt;
2428 if (!f->fifo || f->joined)
2429 continue;
2431 pthread_mutex_lock(&f->fifo_lock);
2432 while (av_fifo_size(f->fifo)) {
2433 av_fifo_generic_read(f->fifo, &pkt, sizeof(pkt), NULL);
2434 av_packet_unref(&pkt);
2436 pthread_cond_signal(&f->fifo_cond);
2437 pthread_mutex_unlock(&f->fifo_lock);
2439 pthread_join(f->thread, NULL);
2440 f->joined = 1;
2442 while (av_fifo_size(f->fifo)) {
2443 av_fifo_generic_read(f->fifo, &pkt, sizeof(pkt), NULL);
2444 av_packet_unref(&pkt);
2446 av_fifo_free(f->fifo);
2450 static int init_input_threads(void)
2452 int i, ret;
2454 if (nb_input_files == 1)
2455 return 0;
2457 for (i = 0; i < nb_input_files; i++) {
2458 InputFile *f = input_files[i];
2460 if (!(f->fifo = av_fifo_alloc(8*sizeof(AVPacket))))
2461 return AVERROR(ENOMEM);
2463 pthread_mutex_init(&f->fifo_lock, NULL);
2464 pthread_cond_init (&f->fifo_cond, NULL);
2466 if ((ret = pthread_create(&f->thread, NULL, input_thread, f)))
2467 return AVERROR(ret);
2469 return 0;
2472 static int get_input_packet_mt(InputFile *f, AVPacket *pkt)
2474 int ret = 0;
2476 pthread_mutex_lock(&f->fifo_lock);
2478 if (av_fifo_size(f->fifo)) {
2479 av_fifo_generic_read(f->fifo, pkt, sizeof(*pkt), NULL);
2480 pthread_cond_signal(&f->fifo_cond);
2481 } else {
2482 if (f->finished)
2483 ret = AVERROR_EOF;
2484 else
2485 ret = AVERROR(EAGAIN);
2488 pthread_mutex_unlock(&f->fifo_lock);
2490 return ret;
2492 #endif
2494 static int get_input_packet(InputFile *f, AVPacket *pkt)
2496 if (f->rate_emu) {
2497 int i;
2498 for (i = 0; i < f->nb_streams; i++) {
2499 InputStream *ist = input_streams[f->ist_index + i];
2500 int64_t pts = av_rescale(ist->last_dts, 1000000, AV_TIME_BASE);
2501 int64_t now = av_gettime_relative() - ist->start;
2502 if (pts > now)
2503 return AVERROR(EAGAIN);
2507 #if HAVE_PTHREADS
2508 if (nb_input_files > 1)
2509 return get_input_packet_mt(f, pkt);
2510 #endif
2511 return av_read_frame(f->ctx, pkt);
2514 static int got_eagain(void)
2516 int i;
2517 for (i = 0; i < nb_input_files; i++)
2518 if (input_files[i]->eagain)
2519 return 1;
2520 return 0;
2523 static void reset_eagain(void)
2525 int i;
2526 for (i = 0; i < nb_input_files; i++)
2527 input_files[i]->eagain = 0;
2530 // set duration to max(tmp, duration) in a proper time base and return duration's time_base
2531 static AVRational duration_max(int64_t tmp, int64_t *duration, AVRational tmp_time_base,
2532 AVRational time_base)
2534 int ret;
2536 if (!*duration) {
2537 *duration = tmp;
2538 return tmp_time_base;
2541 ret = av_compare_ts(*duration, time_base, tmp, tmp_time_base);
2542 if (ret < 0) {
2543 *duration = tmp;
2544 return tmp_time_base;
2547 return time_base;
2550 static int seek_to_start(InputFile *ifile, AVFormatContext *is)
2552 InputStream *ist;
2553 AVCodecContext *avctx;
2554 int i, ret, has_audio = 0;
2555 int64_t duration = 0;
2557 ret = av_seek_frame(is, -1, is->start_time, 0);
2558 if (ret < 0)
2559 return ret;
2561 for (i = 0; i < ifile->nb_streams; i++) {
2562 ist = input_streams[ifile->ist_index + i];
2563 avctx = ist->dec_ctx;
2565 // flush decoders
2566 if (ist->decoding_needed) {
2567 process_input_packet(ist, NULL, 1);
2568 avcodec_flush_buffers(avctx);
2571 /* duration is the length of the last frame in a stream
2572 * when audio stream is present we don't care about
2573 * last video frame length because it's not defined exactly */
2574 if (avctx->codec_type == AVMEDIA_TYPE_AUDIO && ist->nb_samples)
2575 has_audio = 1;
2578 for (i = 0; i < ifile->nb_streams; i++) {
2579 ist = input_streams[ifile->ist_index + i];
2580 avctx = ist->dec_ctx;
2582 if (has_audio) {
2583 if (avctx->codec_type == AVMEDIA_TYPE_AUDIO && ist->nb_samples) {
2584 AVRational sample_rate = {1, avctx->sample_rate};
2586 duration = av_rescale_q(ist->nb_samples, sample_rate, ist->st->time_base);
2587 } else
2588 continue;
2589 } else {
2590 if (ist->framerate.num) {
2591 duration = FFMAX(av_rescale_q(1, av_inv_q(ist->framerate), ist->st->time_base), 1);
2592 } else if (ist->st->avg_frame_rate.num) {
2593 duration = FFMAX(av_rescale_q(1, av_inv_q(ist->st->avg_frame_rate), ist->st->time_base), 1);
2594 } else duration = 1;
2596 if (!ifile->duration)
2597 ifile->time_base = ist->st->time_base;
2598 /* the total duration of the stream, max_pts - min_pts is
2599 * the duration of the stream without the last frame */
2600 duration += ist->max_pts - ist->min_pts;
2601 ifile->time_base = duration_max(duration, &ifile->duration, ist->st->time_base,
2602 ifile->time_base);
2605 if (ifile->loop > 0)
2606 ifile->loop--;
2608 return ret;
2612 * Read one packet from an input file and send it for
2613 * - decoding -> lavfi (audio/video)
2614 * - decoding -> encoding -> muxing (subtitles)
2615 * - muxing (streamcopy)
2617 * Return
2618 * - 0 -- one packet was read and processed
2619 * - AVERROR(EAGAIN) -- no packets were available for selected file,
2620 * this function should be called again
2621 * - AVERROR_EOF -- this function should not be called again
2623 static int process_input(void)
2625 InputFile *ifile;
2626 AVFormatContext *is;
2627 InputStream *ist;
2628 AVPacket pkt;
2629 int ret, i, j;
2630 int64_t duration;
2632 /* select the stream that we must read now */
2633 ifile = select_input_file();
2634 /* if none, if is finished */
2635 if (!ifile) {
2636 if (got_eagain()) {
2637 reset_eagain();
2638 av_usleep(10000);
2639 return AVERROR(EAGAIN);
2641 av_log(NULL, AV_LOG_VERBOSE, "No more inputs to read from.\n");
2642 return AVERROR_EOF;
2645 is = ifile->ctx;
2646 ret = get_input_packet(ifile, &pkt);
2648 if (ret == AVERROR(EAGAIN)) {
2649 ifile->eagain = 1;
2650 return ret;
2652 if (ret < 0 && ifile->loop) {
2653 ret = seek_to_start(ifile, is);
2654 if(ret < 0)
2655 av_log(NULL, AV_LOG_WARNING, "Seek to start failed.\n");
2656 else
2657 ret = get_input_packet(ifile, &pkt);
2659 if (ret < 0) {
2660 if (ret != AVERROR_EOF) {
2661 print_error(is->filename, ret);
2662 if (exit_on_error)
2663 exit_program(1);
2665 ifile->eof_reached = 1;
2667 for (i = 0; i < ifile->nb_streams; i++) {
2668 ist = input_streams[ifile->ist_index + i];
2669 if (ist->decoding_needed)
2670 process_input_packet(ist, NULL, 0);
2672 /* mark all outputs that don't go through lavfi as finished */
2673 for (j = 0; j < nb_output_streams; j++) {
2674 OutputStream *ost = output_streams[j];
2676 if (ost->source_index == ifile->ist_index + i &&
2677 (ost->stream_copy || ost->enc->type == AVMEDIA_TYPE_SUBTITLE))
2678 finish_output_stream(ost);
2682 return AVERROR(EAGAIN);
2685 reset_eagain();
2687 if (do_pkt_dump) {
2688 av_pkt_dump_log2(NULL, AV_LOG_DEBUG, &pkt, do_hex_dump,
2689 is->streams[pkt.stream_index]);
2691 /* the following test is needed in case new streams appear
2692 dynamically in stream : we ignore them */
2693 if (pkt.stream_index >= ifile->nb_streams)
2694 goto discard_packet;
2696 ist = input_streams[ifile->ist_index + pkt.stream_index];
2698 ist->data_size += pkt.size;
2699 ist->nb_packets++;
2701 if (ist->discard)
2702 goto discard_packet;
2704 /* add the stream-global side data to the first packet */
2705 if (ist->nb_packets == 1)
2706 for (i = 0; i < ist->st->nb_side_data; i++) {
2707 AVPacketSideData *src_sd = &ist->st->side_data[i];
2708 uint8_t *dst_data;
2710 if (av_packet_get_side_data(&pkt, src_sd->type, NULL))
2711 continue;
2712 if (ist->autorotate && src_sd->type == AV_PKT_DATA_DISPLAYMATRIX)
2713 continue;
2715 dst_data = av_packet_new_side_data(&pkt, src_sd->type, src_sd->size);
2716 if (!dst_data)
2717 exit_program(1);
2719 memcpy(dst_data, src_sd->data, src_sd->size);
2722 if (pkt.dts != AV_NOPTS_VALUE)
2723 pkt.dts += av_rescale_q(ifile->ts_offset, AV_TIME_BASE_Q, ist->st->time_base);
2724 if (pkt.pts != AV_NOPTS_VALUE)
2725 pkt.pts += av_rescale_q(ifile->ts_offset, AV_TIME_BASE_Q, ist->st->time_base);
2727 if (pkt.pts != AV_NOPTS_VALUE)
2728 pkt.pts *= ist->ts_scale;
2729 if (pkt.dts != AV_NOPTS_VALUE)
2730 pkt.dts *= ist->ts_scale;
2732 if ((ist->dec_ctx->codec_type == AVMEDIA_TYPE_VIDEO ||
2733 ist->dec_ctx->codec_type == AVMEDIA_TYPE_AUDIO) &&
2734 pkt.dts != AV_NOPTS_VALUE && ist->next_dts != AV_NOPTS_VALUE &&
2735 (is->iformat->flags & AVFMT_TS_DISCONT)) {
2736 int64_t pkt_dts = av_rescale_q(pkt.dts, ist->st->time_base, AV_TIME_BASE_Q);
2737 int64_t delta = pkt_dts - ist->next_dts;
2739 if ((FFABS(delta) > 1LL * dts_delta_threshold * AV_TIME_BASE || pkt_dts + 1 < ist->last_dts) && !copy_ts) {
2740 ifile->ts_offset -= delta;
2741 av_log(NULL, AV_LOG_DEBUG,
2742 "timestamp discontinuity %"PRId64", new offset= %"PRId64"\n",
2743 delta, ifile->ts_offset);
2744 pkt.dts -= av_rescale_q(delta, AV_TIME_BASE_Q, ist->st->time_base);
2745 if (pkt.pts != AV_NOPTS_VALUE)
2746 pkt.pts -= av_rescale_q(delta, AV_TIME_BASE_Q, ist->st->time_base);
2749 duration = av_rescale_q(ifile->duration, ifile->time_base, ist->st->time_base);
2750 if (pkt.pts != AV_NOPTS_VALUE) {
2751 pkt.pts += duration;
2752 ist->max_pts = FFMAX(pkt.pts, ist->max_pts);
2753 ist->min_pts = FFMIN(pkt.pts, ist->min_pts);
2756 if (pkt.dts != AV_NOPTS_VALUE)
2757 pkt.dts += duration;
2759 process_input_packet(ist, &pkt, 0);
2761 discard_packet:
2762 av_packet_unref(&pkt);
2764 return 0;
2768 * The following code is the main loop of the file converter
2770 static int transcode(void)
2772 int ret, i, need_input = 1;
2773 AVFormatContext *os;
2774 OutputStream *ost;
2775 InputStream *ist;
2776 int64_t timer_start;
2778 ret = transcode_init();
2779 if (ret < 0)
2780 goto fail;
2782 av_log(NULL, AV_LOG_INFO, "Press ctrl-c to stop encoding\n");
2783 term_init();
2785 timer_start = av_gettime_relative();
2787 #if HAVE_PTHREADS
2788 if ((ret = init_input_threads()) < 0)
2789 goto fail;
2790 #endif
2792 while (!received_sigterm) {
2793 /* check if there's any stream where output is still needed */
2794 if (!need_output()) {
2795 av_log(NULL, AV_LOG_VERBOSE, "No more output streams to write to, finishing.\n");
2796 break;
2799 /* read and process one input packet if needed */
2800 if (need_input) {
2801 ret = process_input();
2802 if (ret == AVERROR_EOF)
2803 need_input = 0;
2806 ret = poll_filters();
2807 if (ret < 0 && ret != AVERROR_EOF) {
2808 char errbuf[128];
2809 av_strerror(ret, errbuf, sizeof(errbuf));
2811 av_log(NULL, AV_LOG_ERROR, "Error while filtering: %s\n", errbuf);
2812 break;
2815 /* dump report by using the output first video and audio streams */
2816 print_report(0, timer_start);
2818 #if HAVE_PTHREADS
2819 free_input_threads();
2820 #endif
2822 /* at the end of stream, we must flush the decoder buffers */
2823 for (i = 0; i < nb_input_streams; i++) {
2824 ist = input_streams[i];
2825 if (!input_files[ist->file_index]->eof_reached) {
2826 process_input_packet(ist, NULL, 0);
2829 poll_filters();
2830 flush_encoders();
2832 term_exit();
2834 /* write the trailer if needed and close file */
2835 for (i = 0; i < nb_output_files; i++) {
2836 os = output_files[i]->ctx;
2837 if (!output_files[i]->header_written) {
2838 av_log(NULL, AV_LOG_ERROR,
2839 "Nothing was written into output file %d (%s), because "
2840 "at least one of its streams received no packets.\n",
2841 i, os->filename);
2842 continue;
2844 av_write_trailer(os);
2847 /* dump report by using the first video and audio streams */
2848 print_report(1, timer_start);
2850 /* close each encoder */
2851 for (i = 0; i < nb_output_streams; i++) {
2852 ost = output_streams[i];
2853 if (ost->encoding_needed) {
2854 av_freep(&ost->enc_ctx->stats_in);
2858 /* close each decoder */
2859 for (i = 0; i < nb_input_streams; i++) {
2860 ist = input_streams[i];
2861 if (ist->decoding_needed) {
2862 avcodec_close(ist->dec_ctx);
2863 if (ist->hwaccel_uninit)
2864 ist->hwaccel_uninit(ist->dec_ctx);
2868 av_buffer_unref(&hw_device_ctx);
2869 hw_device_free_all();
2871 /* finished ! */
2872 ret = 0;
2874 fail:
2875 #if HAVE_PTHREADS
2876 free_input_threads();
2877 #endif
2879 if (output_streams) {
2880 for (i = 0; i < nb_output_streams; i++) {
2881 ost = output_streams[i];
2882 if (ost) {
2883 if (ost->logfile) {
2884 fclose(ost->logfile);
2885 ost->logfile = NULL;
2887 av_free(ost->forced_kf_pts);
2888 av_dict_free(&ost->encoder_opts);
2889 av_dict_free(&ost->resample_opts);
2893 return ret;
2896 static int64_t getutime(void)
2898 #if HAVE_GETRUSAGE
2899 struct rusage rusage;
2901 getrusage(RUSAGE_SELF, &rusage);
2902 return (rusage.ru_utime.tv_sec * 1000000LL) + rusage.ru_utime.tv_usec;
2903 #elif HAVE_GETPROCESSTIMES
2904 HANDLE proc;
2905 FILETIME c, e, k, u;
2906 proc = GetCurrentProcess();
2907 GetProcessTimes(proc, &c, &e, &k, &u);
2908 return ((int64_t) u.dwHighDateTime << 32 | u.dwLowDateTime) / 10;
2909 #else
2910 return av_gettime_relative();
2911 #endif
2914 static int64_t getmaxrss(void)
2916 #if HAVE_GETRUSAGE && HAVE_STRUCT_RUSAGE_RU_MAXRSS
2917 struct rusage rusage;
2918 getrusage(RUSAGE_SELF, &rusage);
2919 return (int64_t)rusage.ru_maxrss * 1024;
2920 #elif HAVE_GETPROCESSMEMORYINFO
2921 HANDLE proc;
2922 PROCESS_MEMORY_COUNTERS memcounters;
2923 proc = GetCurrentProcess();
2924 memcounters.cb = sizeof(memcounters);
2925 GetProcessMemoryInfo(proc, &memcounters, sizeof(memcounters));
2926 return memcounters.PeakPagefileUsage;
2927 #else
2928 return 0;
2929 #endif
2932 int main(int argc, char **argv)
2934 int i, ret;
2935 int64_t ti;
2937 register_exit(avconv_cleanup);
2939 av_log_set_flags(AV_LOG_SKIP_REPEATED);
2940 parse_loglevel(argc, argv, options);
2942 avcodec_register_all();
2943 #if CONFIG_AVDEVICE
2944 avdevice_register_all();
2945 #endif
2946 avfilter_register_all();
2947 av_register_all();
2948 avformat_network_init();
2950 show_banner();
2952 /* parse options and open all input/output files */
2953 ret = avconv_parse_options(argc, argv);
2954 if (ret < 0)
2955 exit_program(1);
2957 if (nb_output_files <= 0 && nb_input_files == 0) {
2958 show_usage();
2959 av_log(NULL, AV_LOG_WARNING, "Use -h to get full help or, even better, run 'man %s'\n", program_name);
2960 exit_program(1);
2963 /* file converter / grab */
2964 if (nb_output_files <= 0) {
2965 fprintf(stderr, "At least one output file must be specified\n");
2966 exit_program(1);
2969 for (i = 0; i < nb_output_files; i++) {
2970 if (strcmp(output_files[i]->ctx->oformat->name, "rtp"))
2971 want_sdp = 0;
2974 ti = getutime();
2975 if (transcode() < 0)
2976 exit_program(1);
2977 ti = getutime() - ti;
2978 if (do_benchmark) {
2979 int maxrss = getmaxrss() / 1024;
2980 printf("bench: utime=%0.3fs maxrss=%ikB\n", ti / 1000000.0, maxrss);
2983 exit_program(0);
2984 return 0;