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
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/intreadwrite.h"
42 #include "libavutil/dict.h"
43 #include "libavutil/mathematics.h"
44 #include "libavutil/pixdesc.h"
45 #include "libavutil/avstring.h"
46 #include "libavutil/libm.h"
47 #include "libavutil/imgutils.h"
48 #include "libavutil/time.h"
49 #include "libavformat/os_support.h"
51 # include "libavfilter/avfilter.h"
52 # include "libavfilter/buffersrc.h"
53 # include "libavfilter/buffersink.h"
55 #if HAVE_SYS_RESOURCE_H
57 #include <sys/types.h>
58 #include <sys/resource.h>
59 #elif HAVE_GETPROCESSTIMES
62 #if HAVE_GETPROCESSMEMORYINFO
68 #include <sys/select.h>
80 #include "libavutil/avassert.h"
82 const char program_name[] = "avconv";
83 const int program_birth_year = 2000;
85 static FILE *vstats_file;
87 static int nb_frames_drop = 0;
92 /* signal to input threads that they should exit; set by the main thread */
93 static int transcoding_finished;
96 InputStream **input_streams = NULL;
97 int nb_input_streams = 0;
98 InputFile **input_files = NULL;
99 int nb_input_files = 0;
101 OutputStream **output_streams = NULL;
102 int nb_output_streams = 0;
103 OutputFile **output_files = NULL;
104 int nb_output_files = 0;
106 FilterGraph **filtergraphs;
109 static void term_exit(void)
111 av_log(NULL, AV_LOG_QUIET, "");
114 static volatile int received_sigterm = 0;
115 static volatile int received_nb_signals = 0;
118 sigterm_handler(int sig)
120 received_sigterm = sig;
121 received_nb_signals++;
125 static void term_init(void)
127 signal(SIGINT , sigterm_handler); /* Interrupt (ANSI). */
128 signal(SIGTERM, sigterm_handler); /* Termination (ANSI). */
130 signal(SIGXCPU, sigterm_handler);
134 static int decode_interrupt_cb(void *ctx)
136 return received_nb_signals > 1;
139 const AVIOInterruptCB int_cb = { decode_interrupt_cb, NULL };
141 static void avconv_cleanup(int ret)
145 for (i = 0; i < nb_filtergraphs; i++) {
146 FilterGraph *fg = filtergraphs[i];
147 avfilter_graph_free(&fg->graph);
148 for (j = 0; j < fg->nb_inputs; j++) {
149 av_freep(&fg->inputs[j]->name);
150 av_freep(&fg->inputs[j]);
152 av_freep(&fg->inputs);
153 for (j = 0; j < fg->nb_outputs; j++) {
154 av_freep(&fg->outputs[j]->name);
155 av_freep(&fg->outputs[j]);
157 av_freep(&fg->outputs);
158 av_freep(&fg->graph_desc);
160 av_freep(&filtergraphs[i]);
162 av_freep(&filtergraphs);
165 for (i = 0; i < nb_output_files; i++) {
166 OutputFile *of = output_files[i];
167 AVFormatContext *s = of->ctx;
168 if (s && s->oformat && !(s->oformat->flags & AVFMT_NOFILE) && s->pb)
170 avformat_free_context(s);
171 av_dict_free(&of->opts);
173 av_freep(&output_files[i]);
175 for (i = 0; i < nb_output_streams; i++) {
176 OutputStream *ost = output_streams[i];
177 AVBitStreamFilterContext *bsfc = ost->bitstream_filters;
179 AVBitStreamFilterContext *next = bsfc->next;
180 av_bitstream_filter_close(bsfc);
183 ost->bitstream_filters = NULL;
184 av_frame_free(&ost->filtered_frame);
186 av_parser_close(ost->parser);
188 av_freep(&ost->forced_keyframes);
189 av_freep(&ost->avfilter);
190 av_freep(&ost->logfile_prefix);
192 avcodec_free_context(&ost->enc_ctx);
194 av_freep(&output_streams[i]);
196 for (i = 0; i < nb_input_files; i++) {
197 avformat_close_input(&input_files[i]->ctx);
198 av_freep(&input_files[i]);
200 for (i = 0; i < nb_input_streams; i++) {
201 InputStream *ist = input_streams[i];
203 av_frame_free(&ist->decoded_frame);
204 av_frame_free(&ist->filter_frame);
205 av_dict_free(&ist->decoder_opts);
206 av_freep(&ist->filters);
207 av_freep(&ist->hwaccel_device);
209 avcodec_free_context(&ist->dec_ctx);
211 av_freep(&input_streams[i]);
216 av_free(vstats_filename);
218 av_freep(&input_streams);
219 av_freep(&input_files);
220 av_freep(&output_streams);
221 av_freep(&output_files);
225 avformat_network_deinit();
227 if (received_sigterm) {
228 av_log(NULL, AV_LOG_INFO, "Received signal %d: terminating.\n",
229 (int) received_sigterm);
234 void assert_avoptions(AVDictionary *m)
236 AVDictionaryEntry *t;
237 if ((t = av_dict_get(m, "", NULL, AV_DICT_IGNORE_SUFFIX))) {
238 av_log(NULL, AV_LOG_FATAL, "Option %s not found.\n", t->key);
243 static void abort_codec_experimental(AVCodec *c, int encoder)
245 const char *codec_string = encoder ? "encoder" : "decoder";
247 av_log(NULL, AV_LOG_FATAL, "%s '%s' is experimental and might produce bad "
248 "results.\nAdd '-strict experimental' if you want to use it.\n",
249 codec_string, c->name);
250 codec = encoder ? avcodec_find_encoder(c->id) : avcodec_find_decoder(c->id);
251 if (!(codec->capabilities & CODEC_CAP_EXPERIMENTAL))
252 av_log(NULL, AV_LOG_FATAL, "Or use the non experimental %s '%s'.\n",
253 codec_string, codec->name);
257 static void write_frame(AVFormatContext *s, AVPacket *pkt, OutputStream *ost)
259 AVBitStreamFilterContext *bsfc = ost->bitstream_filters;
260 AVCodecContext *avctx = ost->encoding_needed ? ost->enc_ctx : ost->st->codec;
264 * Audio encoders may split the packets -- #frames in != #packets out.
265 * But there is no reordering, so we can limit the number of output packets
266 * by simply dropping them here.
267 * Counting encoded video frames needs to be done separately because of
268 * reordering, see do_video_out()
270 if (!(avctx->codec_type == AVMEDIA_TYPE_VIDEO && avctx->codec)) {
271 if (ost->frame_number >= ost->max_frames) {
279 AVPacket new_pkt = *pkt;
280 int a = av_bitstream_filter_filter(bsfc, avctx, NULL,
281 &new_pkt.data, &new_pkt.size,
282 pkt->data, pkt->size,
283 pkt->flags & AV_PKT_FLAG_KEY);
286 new_pkt.buf = av_buffer_create(new_pkt.data, new_pkt.size,
287 av_buffer_default_free, NULL, 0);
291 av_log(NULL, AV_LOG_ERROR, "%s failed for stream %d, codec %s",
292 bsfc->filter->name, pkt->stream_index,
293 avctx->codec ? avctx->codec->name : "copy");
303 if (!(s->oformat->flags & AVFMT_NOTIMESTAMPS) &&
304 ost->last_mux_dts != AV_NOPTS_VALUE &&
305 pkt->dts < ost->last_mux_dts + !(s->oformat->flags & AVFMT_TS_NONSTRICT)) {
306 av_log(NULL, AV_LOG_WARNING, "Non-monotonous DTS in output stream "
307 "%d:%d; previous: %"PRId64", current: %"PRId64"; ",
308 ost->file_index, ost->st->index, ost->last_mux_dts, pkt->dts);
310 av_log(NULL, AV_LOG_FATAL, "aborting.\n");
313 av_log(NULL, AV_LOG_WARNING, "changing to %"PRId64". This may result "
314 "in incorrect timestamps in the output file.\n",
315 ost->last_mux_dts + 1);
316 pkt->dts = ost->last_mux_dts + 1;
317 if (pkt->pts != AV_NOPTS_VALUE)
318 pkt->pts = FFMAX(pkt->pts, pkt->dts);
320 ost->last_mux_dts = pkt->dts;
322 ost->data_size += pkt->size;
323 ost->packets_written++;
325 pkt->stream_index = ost->index;
326 ret = av_interleaved_write_frame(s, pkt);
328 print_error("av_interleaved_write_frame()", ret);
333 static int check_recording_time(OutputStream *ost)
335 OutputFile *of = output_files[ost->file_index];
337 if (of->recording_time != INT64_MAX &&
338 av_compare_ts(ost->sync_opts - ost->first_pts, ost->enc_ctx->time_base, of->recording_time,
339 AV_TIME_BASE_Q) >= 0) {
346 static void do_audio_out(AVFormatContext *s, OutputStream *ost,
349 AVCodecContext *enc = ost->enc_ctx;
353 av_init_packet(&pkt);
357 if (frame->pts == AV_NOPTS_VALUE || audio_sync_method < 0)
358 frame->pts = ost->sync_opts;
359 ost->sync_opts = frame->pts + frame->nb_samples;
361 ost->samples_encoded += frame->nb_samples;
362 ost->frames_encoded++;
364 if (avcodec_encode_audio2(enc, &pkt, frame, &got_packet) < 0) {
365 av_log(NULL, AV_LOG_FATAL, "Audio encoding failed\n");
370 av_packet_rescale_ts(&pkt, enc->time_base, ost->st->time_base);
371 write_frame(s, &pkt, ost);
375 static void do_subtitle_out(AVFormatContext *s,
381 static uint8_t *subtitle_out = NULL;
382 int subtitle_out_max_size = 1024 * 1024;
383 int subtitle_out_size, nb, i;
387 if (pts == AV_NOPTS_VALUE) {
388 av_log(NULL, AV_LOG_ERROR, "Subtitle packets must have a pts\n");
397 subtitle_out = av_malloc(subtitle_out_max_size);
400 /* Note: DVB subtitle need one packet to draw them and one other
401 packet to clear them */
402 /* XXX: signal it in the codec context ? */
403 if (enc->codec_id == AV_CODEC_ID_DVB_SUBTITLE)
408 for (i = 0; i < nb; i++) {
409 ost->sync_opts = av_rescale_q(pts, ist->st->time_base, enc->time_base);
410 if (!check_recording_time(ost))
413 sub->pts = av_rescale_q(pts, ist->st->time_base, AV_TIME_BASE_Q);
414 // start_display_time is required to be 0
415 sub->pts += av_rescale_q(sub->start_display_time, (AVRational){ 1, 1000 }, AV_TIME_BASE_Q);
416 sub->end_display_time -= sub->start_display_time;
417 sub->start_display_time = 0;
419 ost->frames_encoded++;
421 subtitle_out_size = avcodec_encode_subtitle(enc, subtitle_out,
422 subtitle_out_max_size, sub);
423 if (subtitle_out_size < 0) {
424 av_log(NULL, AV_LOG_FATAL, "Subtitle encoding failed\n");
428 av_init_packet(&pkt);
429 pkt.data = subtitle_out;
430 pkt.size = subtitle_out_size;
431 pkt.pts = av_rescale_q(sub->pts, AV_TIME_BASE_Q, ost->st->time_base);
432 if (enc->codec_id == AV_CODEC_ID_DVB_SUBTITLE) {
433 /* XXX: the pts correction is handled here. Maybe handling
434 it in the codec would be better */
436 pkt.pts += 90 * sub->start_display_time;
438 pkt.pts += 90 * sub->end_display_time;
440 write_frame(s, &pkt, ost);
444 static void do_video_out(AVFormatContext *s,
449 int ret, format_video_sync;
451 AVCodecContext *enc = ost->enc_ctx;
455 format_video_sync = video_sync_method;
456 if (format_video_sync == VSYNC_AUTO)
457 format_video_sync = (s->oformat->flags & AVFMT_NOTIMESTAMPS) ? VSYNC_PASSTHROUGH :
458 (s->oformat->flags & AVFMT_VARIABLE_FPS) ? VSYNC_VFR : VSYNC_CFR;
459 if (format_video_sync != VSYNC_PASSTHROUGH &&
461 in_picture->pts != AV_NOPTS_VALUE &&
462 in_picture->pts < ost->sync_opts) {
464 av_log(NULL, AV_LOG_WARNING,
465 "*** dropping frame %d from stream %d at ts %"PRId64"\n",
466 ost->frame_number, ost->st->index, in_picture->pts);
470 if (in_picture->pts == AV_NOPTS_VALUE)
471 in_picture->pts = ost->sync_opts;
472 ost->sync_opts = in_picture->pts;
475 if (!ost->frame_number)
476 ost->first_pts = in_picture->pts;
478 av_init_packet(&pkt);
482 if (ost->frame_number >= ost->max_frames)
485 if (s->oformat->flags & AVFMT_RAWPICTURE &&
486 enc->codec->id == AV_CODEC_ID_RAWVIDEO) {
487 /* raw pictures are written as AVPicture structure to
488 avoid any copies. We support temporarily the older
490 enc->coded_frame->interlaced_frame = in_picture->interlaced_frame;
491 enc->coded_frame->top_field_first = in_picture->top_field_first;
492 pkt.data = (uint8_t *)in_picture;
493 pkt.size = sizeof(AVPicture);
494 pkt.pts = av_rescale_q(in_picture->pts, enc->time_base, ost->st->time_base);
495 pkt.flags |= AV_PKT_FLAG_KEY;
497 write_frame(s, &pkt, ost);
501 if (enc->flags & (CODEC_FLAG_INTERLACED_DCT|CODEC_FLAG_INTERLACED_ME) &&
502 ost->top_field_first >= 0)
503 in_picture->top_field_first = !!ost->top_field_first;
505 in_picture->quality = enc->global_quality;
506 in_picture->pict_type = 0;
507 if (ost->forced_kf_index < ost->forced_kf_count &&
508 in_picture->pts >= ost->forced_kf_pts[ost->forced_kf_index]) {
509 in_picture->pict_type = AV_PICTURE_TYPE_I;
510 ost->forced_kf_index++;
513 ost->frames_encoded++;
515 ret = avcodec_encode_video2(enc, &pkt, in_picture, &got_packet);
517 av_log(NULL, AV_LOG_FATAL, "Video encoding failed\n");
522 av_packet_rescale_ts(&pkt, enc->time_base, ost->st->time_base);
523 write_frame(s, &pkt, ost);
524 *frame_size = pkt.size;
526 /* if two pass, output log */
527 if (ost->logfile && enc->stats_out) {
528 fprintf(ost->logfile, "%s", enc->stats_out);
534 * For video, number of frames in == number of packets out.
535 * But there may be reordering, so we can't throw away frames on encoder
536 * flush, we need to limit them here, before they go into encoder.
541 static double psnr(double d)
543 return -10.0 * log(d) / log(10.0);
546 static void do_video_stats(OutputStream *ost, int frame_size)
550 double ti1, bitrate, avg_bitrate;
552 /* this is executed just the first time do_video_stats is called */
554 vstats_file = fopen(vstats_filename, "w");
562 if (enc->codec_type == AVMEDIA_TYPE_VIDEO) {
563 frame_number = ost->frame_number;
564 fprintf(vstats_file, "frame= %5d q= %2.1f ", frame_number, enc->coded_frame->quality / (float)FF_QP2LAMBDA);
565 if (enc->flags&CODEC_FLAG_PSNR)
566 fprintf(vstats_file, "PSNR= %6.2f ", psnr(enc->coded_frame->error[0] / (enc->width * enc->height * 255.0 * 255.0)));
568 fprintf(vstats_file,"f_size= %6d ", frame_size);
569 /* compute pts value */
570 ti1 = ost->sync_opts * av_q2d(enc->time_base);
574 bitrate = (frame_size * 8) / av_q2d(enc->time_base) / 1000.0;
575 avg_bitrate = (double)(ost->data_size * 8) / ti1 / 1000.0;
576 fprintf(vstats_file, "s_size= %8.0fkB time= %0.3f br= %7.1fkbits/s avg_br= %7.1fkbits/s ",
577 (double)ost->data_size / 1024, ti1, bitrate, avg_bitrate);
578 fprintf(vstats_file, "type= %c\n", av_get_picture_type_char(enc->coded_frame->pict_type));
583 * Read one frame for lavfi output for ost and encode it.
585 static int poll_filter(OutputStream *ost)
587 OutputFile *of = output_files[ost->file_index];
588 AVFrame *filtered_frame = NULL;
591 if (!ost->filtered_frame && !(ost->filtered_frame = av_frame_alloc())) {
592 return AVERROR(ENOMEM);
594 filtered_frame = ost->filtered_frame;
596 if (ost->enc->type == AVMEDIA_TYPE_AUDIO &&
597 !(ost->enc->capabilities & CODEC_CAP_VARIABLE_FRAME_SIZE))
598 ret = av_buffersink_get_samples(ost->filter->filter, filtered_frame,
599 ost->enc_ctx->frame_size);
601 ret = av_buffersink_get_frame(ost->filter->filter, filtered_frame);
606 if (filtered_frame->pts != AV_NOPTS_VALUE) {
607 int64_t start_time = (of->start_time == AV_NOPTS_VALUE) ? 0 : of->start_time;
608 filtered_frame->pts = av_rescale_q(filtered_frame->pts,
609 ost->filter->filter->inputs[0]->time_base,
610 ost->enc_ctx->time_base) -
611 av_rescale_q(start_time,
613 ost->enc_ctx->time_base);
616 switch (ost->filter->filter->inputs[0]->type) {
617 case AVMEDIA_TYPE_VIDEO:
618 if (!ost->frame_aspect_ratio)
619 ost->enc_ctx->sample_aspect_ratio = filtered_frame->sample_aspect_ratio;
621 do_video_out(of->ctx, ost, filtered_frame, &frame_size);
622 if (vstats_filename && frame_size)
623 do_video_stats(ost, frame_size);
625 case AVMEDIA_TYPE_AUDIO:
626 do_audio_out(of->ctx, ost, filtered_frame);
629 // TODO support subtitle filters
633 av_frame_unref(filtered_frame);
638 static void finish_output_stream(OutputStream *ost)
640 OutputFile *of = output_files[ost->file_index];
646 for (i = 0; i < of->ctx->nb_streams; i++)
647 output_streams[of->ost_index + i]->finished = 1;
652 * Read as many frames from possible from lavfi and encode them.
654 * Always read from the active stream with the lowest timestamp. If no frames
655 * are available for it then return EAGAIN and wait for more input. This way we
656 * can use lavfi sources that generate unlimited amount of frames without memory
659 static int poll_filters(void)
663 while (ret >= 0 && !received_sigterm) {
664 OutputStream *ost = NULL;
665 int64_t min_pts = INT64_MAX;
667 /* choose output stream with the lowest timestamp */
668 for (i = 0; i < nb_output_streams; i++) {
669 int64_t pts = output_streams[i]->sync_opts;
671 if (!output_streams[i]->filter || output_streams[i]->finished)
674 pts = av_rescale_q(pts, output_streams[i]->enc_ctx->time_base,
678 ost = output_streams[i];
685 ret = poll_filter(ost);
687 if (ret == AVERROR_EOF) {
688 finish_output_stream(ost);
690 } else if (ret == AVERROR(EAGAIN))
697 static void print_final_stats(int64_t total_size)
699 uint64_t video_size = 0, audio_size = 0, extra_size = 0, other_size = 0;
700 uint64_t data_size = 0;
701 float percent = -1.0;
704 for (i = 0; i < nb_output_streams; i++) {
705 OutputStream *ost = output_streams[i];
706 switch (ost->enc_ctx->codec_type) {
707 case AVMEDIA_TYPE_VIDEO: video_size += ost->data_size; break;
708 case AVMEDIA_TYPE_AUDIO: audio_size += ost->data_size; break;
709 default: other_size += ost->data_size; break;
711 extra_size += ost->enc_ctx->extradata_size;
712 data_size += ost->data_size;
715 if (data_size && total_size >= data_size)
716 percent = 100.0 * (total_size - data_size) / data_size;
718 av_log(NULL, AV_LOG_INFO, "\n");
719 av_log(NULL, AV_LOG_INFO, "video:%1.0fkB audio:%1.0fkB other streams:%1.0fkB global headers:%1.0fkB muxing overhead: ",
723 extra_size / 1024.0);
725 av_log(NULL, AV_LOG_INFO, "%f%%", percent);
727 av_log(NULL, AV_LOG_INFO, "unknown");
728 av_log(NULL, AV_LOG_INFO, "\n");
730 /* print verbose per-stream stats */
731 for (i = 0; i < nb_input_files; i++) {
732 InputFile *f = input_files[i];
733 uint64_t total_packets = 0, total_size = 0;
735 av_log(NULL, AV_LOG_VERBOSE, "Input file #%d (%s):\n",
736 i, f->ctx->filename);
738 for (j = 0; j < f->nb_streams; j++) {
739 InputStream *ist = input_streams[f->ist_index + j];
740 enum AVMediaType type = ist->dec_ctx->codec_type;
742 total_size += ist->data_size;
743 total_packets += ist->nb_packets;
745 av_log(NULL, AV_LOG_VERBOSE, " Input stream #%d:%d (%s): ",
746 i, j, media_type_string(type));
747 av_log(NULL, AV_LOG_VERBOSE, "%"PRIu64" packets read (%"PRIu64" bytes); ",
748 ist->nb_packets, ist->data_size);
750 if (ist->decoding_needed) {
751 av_log(NULL, AV_LOG_VERBOSE, "%"PRIu64" frames decoded",
752 ist->frames_decoded);
753 if (type == AVMEDIA_TYPE_AUDIO)
754 av_log(NULL, AV_LOG_VERBOSE, " (%"PRIu64" samples)", ist->samples_decoded);
755 av_log(NULL, AV_LOG_VERBOSE, "; ");
758 av_log(NULL, AV_LOG_VERBOSE, "\n");
761 av_log(NULL, AV_LOG_VERBOSE, " Total: %"PRIu64" packets (%"PRIu64" bytes) demuxed\n",
762 total_packets, total_size);
765 for (i = 0; i < nb_output_files; i++) {
766 OutputFile *of = output_files[i];
767 uint64_t total_packets = 0, total_size = 0;
769 av_log(NULL, AV_LOG_VERBOSE, "Output file #%d (%s):\n",
770 i, of->ctx->filename);
772 for (j = 0; j < of->ctx->nb_streams; j++) {
773 OutputStream *ost = output_streams[of->ost_index + j];
774 enum AVMediaType type = ost->enc_ctx->codec_type;
776 total_size += ost->data_size;
777 total_packets += ost->packets_written;
779 av_log(NULL, AV_LOG_VERBOSE, " Output stream #%d:%d (%s): ",
780 i, j, media_type_string(type));
781 if (ost->encoding_needed) {
782 av_log(NULL, AV_LOG_VERBOSE, "%"PRIu64" frames encoded",
783 ost->frames_encoded);
784 if (type == AVMEDIA_TYPE_AUDIO)
785 av_log(NULL, AV_LOG_VERBOSE, " (%"PRIu64" samples)", ost->samples_encoded);
786 av_log(NULL, AV_LOG_VERBOSE, "; ");
789 av_log(NULL, AV_LOG_VERBOSE, "%"PRIu64" packets muxed (%"PRIu64" bytes); ",
790 ost->packets_written, ost->data_size);
792 av_log(NULL, AV_LOG_VERBOSE, "\n");
795 av_log(NULL, AV_LOG_VERBOSE, " Total: %"PRIu64" packets (%"PRIu64" bytes) muxed\n",
796 total_packets, total_size);
800 static void print_report(int is_last_report, int64_t timer_start)
807 int frame_number, vid, i;
808 double bitrate, ti1, pts;
809 static int64_t last_time = -1;
810 static int qp_histogram[52];
812 if (!print_stats && !is_last_report)
815 if (!is_last_report) {
817 /* display the report every 0.5 seconds */
818 cur_time = av_gettime_relative();
819 if (last_time == -1) {
820 last_time = cur_time;
823 if ((cur_time - last_time) < 500000)
825 last_time = cur_time;
829 oc = output_files[0]->ctx;
831 total_size = avio_size(oc->pb);
832 if (total_size <= 0) // FIXME improve avio_size() so it works with non seekable output too
833 total_size = avio_tell(oc->pb);
834 if (total_size < 0) {
836 av_strerror(total_size, errbuf, sizeof(errbuf));
837 av_log(NULL, AV_LOG_VERBOSE, "Bitrate not available, "
838 "avio_tell() failed: %s\n", errbuf);
845 for (i = 0; i < nb_output_streams; i++) {
847 ost = output_streams[i];
849 if (!ost->stream_copy && enc->coded_frame)
850 q = enc->coded_frame->quality / (float)FF_QP2LAMBDA;
851 if (vid && enc->codec_type == AVMEDIA_TYPE_VIDEO) {
852 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "q=%2.1f ", q);
854 if (!vid && enc->codec_type == AVMEDIA_TYPE_VIDEO) {
855 float t = (av_gettime_relative() - timer_start) / 1000000.0;
857 frame_number = ost->frame_number;
858 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "frame=%5d fps=%3d q=%3.1f ",
859 frame_number, (t > 1) ? (int)(frame_number / t + 0.5) : 0, q);
861 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "L");
865 if (qp >= 0 && qp < FF_ARRAY_ELEMS(qp_histogram))
867 for (j = 0; j < 32; j++)
868 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "%X", (int)lrintf(log2(qp_histogram[j] + 1)));
870 if (enc->flags&CODEC_FLAG_PSNR) {
872 double error, error_sum = 0;
873 double scale, scale_sum = 0;
874 char type[3] = { 'Y','U','V' };
875 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "PSNR=");
876 for (j = 0; j < 3; j++) {
877 if (is_last_report) {
878 error = enc->error[j];
879 scale = enc->width * enc->height * 255.0 * 255.0 * frame_number;
881 error = enc->coded_frame->error[j];
882 scale = enc->width * enc->height * 255.0 * 255.0;
888 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "%c:%2.2f ", type[j], psnr(error / scale));
890 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "*:%2.2f ", psnr(error_sum / scale_sum));
894 /* compute min output value */
895 pts = (double)ost->last_mux_dts * av_q2d(ost->st->time_base);
896 if ((pts < ti1) && (pts > 0))
902 bitrate = (double)(total_size * 8) / ti1 / 1000.0;
904 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
905 "size=%8.0fkB time=%0.2f bitrate=%6.1fkbits/s",
906 (double)total_size / 1024, ti1, bitrate);
909 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), " drop=%d",
912 av_log(NULL, AV_LOG_INFO, "%s \r", buf);
917 print_final_stats(total_size);
921 static void flush_encoders(void)
925 for (i = 0; i < nb_output_streams; i++) {
926 OutputStream *ost = output_streams[i];
927 AVCodecContext *enc = ost->enc_ctx;
928 AVFormatContext *os = output_files[ost->file_index]->ctx;
929 int stop_encoding = 0;
931 if (!ost->encoding_needed)
934 if (enc->codec_type == AVMEDIA_TYPE_AUDIO && enc->frame_size <= 1)
936 if (enc->codec_type == AVMEDIA_TYPE_VIDEO && (os->oformat->flags & AVFMT_RAWPICTURE) && enc->codec->id == AV_CODEC_ID_RAWVIDEO)
940 int (*encode)(AVCodecContext*, AVPacket*, const AVFrame*, int*) = NULL;
943 switch (enc->codec_type) {
944 case AVMEDIA_TYPE_AUDIO:
945 encode = avcodec_encode_audio2;
948 case AVMEDIA_TYPE_VIDEO:
949 encode = avcodec_encode_video2;
959 av_init_packet(&pkt);
963 ret = encode(enc, &pkt, NULL, &got_packet);
965 av_log(NULL, AV_LOG_FATAL, "%s encoding failed\n", desc);
968 if (ost->logfile && enc->stats_out) {
969 fprintf(ost->logfile, "%s", enc->stats_out);
975 av_packet_rescale_ts(&pkt, enc->time_base, ost->st->time_base);
976 write_frame(os, &pkt, ost);
986 * Check whether a packet from ist should be written into ost at this time
988 static int check_output_constraints(InputStream *ist, OutputStream *ost)
990 OutputFile *of = output_files[ost->file_index];
991 int ist_index = input_files[ist->file_index]->ist_index + ist->st->index;
993 if (ost->source_index != ist_index)
996 if (of->start_time != AV_NOPTS_VALUE && ist->last_dts < of->start_time)
1002 static void do_streamcopy(InputStream *ist, OutputStream *ost, const AVPacket *pkt)
1004 OutputFile *of = output_files[ost->file_index];
1005 InputFile *f = input_files [ist->file_index];
1006 int64_t start_time = (of->start_time == AV_NOPTS_VALUE) ? 0 : of->start_time;
1007 int64_t ost_tb_start_time = av_rescale_q(start_time, AV_TIME_BASE_Q, ost->st->time_base);
1010 av_init_packet(&opkt);
1012 if ((!ost->frame_number && !(pkt->flags & AV_PKT_FLAG_KEY)) &&
1013 !ost->copy_initial_nonkeyframes)
1016 if (of->recording_time != INT64_MAX &&
1017 ist->last_dts >= of->recording_time + start_time) {
1022 if (f->recording_time != INT64_MAX) {
1023 start_time = f->ctx->start_time;
1024 if (f->start_time != AV_NOPTS_VALUE)
1025 start_time += f->start_time;
1026 if (ist->last_dts >= f->recording_time + start_time) {
1032 /* force the input stream PTS */
1033 if (ost->enc_ctx->codec_type == AVMEDIA_TYPE_VIDEO)
1036 if (pkt->pts != AV_NOPTS_VALUE)
1037 opkt.pts = av_rescale_q(pkt->pts, ist->st->time_base, ost->st->time_base) - ost_tb_start_time;
1039 opkt.pts = AV_NOPTS_VALUE;
1041 if (pkt->dts == AV_NOPTS_VALUE)
1042 opkt.dts = av_rescale_q(ist->last_dts, AV_TIME_BASE_Q, ost->st->time_base);
1044 opkt.dts = av_rescale_q(pkt->dts, ist->st->time_base, ost->st->time_base);
1045 opkt.dts -= ost_tb_start_time;
1047 opkt.duration = av_rescale_q(pkt->duration, ist->st->time_base, ost->st->time_base);
1048 opkt.flags = pkt->flags;
1050 // FIXME remove the following 2 lines they shall be replaced by the bitstream filters
1051 if ( ost->enc_ctx->codec_id != AV_CODEC_ID_H264
1052 && ost->enc_ctx->codec_id != AV_CODEC_ID_MPEG1VIDEO
1053 && ost->enc_ctx->codec_id != AV_CODEC_ID_MPEG2VIDEO
1054 && ost->enc_ctx->codec_id != AV_CODEC_ID_VC1
1056 if (av_parser_change(ost->parser, ost->st->codec,
1057 &opkt.data, &opkt.size,
1058 pkt->data, pkt->size,
1059 pkt->flags & AV_PKT_FLAG_KEY)) {
1060 opkt.buf = av_buffer_create(opkt.data, opkt.size, av_buffer_default_free, NULL, 0);
1065 opkt.data = pkt->data;
1066 opkt.size = pkt->size;
1069 write_frame(of->ctx, &opkt, ost);
1072 int guess_input_channel_layout(InputStream *ist)
1074 AVCodecContext *dec = ist->dec_ctx;
1076 if (!dec->channel_layout) {
1077 char layout_name[256];
1079 dec->channel_layout = av_get_default_channel_layout(dec->channels);
1080 if (!dec->channel_layout)
1082 av_get_channel_layout_string(layout_name, sizeof(layout_name),
1083 dec->channels, dec->channel_layout);
1084 av_log(NULL, AV_LOG_WARNING, "Guessed Channel Layout for Input Stream "
1085 "#%d.%d : %s\n", ist->file_index, ist->st->index, layout_name);
1090 static int decode_audio(InputStream *ist, AVPacket *pkt, int *got_output)
1092 AVFrame *decoded_frame, *f;
1093 AVCodecContext *avctx = ist->dec_ctx;
1094 int i, ret, err = 0, resample_changed;
1096 if (!ist->decoded_frame && !(ist->decoded_frame = av_frame_alloc()))
1097 return AVERROR(ENOMEM);
1098 if (!ist->filter_frame && !(ist->filter_frame = av_frame_alloc()))
1099 return AVERROR(ENOMEM);
1100 decoded_frame = ist->decoded_frame;
1102 ret = avcodec_decode_audio4(avctx, decoded_frame, got_output, pkt);
1103 if (!*got_output || ret < 0)
1106 ist->samples_decoded += decoded_frame->nb_samples;
1107 ist->frames_decoded++;
1109 /* if the decoder provides a pts, use it instead of the last packet pts.
1110 the decoder could be delaying output by a packet or more. */
1111 if (decoded_frame->pts != AV_NOPTS_VALUE)
1112 ist->next_dts = decoded_frame->pts;
1113 else if (pkt->pts != AV_NOPTS_VALUE)
1114 decoded_frame->pts = pkt->pts;
1115 pkt->pts = AV_NOPTS_VALUE;
1117 resample_changed = ist->resample_sample_fmt != decoded_frame->format ||
1118 ist->resample_channels != avctx->channels ||
1119 ist->resample_channel_layout != decoded_frame->channel_layout ||
1120 ist->resample_sample_rate != decoded_frame->sample_rate;
1121 if (resample_changed) {
1122 char layout1[64], layout2[64];
1124 if (!guess_input_channel_layout(ist)) {
1125 av_log(NULL, AV_LOG_FATAL, "Unable to find default channel "
1126 "layout for Input Stream #%d.%d\n", ist->file_index,
1130 decoded_frame->channel_layout = avctx->channel_layout;
1132 av_get_channel_layout_string(layout1, sizeof(layout1), ist->resample_channels,
1133 ist->resample_channel_layout);
1134 av_get_channel_layout_string(layout2, sizeof(layout2), avctx->channels,
1135 decoded_frame->channel_layout);
1137 av_log(NULL, AV_LOG_INFO,
1138 "Input stream #%d:%d frame changed from rate:%d fmt:%s ch:%d chl:%s to rate:%d fmt:%s ch:%d chl:%s\n",
1139 ist->file_index, ist->st->index,
1140 ist->resample_sample_rate, av_get_sample_fmt_name(ist->resample_sample_fmt),
1141 ist->resample_channels, layout1,
1142 decoded_frame->sample_rate, av_get_sample_fmt_name(decoded_frame->format),
1143 avctx->channels, layout2);
1145 ist->resample_sample_fmt = decoded_frame->format;
1146 ist->resample_sample_rate = decoded_frame->sample_rate;
1147 ist->resample_channel_layout = decoded_frame->channel_layout;
1148 ist->resample_channels = avctx->channels;
1150 for (i = 0; i < nb_filtergraphs; i++)
1151 if (ist_in_filtergraph(filtergraphs[i], ist) &&
1152 configure_filtergraph(filtergraphs[i]) < 0) {
1153 av_log(NULL, AV_LOG_FATAL, "Error reinitializing filters!\n");
1158 if (decoded_frame->pts != AV_NOPTS_VALUE)
1159 decoded_frame->pts = av_rescale_q(decoded_frame->pts,
1161 (AVRational){1, avctx->sample_rate});
1162 for (i = 0; i < ist->nb_filters; i++) {
1163 if (i < ist->nb_filters - 1) {
1164 f = ist->filter_frame;
1165 err = av_frame_ref(f, decoded_frame);
1171 err = av_buffersrc_add_frame(ist->filters[i]->filter, f);
1176 av_frame_unref(ist->filter_frame);
1177 av_frame_unref(decoded_frame);
1178 return err < 0 ? err : ret;
1181 static int decode_video(InputStream *ist, AVPacket *pkt, int *got_output)
1183 AVFrame *decoded_frame, *f;
1184 int i, ret = 0, err = 0, resample_changed;
1186 if (!ist->decoded_frame && !(ist->decoded_frame = av_frame_alloc()))
1187 return AVERROR(ENOMEM);
1188 if (!ist->filter_frame && !(ist->filter_frame = av_frame_alloc()))
1189 return AVERROR(ENOMEM);
1190 decoded_frame = ist->decoded_frame;
1192 ret = avcodec_decode_video2(ist->dec_ctx,
1193 decoded_frame, got_output, pkt);
1194 if (!*got_output || ret < 0)
1197 ist->frames_decoded++;
1199 if (ist->hwaccel_retrieve_data && decoded_frame->format == ist->hwaccel_pix_fmt) {
1200 err = ist->hwaccel_retrieve_data(ist->dec_ctx, decoded_frame);
1204 ist->hwaccel_retrieved_pix_fmt = decoded_frame->format;
1206 decoded_frame->pts = guess_correct_pts(&ist->pts_ctx, decoded_frame->pkt_pts,
1207 decoded_frame->pkt_dts);
1210 if (ist->st->sample_aspect_ratio.num)
1211 decoded_frame->sample_aspect_ratio = ist->st->sample_aspect_ratio;
1213 resample_changed = ist->resample_width != decoded_frame->width ||
1214 ist->resample_height != decoded_frame->height ||
1215 ist->resample_pix_fmt != decoded_frame->format;
1216 if (resample_changed) {
1217 av_log(NULL, AV_LOG_INFO,
1218 "Input stream #%d:%d frame changed from size:%dx%d fmt:%s to size:%dx%d fmt:%s\n",
1219 ist->file_index, ist->st->index,
1220 ist->resample_width, ist->resample_height, av_get_pix_fmt_name(ist->resample_pix_fmt),
1221 decoded_frame->width, decoded_frame->height, av_get_pix_fmt_name(decoded_frame->format));
1223 ret = poll_filters();
1224 if (ret < 0 && (ret != AVERROR_EOF && ret != AVERROR(EAGAIN))) {
1226 av_strerror(ret, errbuf, sizeof(errbuf));
1228 av_log(NULL, AV_LOG_ERROR, "Error while filtering: %s\n", errbuf);
1231 ist->resample_width = decoded_frame->width;
1232 ist->resample_height = decoded_frame->height;
1233 ist->resample_pix_fmt = decoded_frame->format;
1235 for (i = 0; i < nb_filtergraphs; i++)
1236 if (ist_in_filtergraph(filtergraphs[i], ist) &&
1237 configure_filtergraph(filtergraphs[i]) < 0) {
1238 av_log(NULL, AV_LOG_FATAL, "Error reinitializing filters!\n");
1243 for (i = 0; i < ist->nb_filters; i++) {
1244 if (i < ist->nb_filters - 1) {
1245 f = ist->filter_frame;
1246 err = av_frame_ref(f, decoded_frame);
1252 err = av_buffersrc_add_frame(ist->filters[i]->filter, f);
1258 av_frame_unref(ist->filter_frame);
1259 av_frame_unref(decoded_frame);
1260 return err < 0 ? err : ret;
1263 static int transcode_subtitles(InputStream *ist, AVPacket *pkt, int *got_output)
1265 AVSubtitle subtitle;
1266 int i, ret = avcodec_decode_subtitle2(ist->dec_ctx,
1267 &subtitle, got_output, pkt);
1273 ist->frames_decoded++;
1275 for (i = 0; i < nb_output_streams; i++) {
1276 OutputStream *ost = output_streams[i];
1278 if (!check_output_constraints(ist, ost) || !ost->encoding_needed)
1281 do_subtitle_out(output_files[ost->file_index]->ctx, ost, ist, &subtitle, pkt->pts);
1284 avsubtitle_free(&subtitle);
1288 static int send_filter_eof(InputStream *ist)
1291 for (i = 0; i < ist->nb_filters; i++) {
1292 ret = av_buffersrc_add_frame(ist->filters[i]->filter, NULL);
1299 /* pkt = NULL means EOF (needed to flush decoder buffers) */
1300 static void process_input_packet(InputStream *ist, const AVPacket *pkt)
1306 if (ist->next_dts == AV_NOPTS_VALUE)
1307 ist->next_dts = ist->last_dts;
1311 av_init_packet(&avpkt);
1319 if (pkt->dts != AV_NOPTS_VALUE)
1320 ist->next_dts = ist->last_dts = av_rescale_q(pkt->dts, ist->st->time_base, AV_TIME_BASE_Q);
1322 // while we have more to decode or while the decoder did output something on EOF
1323 while (ist->decoding_needed && (avpkt.size > 0 || (!pkt && got_output))) {
1327 ist->last_dts = ist->next_dts;
1329 if (avpkt.size && avpkt.size != pkt->size &&
1330 !(ist->dec->capabilities & CODEC_CAP_SUBFRAMES)) {
1331 av_log(NULL, ist->showed_multi_packet_warning ? AV_LOG_VERBOSE : AV_LOG_WARNING,
1332 "Multiple frames in a packet from stream %d\n", pkt->stream_index);
1333 ist->showed_multi_packet_warning = 1;
1336 switch (ist->dec_ctx->codec_type) {
1337 case AVMEDIA_TYPE_AUDIO:
1338 ret = decode_audio (ist, &avpkt, &got_output);
1340 case AVMEDIA_TYPE_VIDEO:
1341 ret = decode_video (ist, &avpkt, &got_output);
1343 ist->next_dts += av_rescale_q(avpkt.duration, ist->st->time_base, AV_TIME_BASE_Q);
1344 else if (ist->st->avg_frame_rate.num)
1345 ist->next_dts += av_rescale_q(1, av_inv_q(ist->st->avg_frame_rate),
1347 else if (ist->dec_ctx->framerate.num != 0) {
1348 int ticks = ist->st->parser ? ist->st->parser->repeat_pict + 1 :
1349 ist->dec_ctx->ticks_per_frame;
1350 ist->next_dts += av_rescale_q(ticks, ist->dec_ctx->framerate, AV_TIME_BASE_Q);
1353 case AVMEDIA_TYPE_SUBTITLE:
1354 ret = transcode_subtitles(ist, &avpkt, &got_output);
1361 av_log(NULL, AV_LOG_ERROR, "Error while decoding stream #%d:%d\n",
1362 ist->file_index, ist->st->index);
1368 // touch data and size only if not EOF
1378 /* after flushing, send an EOF on all the filter inputs attached to the stream */
1379 if (!pkt && ist->decoding_needed) {
1380 int ret = send_filter_eof(ist);
1382 av_log(NULL, AV_LOG_FATAL, "Error marking filters as finished\n");
1387 /* handle stream copy */
1388 if (!ist->decoding_needed) {
1389 ist->last_dts = ist->next_dts;
1390 switch (ist->dec_ctx->codec_type) {
1391 case AVMEDIA_TYPE_AUDIO:
1392 ist->next_dts += ((int64_t)AV_TIME_BASE * ist->dec_ctx->frame_size) /
1393 ist->dec_ctx->sample_rate;
1395 case AVMEDIA_TYPE_VIDEO:
1396 if (ist->dec_ctx->framerate.num != 0) {
1397 int ticks = ist->st->parser ? ist->st->parser->repeat_pict + 1 : ist->dec_ctx->ticks_per_frame;
1398 ist->next_dts += ((int64_t)AV_TIME_BASE *
1399 ist->dec_ctx->framerate.den * ticks) /
1400 ist->dec_ctx->framerate.num;
1405 for (i = 0; pkt && i < nb_output_streams; i++) {
1406 OutputStream *ost = output_streams[i];
1408 if (!check_output_constraints(ist, ost) || ost->encoding_needed)
1411 do_streamcopy(ist, ost, pkt);
1417 static void print_sdp(void)
1421 AVFormatContext **avc = av_malloc(sizeof(*avc) * nb_output_files);
1425 for (i = 0; i < nb_output_files; i++)
1426 avc[i] = output_files[i]->ctx;
1428 av_sdp_create(avc, nb_output_files, sdp, sizeof(sdp));
1429 printf("SDP:\n%s\n", sdp);
1434 static const HWAccel *get_hwaccel(enum AVPixelFormat pix_fmt)
1437 for (i = 0; hwaccels[i].name; i++)
1438 if (hwaccels[i].pix_fmt == pix_fmt)
1439 return &hwaccels[i];
1443 static enum AVPixelFormat get_format(AVCodecContext *s, const enum AVPixelFormat *pix_fmts)
1445 InputStream *ist = s->opaque;
1446 const enum AVPixelFormat *p;
1449 for (p = pix_fmts; *p != -1; p++) {
1450 const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(*p);
1451 const HWAccel *hwaccel;
1453 if (!(desc->flags & AV_PIX_FMT_FLAG_HWACCEL))
1456 hwaccel = get_hwaccel(*p);
1458 (ist->active_hwaccel_id && ist->active_hwaccel_id != hwaccel->id) ||
1459 (ist->hwaccel_id != HWACCEL_AUTO && ist->hwaccel_id != hwaccel->id))
1462 ret = hwaccel->init(s);
1464 if (ist->hwaccel_id == hwaccel->id) {
1465 av_log(NULL, AV_LOG_FATAL,
1466 "%s hwaccel requested for input stream #%d:%d, "
1467 "but cannot be initialized.\n", hwaccel->name,
1468 ist->file_index, ist->st->index);
1469 return AV_PIX_FMT_NONE;
1473 ist->active_hwaccel_id = hwaccel->id;
1474 ist->hwaccel_pix_fmt = *p;
1481 static int get_buffer(AVCodecContext *s, AVFrame *frame, int flags)
1483 InputStream *ist = s->opaque;
1485 if (ist->hwaccel_get_buffer && frame->format == ist->hwaccel_pix_fmt)
1486 return ist->hwaccel_get_buffer(s, frame, flags);
1488 return avcodec_default_get_buffer2(s, frame, flags);
1491 static int init_input_stream(int ist_index, char *error, int error_len)
1494 InputStream *ist = input_streams[ist_index];
1495 if (ist->decoding_needed) {
1496 AVCodec *codec = ist->dec;
1498 snprintf(error, error_len, "Decoder (codec id %d) not found for input stream #%d:%d",
1499 ist->dec_ctx->codec_id, ist->file_index, ist->st->index);
1500 return AVERROR(EINVAL);
1503 ist->dec_ctx->opaque = ist;
1504 ist->dec_ctx->get_format = get_format;
1505 ist->dec_ctx->get_buffer2 = get_buffer;
1506 ist->dec_ctx->thread_safe_callbacks = 1;
1508 av_opt_set_int(ist->dec_ctx, "refcounted_frames", 1, 0);
1510 if (!av_dict_get(ist->decoder_opts, "threads", NULL, 0))
1511 av_dict_set(&ist->decoder_opts, "threads", "auto", 0);
1512 if ((ret = avcodec_open2(ist->dec_ctx, codec, &ist->decoder_opts)) < 0) {
1514 if (ret == AVERROR_EXPERIMENTAL)
1515 abort_codec_experimental(codec, 0);
1517 av_strerror(ret, errbuf, sizeof(errbuf));
1519 snprintf(error, error_len,
1520 "Error while opening decoder for input stream "
1522 ist->file_index, ist->st->index, errbuf);
1525 assert_avoptions(ist->decoder_opts);
1528 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;
1529 ist->next_dts = AV_NOPTS_VALUE;
1530 init_pts_correction(&ist->pts_ctx);
1535 static InputStream *get_input_stream(OutputStream *ost)
1537 if (ost->source_index >= 0)
1538 return input_streams[ost->source_index];
1541 FilterGraph *fg = ost->filter->graph;
1544 for (i = 0; i < fg->nb_inputs; i++)
1545 if (fg->inputs[i]->ist->dec_ctx->codec_type == ost->enc_ctx->codec_type)
1546 return fg->inputs[i]->ist;
1552 static int init_output_stream(OutputStream *ost, char *error, int error_len)
1556 if (ost->encoding_needed) {
1557 AVCodec *codec = ost->enc;
1558 AVCodecContext *dec = NULL;
1561 if ((ist = get_input_stream(ost)))
1563 if (dec && dec->subtitle_header) {
1564 ost->enc_ctx->subtitle_header = av_malloc(dec->subtitle_header_size);
1565 if (!ost->enc_ctx->subtitle_header)
1566 return AVERROR(ENOMEM);
1567 memcpy(ost->enc_ctx->subtitle_header, dec->subtitle_header, dec->subtitle_header_size);
1568 ost->enc_ctx->subtitle_header_size = dec->subtitle_header_size;
1570 if (!av_dict_get(ost->encoder_opts, "threads", NULL, 0))
1571 av_dict_set(&ost->encoder_opts, "threads", "auto", 0);
1572 av_dict_set(&ost->encoder_opts, "side_data_only_packets", "1", 0);
1574 if ((ret = avcodec_open2(ost->enc_ctx, codec, &ost->encoder_opts)) < 0) {
1575 if (ret == AVERROR_EXPERIMENTAL)
1576 abort_codec_experimental(codec, 1);
1577 snprintf(error, error_len,
1578 "Error while opening encoder for output stream #%d:%d - "
1579 "maybe incorrect parameters such as bit_rate, rate, width or height",
1580 ost->file_index, ost->index);
1583 assert_avoptions(ost->encoder_opts);
1584 if (ost->enc_ctx->bit_rate && ost->enc_ctx->bit_rate < 1000)
1585 av_log(NULL, AV_LOG_WARNING, "The bitrate parameter is set too low."
1586 "It takes bits/s as argument, not kbits/s\n");
1588 ret = avcodec_copy_context(ost->st->codec, ost->enc_ctx);
1590 av_log(NULL, AV_LOG_FATAL,
1591 "Error initializing the output stream codec context.\n");
1595 ost->st->time_base = ost->enc_ctx->time_base;
1597 ret = av_opt_set_dict(ost->enc_ctx, &ost->encoder_opts);
1600 ost->st->time_base = ost->st->codec->time_base;
1606 static void parse_forced_key_frames(char *kf, OutputStream *ost,
1607 AVCodecContext *avctx)
1613 for (p = kf; *p; p++)
1616 ost->forced_kf_count = n;
1617 ost->forced_kf_pts = av_malloc(sizeof(*ost->forced_kf_pts) * n);
1618 if (!ost->forced_kf_pts) {
1619 av_log(NULL, AV_LOG_FATAL, "Could not allocate forced key frames array.\n");
1624 for (i = 0; i < n; i++) {
1625 char *next = strchr(p, ',');
1630 t = parse_time_or_die("force_key_frames", p, 1);
1631 ost->forced_kf_pts[i] = av_rescale_q(t, AV_TIME_BASE_Q, avctx->time_base);
1637 static void set_encoder_id(OutputFile *of, OutputStream *ost)
1639 AVDictionaryEntry *e;
1641 uint8_t *encoder_string;
1642 int encoder_string_len;
1643 int format_flags = 0;
1645 e = av_dict_get(of->opts, "fflags", NULL, 0);
1647 const AVOption *o = av_opt_find(of->ctx, "fflags", NULL, 0, 0);
1650 av_opt_eval_flags(of->ctx, o, e->value, &format_flags);
1653 encoder_string_len = sizeof(LIBAVCODEC_IDENT) + strlen(ost->enc->name) + 2;
1654 encoder_string = av_mallocz(encoder_string_len);
1655 if (!encoder_string)
1658 if (!(format_flags & AVFMT_FLAG_BITEXACT))
1659 av_strlcpy(encoder_string, LIBAVCODEC_IDENT " ", encoder_string_len);
1660 av_strlcat(encoder_string, ost->enc->name, encoder_string_len);
1661 av_dict_set(&ost->st->metadata, "encoder", encoder_string,
1662 AV_DICT_DONT_STRDUP_VAL | AV_DICT_DONT_OVERWRITE);
1665 static int transcode_init(void)
1667 int ret = 0, i, j, k;
1668 AVFormatContext *oc;
1674 /* init framerate emulation */
1675 for (i = 0; i < nb_input_files; i++) {
1676 InputFile *ifile = input_files[i];
1677 if (ifile->rate_emu)
1678 for (j = 0; j < ifile->nb_streams; j++)
1679 input_streams[j + ifile->ist_index]->start = av_gettime_relative();
1682 /* for each output stream, we compute the right encoding parameters */
1683 for (i = 0; i < nb_output_streams; i++) {
1684 AVCodecContext *enc_ctx;
1685 AVCodecContext *dec_ctx = NULL;
1686 ost = output_streams[i];
1687 oc = output_files[ost->file_index]->ctx;
1688 ist = get_input_stream(ost);
1690 if (ost->attachment_filename)
1693 enc_ctx = ost->stream_copy ? ost->st->codec : ost->enc_ctx;
1696 dec_ctx = ist->dec_ctx;
1698 ost->st->disposition = ist->st->disposition;
1699 enc_ctx->bits_per_raw_sample = dec_ctx->bits_per_raw_sample;
1700 enc_ctx->chroma_sample_location = dec_ctx->chroma_sample_location;
1703 if (ost->stream_copy) {
1705 uint64_t extra_size;
1707 av_assert0(ist && !ost->filter);
1709 extra_size = (uint64_t)dec_ctx->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE;
1711 if (extra_size > INT_MAX) {
1712 return AVERROR(EINVAL);
1715 /* if stream_copy is selected, no need to decode or encode */
1716 enc_ctx->codec_id = dec_ctx->codec_id;
1717 enc_ctx->codec_type = dec_ctx->codec_type;
1719 if (!enc_ctx->codec_tag) {
1720 if (!oc->oformat->codec_tag ||
1721 av_codec_get_id (oc->oformat->codec_tag, dec_ctx->codec_tag) == enc_ctx->codec_id ||
1722 av_codec_get_tag(oc->oformat->codec_tag, dec_ctx->codec_id) <= 0)
1723 enc_ctx->codec_tag = dec_ctx->codec_tag;
1726 enc_ctx->bit_rate = dec_ctx->bit_rate;
1727 enc_ctx->rc_max_rate = dec_ctx->rc_max_rate;
1728 enc_ctx->rc_buffer_size = dec_ctx->rc_buffer_size;
1729 enc_ctx->field_order = dec_ctx->field_order;
1730 enc_ctx->extradata = av_mallocz(extra_size);
1731 if (!enc_ctx->extradata) {
1732 return AVERROR(ENOMEM);
1734 memcpy(enc_ctx->extradata, dec_ctx->extradata, dec_ctx->extradata_size);
1735 enc_ctx->extradata_size = dec_ctx->extradata_size;
1737 enc_ctx->time_base = dec_ctx->time_base;
1738 enc_ctx->time_base.num *= dec_ctx->ticks_per_frame;
1739 av_reduce(&enc_ctx->time_base.num, &enc_ctx->time_base.den,
1740 enc_ctx->time_base.num, enc_ctx->time_base.den, INT_MAX);
1742 enc_ctx->time_base = ist->st->time_base;
1744 if (ist->st->nb_side_data) {
1745 ost->st->side_data = av_realloc_array(NULL, ist->st->nb_side_data,
1746 sizeof(*ist->st->side_data));
1747 if (!ost->st->side_data)
1748 return AVERROR(ENOMEM);
1750 for (j = 0; j < ist->st->nb_side_data; j++) {
1751 const AVPacketSideData *sd_src = &ist->st->side_data[j];
1752 AVPacketSideData *sd_dst = &ost->st->side_data[j];
1754 sd_dst->data = av_malloc(sd_src->size);
1756 return AVERROR(ENOMEM);
1757 memcpy(sd_dst->data, sd_src->data, sd_src->size);
1758 sd_dst->size = sd_src->size;
1759 sd_dst->type = sd_src->type;
1760 ost->st->nb_side_data++;
1764 ost->parser = av_parser_init(enc_ctx->codec_id);
1766 switch (enc_ctx->codec_type) {
1767 case AVMEDIA_TYPE_AUDIO:
1768 if (audio_volume != 256) {
1769 av_log(NULL, AV_LOG_FATAL, "-acodec copy and -vol are incompatible (frames are not decoded)\n");
1772 enc_ctx->channel_layout = dec_ctx->channel_layout;
1773 enc_ctx->sample_rate = dec_ctx->sample_rate;
1774 enc_ctx->channels = dec_ctx->channels;
1775 enc_ctx->frame_size = dec_ctx->frame_size;
1776 enc_ctx->audio_service_type = dec_ctx->audio_service_type;
1777 enc_ctx->block_align = dec_ctx->block_align;
1779 case AVMEDIA_TYPE_VIDEO:
1780 enc_ctx->pix_fmt = dec_ctx->pix_fmt;
1781 enc_ctx->width = dec_ctx->width;
1782 enc_ctx->height = dec_ctx->height;
1783 enc_ctx->has_b_frames = dec_ctx->has_b_frames;
1784 if (ost->frame_aspect_ratio)
1785 sar = av_d2q(ost->frame_aspect_ratio * enc_ctx->height / enc_ctx->width, 255);
1786 else if (ist->st->sample_aspect_ratio.num)
1787 sar = ist->st->sample_aspect_ratio;
1789 sar = dec_ctx->sample_aspect_ratio;
1790 ost->st->sample_aspect_ratio = enc_ctx->sample_aspect_ratio = sar;
1792 case AVMEDIA_TYPE_SUBTITLE:
1793 enc_ctx->width = dec_ctx->width;
1794 enc_ctx->height = dec_ctx->height;
1796 case AVMEDIA_TYPE_DATA:
1797 case AVMEDIA_TYPE_ATTACHMENT:
1804 /* should only happen when a default codec is not present. */
1805 snprintf(error, sizeof(error), "Automatic encoder selection "
1806 "failed for output stream #%d:%d. Default encoder for "
1807 "format %s is probably disabled. Please choose an "
1808 "encoder manually.\n", ost->file_index, ost->index,
1810 ret = AVERROR(EINVAL);
1814 set_encoder_id(output_files[ost->file_index], ost);
1817 * We want CFR output if and only if one of those is true:
1818 * 1) user specified output framerate with -r
1819 * 2) user specified -vsync cfr
1820 * 3) output format is CFR and the user didn't force vsync to
1821 * something else than CFR
1823 * in such a case, set ost->frame_rate
1825 if (enc_ctx->codec_type == AVMEDIA_TYPE_VIDEO &&
1826 !ost->frame_rate.num && ist &&
1827 (video_sync_method == VSYNC_CFR ||
1828 (video_sync_method == VSYNC_AUTO &&
1829 !(oc->oformat->flags & (AVFMT_NOTIMESTAMPS | AVFMT_VARIABLE_FPS))))) {
1830 if (ist->framerate.num)
1831 ost->frame_rate = ist->framerate;
1832 else if (ist->st->avg_frame_rate.num)
1833 ost->frame_rate = ist->st->avg_frame_rate;
1835 av_log(NULL, AV_LOG_WARNING, "Constant framerate requested "
1836 "for the output stream #%d:%d, but no information "
1837 "about the input framerate is available. Falling "
1838 "back to a default value of 25fps. Use the -r option "
1839 "if you want a different framerate.\n",
1840 ost->file_index, ost->index);
1841 ost->frame_rate = (AVRational){ 25, 1 };
1844 if (ost->enc && ost->enc->supported_framerates && !ost->force_fps) {
1845 int idx = av_find_nearest_q_idx(ost->frame_rate, ost->enc->supported_framerates);
1846 ost->frame_rate = ost->enc->supported_framerates[idx];
1851 (enc_ctx->codec_type == AVMEDIA_TYPE_VIDEO ||
1852 enc_ctx->codec_type == AVMEDIA_TYPE_AUDIO)) {
1854 fg = init_simple_filtergraph(ist, ost);
1855 if (configure_filtergraph(fg)) {
1856 av_log(NULL, AV_LOG_FATAL, "Error opening filters!\n");
1861 switch (enc_ctx->codec_type) {
1862 case AVMEDIA_TYPE_AUDIO:
1863 enc_ctx->sample_fmt = ost->filter->filter->inputs[0]->format;
1864 enc_ctx->sample_rate = ost->filter->filter->inputs[0]->sample_rate;
1865 enc_ctx->channel_layout = ost->filter->filter->inputs[0]->channel_layout;
1866 enc_ctx->channels = av_get_channel_layout_nb_channels(enc_ctx->channel_layout);
1867 enc_ctx->time_base = (AVRational){ 1, enc_ctx->sample_rate };
1869 case AVMEDIA_TYPE_VIDEO:
1870 enc_ctx->time_base = ost->filter->filter->inputs[0]->time_base;
1872 enc_ctx->width = ost->filter->filter->inputs[0]->w;
1873 enc_ctx->height = ost->filter->filter->inputs[0]->h;
1874 enc_ctx->sample_aspect_ratio = ost->st->sample_aspect_ratio =
1875 ost->frame_aspect_ratio ? // overridden by the -aspect cli option
1876 av_d2q(ost->frame_aspect_ratio * enc_ctx->height/enc_ctx->width, 255) :
1877 ost->filter->filter->inputs[0]->sample_aspect_ratio;
1878 enc_ctx->pix_fmt = ost->filter->filter->inputs[0]->format;
1880 ost->st->avg_frame_rate = ost->frame_rate;
1883 (enc_ctx->width != dec_ctx->width ||
1884 enc_ctx->height != dec_ctx->height ||
1885 enc_ctx->pix_fmt != dec_ctx->pix_fmt)) {
1886 enc_ctx->bits_per_raw_sample = 0;
1889 if (ost->forced_keyframes)
1890 parse_forced_key_frames(ost->forced_keyframes, ost,
1893 case AVMEDIA_TYPE_SUBTITLE:
1894 enc_ctx->time_base = (AVRational){1, 1000};
1903 /* open each encoder */
1904 for (i = 0; i < nb_output_streams; i++) {
1905 ret = init_output_stream(output_streams[i], error, sizeof(error));
1910 /* init input streams */
1911 for (i = 0; i < nb_input_streams; i++)
1912 if ((ret = init_input_stream(i, error, sizeof(error))) < 0)
1915 /* discard unused programs */
1916 for (i = 0; i < nb_input_files; i++) {
1917 InputFile *ifile = input_files[i];
1918 for (j = 0; j < ifile->ctx->nb_programs; j++) {
1919 AVProgram *p = ifile->ctx->programs[j];
1920 int discard = AVDISCARD_ALL;
1922 for (k = 0; k < p->nb_stream_indexes; k++)
1923 if (!input_streams[ifile->ist_index + p->stream_index[k]]->discard) {
1924 discard = AVDISCARD_DEFAULT;
1927 p->discard = discard;
1931 /* open files and write file headers */
1932 for (i = 0; i < nb_output_files; i++) {
1933 oc = output_files[i]->ctx;
1934 oc->interrupt_callback = int_cb;
1935 if ((ret = avformat_write_header(oc, &output_files[i]->opts)) < 0) {
1937 av_strerror(ret, errbuf, sizeof(errbuf));
1938 snprintf(error, sizeof(error),
1939 "Could not write header for output file #%d "
1940 "(incorrect codec parameters ?): %s",
1942 ret = AVERROR(EINVAL);
1945 assert_avoptions(output_files[i]->opts);
1946 if (strcmp(oc->oformat->name, "rtp")) {
1952 /* dump the file output parameters - cannot be done before in case
1954 for (i = 0; i < nb_output_files; i++) {
1955 av_dump_format(output_files[i]->ctx, i, output_files[i]->ctx->filename, 1);
1958 /* dump the stream mapping */
1959 av_log(NULL, AV_LOG_INFO, "Stream mapping:\n");
1960 for (i = 0; i < nb_input_streams; i++) {
1961 ist = input_streams[i];
1963 for (j = 0; j < ist->nb_filters; j++) {
1964 if (ist->filters[j]->graph->graph_desc) {
1965 av_log(NULL, AV_LOG_INFO, " Stream #%d:%d (%s) -> %s",
1966 ist->file_index, ist->st->index, ist->dec ? ist->dec->name : "?",
1967 ist->filters[j]->name);
1968 if (nb_filtergraphs > 1)
1969 av_log(NULL, AV_LOG_INFO, " (graph %d)", ist->filters[j]->graph->index);
1970 av_log(NULL, AV_LOG_INFO, "\n");
1975 for (i = 0; i < nb_output_streams; i++) {
1976 ost = output_streams[i];
1978 if (ost->attachment_filename) {
1979 /* an attached file */
1980 av_log(NULL, AV_LOG_INFO, " File %s -> Stream #%d:%d\n",
1981 ost->attachment_filename, ost->file_index, ost->index);
1985 if (ost->filter && ost->filter->graph->graph_desc) {
1986 /* output from a complex graph */
1987 av_log(NULL, AV_LOG_INFO, " %s", ost->filter->name);
1988 if (nb_filtergraphs > 1)
1989 av_log(NULL, AV_LOG_INFO, " (graph %d)", ost->filter->graph->index);
1991 av_log(NULL, AV_LOG_INFO, " -> Stream #%d:%d (%s)\n", ost->file_index,
1992 ost->index, ost->enc ? ost->enc->name : "?");
1996 av_log(NULL, AV_LOG_INFO, " Stream #%d:%d -> #%d:%d",
1997 input_streams[ost->source_index]->file_index,
1998 input_streams[ost->source_index]->st->index,
2001 if (ost->sync_ist != input_streams[ost->source_index])
2002 av_log(NULL, AV_LOG_INFO, " [sync #%d:%d]",
2003 ost->sync_ist->file_index,
2004 ost->sync_ist->st->index);
2005 if (ost->stream_copy)
2006 av_log(NULL, AV_LOG_INFO, " (copy)");
2008 const AVCodec *in_codec = input_streams[ost->source_index]->dec;
2009 const AVCodec *out_codec = ost->enc;
2010 const char *decoder_name = "?";
2011 const char *in_codec_name = "?";
2012 const char *encoder_name = "?";
2013 const char *out_codec_name = "?";
2014 const AVCodecDescriptor *desc;
2017 decoder_name = in_codec->name;
2018 desc = avcodec_descriptor_get(in_codec->id);
2020 in_codec_name = desc->name;
2021 if (!strcmp(decoder_name, in_codec_name))
2022 decoder_name = "native";
2026 encoder_name = out_codec->name;
2027 desc = avcodec_descriptor_get(out_codec->id);
2029 out_codec_name = desc->name;
2030 if (!strcmp(encoder_name, out_codec_name))
2031 encoder_name = "native";
2034 av_log(NULL, AV_LOG_INFO, " (%s (%s) -> %s (%s))",
2035 in_codec_name, decoder_name,
2036 out_codec_name, encoder_name);
2038 av_log(NULL, AV_LOG_INFO, "\n");
2042 av_log(NULL, AV_LOG_ERROR, "%s\n", error);
2053 /* Return 1 if there remain streams where more output is wanted, 0 otherwise. */
2054 static int need_output(void)
2058 for (i = 0; i < nb_output_streams; i++) {
2059 OutputStream *ost = output_streams[i];
2060 OutputFile *of = output_files[ost->file_index];
2061 AVFormatContext *os = output_files[ost->file_index]->ctx;
2063 if (ost->finished ||
2064 (os->pb && avio_tell(os->pb) >= of->limit_filesize))
2066 if (ost->frame_number >= ost->max_frames) {
2068 for (j = 0; j < of->ctx->nb_streams; j++)
2069 output_streams[of->ost_index + j]->finished = 1;
2079 static InputFile *select_input_file(void)
2081 InputFile *ifile = NULL;
2082 int64_t ipts_min = INT64_MAX;
2085 for (i = 0; i < nb_input_streams; i++) {
2086 InputStream *ist = input_streams[i];
2087 int64_t ipts = ist->last_dts;
2089 if (ist->discard || input_files[ist->file_index]->eagain)
2091 if (!input_files[ist->file_index]->eof_reached) {
2092 if (ipts < ipts_min) {
2094 ifile = input_files[ist->file_index];
2103 static void *input_thread(void *arg)
2108 while (!transcoding_finished && ret >= 0) {
2110 ret = av_read_frame(f->ctx, &pkt);
2112 if (ret == AVERROR(EAGAIN)) {
2119 pthread_mutex_lock(&f->fifo_lock);
2120 while (!av_fifo_space(f->fifo))
2121 pthread_cond_wait(&f->fifo_cond, &f->fifo_lock);
2123 av_dup_packet(&pkt);
2124 av_fifo_generic_write(f->fifo, &pkt, sizeof(pkt), NULL);
2126 pthread_mutex_unlock(&f->fifo_lock);
2133 static void free_input_threads(void)
2137 if (nb_input_files == 1)
2140 transcoding_finished = 1;
2142 for (i = 0; i < nb_input_files; i++) {
2143 InputFile *f = input_files[i];
2146 if (!f->fifo || f->joined)
2149 pthread_mutex_lock(&f->fifo_lock);
2150 while (av_fifo_size(f->fifo)) {
2151 av_fifo_generic_read(f->fifo, &pkt, sizeof(pkt), NULL);
2152 av_free_packet(&pkt);
2154 pthread_cond_signal(&f->fifo_cond);
2155 pthread_mutex_unlock(&f->fifo_lock);
2157 pthread_join(f->thread, NULL);
2160 while (av_fifo_size(f->fifo)) {
2161 av_fifo_generic_read(f->fifo, &pkt, sizeof(pkt), NULL);
2162 av_free_packet(&pkt);
2164 av_fifo_free(f->fifo);
2168 static int init_input_threads(void)
2172 if (nb_input_files == 1)
2175 for (i = 0; i < nb_input_files; i++) {
2176 InputFile *f = input_files[i];
2178 if (!(f->fifo = av_fifo_alloc(8*sizeof(AVPacket))))
2179 return AVERROR(ENOMEM);
2181 pthread_mutex_init(&f->fifo_lock, NULL);
2182 pthread_cond_init (&f->fifo_cond, NULL);
2184 if ((ret = pthread_create(&f->thread, NULL, input_thread, f)))
2185 return AVERROR(ret);
2190 static int get_input_packet_mt(InputFile *f, AVPacket *pkt)
2194 pthread_mutex_lock(&f->fifo_lock);
2196 if (av_fifo_size(f->fifo)) {
2197 av_fifo_generic_read(f->fifo, pkt, sizeof(*pkt), NULL);
2198 pthread_cond_signal(&f->fifo_cond);
2203 ret = AVERROR(EAGAIN);
2206 pthread_mutex_unlock(&f->fifo_lock);
2212 static int get_input_packet(InputFile *f, AVPacket *pkt)
2216 for (i = 0; i < f->nb_streams; i++) {
2217 InputStream *ist = input_streams[f->ist_index + i];
2218 int64_t pts = av_rescale(ist->last_dts, 1000000, AV_TIME_BASE);
2219 int64_t now = av_gettime_relative() - ist->start;
2221 return AVERROR(EAGAIN);
2226 if (nb_input_files > 1)
2227 return get_input_packet_mt(f, pkt);
2229 return av_read_frame(f->ctx, pkt);
2232 static int got_eagain(void)
2235 for (i = 0; i < nb_input_files; i++)
2236 if (input_files[i]->eagain)
2241 static void reset_eagain(void)
2244 for (i = 0; i < nb_input_files; i++)
2245 input_files[i]->eagain = 0;
2249 * Read one packet from an input file and send it for
2250 * - decoding -> lavfi (audio/video)
2251 * - decoding -> encoding -> muxing (subtitles)
2252 * - muxing (streamcopy)
2255 * - 0 -- one packet was read and processed
2256 * - AVERROR(EAGAIN) -- no packets were available for selected file,
2257 * this function should be called again
2258 * - AVERROR_EOF -- this function should not be called again
2260 static int process_input(void)
2263 AVFormatContext *is;
2268 /* select the stream that we must read now */
2269 ifile = select_input_file();
2270 /* if none, if is finished */
2275 return AVERROR(EAGAIN);
2277 av_log(NULL, AV_LOG_VERBOSE, "No more inputs to read from.\n");
2282 ret = get_input_packet(ifile, &pkt);
2284 if (ret == AVERROR(EAGAIN)) {
2289 if (ret != AVERROR_EOF) {
2290 print_error(is->filename, ret);
2294 ifile->eof_reached = 1;
2296 for (i = 0; i < ifile->nb_streams; i++) {
2297 ist = input_streams[ifile->ist_index + i];
2298 if (ist->decoding_needed)
2299 process_input_packet(ist, NULL);
2301 /* mark all outputs that don't go through lavfi as finished */
2302 for (j = 0; j < nb_output_streams; j++) {
2303 OutputStream *ost = output_streams[j];
2305 if (ost->source_index == ifile->ist_index + i &&
2306 (ost->stream_copy || ost->enc->type == AVMEDIA_TYPE_SUBTITLE))
2307 finish_output_stream(ost);
2311 return AVERROR(EAGAIN);
2317 av_pkt_dump_log2(NULL, AV_LOG_DEBUG, &pkt, do_hex_dump,
2318 is->streams[pkt.stream_index]);
2320 /* the following test is needed in case new streams appear
2321 dynamically in stream : we ignore them */
2322 if (pkt.stream_index >= ifile->nb_streams)
2323 goto discard_packet;
2325 ist = input_streams[ifile->ist_index + pkt.stream_index];
2327 ist->data_size += pkt.size;
2331 goto discard_packet;
2333 /* add the stream-global side data to the first packet */
2334 if (ist->nb_packets == 1)
2335 for (i = 0; i < ist->st->nb_side_data; i++) {
2336 AVPacketSideData *src_sd = &ist->st->side_data[i];
2339 if (av_packet_get_side_data(&pkt, src_sd->type, NULL))
2341 if (ist->autorotate && src_sd->type == AV_PKT_DATA_DISPLAYMATRIX)
2344 dst_data = av_packet_new_side_data(&pkt, src_sd->type, src_sd->size);
2348 memcpy(dst_data, src_sd->data, src_sd->size);
2351 if (pkt.dts != AV_NOPTS_VALUE)
2352 pkt.dts += av_rescale_q(ifile->ts_offset, AV_TIME_BASE_Q, ist->st->time_base);
2353 if (pkt.pts != AV_NOPTS_VALUE)
2354 pkt.pts += av_rescale_q(ifile->ts_offset, AV_TIME_BASE_Q, ist->st->time_base);
2356 if (pkt.pts != AV_NOPTS_VALUE)
2357 pkt.pts *= ist->ts_scale;
2358 if (pkt.dts != AV_NOPTS_VALUE)
2359 pkt.dts *= ist->ts_scale;
2361 if ((ist->dec_ctx->codec_type == AVMEDIA_TYPE_VIDEO ||
2362 ist->dec_ctx->codec_type == AVMEDIA_TYPE_AUDIO) &&
2363 pkt.dts != AV_NOPTS_VALUE && ist->next_dts != AV_NOPTS_VALUE &&
2364 (is->iformat->flags & AVFMT_TS_DISCONT)) {
2365 int64_t pkt_dts = av_rescale_q(pkt.dts, ist->st->time_base, AV_TIME_BASE_Q);
2366 int64_t delta = pkt_dts - ist->next_dts;
2368 if ((FFABS(delta) > 1LL * dts_delta_threshold * AV_TIME_BASE || pkt_dts + 1 < ist->last_dts) && !copy_ts) {
2369 ifile->ts_offset -= delta;
2370 av_log(NULL, AV_LOG_DEBUG,
2371 "timestamp discontinuity %"PRId64", new offset= %"PRId64"\n",
2372 delta, ifile->ts_offset);
2373 pkt.dts -= av_rescale_q(delta, AV_TIME_BASE_Q, ist->st->time_base);
2374 if (pkt.pts != AV_NOPTS_VALUE)
2375 pkt.pts -= av_rescale_q(delta, AV_TIME_BASE_Q, ist->st->time_base);
2379 process_input_packet(ist, &pkt);
2382 av_free_packet(&pkt);
2388 * The following code is the main loop of the file converter
2390 static int transcode(void)
2392 int ret, i, need_input = 1;
2393 AVFormatContext *os;
2396 int64_t timer_start;
2398 ret = transcode_init();
2402 av_log(NULL, AV_LOG_INFO, "Press ctrl-c to stop encoding\n");
2405 timer_start = av_gettime_relative();
2408 if ((ret = init_input_threads()) < 0)
2412 while (!received_sigterm) {
2413 /* check if there's any stream where output is still needed */
2414 if (!need_output()) {
2415 av_log(NULL, AV_LOG_VERBOSE, "No more output streams to write to, finishing.\n");
2419 /* read and process one input packet if needed */
2421 ret = process_input();
2422 if (ret == AVERROR_EOF)
2426 ret = poll_filters();
2428 if (ret == AVERROR_EOF || ret == AVERROR(EAGAIN)) {
2432 av_strerror(ret, errbuf, sizeof(errbuf));
2434 av_log(NULL, AV_LOG_ERROR, "Error while filtering: %s\n", errbuf);
2439 /* dump report by using the output first video and audio streams */
2440 print_report(0, timer_start);
2443 free_input_threads();
2446 /* at the end of stream, we must flush the decoder buffers */
2447 for (i = 0; i < nb_input_streams; i++) {
2448 ist = input_streams[i];
2449 if (!input_files[ist->file_index]->eof_reached && ist->decoding_needed) {
2450 process_input_packet(ist, NULL);
2458 /* write the trailer if needed and close file */
2459 for (i = 0; i < nb_output_files; i++) {
2460 os = output_files[i]->ctx;
2461 av_write_trailer(os);
2464 /* dump report by using the first video and audio streams */
2465 print_report(1, timer_start);
2467 /* close each encoder */
2468 for (i = 0; i < nb_output_streams; i++) {
2469 ost = output_streams[i];
2470 if (ost->encoding_needed) {
2471 av_freep(&ost->enc_ctx->stats_in);
2475 /* close each decoder */
2476 for (i = 0; i < nb_input_streams; i++) {
2477 ist = input_streams[i];
2478 if (ist->decoding_needed) {
2479 avcodec_close(ist->dec_ctx);
2480 if (ist->hwaccel_uninit)
2481 ist->hwaccel_uninit(ist->dec_ctx);
2490 free_input_threads();
2493 if (output_streams) {
2494 for (i = 0; i < nb_output_streams; i++) {
2495 ost = output_streams[i];
2498 fclose(ost->logfile);
2499 ost->logfile = NULL;
2501 av_free(ost->forced_kf_pts);
2502 av_dict_free(&ost->encoder_opts);
2503 av_dict_free(&ost->resample_opts);
2510 static int64_t getutime(void)
2513 struct rusage rusage;
2515 getrusage(RUSAGE_SELF, &rusage);
2516 return (rusage.ru_utime.tv_sec * 1000000LL) + rusage.ru_utime.tv_usec;
2517 #elif HAVE_GETPROCESSTIMES
2519 FILETIME c, e, k, u;
2520 proc = GetCurrentProcess();
2521 GetProcessTimes(proc, &c, &e, &k, &u);
2522 return ((int64_t) u.dwHighDateTime << 32 | u.dwLowDateTime) / 10;
2524 return av_gettime_relative();
2528 static int64_t getmaxrss(void)
2530 #if HAVE_GETRUSAGE && HAVE_STRUCT_RUSAGE_RU_MAXRSS
2531 struct rusage rusage;
2532 getrusage(RUSAGE_SELF, &rusage);
2533 return (int64_t)rusage.ru_maxrss * 1024;
2534 #elif HAVE_GETPROCESSMEMORYINFO
2536 PROCESS_MEMORY_COUNTERS memcounters;
2537 proc = GetCurrentProcess();
2538 memcounters.cb = sizeof(memcounters);
2539 GetProcessMemoryInfo(proc, &memcounters, sizeof(memcounters));
2540 return memcounters.PeakPagefileUsage;
2546 int main(int argc, char **argv)
2551 register_exit(avconv_cleanup);
2553 av_log_set_flags(AV_LOG_SKIP_REPEATED);
2554 parse_loglevel(argc, argv, options);
2556 avcodec_register_all();
2558 avdevice_register_all();
2560 avfilter_register_all();
2562 avformat_network_init();
2566 /* parse options and open all input/output files */
2567 ret = avconv_parse_options(argc, argv);
2571 if (nb_output_files <= 0 && nb_input_files == 0) {
2573 av_log(NULL, AV_LOG_WARNING, "Use -h to get full help or, even better, run 'man %s'\n", program_name);
2577 /* file converter / grab */
2578 if (nb_output_files <= 0) {
2579 fprintf(stderr, "At least one output file must be specified\n");
2584 if (transcode() < 0)
2586 ti = getutime() - ti;
2588 int maxrss = getmaxrss() / 1024;
2589 printf("bench: utime=%0.3fs maxrss=%ikB\n", ti / 1000000.0, maxrss);