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/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
59 #include <sys/types.h>
60 #include <sys/resource.h>
61 #elif HAVE_GETPROCESSTIMES
64 #if HAVE_GETPROCESSMEMORYINFO
70 #include <sys/select.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;
94 /* signal to input threads that they should exit; set by the main thread */
95 static int transcoding_finished;
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;
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;
120 sigterm_handler(int sig)
122 received_sigterm = sig;
123 received_nb_signals++;
127 static void term_init(void)
129 signal(SIGINT , sigterm_handler); /* Interrupt (ANSI). */
130 signal(SIGTERM, sigterm_handler); /* Termination (ANSI). */
132 signal(SIGXCPU, sigterm_handler);
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)
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)) {
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);
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)
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)) {
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]);
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);
245 avformat_network_deinit();
247 if (received_sigterm) {
248 av_log(NULL, AV_LOG_INFO, "Received signal %d: terminating.\n",
249 (int) received_sigterm);
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);
263 static void abort_codec_experimental(AVCodec *c, int encoder)
265 const char *codec_string = encoder ? "encoder" : "decoder";
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);
277 static void write_packet(OutputFile *of, AVPacket *pkt, OutputStream *ost)
279 AVFormatContext *s = of->ctx;
280 AVStream *st = ost->st;
283 if (!of->header_written) {
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);
295 ret = av_fifo_realloc2(ost->muxing_queue, new_size);
299 av_packet_move_ref(&tmp_pkt, pkt);
300 av_fifo_generic_write(ost->muxing_queue, &tmp_pkt, sizeof(tmp_pkt), NULL);
305 * Audio encoders may split the packets -- #frames in != #packets out.
306 * But there is no reordering, so we can limit the number of output packets
307 * by simply dropping them here.
308 * Counting encoded video frames needs to be done separately because of
309 * reordering, see do_video_out()
311 if (!(st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO && ost->encoding_needed)) {
312 if (ost->frame_number >= ost->max_frames) {
313 av_packet_unref(pkt);
318 if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
319 uint8_t *sd = av_packet_get_side_data(pkt, AV_PKT_DATA_QUALITY_FACTOR,
321 ost->quality = sd ? *(int *)sd : -1;
323 if (ost->frame_rate.num) {
324 pkt->duration = av_rescale_q(1, av_inv_q(ost->frame_rate),
329 av_packet_rescale_ts(pkt, ost->mux_timebase, ost->st->time_base);
331 if (!(s->oformat->flags & AVFMT_NOTIMESTAMPS) &&
332 ost->last_mux_dts != AV_NOPTS_VALUE &&
333 pkt->dts < ost->last_mux_dts + !(s->oformat->flags & AVFMT_TS_NONSTRICT)) {
334 av_log(NULL, AV_LOG_WARNING, "Non-monotonous DTS in output stream "
335 "%d:%d; previous: %"PRId64", current: %"PRId64"; ",
336 ost->file_index, ost->st->index, ost->last_mux_dts, pkt->dts);
338 av_log(NULL, AV_LOG_FATAL, "aborting.\n");
341 av_log(NULL, AV_LOG_WARNING, "changing to %"PRId64". This may result "
342 "in incorrect timestamps in the output file.\n",
343 ost->last_mux_dts + 1);
344 pkt->dts = ost->last_mux_dts + 1;
345 if (pkt->pts != AV_NOPTS_VALUE)
346 pkt->pts = FFMAX(pkt->pts, pkt->dts);
348 ost->last_mux_dts = pkt->dts;
350 ost->data_size += pkt->size;
351 ost->packets_written++;
353 pkt->stream_index = ost->index;
355 ret = av_interleaved_write_frame(s, pkt);
357 print_error("av_interleaved_write_frame()", ret);
362 static void output_packet(OutputFile *of, AVPacket *pkt, OutputStream *ost)
366 /* apply the output bitstream filters, if any */
367 if (ost->nb_bitstream_filters) {
370 ret = av_bsf_send_packet(ost->bsf_ctx[0], pkt);
376 /* get a packet from the previous filter up the chain */
377 ret = av_bsf_receive_packet(ost->bsf_ctx[idx - 1], pkt);
378 if (ret == AVERROR(EAGAIN)) {
385 /* send it to the next filter down the chain or to the muxer */
386 if (idx < ost->nb_bitstream_filters) {
387 ret = av_bsf_send_packet(ost->bsf_ctx[idx], pkt);
392 write_packet(of, pkt, ost);
395 write_packet(of, pkt, ost);
398 if (ret < 0 && ret != AVERROR_EOF) {
399 av_log(NULL, AV_LOG_FATAL, "Error applying bitstream filters to an output "
400 "packet for stream #%d:%d.\n", ost->file_index, ost->index);
405 static int check_recording_time(OutputStream *ost)
407 OutputFile *of = output_files[ost->file_index];
409 if (of->recording_time != INT64_MAX &&
410 av_compare_ts(ost->sync_opts - ost->first_pts, ost->enc_ctx->time_base, of->recording_time,
411 AV_TIME_BASE_Q) >= 0) {
418 static void do_audio_out(OutputFile *of, OutputStream *ost,
421 AVCodecContext *enc = ost->enc_ctx;
425 av_init_packet(&pkt);
429 if (frame->pts == AV_NOPTS_VALUE || audio_sync_method < 0)
430 frame->pts = ost->sync_opts;
431 ost->sync_opts = frame->pts + frame->nb_samples;
433 ost->samples_encoded += frame->nb_samples;
434 ost->frames_encoded++;
436 ret = avcodec_send_frame(enc, frame);
441 ret = avcodec_receive_packet(enc, &pkt);
442 if (ret == AVERROR(EAGAIN))
447 output_packet(of, &pkt, ost);
452 av_log(NULL, AV_LOG_FATAL, "Audio encoding failed\n");
456 static void do_subtitle_out(OutputFile *of,
462 static uint8_t *subtitle_out = NULL;
463 int subtitle_out_max_size = 1024 * 1024;
464 int subtitle_out_size, nb, i;
468 if (pts == AV_NOPTS_VALUE) {
469 av_log(NULL, AV_LOG_ERROR, "Subtitle packets must have a pts\n");
478 subtitle_out = av_malloc(subtitle_out_max_size);
481 /* Note: DVB subtitle need one packet to draw them and one other
482 packet to clear them */
483 /* XXX: signal it in the codec context ? */
484 if (enc->codec_id == AV_CODEC_ID_DVB_SUBTITLE)
489 for (i = 0; i < nb; i++) {
490 ost->sync_opts = av_rescale_q(pts, ist->st->time_base, enc->time_base);
491 if (!check_recording_time(ost))
494 sub->pts = av_rescale_q(pts, ist->st->time_base, AV_TIME_BASE_Q);
495 // start_display_time is required to be 0
496 sub->pts += av_rescale_q(sub->start_display_time, (AVRational){ 1, 1000 }, AV_TIME_BASE_Q);
497 sub->end_display_time -= sub->start_display_time;
498 sub->start_display_time = 0;
500 ost->frames_encoded++;
502 subtitle_out_size = avcodec_encode_subtitle(enc, subtitle_out,
503 subtitle_out_max_size, sub);
504 if (subtitle_out_size < 0) {
505 av_log(NULL, AV_LOG_FATAL, "Subtitle encoding failed\n");
509 av_init_packet(&pkt);
510 pkt.data = subtitle_out;
511 pkt.size = subtitle_out_size;
512 pkt.pts = av_rescale_q(sub->pts, AV_TIME_BASE_Q, ost->mux_timebase);
513 if (enc->codec_id == AV_CODEC_ID_DVB_SUBTITLE) {
514 /* XXX: the pts correction is handled here. Maybe handling
515 it in the codec would be better */
517 pkt.pts += 90 * sub->start_display_time;
519 pkt.pts += 90 * sub->end_display_time;
521 output_packet(of, &pkt, ost);
525 static void do_video_out(OutputFile *of,
530 int ret, format_video_sync;
532 AVCodecContext *enc = ost->enc_ctx;
536 format_video_sync = video_sync_method;
537 if (format_video_sync == VSYNC_AUTO)
538 format_video_sync = (of->ctx->oformat->flags & AVFMT_NOTIMESTAMPS) ? VSYNC_PASSTHROUGH :
539 (of->ctx->oformat->flags & AVFMT_VARIABLE_FPS) ? VSYNC_VFR : VSYNC_CFR;
540 if (format_video_sync != VSYNC_PASSTHROUGH &&
542 in_picture->pts != AV_NOPTS_VALUE &&
543 in_picture->pts < ost->sync_opts) {
545 av_log(NULL, AV_LOG_WARNING,
546 "*** dropping frame %d from stream %d at ts %"PRId64"\n",
547 ost->frame_number, ost->st->index, in_picture->pts);
551 if (in_picture->pts == AV_NOPTS_VALUE)
552 in_picture->pts = ost->sync_opts;
553 ost->sync_opts = in_picture->pts;
556 if (!ost->frame_number)
557 ost->first_pts = in_picture->pts;
559 av_init_packet(&pkt);
563 if (ost->frame_number >= ost->max_frames)
566 if (enc->flags & (AV_CODEC_FLAG_INTERLACED_DCT | AV_CODEC_FLAG_INTERLACED_ME) &&
567 ost->top_field_first >= 0)
568 in_picture->top_field_first = !!ost->top_field_first;
570 in_picture->quality = enc->global_quality;
571 in_picture->pict_type = 0;
572 if (ost->forced_kf_index < ost->forced_kf_count &&
573 in_picture->pts >= ost->forced_kf_pts[ost->forced_kf_index]) {
574 in_picture->pict_type = AV_PICTURE_TYPE_I;
575 ost->forced_kf_index++;
578 ost->frames_encoded++;
580 ret = avcodec_send_frame(enc, in_picture);
585 * For video, there may be reordering, so we can't throw away frames on
586 * encoder flush, we need to limit them here, before they go into encoder.
591 ret = avcodec_receive_packet(enc, &pkt);
592 if (ret == AVERROR(EAGAIN))
597 output_packet(of, &pkt, ost);
598 *frame_size = pkt.size;
600 /* if two pass, output log */
601 if (ost->logfile && enc->stats_out) {
602 fprintf(ost->logfile, "%s", enc->stats_out);
610 av_assert0(ret != AVERROR(EAGAIN) && ret != AVERROR_EOF);
611 av_log(NULL, AV_LOG_FATAL, "Video encoding failed\n");
615 #if FF_API_CODED_FRAME && FF_API_ERROR_FRAME
616 static double psnr(double d)
618 return -10.0 * log(d) / log(10.0);
622 static void do_video_stats(OutputStream *ost, int frame_size)
626 double ti1, bitrate, avg_bitrate;
628 /* this is executed just the first time do_video_stats is called */
630 vstats_file = fopen(vstats_filename, "w");
638 if (enc->codec_type == AVMEDIA_TYPE_VIDEO) {
639 frame_number = ost->frame_number;
640 fprintf(vstats_file, "frame= %5d q= %2.1f ", frame_number,
641 ost->quality / (float)FF_QP2LAMBDA);
643 #if FF_API_CODED_FRAME && FF_API_ERROR_FRAME
644 FF_DISABLE_DEPRECATION_WARNINGS
645 if (enc->flags & AV_CODEC_FLAG_PSNR)
646 fprintf(vstats_file, "PSNR= %6.2f ", psnr(enc->coded_frame->error[0] / (enc->width * enc->height * 255.0 * 255.0)));
647 FF_ENABLE_DEPRECATION_WARNINGS
650 fprintf(vstats_file,"f_size= %6d ", frame_size);
651 /* compute pts value */
652 ti1 = ost->sync_opts * av_q2d(enc->time_base);
656 bitrate = (frame_size * 8) / av_q2d(enc->time_base) / 1000.0;
657 avg_bitrate = (double)(ost->data_size * 8) / ti1 / 1000.0;
658 fprintf(vstats_file, "s_size= %8.0fkB time= %0.3f br= %7.1fkbits/s avg_br= %7.1fkbits/s ",
659 (double)ost->data_size / 1024, ti1, bitrate, avg_bitrate);
660 #if FF_API_CODED_FRAME
661 FF_DISABLE_DEPRECATION_WARNINGS
662 fprintf(vstats_file, "type= %c\n", av_get_picture_type_char(enc->coded_frame->pict_type));
663 FF_ENABLE_DEPRECATION_WARNINGS
668 static int init_output_stream(OutputStream *ost, char *error, int error_len);
671 * Read one frame for lavfi output for ost and encode it.
673 static int poll_filter(OutputStream *ost)
675 OutputFile *of = output_files[ost->file_index];
676 AVFrame *filtered_frame = NULL;
679 if (!ost->filtered_frame && !(ost->filtered_frame = av_frame_alloc())) {
680 return AVERROR(ENOMEM);
682 filtered_frame = ost->filtered_frame;
684 if (!ost->initialized) {
686 ret = init_output_stream(ost, error, sizeof(error));
688 av_log(NULL, AV_LOG_ERROR, "Error initializing output stream %d:%d -- %s\n",
689 ost->file_index, ost->index, error);
694 if (ost->enc->type == AVMEDIA_TYPE_AUDIO &&
695 !(ost->enc->capabilities & AV_CODEC_CAP_VARIABLE_FRAME_SIZE))
696 ret = av_buffersink_get_samples(ost->filter->filter, filtered_frame,
697 ost->enc_ctx->frame_size);
699 ret = av_buffersink_get_frame(ost->filter->filter, filtered_frame);
704 if (filtered_frame->pts != AV_NOPTS_VALUE) {
705 int64_t start_time = (of->start_time == AV_NOPTS_VALUE) ? 0 : of->start_time;
706 filtered_frame->pts = av_rescale_q(filtered_frame->pts,
707 ost->filter->filter->inputs[0]->time_base,
708 ost->enc_ctx->time_base) -
709 av_rescale_q(start_time,
711 ost->enc_ctx->time_base);
714 switch (ost->filter->filter->inputs[0]->type) {
715 case AVMEDIA_TYPE_VIDEO:
716 if (!ost->frame_aspect_ratio)
717 ost->enc_ctx->sample_aspect_ratio = filtered_frame->sample_aspect_ratio;
719 do_video_out(of, ost, filtered_frame, &frame_size);
720 if (vstats_filename && frame_size)
721 do_video_stats(ost, frame_size);
723 case AVMEDIA_TYPE_AUDIO:
724 do_audio_out(of, ost, filtered_frame);
727 // TODO support subtitle filters
731 av_frame_unref(filtered_frame);
736 static void finish_output_stream(OutputStream *ost)
738 OutputFile *of = output_files[ost->file_index];
744 for (i = 0; i < of->ctx->nb_streams; i++)
745 output_streams[of->ost_index + i]->finished = 1;
750 * Read as many frames from possible from lavfi and encode them.
752 * Always read from the active stream with the lowest timestamp. If no frames
753 * are available for it then return EAGAIN and wait for more input. This way we
754 * can use lavfi sources that generate unlimited amount of frames without memory
757 static int poll_filters(void)
761 while (ret >= 0 && !received_sigterm) {
762 OutputStream *ost = NULL;
763 int64_t min_pts = INT64_MAX;
765 /* choose output stream with the lowest timestamp */
766 for (i = 0; i < nb_output_streams; i++) {
767 int64_t pts = output_streams[i]->sync_opts;
769 if (output_streams[i]->filter && !output_streams[i]->filter->graph->graph &&
770 !output_streams[i]->filter->graph->nb_inputs) {
771 ret = configure_filtergraph(output_streams[i]->filter->graph);
773 av_log(NULL, AV_LOG_ERROR, "Error reinitializing filters!\n");
778 if (!output_streams[i]->filter || output_streams[i]->finished ||
779 !output_streams[i]->filter->graph->graph)
782 pts = av_rescale_q(pts, output_streams[i]->enc_ctx->time_base,
786 ost = output_streams[i];
793 ret = poll_filter(ost);
795 if (ret == AVERROR_EOF) {
796 finish_output_stream(ost);
798 } else if (ret == AVERROR(EAGAIN))
805 static void print_final_stats(int64_t total_size)
807 uint64_t video_size = 0, audio_size = 0, extra_size = 0, other_size = 0;
808 uint64_t data_size = 0;
809 float percent = -1.0;
812 for (i = 0; i < nb_output_streams; i++) {
813 OutputStream *ost = output_streams[i];
814 switch (ost->enc_ctx->codec_type) {
815 case AVMEDIA_TYPE_VIDEO: video_size += ost->data_size; break;
816 case AVMEDIA_TYPE_AUDIO: audio_size += ost->data_size; break;
817 default: other_size += ost->data_size; break;
819 extra_size += ost->enc_ctx->extradata_size;
820 data_size += ost->data_size;
823 if (data_size && total_size >= data_size)
824 percent = 100.0 * (total_size - data_size) / data_size;
826 av_log(NULL, AV_LOG_INFO, "\n");
827 av_log(NULL, AV_LOG_INFO, "video:%1.0fkB audio:%1.0fkB other streams:%1.0fkB global headers:%1.0fkB muxing overhead: ",
831 extra_size / 1024.0);
833 av_log(NULL, AV_LOG_INFO, "%f%%", percent);
835 av_log(NULL, AV_LOG_INFO, "unknown");
836 av_log(NULL, AV_LOG_INFO, "\n");
838 /* print verbose per-stream stats */
839 for (i = 0; i < nb_input_files; i++) {
840 InputFile *f = input_files[i];
841 uint64_t total_packets = 0, total_size = 0;
843 av_log(NULL, AV_LOG_VERBOSE, "Input file #%d (%s):\n",
844 i, f->ctx->filename);
846 for (j = 0; j < f->nb_streams; j++) {
847 InputStream *ist = input_streams[f->ist_index + j];
848 enum AVMediaType type = ist->dec_ctx->codec_type;
850 total_size += ist->data_size;
851 total_packets += ist->nb_packets;
853 av_log(NULL, AV_LOG_VERBOSE, " Input stream #%d:%d (%s): ",
854 i, j, media_type_string(type));
855 av_log(NULL, AV_LOG_VERBOSE, "%"PRIu64" packets read (%"PRIu64" bytes); ",
856 ist->nb_packets, ist->data_size);
858 if (ist->decoding_needed) {
859 av_log(NULL, AV_LOG_VERBOSE, "%"PRIu64" frames decoded",
860 ist->frames_decoded);
861 if (type == AVMEDIA_TYPE_AUDIO)
862 av_log(NULL, AV_LOG_VERBOSE, " (%"PRIu64" samples)", ist->samples_decoded);
863 av_log(NULL, AV_LOG_VERBOSE, "; ");
866 av_log(NULL, AV_LOG_VERBOSE, "\n");
869 av_log(NULL, AV_LOG_VERBOSE, " Total: %"PRIu64" packets (%"PRIu64" bytes) demuxed\n",
870 total_packets, total_size);
873 for (i = 0; i < nb_output_files; i++) {
874 OutputFile *of = output_files[i];
875 uint64_t total_packets = 0, total_size = 0;
877 av_log(NULL, AV_LOG_VERBOSE, "Output file #%d (%s):\n",
878 i, of->ctx->filename);
880 for (j = 0; j < of->ctx->nb_streams; j++) {
881 OutputStream *ost = output_streams[of->ost_index + j];
882 enum AVMediaType type = ost->enc_ctx->codec_type;
884 total_size += ost->data_size;
885 total_packets += ost->packets_written;
887 av_log(NULL, AV_LOG_VERBOSE, " Output stream #%d:%d (%s): ",
888 i, j, media_type_string(type));
889 if (ost->encoding_needed) {
890 av_log(NULL, AV_LOG_VERBOSE, "%"PRIu64" frames encoded",
891 ost->frames_encoded);
892 if (type == AVMEDIA_TYPE_AUDIO)
893 av_log(NULL, AV_LOG_VERBOSE, " (%"PRIu64" samples)", ost->samples_encoded);
894 av_log(NULL, AV_LOG_VERBOSE, "; ");
897 av_log(NULL, AV_LOG_VERBOSE, "%"PRIu64" packets muxed (%"PRIu64" bytes); ",
898 ost->packets_written, ost->data_size);
900 av_log(NULL, AV_LOG_VERBOSE, "\n");
903 av_log(NULL, AV_LOG_VERBOSE, " Total: %"PRIu64" packets (%"PRIu64" bytes) muxed\n",
904 total_packets, total_size);
908 static void print_report(int is_last_report, int64_t timer_start)
913 int64_t total_size = 0;
915 int frame_number, vid, i;
916 double bitrate, ti1, pts;
917 static int64_t last_time = -1;
918 static int qp_histogram[52];
920 if (!print_stats && !is_last_report)
923 if (!is_last_report) {
925 /* display the report every 0.5 seconds */
926 cur_time = av_gettime_relative();
927 if (last_time == -1) {
928 last_time = cur_time;
931 if ((cur_time - last_time) < 500000)
933 last_time = cur_time;
937 oc = output_files[0]->ctx;
939 total_size = avio_size(oc->pb);
940 if (total_size <= 0) // FIXME improve avio_size() so it works with non seekable output too
941 total_size = avio_tell(oc->pb);
942 if (total_size < 0) {
944 av_strerror(total_size, errbuf, sizeof(errbuf));
945 av_log(NULL, AV_LOG_VERBOSE, "Bitrate not available, "
946 "avio_tell() failed: %s\n", errbuf);
954 for (i = 0; i < nb_output_streams; i++) {
956 ost = output_streams[i];
958 if (!ost->stream_copy)
959 q = ost->quality / (float) FF_QP2LAMBDA;
961 if (vid && enc->codec_type == AVMEDIA_TYPE_VIDEO) {
962 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "q=%2.1f ", q);
964 if (!vid && enc->codec_type == AVMEDIA_TYPE_VIDEO) {
965 float t = (av_gettime_relative() - timer_start) / 1000000.0;
967 frame_number = ost->frame_number;
968 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "frame=%5d fps=%3d q=%3.1f ",
969 frame_number, (t > 1) ? (int)(frame_number / t + 0.5) : 0, q);
971 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "L");
975 if (qp >= 0 && qp < FF_ARRAY_ELEMS(qp_histogram))
977 for (j = 0; j < 32; j++)
978 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "%X", (int)lrintf(log2(qp_histogram[j] + 1)));
981 #if FF_API_CODED_FRAME && FF_API_ERROR_FRAME
982 FF_DISABLE_DEPRECATION_WARNINGS
983 if (enc->flags & AV_CODEC_FLAG_PSNR) {
985 double error, error_sum = 0;
986 double scale, scale_sum = 0;
987 char type[3] = { 'Y','U','V' };
988 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "PSNR=");
989 for (j = 0; j < 3; j++) {
990 if (is_last_report) {
991 error = enc->error[j];
992 scale = enc->width * enc->height * 255.0 * 255.0 * frame_number;
994 error = enc->coded_frame->error[j];
995 scale = enc->width * enc->height * 255.0 * 255.0;
1001 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "%c:%2.2f ", type[j], psnr(error / scale));
1003 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "*:%2.2f ", psnr(error_sum / scale_sum));
1005 FF_ENABLE_DEPRECATION_WARNINGS
1009 /* compute min output value */
1010 pts = (double)ost->last_mux_dts * av_q2d(ost->st->time_base);
1011 if ((pts < ti1) && (pts > 0))
1017 bitrate = (double)(total_size * 8) / ti1 / 1000.0;
1019 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
1020 "size=%8.0fkB time=%0.2f bitrate=%6.1fkbits/s",
1021 (double)total_size / 1024, ti1, bitrate);
1024 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), " drop=%d",
1027 av_log(NULL, AV_LOG_INFO, "%s \r", buf);
1032 print_final_stats(total_size);
1036 static void flush_encoders(void)
1040 for (i = 0; i < nb_output_streams; i++) {
1041 OutputStream *ost = output_streams[i];
1042 AVCodecContext *enc = ost->enc_ctx;
1043 OutputFile *of = output_files[ost->file_index];
1044 int stop_encoding = 0;
1046 if (!ost->encoding_needed)
1049 if (enc->codec_type == AVMEDIA_TYPE_AUDIO && enc->frame_size <= 1)
1052 if (enc->codec_type != AVMEDIA_TYPE_VIDEO && enc->codec_type != AVMEDIA_TYPE_AUDIO)
1055 avcodec_send_frame(enc, NULL);
1058 const char *desc = NULL;
1060 switch (enc->codec_type) {
1061 case AVMEDIA_TYPE_AUDIO:
1064 case AVMEDIA_TYPE_VIDEO:
1073 av_init_packet(&pkt);
1077 ret = avcodec_receive_packet(enc, &pkt);
1078 if (ret < 0 && ret != AVERROR_EOF) {
1079 av_log(NULL, AV_LOG_FATAL, "%s encoding failed\n", desc);
1082 if (ost->logfile && enc->stats_out) {
1083 fprintf(ost->logfile, "%s", enc->stats_out);
1085 if (ret == AVERROR_EOF) {
1089 output_packet(of, &pkt, ost);
1099 * Check whether a packet from ist should be written into ost at this time
1101 static int check_output_constraints(InputStream *ist, OutputStream *ost)
1103 OutputFile *of = output_files[ost->file_index];
1104 int ist_index = input_files[ist->file_index]->ist_index + ist->st->index;
1106 if (ost->source_index != ist_index)
1109 if (of->start_time != AV_NOPTS_VALUE && ist->last_dts < of->start_time)
1115 static void do_streamcopy(InputStream *ist, OutputStream *ost, const AVPacket *pkt)
1117 OutputFile *of = output_files[ost->file_index];
1118 InputFile *f = input_files [ist->file_index];
1119 int64_t start_time = (of->start_time == AV_NOPTS_VALUE) ? 0 : of->start_time;
1120 int64_t ost_tb_start_time = av_rescale_q(start_time, AV_TIME_BASE_Q, ost->mux_timebase);
1123 av_init_packet(&opkt);
1125 if ((!ost->frame_number && !(pkt->flags & AV_PKT_FLAG_KEY)) &&
1126 !ost->copy_initial_nonkeyframes)
1129 if (of->recording_time != INT64_MAX &&
1130 ist->last_dts >= of->recording_time + start_time) {
1135 if (f->recording_time != INT64_MAX) {
1136 start_time = f->ctx->start_time;
1137 if (f->start_time != AV_NOPTS_VALUE)
1138 start_time += f->start_time;
1139 if (ist->last_dts >= f->recording_time + start_time) {
1145 /* force the input stream PTS */
1146 if (ost->enc_ctx->codec_type == AVMEDIA_TYPE_VIDEO)
1149 if (pkt->pts != AV_NOPTS_VALUE)
1150 opkt.pts = av_rescale_q(pkt->pts, ist->st->time_base, ost->mux_timebase) - ost_tb_start_time;
1152 opkt.pts = AV_NOPTS_VALUE;
1154 if (pkt->dts == AV_NOPTS_VALUE)
1155 opkt.dts = av_rescale_q(ist->last_dts, AV_TIME_BASE_Q, ost->mux_timebase);
1157 opkt.dts = av_rescale_q(pkt->dts, ist->st->time_base, ost->mux_timebase);
1158 opkt.dts -= ost_tb_start_time;
1160 opkt.duration = av_rescale_q(pkt->duration, ist->st->time_base, ost->mux_timebase);
1161 opkt.flags = pkt->flags;
1163 // FIXME remove the following 2 lines they shall be replaced by the bitstream filters
1164 if ( ost->enc_ctx->codec_id != AV_CODEC_ID_H264
1165 && ost->enc_ctx->codec_id != AV_CODEC_ID_MPEG1VIDEO
1166 && ost->enc_ctx->codec_id != AV_CODEC_ID_MPEG2VIDEO
1167 && ost->enc_ctx->codec_id != AV_CODEC_ID_VC1
1169 if (av_parser_change(ost->parser, ost->parser_avctx,
1170 &opkt.data, &opkt.size,
1171 pkt->data, pkt->size,
1172 pkt->flags & AV_PKT_FLAG_KEY)) {
1173 opkt.buf = av_buffer_create(opkt.data, opkt.size, av_buffer_default_free, NULL, 0);
1178 opkt.data = pkt->data;
1179 opkt.size = pkt->size;
1182 output_packet(of, &opkt, ost);
1185 static int ifilter_send_frame(InputFilter *ifilter, AVFrame *frame)
1187 FilterGraph *fg = ifilter->graph;
1188 int need_reinit, ret, i;
1190 /* determine if the parameters for this input changed */
1191 need_reinit = ifilter->format != frame->format;
1192 if (!!ifilter->hw_frames_ctx != !!frame->hw_frames_ctx ||
1193 (ifilter->hw_frames_ctx && ifilter->hw_frames_ctx->data != frame->hw_frames_ctx->data))
1196 switch (ifilter->ist->st->codecpar->codec_type) {
1197 case AVMEDIA_TYPE_AUDIO:
1198 need_reinit |= ifilter->sample_rate != frame->sample_rate ||
1199 ifilter->channel_layout != frame->channel_layout;
1201 case AVMEDIA_TYPE_VIDEO:
1202 need_reinit |= ifilter->width != frame->width ||
1203 ifilter->height != frame->height;
1208 ret = ifilter_parameters_from_frame(ifilter, frame);
1213 /* (re)init the graph if possible, otherwise buffer the frame and return */
1214 if (need_reinit || !fg->graph) {
1215 for (i = 0; i < fg->nb_inputs; i++) {
1216 if (fg->inputs[i]->format < 0) {
1217 AVFrame *tmp = av_frame_clone(frame);
1219 return AVERROR(ENOMEM);
1220 av_frame_unref(frame);
1222 if (!av_fifo_space(ifilter->frame_queue)) {
1223 ret = av_fifo_realloc2(ifilter->frame_queue, 2 * av_fifo_size(ifilter->frame_queue));
1227 av_fifo_generic_write(ifilter->frame_queue, &tmp, sizeof(tmp), NULL);
1232 ret = poll_filters();
1233 if (ret < 0 && ret != AVERROR_EOF) {
1235 av_strerror(ret, errbuf, sizeof(errbuf));
1237 av_log(NULL, AV_LOG_ERROR, "Error while filtering: %s\n", errbuf);
1241 ret = configure_filtergraph(fg);
1243 av_log(NULL, AV_LOG_ERROR, "Error reinitializing filters!\n");
1248 ret = av_buffersrc_add_frame(ifilter->filter, frame);
1250 av_log(NULL, AV_LOG_ERROR, "Error while filtering\n");
1257 static int ifilter_send_eof(InputFilter *ifilter)
1263 if (ifilter->filter) {
1264 ret = av_buffersrc_add_frame(ifilter->filter, NULL);
1268 // the filtergraph was never configured
1269 FilterGraph *fg = ifilter->graph;
1270 for (i = 0; i < fg->nb_inputs; i++)
1271 if (!fg->inputs[i]->eof)
1273 if (i == fg->nb_inputs) {
1274 // All the input streams have finished without the filtergraph
1275 // ever being configured.
1276 // Mark the output streams as finished.
1277 for (j = 0; j < fg->nb_outputs; j++)
1278 finish_output_stream(fg->outputs[j]->ost);
1285 // This does not quite work like avcodec_decode_audio4/avcodec_decode_video2.
1286 // There is the following difference: if you got a frame, you must call
1287 // it again with pkt=NULL. pkt==NULL is treated differently from pkt.size==0
1288 // (pkt==NULL means get more output, pkt.size==0 is a flush/drain packet)
1289 static int decode(AVCodecContext *avctx, AVFrame *frame, int *got_frame, AVPacket *pkt)
1296 ret = avcodec_send_packet(avctx, pkt);
1297 // In particular, we don't expect AVERROR(EAGAIN), because we read all
1298 // decoded frames with avcodec_receive_frame() until done.
1300 return ret == AVERROR_EOF ? 0 : ret;
1303 ret = avcodec_receive_frame(avctx, frame);
1304 if (ret < 0 && ret != AVERROR(EAGAIN) && ret != AVERROR_EOF)
1312 int guess_input_channel_layout(InputStream *ist)
1314 AVCodecContext *dec = ist->dec_ctx;
1316 if (!dec->channel_layout) {
1317 char layout_name[256];
1319 dec->channel_layout = av_get_default_channel_layout(dec->channels);
1320 if (!dec->channel_layout)
1322 av_get_channel_layout_string(layout_name, sizeof(layout_name),
1323 dec->channels, dec->channel_layout);
1324 av_log(NULL, AV_LOG_WARNING, "Guessed Channel Layout for Input Stream "
1325 "#%d.%d : %s\n", ist->file_index, ist->st->index, layout_name);
1330 static int decode_audio(InputStream *ist, AVPacket *pkt, int *got_output,
1333 AVFrame *decoded_frame, *f;
1334 AVCodecContext *avctx = ist->dec_ctx;
1335 int i, ret, err = 0;
1337 if (!ist->decoded_frame && !(ist->decoded_frame = av_frame_alloc()))
1338 return AVERROR(ENOMEM);
1339 if (!ist->filter_frame && !(ist->filter_frame = av_frame_alloc()))
1340 return AVERROR(ENOMEM);
1341 decoded_frame = ist->decoded_frame;
1343 ret = decode(avctx, decoded_frame, got_output, pkt);
1346 if (!*got_output || ret < 0)
1349 ist->samples_decoded += decoded_frame->nb_samples;
1350 ist->frames_decoded++;
1352 /* if the decoder provides a pts, use it instead of the last packet pts.
1353 the decoder could be delaying output by a packet or more. */
1354 if (decoded_frame->pts != AV_NOPTS_VALUE)
1355 ist->next_dts = av_rescale_q(decoded_frame->pts, ist->st->time_base, AV_TIME_BASE_Q);
1356 else if (pkt && pkt->pts != AV_NOPTS_VALUE) {
1357 decoded_frame->pts = pkt->pts;
1360 if (decoded_frame->pts != AV_NOPTS_VALUE)
1361 decoded_frame->pts = av_rescale_q(decoded_frame->pts,
1363 (AVRational){1, avctx->sample_rate});
1364 ist->nb_samples = decoded_frame->nb_samples;
1365 for (i = 0; i < ist->nb_filters; i++) {
1366 if (i < ist->nb_filters - 1) {
1367 f = ist->filter_frame;
1368 err = av_frame_ref(f, decoded_frame);
1374 err = ifilter_send_frame(ist->filters[i], f);
1379 av_frame_unref(ist->filter_frame);
1380 av_frame_unref(decoded_frame);
1381 return err < 0 ? err : ret;
1384 static int decode_video(InputStream *ist, AVPacket *pkt, int *got_output,
1387 AVFrame *decoded_frame, *f;
1388 int i, ret = 0, err = 0;
1390 if (!ist->decoded_frame && !(ist->decoded_frame = av_frame_alloc()))
1391 return AVERROR(ENOMEM);
1392 if (!ist->filter_frame && !(ist->filter_frame = av_frame_alloc()))
1393 return AVERROR(ENOMEM);
1394 decoded_frame = ist->decoded_frame;
1396 ret = decode(ist->dec_ctx, decoded_frame, got_output, pkt);
1399 if (!*got_output || ret < 0)
1402 ist->frames_decoded++;
1404 if (ist->hwaccel_retrieve_data && decoded_frame->format == ist->hwaccel_pix_fmt) {
1405 err = ist->hwaccel_retrieve_data(ist->dec_ctx, decoded_frame);
1409 ist->hwaccel_retrieved_pix_fmt = decoded_frame->format;
1411 decoded_frame->pts = guess_correct_pts(&ist->pts_ctx, decoded_frame->pts,
1412 decoded_frame->pkt_dts);
1413 if (ist->framerate.num)
1414 decoded_frame->pts = ist->cfr_next_pts++;
1416 if (ist->st->sample_aspect_ratio.num)
1417 decoded_frame->sample_aspect_ratio = ist->st->sample_aspect_ratio;
1419 for (i = 0; i < ist->nb_filters; i++) {
1420 if (i < ist->nb_filters - 1) {
1421 f = ist->filter_frame;
1422 err = av_frame_ref(f, decoded_frame);
1428 err = ifilter_send_frame(ist->filters[i], f);
1434 av_frame_unref(ist->filter_frame);
1435 av_frame_unref(decoded_frame);
1436 return err < 0 ? err : ret;
1439 static int transcode_subtitles(InputStream *ist, AVPacket *pkt, int *got_output,
1442 AVSubtitle subtitle;
1443 int i, ret = avcodec_decode_subtitle2(ist->dec_ctx,
1444 &subtitle, got_output, pkt);
1452 ist->frames_decoded++;
1454 for (i = 0; i < nb_output_streams; i++) {
1455 OutputStream *ost = output_streams[i];
1457 if (!check_output_constraints(ist, ost) || !ost->encoding_needed)
1460 do_subtitle_out(output_files[ost->file_index], ost, ist, &subtitle, pkt->pts);
1463 avsubtitle_free(&subtitle);
1467 static int send_filter_eof(InputStream *ist)
1470 for (i = 0; i < ist->nb_filters; i++) {
1471 ret = ifilter_send_eof(ist->filters[i]);
1478 /* pkt = NULL means EOF (needed to flush decoder buffers) */
1479 static void process_input_packet(InputStream *ist, const AVPacket *pkt, int no_eof)
1485 if (ist->next_dts == AV_NOPTS_VALUE)
1486 ist->next_dts = ist->last_dts;
1490 av_init_packet(&avpkt);
1497 if (pkt && pkt->dts != AV_NOPTS_VALUE)
1498 ist->next_dts = ist->last_dts = av_rescale_q(pkt->dts, ist->st->time_base, AV_TIME_BASE_Q);
1500 // while we have more to decode or while the decoder did output something on EOF
1501 while (ist->decoding_needed && (!pkt || avpkt.size > 0)) {
1504 int decode_failed = 0;
1507 ist->last_dts = ist->next_dts;
1509 switch (ist->dec_ctx->codec_type) {
1510 case AVMEDIA_TYPE_AUDIO:
1511 ret = decode_audio (ist, repeating ? NULL : &avpkt, &got_output,
1514 case AVMEDIA_TYPE_VIDEO:
1515 ret = decode_video (ist, repeating ? NULL : &avpkt, &got_output,
1517 if (repeating && !got_output)
1519 else if (pkt && pkt->duration)
1520 ist->next_dts += av_rescale_q(pkt->duration, ist->st->time_base, AV_TIME_BASE_Q);
1521 else if (ist->st->avg_frame_rate.num)
1522 ist->next_dts += av_rescale_q(1, av_inv_q(ist->st->avg_frame_rate),
1524 else if (ist->dec_ctx->framerate.num != 0) {
1525 int ticks = ist->st->parser ? ist->st->parser->repeat_pict + 1 :
1526 ist->dec_ctx->ticks_per_frame;
1527 ist->next_dts += av_rescale_q(ticks, ist->dec_ctx->framerate, AV_TIME_BASE_Q);
1530 case AVMEDIA_TYPE_SUBTITLE:
1533 ret = transcode_subtitles(ist, &avpkt, &got_output, &decode_failed);
1540 if (decode_failed) {
1541 av_log(NULL, AV_LOG_ERROR, "Error while decoding stream #%d:%d\n",
1542 ist->file_index, ist->st->index);
1544 av_log(NULL, AV_LOG_FATAL, "Error while processing the decoded "
1545 "data for stream #%d:%d\n", ist->file_index, ist->st->index);
1547 if (!decode_failed || exit_on_error)
1558 /* after flushing, send an EOF on all the filter inputs attached to the stream */
1559 /* except when looping we need to flush but not to send an EOF */
1560 if (!pkt && ist->decoding_needed && !no_eof) {
1561 int ret = send_filter_eof(ist);
1563 av_log(NULL, AV_LOG_FATAL, "Error marking filters as finished\n");
1568 /* handle stream copy */
1569 if (!ist->decoding_needed) {
1570 ist->last_dts = ist->next_dts;
1571 switch (ist->dec_ctx->codec_type) {
1572 case AVMEDIA_TYPE_AUDIO:
1573 ist->next_dts += ((int64_t)AV_TIME_BASE * ist->dec_ctx->frame_size) /
1574 ist->dec_ctx->sample_rate;
1576 case AVMEDIA_TYPE_VIDEO:
1577 if (ist->dec_ctx->framerate.num != 0) {
1578 int ticks = ist->st->parser ? ist->st->parser->repeat_pict + 1 : ist->dec_ctx->ticks_per_frame;
1579 ist->next_dts += ((int64_t)AV_TIME_BASE *
1580 ist->dec_ctx->framerate.den * ticks) /
1581 ist->dec_ctx->framerate.num;
1586 for (i = 0; pkt && i < nb_output_streams; i++) {
1587 OutputStream *ost = output_streams[i];
1589 if (!check_output_constraints(ist, ost) || ost->encoding_needed)
1592 do_streamcopy(ist, ost, pkt);
1598 static void print_sdp(void)
1602 AVFormatContext **avc;
1604 for (i = 0; i < nb_output_files; i++) {
1605 if (!output_files[i]->header_written)
1609 avc = av_malloc(sizeof(*avc) * nb_output_files);
1612 for (i = 0; i < nb_output_files; i++)
1613 avc[i] = output_files[i]->ctx;
1615 av_sdp_create(avc, nb_output_files, sdp, sizeof(sdp));
1616 printf("SDP:\n%s\n", sdp);
1621 static const HWAccel *get_hwaccel(enum AVPixelFormat pix_fmt)
1624 for (i = 0; hwaccels[i].name; i++)
1625 if (hwaccels[i].pix_fmt == pix_fmt)
1626 return &hwaccels[i];
1630 static enum AVPixelFormat get_format(AVCodecContext *s, const enum AVPixelFormat *pix_fmts)
1632 InputStream *ist = s->opaque;
1633 const enum AVPixelFormat *p;
1636 for (p = pix_fmts; *p != -1; p++) {
1637 const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(*p);
1638 const HWAccel *hwaccel;
1640 if (!(desc->flags & AV_PIX_FMT_FLAG_HWACCEL))
1643 hwaccel = get_hwaccel(*p);
1645 (ist->active_hwaccel_id && ist->active_hwaccel_id != hwaccel->id) ||
1646 (ist->hwaccel_id != HWACCEL_AUTO && ist->hwaccel_id != hwaccel->id))
1649 ret = hwaccel->init(s);
1651 if (ist->hwaccel_id == hwaccel->id) {
1652 av_log(NULL, AV_LOG_FATAL,
1653 "%s hwaccel requested for input stream #%d:%d, "
1654 "but cannot be initialized.\n", hwaccel->name,
1655 ist->file_index, ist->st->index);
1656 return AV_PIX_FMT_NONE;
1661 if (ist->hw_frames_ctx) {
1662 s->hw_frames_ctx = av_buffer_ref(ist->hw_frames_ctx);
1663 if (!s->hw_frames_ctx)
1664 return AV_PIX_FMT_NONE;
1667 ist->active_hwaccel_id = hwaccel->id;
1668 ist->hwaccel_pix_fmt = *p;
1675 static int get_buffer(AVCodecContext *s, AVFrame *frame, int flags)
1677 InputStream *ist = s->opaque;
1679 if (ist->hwaccel_get_buffer && frame->format == ist->hwaccel_pix_fmt)
1680 return ist->hwaccel_get_buffer(s, frame, flags);
1682 return avcodec_default_get_buffer2(s, frame, flags);
1685 static int init_input_stream(int ist_index, char *error, int error_len)
1688 InputStream *ist = input_streams[ist_index];
1690 if (ist->decoding_needed) {
1691 AVCodec *codec = ist->dec;
1693 snprintf(error, error_len, "Decoder (codec id %d) not found for input stream #%d:%d",
1694 ist->dec_ctx->codec_id, ist->file_index, ist->st->index);
1695 return AVERROR(EINVAL);
1698 ist->dec_ctx->opaque = ist;
1699 ist->dec_ctx->get_format = get_format;
1700 ist->dec_ctx->get_buffer2 = get_buffer;
1701 ist->dec_ctx->thread_safe_callbacks = 1;
1703 av_opt_set_int(ist->dec_ctx, "refcounted_frames", 1, 0);
1705 if (!av_dict_get(ist->decoder_opts, "threads", NULL, 0))
1706 av_dict_set(&ist->decoder_opts, "threads", "auto", 0);
1708 ret = hw_device_setup_for_decode(ist);
1711 av_strerror(ret, errbuf, sizeof(errbuf));
1712 snprintf(error, error_len, "Device setup failed for "
1713 "decoder on input stream #%d:%d : %s",
1714 ist->file_index, ist->st->index, errbuf);
1718 if ((ret = avcodec_open2(ist->dec_ctx, codec, &ist->decoder_opts)) < 0) {
1720 if (ret == AVERROR_EXPERIMENTAL)
1721 abort_codec_experimental(codec, 0);
1723 av_strerror(ret, errbuf, sizeof(errbuf));
1725 snprintf(error, error_len,
1726 "Error while opening decoder for input stream "
1728 ist->file_index, ist->st->index, errbuf);
1731 assert_avoptions(ist->decoder_opts);
1734 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;
1735 ist->next_dts = AV_NOPTS_VALUE;
1736 init_pts_correction(&ist->pts_ctx);
1741 static InputStream *get_input_stream(OutputStream *ost)
1743 if (ost->source_index >= 0)
1744 return input_streams[ost->source_index];
1747 FilterGraph *fg = ost->filter->graph;
1750 for (i = 0; i < fg->nb_inputs; i++)
1751 if (fg->inputs[i]->ist->dec_ctx->codec_type == ost->enc_ctx->codec_type)
1752 return fg->inputs[i]->ist;
1758 /* open the muxer when all the streams are initialized */
1759 static int check_init_output_file(OutputFile *of, int file_index)
1763 for (i = 0; i < of->ctx->nb_streams; i++) {
1764 OutputStream *ost = output_streams[of->ost_index + i];
1765 if (!ost->initialized)
1769 of->ctx->interrupt_callback = int_cb;
1771 ret = avformat_write_header(of->ctx, &of->opts);
1775 av_strerror(ret, errbuf, sizeof(errbuf));
1777 av_log(NULL, AV_LOG_ERROR,
1778 "Could not write header for output file #%d "
1779 "(incorrect codec parameters ?): %s",
1780 file_index, errbuf);
1783 assert_avoptions(of->opts);
1784 of->header_written = 1;
1786 av_dump_format(of->ctx, file_index, of->ctx->filename, 1);
1791 /* flush the muxing queues */
1792 for (i = 0; i < of->ctx->nb_streams; i++) {
1793 OutputStream *ost = output_streams[of->ost_index + i];
1795 while (av_fifo_size(ost->muxing_queue)) {
1797 av_fifo_generic_read(ost->muxing_queue, &pkt, sizeof(pkt), NULL);
1798 write_packet(of, &pkt, ost);
1805 static int init_output_bsfs(OutputStream *ost)
1810 if (!ost->nb_bitstream_filters)
1813 for (i = 0; i < ost->nb_bitstream_filters; i++) {
1814 ctx = ost->bsf_ctx[i];
1816 ret = avcodec_parameters_copy(ctx->par_in,
1817 i ? ost->bsf_ctx[i - 1]->par_out : ost->st->codecpar);
1821 ctx->time_base_in = i ? ost->bsf_ctx[i - 1]->time_base_out : ost->st->time_base;
1823 ret = av_bsf_init(ctx);
1825 av_log(NULL, AV_LOG_ERROR, "Error initializing bitstream filter: %s\n",
1831 ret = avcodec_parameters_copy(ost->st->codecpar, ctx->par_out);
1835 ost->st->time_base = ctx->time_base_out;
1840 static int init_output_stream_streamcopy(OutputStream *ost)
1842 OutputFile *of = output_files[ost->file_index];
1843 InputStream *ist = get_input_stream(ost);
1844 AVCodecParameters *par_dst = ost->st->codecpar;
1845 AVCodecParameters *par_src = ist->st->codecpar;
1847 uint32_t codec_tag = par_dst->codec_tag;
1851 if (!of->ctx->oformat->codec_tag ||
1852 av_codec_get_id (of->ctx->oformat->codec_tag, par_src->codec_tag) == par_src->codec_id ||
1853 av_codec_get_tag(of->ctx->oformat->codec_tag, par_src->codec_id) <= 0)
1854 codec_tag = par_src->codec_tag;
1857 ret = avcodec_parameters_copy(par_dst, par_src);
1861 par_dst->codec_tag = codec_tag;
1863 ost->st->disposition = ist->st->disposition;
1865 ost->st->time_base = ist->st->time_base;
1867 if (ost->bitrate_override)
1868 par_dst->bit_rate = ost->bitrate_override;
1870 if (ist->st->nb_side_data) {
1871 ost->st->side_data = av_realloc_array(NULL, ist->st->nb_side_data,
1872 sizeof(*ist->st->side_data));
1873 if (!ost->st->side_data)
1874 return AVERROR(ENOMEM);
1876 for (i = 0; i < ist->st->nb_side_data; i++) {
1877 const AVPacketSideData *sd_src = &ist->st->side_data[i];
1878 AVPacketSideData *sd_dst = &ost->st->side_data[i];
1880 sd_dst->data = av_malloc(sd_src->size);
1882 return AVERROR(ENOMEM);
1883 memcpy(sd_dst->data, sd_src->data, sd_src->size);
1884 sd_dst->size = sd_src->size;
1885 sd_dst->type = sd_src->type;
1886 ost->st->nb_side_data++;
1890 ost->parser = av_parser_init(par_dst->codec_id);
1891 ost->parser_avctx = avcodec_alloc_context3(NULL);
1892 if (!ost->parser_avctx)
1893 return AVERROR(ENOMEM);
1895 if (par_dst->codec_type == AVMEDIA_TYPE_VIDEO) {
1896 if (ost->frame_aspect_ratio)
1897 sar = av_d2q(ost->frame_aspect_ratio * par_dst->height / par_dst->width, 255);
1898 else if (ist->st->sample_aspect_ratio.num)
1899 sar = ist->st->sample_aspect_ratio;
1901 sar = par_src->sample_aspect_ratio;
1902 ost->st->sample_aspect_ratio = par_dst->sample_aspect_ratio = sar;
1908 static void set_encoder_id(OutputFile *of, OutputStream *ost)
1910 AVDictionaryEntry *e;
1912 uint8_t *encoder_string;
1913 int encoder_string_len;
1914 int format_flags = 0;
1916 e = av_dict_get(of->opts, "fflags", NULL, 0);
1918 const AVOption *o = av_opt_find(of->ctx, "fflags", NULL, 0, 0);
1921 av_opt_eval_flags(of->ctx, o, e->value, &format_flags);
1924 encoder_string_len = sizeof(LIBAVCODEC_IDENT) + strlen(ost->enc->name) + 2;
1925 encoder_string = av_mallocz(encoder_string_len);
1926 if (!encoder_string)
1929 if (!(format_flags & AVFMT_FLAG_BITEXACT))
1930 av_strlcpy(encoder_string, LIBAVCODEC_IDENT " ", encoder_string_len);
1931 av_strlcat(encoder_string, ost->enc->name, encoder_string_len);
1932 av_dict_set(&ost->st->metadata, "encoder", encoder_string,
1933 AV_DICT_DONT_STRDUP_VAL | AV_DICT_DONT_OVERWRITE);
1936 static void parse_forced_key_frames(char *kf, OutputStream *ost,
1937 AVCodecContext *avctx)
1943 for (p = kf; *p; p++)
1946 ost->forced_kf_count = n;
1947 ost->forced_kf_pts = av_malloc(sizeof(*ost->forced_kf_pts) * n);
1948 if (!ost->forced_kf_pts) {
1949 av_log(NULL, AV_LOG_FATAL, "Could not allocate forced key frames array.\n");
1954 for (i = 0; i < n; i++) {
1955 char *next = strchr(p, ',');
1960 t = parse_time_or_die("force_key_frames", p, 1);
1961 ost->forced_kf_pts[i] = av_rescale_q(t, AV_TIME_BASE_Q, avctx->time_base);
1967 static int init_output_stream_encode(OutputStream *ost)
1969 InputStream *ist = get_input_stream(ost);
1970 AVCodecContext *enc_ctx = ost->enc_ctx;
1971 AVCodecContext *dec_ctx = NULL;
1973 set_encoder_id(output_files[ost->file_index], ost);
1976 ost->st->disposition = ist->st->disposition;
1978 dec_ctx = ist->dec_ctx;
1980 enc_ctx->bits_per_raw_sample = dec_ctx->bits_per_raw_sample;
1981 enc_ctx->chroma_sample_location = dec_ctx->chroma_sample_location;
1984 switch (enc_ctx->codec_type) {
1985 case AVMEDIA_TYPE_AUDIO:
1986 enc_ctx->sample_fmt = ost->filter->filter->inputs[0]->format;
1987 enc_ctx->sample_rate = ost->filter->filter->inputs[0]->sample_rate;
1988 enc_ctx->channel_layout = ost->filter->filter->inputs[0]->channel_layout;
1989 enc_ctx->channels = av_get_channel_layout_nb_channels(enc_ctx->channel_layout);
1990 enc_ctx->time_base = (AVRational){ 1, enc_ctx->sample_rate };
1992 case AVMEDIA_TYPE_VIDEO:
1993 enc_ctx->time_base = ost->filter->filter->inputs[0]->time_base;
1995 enc_ctx->width = ost->filter->filter->inputs[0]->w;
1996 enc_ctx->height = ost->filter->filter->inputs[0]->h;
1997 enc_ctx->sample_aspect_ratio = ost->st->sample_aspect_ratio =
1998 ost->frame_aspect_ratio ? // overridden by the -aspect cli option
1999 av_d2q(ost->frame_aspect_ratio * enc_ctx->height/enc_ctx->width, 255) :
2000 ost->filter->filter->inputs[0]->sample_aspect_ratio;
2001 enc_ctx->pix_fmt = ost->filter->filter->inputs[0]->format;
2003 enc_ctx->framerate = ost->frame_rate;
2005 ost->st->avg_frame_rate = ost->frame_rate;
2008 (enc_ctx->width != dec_ctx->width ||
2009 enc_ctx->height != dec_ctx->height ||
2010 enc_ctx->pix_fmt != dec_ctx->pix_fmt)) {
2011 enc_ctx->bits_per_raw_sample = 0;
2014 if (ost->forced_keyframes)
2015 parse_forced_key_frames(ost->forced_keyframes, ost,
2018 case AVMEDIA_TYPE_SUBTITLE:
2019 enc_ctx->time_base = (AVRational){1, 1000};
2029 static int init_output_stream(OutputStream *ost, char *error, int error_len)
2033 if (ost->encoding_needed) {
2034 AVCodec *codec = ost->enc;
2035 AVCodecContext *dec = NULL;
2038 ret = init_output_stream_encode(ost);
2042 if ((ist = get_input_stream(ost)))
2044 if (dec && dec->subtitle_header) {
2045 ost->enc_ctx->subtitle_header = av_malloc(dec->subtitle_header_size);
2046 if (!ost->enc_ctx->subtitle_header)
2047 return AVERROR(ENOMEM);
2048 memcpy(ost->enc_ctx->subtitle_header, dec->subtitle_header, dec->subtitle_header_size);
2049 ost->enc_ctx->subtitle_header_size = dec->subtitle_header_size;
2051 if (!av_dict_get(ost->encoder_opts, "threads", NULL, 0))
2052 av_dict_set(&ost->encoder_opts, "threads", "auto", 0);
2054 if (ost->filter && ost->filter->filter->inputs[0]->hw_frames_ctx &&
2055 ((AVHWFramesContext*)ost->filter->filter->inputs[0]->hw_frames_ctx->data)->format ==
2056 ost->filter->filter->inputs[0]->format) {
2057 ost->enc_ctx->hw_frames_ctx = av_buffer_ref(ost->filter->filter->inputs[0]->hw_frames_ctx);
2058 if (!ost->enc_ctx->hw_frames_ctx)
2059 return AVERROR(ENOMEM);
2061 ret = hw_device_setup_for_encode(ost);
2064 av_strerror(ret, errbuf, sizeof(errbuf));
2065 snprintf(error, error_len, "Device setup failed for "
2066 "encoder on output stream #%d:%d : %s",
2067 ost->file_index, ost->index, errbuf);
2072 if ((ret = avcodec_open2(ost->enc_ctx, codec, &ost->encoder_opts)) < 0) {
2073 if (ret == AVERROR_EXPERIMENTAL)
2074 abort_codec_experimental(codec, 1);
2075 snprintf(error, error_len,
2076 "Error while opening encoder for output stream #%d:%d - "
2077 "maybe incorrect parameters such as bit_rate, rate, width or height",
2078 ost->file_index, ost->index);
2081 assert_avoptions(ost->encoder_opts);
2082 if (ost->enc_ctx->bit_rate && ost->enc_ctx->bit_rate < 1000)
2083 av_log(NULL, AV_LOG_WARNING, "The bitrate parameter is set too low."
2084 "It takes bits/s as argument, not kbits/s\n");
2086 ret = avcodec_parameters_from_context(ost->st->codecpar, ost->enc_ctx);
2088 av_log(NULL, AV_LOG_FATAL,
2089 "Error initializing the output stream codec context.\n");
2093 if (ost->enc_ctx->nb_coded_side_data) {
2096 ost->st->side_data = av_realloc_array(NULL, ost->enc_ctx->nb_coded_side_data,
2097 sizeof(*ost->st->side_data));
2098 if (!ost->st->side_data)
2099 return AVERROR(ENOMEM);
2101 for (i = 0; i < ost->enc_ctx->nb_coded_side_data; i++) {
2102 const AVPacketSideData *sd_src = &ost->enc_ctx->coded_side_data[i];
2103 AVPacketSideData *sd_dst = &ost->st->side_data[i];
2105 sd_dst->data = av_malloc(sd_src->size);
2107 return AVERROR(ENOMEM);
2108 memcpy(sd_dst->data, sd_src->data, sd_src->size);
2109 sd_dst->size = sd_src->size;
2110 sd_dst->type = sd_src->type;
2111 ost->st->nb_side_data++;
2115 ost->st->time_base = ost->enc_ctx->time_base;
2116 } else if (ost->stream_copy) {
2117 ret = init_output_stream_streamcopy(ost);
2122 * FIXME: will the codec context used by the parser during streamcopy
2123 * This should go away with the new parser API.
2125 ret = avcodec_parameters_to_context(ost->parser_avctx, ost->st->codecpar);
2130 /* initialize bitstream filters for the output stream
2131 * needs to be done here, because the codec id for streamcopy is not
2132 * known until now */
2133 ret = init_output_bsfs(ost);
2137 ost->mux_timebase = ost->st->time_base;
2139 ost->initialized = 1;
2141 ret = check_init_output_file(output_files[ost->file_index], ost->file_index);
2148 static int transcode_init(void)
2150 int ret = 0, i, j, k;
2155 /* init framerate emulation */
2156 for (i = 0; i < nb_input_files; i++) {
2157 InputFile *ifile = input_files[i];
2158 if (ifile->rate_emu)
2159 for (j = 0; j < ifile->nb_streams; j++)
2160 input_streams[j + ifile->ist_index]->start = av_gettime_relative();
2163 /* init input streams */
2164 for (i = 0; i < nb_input_streams; i++)
2165 if ((ret = init_input_stream(i, error, sizeof(error))) < 0)
2168 /* open each encoder */
2169 for (i = 0; i < nb_output_streams; i++) {
2170 // skip streams fed from filtergraphs until we have a frame for them
2171 if (output_streams[i]->filter)
2174 ret = init_output_stream(output_streams[i], error, sizeof(error));
2180 /* discard unused programs */
2181 for (i = 0; i < nb_input_files; i++) {
2182 InputFile *ifile = input_files[i];
2183 for (j = 0; j < ifile->ctx->nb_programs; j++) {
2184 AVProgram *p = ifile->ctx->programs[j];
2185 int discard = AVDISCARD_ALL;
2187 for (k = 0; k < p->nb_stream_indexes; k++)
2188 if (!input_streams[ifile->ist_index + p->stream_index[k]]->discard) {
2189 discard = AVDISCARD_DEFAULT;
2192 p->discard = discard;
2197 /* dump the stream mapping */
2198 av_log(NULL, AV_LOG_INFO, "Stream mapping:\n");
2199 for (i = 0; i < nb_input_streams; i++) {
2200 ist = input_streams[i];
2202 for (j = 0; j < ist->nb_filters; j++) {
2203 if (!filtergraph_is_simple(ist->filters[j]->graph)) {
2204 av_log(NULL, AV_LOG_INFO, " Stream #%d:%d (%s) -> %s",
2205 ist->file_index, ist->st->index, ist->dec ? ist->dec->name : "?",
2206 ist->filters[j]->name);
2207 if (nb_filtergraphs > 1)
2208 av_log(NULL, AV_LOG_INFO, " (graph %d)", ist->filters[j]->graph->index);
2209 av_log(NULL, AV_LOG_INFO, "\n");
2214 for (i = 0; i < nb_output_streams; i++) {
2215 ost = output_streams[i];
2217 if (ost->attachment_filename) {
2218 /* an attached file */
2219 av_log(NULL, AV_LOG_INFO, " File %s -> Stream #%d:%d\n",
2220 ost->attachment_filename, ost->file_index, ost->index);
2224 if (ost->filter && !filtergraph_is_simple(ost->filter->graph)) {
2225 /* output from a complex graph */
2226 av_log(NULL, AV_LOG_INFO, " %s", ost->filter->name);
2227 if (nb_filtergraphs > 1)
2228 av_log(NULL, AV_LOG_INFO, " (graph %d)", ost->filter->graph->index);
2230 av_log(NULL, AV_LOG_INFO, " -> Stream #%d:%d (%s)\n", ost->file_index,
2231 ost->index, ost->enc ? ost->enc->name : "?");
2235 av_log(NULL, AV_LOG_INFO, " Stream #%d:%d -> #%d:%d",
2236 input_streams[ost->source_index]->file_index,
2237 input_streams[ost->source_index]->st->index,
2240 if (ost->sync_ist != input_streams[ost->source_index])
2241 av_log(NULL, AV_LOG_INFO, " [sync #%d:%d]",
2242 ost->sync_ist->file_index,
2243 ost->sync_ist->st->index);
2244 if (ost->stream_copy)
2245 av_log(NULL, AV_LOG_INFO, " (copy)");
2247 const AVCodec *in_codec = input_streams[ost->source_index]->dec;
2248 const AVCodec *out_codec = ost->enc;
2249 const char *decoder_name = "?";
2250 const char *in_codec_name = "?";
2251 const char *encoder_name = "?";
2252 const char *out_codec_name = "?";
2253 const AVCodecDescriptor *desc;
2256 decoder_name = in_codec->name;
2257 desc = avcodec_descriptor_get(in_codec->id);
2259 in_codec_name = desc->name;
2260 if (!strcmp(decoder_name, in_codec_name))
2261 decoder_name = "native";
2265 encoder_name = out_codec->name;
2266 desc = avcodec_descriptor_get(out_codec->id);
2268 out_codec_name = desc->name;
2269 if (!strcmp(encoder_name, out_codec_name))
2270 encoder_name = "native";
2273 av_log(NULL, AV_LOG_INFO, " (%s (%s) -> %s (%s))",
2274 in_codec_name, decoder_name,
2275 out_codec_name, encoder_name);
2277 av_log(NULL, AV_LOG_INFO, "\n");
2281 av_log(NULL, AV_LOG_ERROR, "%s\n", error);
2288 /* Return 1 if there remain streams where more output is wanted, 0 otherwise. */
2289 static int need_output(void)
2293 for (i = 0; i < nb_output_streams; i++) {
2294 OutputStream *ost = output_streams[i];
2295 OutputFile *of = output_files[ost->file_index];
2296 AVFormatContext *os = output_files[ost->file_index]->ctx;
2298 if (ost->finished ||
2299 (os->pb && avio_tell(os->pb) >= of->limit_filesize))
2301 if (ost->frame_number >= ost->max_frames) {
2303 for (j = 0; j < of->ctx->nb_streams; j++)
2304 output_streams[of->ost_index + j]->finished = 1;
2314 static InputFile *select_input_file(void)
2316 InputFile *ifile = NULL;
2317 int64_t ipts_min = INT64_MAX;
2320 for (i = 0; i < nb_input_streams; i++) {
2321 InputStream *ist = input_streams[i];
2322 int64_t ipts = ist->last_dts;
2324 if (ist->discard || input_files[ist->file_index]->eagain)
2326 if (!input_files[ist->file_index]->eof_reached) {
2327 if (ipts < ipts_min) {
2329 ifile = input_files[ist->file_index];
2338 static void *input_thread(void *arg)
2343 while (!transcoding_finished && ret >= 0) {
2345 ret = av_read_frame(f->ctx, &pkt);
2347 if (ret == AVERROR(EAGAIN)) {
2354 pthread_mutex_lock(&f->fifo_lock);
2355 while (!av_fifo_space(f->fifo))
2356 pthread_cond_wait(&f->fifo_cond, &f->fifo_lock);
2358 av_fifo_generic_write(f->fifo, &pkt, sizeof(pkt), NULL);
2360 pthread_mutex_unlock(&f->fifo_lock);
2367 static void free_input_threads(void)
2371 if (nb_input_files == 1)
2374 transcoding_finished = 1;
2376 for (i = 0; i < nb_input_files; i++) {
2377 InputFile *f = input_files[i];
2380 if (!f->fifo || f->joined)
2383 pthread_mutex_lock(&f->fifo_lock);
2384 while (av_fifo_size(f->fifo)) {
2385 av_fifo_generic_read(f->fifo, &pkt, sizeof(pkt), NULL);
2386 av_packet_unref(&pkt);
2388 pthread_cond_signal(&f->fifo_cond);
2389 pthread_mutex_unlock(&f->fifo_lock);
2391 pthread_join(f->thread, NULL);
2394 while (av_fifo_size(f->fifo)) {
2395 av_fifo_generic_read(f->fifo, &pkt, sizeof(pkt), NULL);
2396 av_packet_unref(&pkt);
2398 av_fifo_free(f->fifo);
2402 static int init_input_threads(void)
2406 if (nb_input_files == 1)
2409 for (i = 0; i < nb_input_files; i++) {
2410 InputFile *f = input_files[i];
2412 if (!(f->fifo = av_fifo_alloc(8*sizeof(AVPacket))))
2413 return AVERROR(ENOMEM);
2415 pthread_mutex_init(&f->fifo_lock, NULL);
2416 pthread_cond_init (&f->fifo_cond, NULL);
2418 if ((ret = pthread_create(&f->thread, NULL, input_thread, f)))
2419 return AVERROR(ret);
2424 static int get_input_packet_mt(InputFile *f, AVPacket *pkt)
2428 pthread_mutex_lock(&f->fifo_lock);
2430 if (av_fifo_size(f->fifo)) {
2431 av_fifo_generic_read(f->fifo, pkt, sizeof(*pkt), NULL);
2432 pthread_cond_signal(&f->fifo_cond);
2437 ret = AVERROR(EAGAIN);
2440 pthread_mutex_unlock(&f->fifo_lock);
2446 static int get_input_packet(InputFile *f, AVPacket *pkt)
2450 for (i = 0; i < f->nb_streams; i++) {
2451 InputStream *ist = input_streams[f->ist_index + i];
2452 int64_t pts = av_rescale(ist->last_dts, 1000000, AV_TIME_BASE);
2453 int64_t now = av_gettime_relative() - ist->start;
2455 return AVERROR(EAGAIN);
2460 if (nb_input_files > 1)
2461 return get_input_packet_mt(f, pkt);
2463 return av_read_frame(f->ctx, pkt);
2466 static int got_eagain(void)
2469 for (i = 0; i < nb_input_files; i++)
2470 if (input_files[i]->eagain)
2475 static void reset_eagain(void)
2478 for (i = 0; i < nb_input_files; i++)
2479 input_files[i]->eagain = 0;
2482 // set duration to max(tmp, duration) in a proper time base and return duration's time_base
2483 static AVRational duration_max(int64_t tmp, int64_t *duration, AVRational tmp_time_base,
2484 AVRational time_base)
2490 return tmp_time_base;
2493 ret = av_compare_ts(*duration, time_base, tmp, tmp_time_base);
2496 return tmp_time_base;
2502 static int seek_to_start(InputFile *ifile, AVFormatContext *is)
2505 AVCodecContext *avctx;
2506 int i, ret, has_audio = 0;
2507 int64_t duration = 0;
2509 ret = av_seek_frame(is, -1, is->start_time, 0);
2513 for (i = 0; i < ifile->nb_streams; i++) {
2514 ist = input_streams[ifile->ist_index + i];
2515 avctx = ist->dec_ctx;
2518 if (ist->decoding_needed) {
2519 process_input_packet(ist, NULL, 1);
2520 avcodec_flush_buffers(avctx);
2523 /* duration is the length of the last frame in a stream
2524 * when audio stream is present we don't care about
2525 * last video frame length because it's not defined exactly */
2526 if (avctx->codec_type == AVMEDIA_TYPE_AUDIO && ist->nb_samples)
2530 for (i = 0; i < ifile->nb_streams; i++) {
2531 ist = input_streams[ifile->ist_index + i];
2532 avctx = ist->dec_ctx;
2535 if (avctx->codec_type == AVMEDIA_TYPE_AUDIO && ist->nb_samples) {
2536 AVRational sample_rate = {1, avctx->sample_rate};
2538 duration = av_rescale_q(ist->nb_samples, sample_rate, ist->st->time_base);
2542 if (ist->framerate.num) {
2543 duration = av_rescale_q(1, ist->framerate, ist->st->time_base);
2544 } else if (ist->st->avg_frame_rate.num) {
2545 duration = av_rescale_q(1, ist->st->avg_frame_rate, ist->st->time_base);
2546 } else duration = 1;
2548 if (!ifile->duration)
2549 ifile->time_base = ist->st->time_base;
2550 /* the total duration of the stream, max_pts - min_pts is
2551 * the duration of the stream without the last frame */
2552 duration += ist->max_pts - ist->min_pts;
2553 ifile->time_base = duration_max(duration, &ifile->duration, ist->st->time_base,
2557 if (ifile->loop > 0)
2564 * Read one packet from an input file and send it for
2565 * - decoding -> lavfi (audio/video)
2566 * - decoding -> encoding -> muxing (subtitles)
2567 * - muxing (streamcopy)
2570 * - 0 -- one packet was read and processed
2571 * - AVERROR(EAGAIN) -- no packets were available for selected file,
2572 * this function should be called again
2573 * - AVERROR_EOF -- this function should not be called again
2575 static int process_input(void)
2578 AVFormatContext *is;
2584 /* select the stream that we must read now */
2585 ifile = select_input_file();
2586 /* if none, if is finished */
2591 return AVERROR(EAGAIN);
2593 av_log(NULL, AV_LOG_VERBOSE, "No more inputs to read from.\n");
2598 ret = get_input_packet(ifile, &pkt);
2600 if (ret == AVERROR(EAGAIN)) {
2604 if (ret < 0 && ifile->loop) {
2605 if ((ret = seek_to_start(ifile, is)) < 0)
2607 ret = get_input_packet(ifile, &pkt);
2610 if (ret != AVERROR_EOF) {
2611 print_error(is->filename, ret);
2615 ifile->eof_reached = 1;
2617 for (i = 0; i < ifile->nb_streams; i++) {
2618 ist = input_streams[ifile->ist_index + i];
2619 if (ist->decoding_needed)
2620 process_input_packet(ist, NULL, 0);
2622 /* mark all outputs that don't go through lavfi as finished */
2623 for (j = 0; j < nb_output_streams; j++) {
2624 OutputStream *ost = output_streams[j];
2626 if (ost->source_index == ifile->ist_index + i &&
2627 (ost->stream_copy || ost->enc->type == AVMEDIA_TYPE_SUBTITLE))
2628 finish_output_stream(ost);
2632 return AVERROR(EAGAIN);
2638 av_pkt_dump_log2(NULL, AV_LOG_DEBUG, &pkt, do_hex_dump,
2639 is->streams[pkt.stream_index]);
2641 /* the following test is needed in case new streams appear
2642 dynamically in stream : we ignore them */
2643 if (pkt.stream_index >= ifile->nb_streams)
2644 goto discard_packet;
2646 ist = input_streams[ifile->ist_index + pkt.stream_index];
2648 ist->data_size += pkt.size;
2652 goto discard_packet;
2654 /* add the stream-global side data to the first packet */
2655 if (ist->nb_packets == 1)
2656 for (i = 0; i < ist->st->nb_side_data; i++) {
2657 AVPacketSideData *src_sd = &ist->st->side_data[i];
2660 if (av_packet_get_side_data(&pkt, src_sd->type, NULL))
2662 if (ist->autorotate && src_sd->type == AV_PKT_DATA_DISPLAYMATRIX)
2665 dst_data = av_packet_new_side_data(&pkt, src_sd->type, src_sd->size);
2669 memcpy(dst_data, src_sd->data, src_sd->size);
2672 if (pkt.dts != AV_NOPTS_VALUE)
2673 pkt.dts += av_rescale_q(ifile->ts_offset, AV_TIME_BASE_Q, ist->st->time_base);
2674 if (pkt.pts != AV_NOPTS_VALUE)
2675 pkt.pts += av_rescale_q(ifile->ts_offset, AV_TIME_BASE_Q, ist->st->time_base);
2677 if (pkt.pts != AV_NOPTS_VALUE)
2678 pkt.pts *= ist->ts_scale;
2679 if (pkt.dts != AV_NOPTS_VALUE)
2680 pkt.dts *= ist->ts_scale;
2682 if ((ist->dec_ctx->codec_type == AVMEDIA_TYPE_VIDEO ||
2683 ist->dec_ctx->codec_type == AVMEDIA_TYPE_AUDIO) &&
2684 pkt.dts != AV_NOPTS_VALUE && ist->next_dts != AV_NOPTS_VALUE &&
2685 (is->iformat->flags & AVFMT_TS_DISCONT)) {
2686 int64_t pkt_dts = av_rescale_q(pkt.dts, ist->st->time_base, AV_TIME_BASE_Q);
2687 int64_t delta = pkt_dts - ist->next_dts;
2689 if ((FFABS(delta) > 1LL * dts_delta_threshold * AV_TIME_BASE || pkt_dts + 1 < ist->last_dts) && !copy_ts) {
2690 ifile->ts_offset -= delta;
2691 av_log(NULL, AV_LOG_DEBUG,
2692 "timestamp discontinuity %"PRId64", new offset= %"PRId64"\n",
2693 delta, ifile->ts_offset);
2694 pkt.dts -= av_rescale_q(delta, AV_TIME_BASE_Q, ist->st->time_base);
2695 if (pkt.pts != AV_NOPTS_VALUE)
2696 pkt.pts -= av_rescale_q(delta, AV_TIME_BASE_Q, ist->st->time_base);
2699 duration = av_rescale_q(ifile->duration, ifile->time_base, ist->st->time_base);
2700 if (pkt.pts != AV_NOPTS_VALUE) {
2701 pkt.pts += duration;
2702 ist->max_pts = FFMAX(pkt.pts, ist->max_pts);
2703 ist->min_pts = FFMIN(pkt.pts, ist->min_pts);
2706 if (pkt.dts != AV_NOPTS_VALUE)
2707 pkt.dts += duration;
2709 process_input_packet(ist, &pkt, 0);
2712 av_packet_unref(&pkt);
2718 * The following code is the main loop of the file converter
2720 static int transcode(void)
2722 int ret, i, need_input = 1;
2723 AVFormatContext *os;
2726 int64_t timer_start;
2728 ret = transcode_init();
2732 av_log(NULL, AV_LOG_INFO, "Press ctrl-c to stop encoding\n");
2735 timer_start = av_gettime_relative();
2738 if ((ret = init_input_threads()) < 0)
2742 while (!received_sigterm) {
2743 /* check if there's any stream where output is still needed */
2744 if (!need_output()) {
2745 av_log(NULL, AV_LOG_VERBOSE, "No more output streams to write to, finishing.\n");
2749 /* read and process one input packet if needed */
2751 ret = process_input();
2752 if (ret == AVERROR_EOF)
2756 ret = poll_filters();
2757 if (ret < 0 && ret != AVERROR_EOF) {
2759 av_strerror(ret, errbuf, sizeof(errbuf));
2761 av_log(NULL, AV_LOG_ERROR, "Error while filtering: %s\n", errbuf);
2765 /* dump report by using the output first video and audio streams */
2766 print_report(0, timer_start);
2769 free_input_threads();
2772 /* at the end of stream, we must flush the decoder buffers */
2773 for (i = 0; i < nb_input_streams; i++) {
2774 ist = input_streams[i];
2775 if (!input_files[ist->file_index]->eof_reached && ist->decoding_needed) {
2776 process_input_packet(ist, NULL, 0);
2784 /* write the trailer if needed and close file */
2785 for (i = 0; i < nb_output_files; i++) {
2786 os = output_files[i]->ctx;
2787 if (!output_files[i]->header_written) {
2788 av_log(NULL, AV_LOG_ERROR,
2789 "Nothing was written into output file %d (%s), because "
2790 "at least one of its streams received no packets.\n",
2794 av_write_trailer(os);
2797 /* dump report by using the first video and audio streams */
2798 print_report(1, timer_start);
2800 /* close each encoder */
2801 for (i = 0; i < nb_output_streams; i++) {
2802 ost = output_streams[i];
2803 if (ost->encoding_needed) {
2804 av_freep(&ost->enc_ctx->stats_in);
2808 /* close each decoder */
2809 for (i = 0; i < nb_input_streams; i++) {
2810 ist = input_streams[i];
2811 if (ist->decoding_needed) {
2812 avcodec_close(ist->dec_ctx);
2813 if (ist->hwaccel_uninit)
2814 ist->hwaccel_uninit(ist->dec_ctx);
2818 av_buffer_unref(&hw_device_ctx);
2819 hw_device_free_all();
2826 free_input_threads();
2829 if (output_streams) {
2830 for (i = 0; i < nb_output_streams; i++) {
2831 ost = output_streams[i];
2834 fclose(ost->logfile);
2835 ost->logfile = NULL;
2837 av_free(ost->forced_kf_pts);
2838 av_dict_free(&ost->encoder_opts);
2839 av_dict_free(&ost->resample_opts);
2846 static int64_t getutime(void)
2849 struct rusage rusage;
2851 getrusage(RUSAGE_SELF, &rusage);
2852 return (rusage.ru_utime.tv_sec * 1000000LL) + rusage.ru_utime.tv_usec;
2853 #elif HAVE_GETPROCESSTIMES
2855 FILETIME c, e, k, u;
2856 proc = GetCurrentProcess();
2857 GetProcessTimes(proc, &c, &e, &k, &u);
2858 return ((int64_t) u.dwHighDateTime << 32 | u.dwLowDateTime) / 10;
2860 return av_gettime_relative();
2864 static int64_t getmaxrss(void)
2866 #if HAVE_GETRUSAGE && HAVE_STRUCT_RUSAGE_RU_MAXRSS
2867 struct rusage rusage;
2868 getrusage(RUSAGE_SELF, &rusage);
2869 return (int64_t)rusage.ru_maxrss * 1024;
2870 #elif HAVE_GETPROCESSMEMORYINFO
2872 PROCESS_MEMORY_COUNTERS memcounters;
2873 proc = GetCurrentProcess();
2874 memcounters.cb = sizeof(memcounters);
2875 GetProcessMemoryInfo(proc, &memcounters, sizeof(memcounters));
2876 return memcounters.PeakPagefileUsage;
2882 int main(int argc, char **argv)
2887 register_exit(avconv_cleanup);
2889 av_log_set_flags(AV_LOG_SKIP_REPEATED);
2890 parse_loglevel(argc, argv, options);
2892 avcodec_register_all();
2894 avdevice_register_all();
2896 avfilter_register_all();
2898 avformat_network_init();
2902 /* parse options and open all input/output files */
2903 ret = avconv_parse_options(argc, argv);
2907 if (nb_output_files <= 0 && nb_input_files == 0) {
2909 av_log(NULL, AV_LOG_WARNING, "Use -h to get full help or, even better, run 'man %s'\n", program_name);
2913 /* file converter / grab */
2914 if (nb_output_files <= 0) {
2915 fprintf(stderr, "At least one output file must be specified\n");
2919 for (i = 0; i < nb_output_files; i++) {
2920 if (strcmp(output_files[i]->ctx->oformat->name, "rtp"))
2925 if (transcode() < 0)
2927 ti = getutime() - ti;
2929 int maxrss = getmaxrss() / 1024;
2930 printf("bench: utime=%0.3fs maxrss=%ikB\n", ti / 1000000.0, maxrss);