3 * Copyright (c) 2000-2003 Fabrice Bellard
5 * This file is part of FFmpeg.
7 * FFmpeg 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 * FFmpeg 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 FFmpeg; if not, write to the Free Software
19 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
31 #include "libavformat/avformat.h"
32 #include "libavdevice/avdevice.h"
33 #include "libswscale/swscale.h"
34 #include "libavutil/opt.h"
35 #include "libavcodec/audioconvert.h"
36 #include "libavutil/audioconvert.h"
37 #include "libavutil/parseutils.h"
38 #include "libavutil/samplefmt.h"
39 #include "libavutil/colorspace.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 "libavformat/os_support.h"
49 #include "libavformat/ffm.h" // not public API
52 # include "libavfilter/avcodec.h"
53 # include "libavfilter/avfilter.h"
54 # include "libavfilter/avfiltergraph.h"
55 # include "libavfilter/buffersink.h"
56 # include "libavfilter/vsrc_buffer.h"
59 #if HAVE_SYS_RESOURCE_H
60 #include <sys/types.h>
62 #include <sys/resource.h>
63 #elif HAVE_GETPROCESSTIMES
66 #if HAVE_GETPROCESSMEMORYINFO
72 #include <sys/select.h>
77 #include <sys/ioctl.h>
87 #include "libavutil/avassert.h"
89 const char program_name[] = "avconv";
90 const int program_birth_year = 2000;
92 /* select an input stream for an output stream */
93 typedef struct StreamMap {
94 int disabled; /** 1 is this mapping is disabled by a negative map */
98 int sync_stream_index;
102 * select an input file for an output file
104 typedef struct MetadataMap {
105 int file; ///< file index
106 char type; ///< type of metadata to copy -- (g)lobal, (s)tream, (c)hapter or (p)rogram
107 int index; ///< stream/chapter/program number
110 static const OptionDef options[];
112 #define MAX_STREAMS 1024 /* arbitrary sanity check value */
114 static int frame_bits_per_raw_sample = 0;
115 static int video_discard = 0;
116 static int same_quant = 0;
117 static int do_deinterlace = 0;
118 static int intra_dc_precision = 8;
119 static int qp_hist = 0;
121 static int file_overwrite = 0;
122 static int do_benchmark = 0;
123 static int do_hex_dump = 0;
124 static int do_pkt_dump = 0;
125 static int do_pass = 0;
126 static const char *pass_logfilename_prefix;
127 static int video_sync_method= -1;
128 static int audio_sync_method= 0;
129 static float audio_drift_threshold= 0.1;
130 static int copy_ts= 0;
131 static int copy_tb= 0;
132 static int opt_shortest = 0;
133 static char *vstats_filename;
134 static FILE *vstats_file;
136 static int audio_volume = 256;
138 static int exit_on_error = 0;
139 static int using_stdin = 0;
140 static int run_as_daemon = 0;
141 static int q_pressed = 0;
142 static int64_t video_size = 0;
143 static int64_t audio_size = 0;
144 static int64_t extra_size = 0;
145 static int nb_frames_dup = 0;
146 static int nb_frames_drop = 0;
147 static int input_sync;
149 static float dts_delta_threshold = 10;
151 static int print_stats = 1;
153 static uint8_t *audio_buf;
154 static uint8_t *audio_out;
155 static unsigned int allocated_audio_out_size, allocated_audio_buf_size;
157 static void *samples;
159 #define DEFAULT_PASS_LOGFILENAME_PREFIX "av2pass"
161 typedef struct InputStream {
164 int discard; /* true if stream data should be discarded */
165 int decoding_needed; /* true if the packets must be decoded in 'raw_fifo' */
168 int64_t start; /* time when read started */
169 int64_t next_pts; /* synthetic pts for cases where pkt.pts
171 int64_t pts; /* current pts */
173 int is_start; /* is 1 at the start and after a discontinuity */
174 int showed_multi_packet_warning;
178 typedef struct InputFile {
179 AVFormatContext *ctx;
180 int eof_reached; /* true if eof reached */
181 int ist_index; /* index of first stream in ist_table */
182 int buffer_size; /* current total buffer size */
184 int nb_streams; /* number of stream that avconv is aware of; may be different
185 from ctx.nb_streams if new streams appear during av_read_frame() */
189 typedef struct OutputStream {
190 int file_index; /* file index */
191 int index; /* stream index in the output file */
192 int source_index; /* InputStream index */
193 AVStream *st; /* stream in the output file */
194 int encoding_needed; /* true if encoding needed for this stream */
196 /* input pts and corresponding output pts
198 //double sync_ipts; /* dts from the AVPacket of the demuxer in second units */
199 struct InputStream *sync_ist; /* input stream to sync against */
200 int64_t sync_opts; /* output frame counter, could be changed to some true timestamp */ //FIXME look at frame_number
201 AVBitStreamFilterContext *bitstream_filters;
207 AVFrame resample_frame; /* temporary frame for image resampling */
208 struct SwsContext *img_resample_ctx; /* for image resampling */
211 int resample_pix_fmt;
212 AVRational frame_rate;
216 float frame_aspect_ratio;
218 /* forced key frames */
219 int64_t *forced_kf_pts;
225 ReSampleContext *resample; /* for audio resampling */
226 int resample_sample_fmt;
227 int resample_channels;
228 int resample_sample_rate;
230 AVAudioConvert *reformat_ctx;
231 AVFifoBuffer *fifo; /* for compression: one audio fifo per codec */
235 AVFilterContext *output_video_filter;
236 AVFilterContext *input_video_filter;
237 AVFilterBufferRef *picref;
239 AVFilterGraph *graph;
244 int is_past_recording_time;
246 const char *attachment_filename;
247 int copy_initial_nonkeyframes;
252 /* init terminal so that we can grab keys */
253 static struct termios oldtty;
256 typedef struct OutputFile {
257 AVFormatContext *ctx;
259 int ost_index; /* index of the first stream in output_streams */
260 int64_t recording_time; /* desired length of the resulting file in microseconds */
261 int64_t start_time; /* start time in microseconds */
262 uint64_t limit_filesize;
265 static InputStream *input_streams = NULL;
266 static int nb_input_streams = 0;
267 static InputFile *input_files = NULL;
268 static int nb_input_files = 0;
270 static OutputStream *output_streams = NULL;
271 static int nb_output_streams = 0;
272 static OutputFile *output_files = NULL;
273 static int nb_output_files = 0;
275 typedef struct OptionsContext {
276 /* input/output options */
280 SpecifierOpt *codec_names;
282 SpecifierOpt *audio_channels;
283 int nb_audio_channels;
284 SpecifierOpt *audio_sample_rate;
285 int nb_audio_sample_rate;
286 SpecifierOpt *frame_rates;
288 SpecifierOpt *frame_sizes;
290 SpecifierOpt *frame_pix_fmts;
291 int nb_frame_pix_fmts;
294 int64_t input_ts_offset;
297 SpecifierOpt *ts_scale;
299 SpecifierOpt *dump_attachment;
300 int nb_dump_attachment;
303 StreamMap *stream_maps;
305 /* first item specifies output metadata, second is input */
306 MetadataMap (*meta_data_maps)[2];
307 int nb_meta_data_maps;
308 int metadata_global_manual;
309 int metadata_streams_manual;
310 int metadata_chapters_manual;
311 const char **attachments;
314 int chapters_input_file;
316 int64_t recording_time;
317 uint64_t limit_filesize;
323 int subtitle_disable;
326 /* indexed by output file stream index */
330 SpecifierOpt *metadata;
332 SpecifierOpt *max_frames;
334 SpecifierOpt *bitstream_filters;
335 int nb_bitstream_filters;
336 SpecifierOpt *codec_tags;
338 SpecifierOpt *sample_fmts;
340 SpecifierOpt *qscale;
342 SpecifierOpt *forced_key_frames;
343 int nb_forced_key_frames;
344 SpecifierOpt *force_fps;
346 SpecifierOpt *frame_aspect_ratios;
347 int nb_frame_aspect_ratios;
348 SpecifierOpt *rc_overrides;
350 SpecifierOpt *intra_matrices;
351 int nb_intra_matrices;
352 SpecifierOpt *inter_matrices;
353 int nb_inter_matrices;
354 SpecifierOpt *top_field_first;
355 int nb_top_field_first;
356 SpecifierOpt *presets;
358 SpecifierOpt *copy_initial_nonkeyframes;
359 int nb_copy_initial_nonkeyframes;
361 SpecifierOpt *filters;
366 #define MATCH_PER_STREAM_OPT(name, type, outvar, fmtctx, st)\
369 for (i = 0; i < o->nb_ ## name; i++) {\
370 char *spec = o->name[i].specifier;\
371 if ((ret = check_stream_specifier(fmtctx, st, spec)) > 0)\
372 outvar = o->name[i].u.type;\
378 static void reset_options(OptionsContext *o)
380 const OptionDef *po = options;
382 /* all OPT_SPEC and OPT_STRING can be freed in generic way */
384 void *dst = (uint8_t*)o + po->u.off;
386 if (po->flags & OPT_SPEC) {
387 SpecifierOpt **so = dst;
388 int i, *count = (int*)(so + 1);
389 for (i = 0; i < *count; i++) {
390 av_freep(&(*so)[i].specifier);
391 if (po->flags & OPT_STRING)
392 av_freep(&(*so)[i].u.str);
396 } else if (po->flags & OPT_OFFSET && po->flags & OPT_STRING)
401 av_freep(&o->stream_maps);
402 av_freep(&o->meta_data_maps);
403 av_freep(&o->streamid_map);
405 memset(o, 0, sizeof(*o));
407 o->mux_max_delay = 0.7;
408 o->recording_time = INT64_MAX;
409 o->limit_filesize = UINT64_MAX;
410 o->chapters_input_file = INT_MAX;
418 static int configure_video_filters(InputStream *ist, OutputStream *ost)
420 AVFilterContext *last_filter, *filter;
421 /** filter graph containing all filters including input & output */
422 AVCodecContext *codec = ost->st->codec;
423 AVCodecContext *icodec = ist->st->codec;
424 enum PixelFormat pix_fmts[] = { codec->pix_fmt, PIX_FMT_NONE };
425 AVBufferSinkParams *buffersink_params = av_buffersink_params_alloc();
426 AVRational sample_aspect_ratio;
430 ost->graph = avfilter_graph_alloc();
432 if (ist->st->sample_aspect_ratio.num){
433 sample_aspect_ratio = ist->st->sample_aspect_ratio;
435 sample_aspect_ratio = ist->st->codec->sample_aspect_ratio;
437 snprintf(args, 255, "%d:%d:%d:%d:%d:%d:%d", ist->st->codec->width,
438 ist->st->codec->height, ist->st->codec->pix_fmt, 1, AV_TIME_BASE,
439 sample_aspect_ratio.num, sample_aspect_ratio.den);
441 ret = avfilter_graph_create_filter(&ost->input_video_filter, avfilter_get_by_name("buffer"),
442 "src", args, NULL, ost->graph);
445 #if FF_API_OLD_VSINK_API
446 ret = avfilter_graph_create_filter(&ost->output_video_filter, avfilter_get_by_name("buffersink"),
447 "out", NULL, pix_fmts, ost->graph);
449 buffersink_params->pixel_fmts = pix_fmts;
450 ret = avfilter_graph_create_filter(&ost->output_video_filter, avfilter_get_by_name("buffersink"),
451 "out", NULL, buffersink_params, ost->graph);
453 av_freep(&buffersink_params);
456 last_filter = ost->input_video_filter;
458 if (codec->width != icodec->width || codec->height != icodec->height) {
459 snprintf(args, 255, "%d:%d:flags=0x%X",
462 (unsigned)ost->sws_flags);
463 if ((ret = avfilter_graph_create_filter(&filter, avfilter_get_by_name("scale"),
464 NULL, args, NULL, ost->graph)) < 0)
466 if ((ret = avfilter_link(last_filter, 0, filter, 0)) < 0)
468 last_filter = filter;
471 snprintf(args, sizeof(args), "flags=0x%X", (unsigned)ost->sws_flags);
472 ost->graph->scale_sws_opts = av_strdup(args);
475 AVFilterInOut *outputs = avfilter_inout_alloc();
476 AVFilterInOut *inputs = avfilter_inout_alloc();
478 outputs->name = av_strdup("in");
479 outputs->filter_ctx = last_filter;
480 outputs->pad_idx = 0;
481 outputs->next = NULL;
483 inputs->name = av_strdup("out");
484 inputs->filter_ctx = ost->output_video_filter;
488 if ((ret = avfilter_graph_parse(ost->graph, ost->avfilter, &inputs, &outputs, NULL)) < 0)
490 av_freep(&ost->avfilter);
492 if ((ret = avfilter_link(last_filter, 0, ost->output_video_filter, 0)) < 0)
496 if ((ret = avfilter_graph_config(ost->graph, NULL)) < 0)
499 codec->width = ost->output_video_filter->inputs[0]->w;
500 codec->height = ost->output_video_filter->inputs[0]->h;
501 codec->sample_aspect_ratio = ost->st->sample_aspect_ratio =
502 ost->frame_aspect_ratio ? // overridden by the -aspect cli option
503 av_d2q(ost->frame_aspect_ratio*codec->height/codec->width, 255) :
504 ost->output_video_filter->inputs[0]->sample_aspect_ratio;
508 #endif /* CONFIG_AVFILTER */
510 static void term_exit(void)
512 av_log(NULL, AV_LOG_QUIET, "%s", "");
515 tcsetattr (0, TCSANOW, &oldtty);
519 static volatile int received_sigterm = 0;
522 sigterm_handler(int sig)
524 received_sigterm = sig;
529 static void term_init(void)
539 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
540 |INLCR|IGNCR|ICRNL|IXON);
541 tty.c_oflag |= OPOST;
542 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
543 tty.c_cflag &= ~(CSIZE|PARENB);
548 tcsetattr (0, TCSANOW, &tty);
549 signal(SIGQUIT, sigterm_handler); /* Quit (POSIX). */
553 signal(SIGINT , sigterm_handler); /* Interrupt (ANSI). */
554 signal(SIGTERM, sigterm_handler); /* Termination (ANSI). */
556 signal(SIGXCPU, sigterm_handler);
560 /* read a key without blocking */
561 static int read_key(void)
576 n = select(1, &rfds, NULL, NULL, &tv);
591 static int decode_interrupt_cb(void *ctx)
593 q_pressed += read_key() == 'q';
594 return q_pressed > 1;
597 static const AVIOInterruptCB int_cb = { decode_interrupt_cb, NULL };
599 void exit_program(int ret)
604 for(i=0;i<nb_output_files;i++) {
605 AVFormatContext *s = output_files[i].ctx;
606 if (!(s->oformat->flags & AVFMT_NOFILE) && s->pb)
608 avformat_free_context(s);
609 av_dict_free(&output_files[i].opts);
611 for(i=0;i<nb_input_files;i++) {
612 av_close_input_file(input_files[i].ctx);
614 for (i = 0; i < nb_input_streams; i++)
615 av_dict_free(&input_streams[i].opts);
619 av_free(vstats_filename);
621 av_freep(&input_streams);
622 av_freep(&input_files);
623 av_freep(&output_streams);
624 av_freep(&output_files);
629 allocated_audio_buf_size= allocated_audio_out_size= 0;
635 avformat_network_deinit();
637 if (received_sigterm) {
638 av_log(NULL, AV_LOG_INFO, "Received signal %d: terminating.\n",
639 (int) received_sigterm);
643 exit(ret); /* not all OS-es handle main() return value */
646 static void assert_avoptions(AVDictionary *m)
648 AVDictionaryEntry *t;
649 if ((t = av_dict_get(m, "", NULL, AV_DICT_IGNORE_SUFFIX))) {
650 av_log(NULL, AV_LOG_FATAL, "Option %s not found.\n", t->key);
655 static void assert_codec_experimental(AVCodecContext *c, int encoder)
657 const char *codec_string = encoder ? "encoder" : "decoder";
659 if (c->codec->capabilities & CODEC_CAP_EXPERIMENTAL &&
660 c->strict_std_compliance > FF_COMPLIANCE_EXPERIMENTAL) {
661 av_log(NULL, AV_LOG_FATAL, "%s '%s' is experimental and might produce bad "
662 "results.\nAdd '-strict experimental' if you want to use it.\n",
663 codec_string, c->codec->name);
664 codec = encoder ? avcodec_find_encoder(c->codec->id) : avcodec_find_decoder(c->codec->id);
665 if (!(codec->capabilities & CODEC_CAP_EXPERIMENTAL))
666 av_log(NULL, AV_LOG_FATAL, "Or use the non experimental %s '%s'.\n",
667 codec_string, codec->name);
672 static void choose_sample_fmt(AVStream *st, AVCodec *codec)
674 if(codec && codec->sample_fmts){
675 const enum AVSampleFormat *p= codec->sample_fmts;
677 if(*p == st->codec->sample_fmt)
681 if((codec->capabilities & CODEC_CAP_LOSSLESS) && av_get_sample_fmt_name(st->codec->sample_fmt) > av_get_sample_fmt_name(codec->sample_fmts[0]))
682 av_log(NULL, AV_LOG_ERROR, "Convertion will not be lossless'\n");
683 if(av_get_sample_fmt_name(st->codec->sample_fmt))
684 av_log(NULL, AV_LOG_WARNING,
685 "Incompatible sample format '%s' for codec '%s', auto-selecting format '%s'\n",
686 av_get_sample_fmt_name(st->codec->sample_fmt),
688 av_get_sample_fmt_name(codec->sample_fmts[0]));
689 st->codec->sample_fmt = codec->sample_fmts[0];
694 static void choose_sample_rate(AVStream *st, AVCodec *codec)
696 if(codec && codec->supported_samplerates){
697 const int *p= codec->supported_samplerates;
699 int best_dist=INT_MAX;
701 int dist= abs(st->codec->sample_rate - *p);
702 if(dist < best_dist){
708 av_log(st->codec, AV_LOG_WARNING, "Requested sampling rate unsupported using closest supported (%d)\n", best);
710 st->codec->sample_rate= best;
714 static void choose_pixel_fmt(AVStream *st, AVCodec *codec)
716 if(codec && codec->pix_fmts){
717 const enum PixelFormat *p= codec->pix_fmts;
718 if(st->codec->strict_std_compliance <= FF_COMPLIANCE_UNOFFICIAL){
719 if(st->codec->codec_id==CODEC_ID_MJPEG){
720 p= (const enum PixelFormat[]){PIX_FMT_YUVJ420P, PIX_FMT_YUVJ422P, PIX_FMT_YUV420P, PIX_FMT_YUV422P, PIX_FMT_NONE};
721 }else if(st->codec->codec_id==CODEC_ID_LJPEG){
722 p= (const enum PixelFormat[]){PIX_FMT_YUVJ420P, PIX_FMT_YUVJ422P, PIX_FMT_YUVJ444P, PIX_FMT_YUV420P, PIX_FMT_YUV422P, PIX_FMT_YUV444P, PIX_FMT_BGRA, PIX_FMT_NONE};
725 for (; *p != PIX_FMT_NONE; p++) {
726 if(*p == st->codec->pix_fmt)
729 if (*p == PIX_FMT_NONE) {
730 if(st->codec->pix_fmt != PIX_FMT_NONE)
731 av_log(NULL, AV_LOG_WARNING,
732 "Incompatible pixel format '%s' for codec '%s', auto-selecting format '%s'\n",
733 av_pix_fmt_descriptors[st->codec->pix_fmt].name,
735 av_pix_fmt_descriptors[codec->pix_fmts[0]].name);
736 st->codec->pix_fmt = codec->pix_fmts[0];
742 get_sync_ipts(const OutputStream *ost)
744 const InputStream *ist = ost->sync_ist;
745 OutputFile *of = &output_files[ost->file_index];
746 return (double)(ist->pts - of->start_time)/AV_TIME_BASE;
749 static void write_frame(AVFormatContext *s, AVPacket *pkt, AVCodecContext *avctx, AVBitStreamFilterContext *bsfc){
753 AVPacket new_pkt= *pkt;
754 int a= av_bitstream_filter_filter(bsfc, avctx, NULL,
755 &new_pkt.data, &new_pkt.size,
756 pkt->data, pkt->size,
757 pkt->flags & AV_PKT_FLAG_KEY);
760 new_pkt.destruct= av_destruct_packet;
762 av_log(NULL, AV_LOG_ERROR, "%s failed for stream %d, codec %s",
763 bsfc->filter->name, pkt->stream_index,
764 avctx->codec ? avctx->codec->name : "copy");
774 ret= av_interleaved_write_frame(s, pkt);
776 print_error("av_interleaved_write_frame()", ret);
781 static void do_audio_out(AVFormatContext *s,
784 unsigned char *buf, int size)
787 int64_t audio_out_size, audio_buf_size;
788 int64_t allocated_for_size= size;
790 int size_out, frame_bytes, ret, resample_changed;
791 AVCodecContext *enc= ost->st->codec;
792 AVCodecContext *dec= ist->st->codec;
793 int osize = av_get_bytes_per_sample(enc->sample_fmt);
794 int isize = av_get_bytes_per_sample(dec->sample_fmt);
795 const int coded_bps = av_get_bits_per_sample(enc->codec->id);
798 audio_buf_size= (allocated_for_size + isize*dec->channels - 1) / (isize*dec->channels);
799 audio_buf_size= (audio_buf_size*enc->sample_rate + dec->sample_rate) / dec->sample_rate;
800 audio_buf_size= audio_buf_size*2 + 10000; //safety factors for the deprecated resampling API
801 audio_buf_size= FFMAX(audio_buf_size, enc->frame_size);
802 audio_buf_size*= osize*enc->channels;
804 audio_out_size= FFMAX(audio_buf_size, enc->frame_size * osize * enc->channels);
805 if(coded_bps > 8*osize)
806 audio_out_size= audio_out_size * coded_bps / (8*osize);
807 audio_out_size += FF_MIN_BUFFER_SIZE;
809 if(audio_out_size > INT_MAX || audio_buf_size > INT_MAX){
810 av_log(NULL, AV_LOG_FATAL, "Buffer sizes too large\n");
814 av_fast_malloc(&audio_buf, &allocated_audio_buf_size, audio_buf_size);
815 av_fast_malloc(&audio_out, &allocated_audio_out_size, audio_out_size);
816 if (!audio_buf || !audio_out){
817 av_log(NULL, AV_LOG_FATAL, "Out of memory in do_audio_out\n");
821 if (enc->channels != dec->channels)
822 ost->audio_resample = 1;
824 resample_changed = ost->resample_sample_fmt != dec->sample_fmt ||
825 ost->resample_channels != dec->channels ||
826 ost->resample_sample_rate != dec->sample_rate;
828 if ((ost->audio_resample && !ost->resample) || resample_changed) {
829 if (resample_changed) {
830 av_log(NULL, AV_LOG_INFO, "Input stream #%d:%d frame changed from rate:%d fmt:%s ch:%d to rate:%d fmt:%s ch:%d\n",
831 ist->file_index, ist->st->index,
832 ost->resample_sample_rate, av_get_sample_fmt_name(ost->resample_sample_fmt), ost->resample_channels,
833 dec->sample_rate, av_get_sample_fmt_name(dec->sample_fmt), dec->channels);
834 ost->resample_sample_fmt = dec->sample_fmt;
835 ost->resample_channels = dec->channels;
836 ost->resample_sample_rate = dec->sample_rate;
838 audio_resample_close(ost->resample);
840 /* if audio_sync_method is >1 the resampler is needed for audio drift compensation */
841 if (audio_sync_method <= 1 &&
842 ost->resample_sample_fmt == enc->sample_fmt &&
843 ost->resample_channels == enc->channels &&
844 ost->resample_sample_rate == enc->sample_rate) {
845 ost->resample = NULL;
846 ost->audio_resample = 0;
848 if (dec->sample_fmt != AV_SAMPLE_FMT_S16)
849 av_log(NULL, AV_LOG_WARNING, "Using s16 intermediate sample format for resampling\n");
850 ost->resample = av_audio_resample_init(enc->channels, dec->channels,
851 enc->sample_rate, dec->sample_rate,
852 enc->sample_fmt, dec->sample_fmt,
854 if (!ost->resample) {
855 av_log(NULL, AV_LOG_FATAL, "Can not resample %d channels @ %d Hz to %d channels @ %d Hz\n",
856 dec->channels, dec->sample_rate,
857 enc->channels, enc->sample_rate);
863 #define MAKE_SFMT_PAIR(a,b) ((a)+AV_SAMPLE_FMT_NB*(b))
864 if (!ost->audio_resample && dec->sample_fmt!=enc->sample_fmt &&
865 MAKE_SFMT_PAIR(enc->sample_fmt,dec->sample_fmt)!=ost->reformat_pair) {
866 if (ost->reformat_ctx)
867 av_audio_convert_free(ost->reformat_ctx);
868 ost->reformat_ctx = av_audio_convert_alloc(enc->sample_fmt, 1,
869 dec->sample_fmt, 1, NULL, 0);
870 if (!ost->reformat_ctx) {
871 av_log(NULL, AV_LOG_FATAL, "Cannot convert %s sample format to %s sample format\n",
872 av_get_sample_fmt_name(dec->sample_fmt),
873 av_get_sample_fmt_name(enc->sample_fmt));
876 ost->reformat_pair=MAKE_SFMT_PAIR(enc->sample_fmt,dec->sample_fmt);
879 if(audio_sync_method){
880 double delta = get_sync_ipts(ost) * enc->sample_rate - ost->sync_opts
881 - av_fifo_size(ost->fifo)/(enc->channels * 2);
882 double idelta= delta*dec->sample_rate / enc->sample_rate;
883 int byte_delta= ((int)idelta)*2*dec->channels;
885 //FIXME resample delay
886 if(fabs(delta) > 50){
887 if(ist->is_start || fabs(delta) > audio_drift_threshold*enc->sample_rate){
889 byte_delta= FFMAX(byte_delta, -size);
892 av_log(NULL, AV_LOG_VERBOSE, "discarding %d audio samples\n", (int)-delta);
897 static uint8_t *input_tmp= NULL;
898 input_tmp= av_realloc(input_tmp, byte_delta + size);
900 if(byte_delta > allocated_for_size - size){
901 allocated_for_size= byte_delta + (int64_t)size;
906 memset(input_tmp, 0, byte_delta);
907 memcpy(input_tmp + byte_delta, buf, size);
910 av_log(NULL, AV_LOG_VERBOSE, "adding %d audio samples of silence\n", (int)delta);
912 }else if(audio_sync_method>1){
913 int comp= av_clip(delta, -audio_sync_method, audio_sync_method);
914 av_assert0(ost->audio_resample);
915 av_log(NULL, AV_LOG_VERBOSE, "compensating audio timestamp drift:%f compensation:%d in:%d\n",
916 delta, comp, enc->sample_rate);
917 // fprintf(stderr, "drift:%f len:%d opts:%"PRId64" ipts:%"PRId64" fifo:%d\n", delta, -1, ost->sync_opts, (int64_t)(get_sync_ipts(ost) * enc->sample_rate), av_fifo_size(ost->fifo)/(ost->st->codec->channels * 2));
918 av_resample_compensate(*(struct AVResampleContext**)ost->resample, comp, enc->sample_rate);
922 ost->sync_opts= lrintf(get_sync_ipts(ost) * enc->sample_rate)
923 - av_fifo_size(ost->fifo)/(enc->channels * 2); //FIXME wrong
925 if (ost->audio_resample) {
927 size_out = audio_resample(ost->resample,
928 (short *)buftmp, (short *)buf,
929 size / (dec->channels * isize));
930 size_out = size_out * enc->channels * osize;
936 if (!ost->audio_resample && dec->sample_fmt!=enc->sample_fmt) {
937 const void *ibuf[6]= {buftmp};
938 void *obuf[6]= {audio_buf};
939 int istride[6]= {isize};
940 int ostride[6]= {osize};
941 int len= size_out/istride[0];
942 if (av_audio_convert(ost->reformat_ctx, obuf, ostride, ibuf, istride, len)<0) {
943 printf("av_audio_convert() failed\n");
949 size_out = len*osize;
952 /* now encode as many frames as possible */
953 if (enc->frame_size > 1) {
954 /* output resampled raw samples */
955 if (av_fifo_realloc2(ost->fifo, av_fifo_size(ost->fifo) + size_out) < 0) {
956 av_log(NULL, AV_LOG_FATAL, "av_fifo_realloc2() failed\n");
959 av_fifo_generic_write(ost->fifo, buftmp, size_out, NULL);
961 frame_bytes = enc->frame_size * osize * enc->channels;
963 while (av_fifo_size(ost->fifo) >= frame_bytes) {
965 av_init_packet(&pkt);
967 av_fifo_generic_read(ost->fifo, audio_buf, frame_bytes, NULL);
969 //FIXME pass ost->sync_opts as AVFrame.pts in avcodec_encode_audio()
971 ret = avcodec_encode_audio(enc, audio_out, audio_out_size,
974 av_log(NULL, AV_LOG_FATAL, "Audio encoding failed\n");
978 pkt.stream_index= ost->index;
981 if(enc->coded_frame && enc->coded_frame->pts != AV_NOPTS_VALUE)
982 pkt.pts= av_rescale_q(enc->coded_frame->pts, enc->time_base, ost->st->time_base);
983 pkt.flags |= AV_PKT_FLAG_KEY;
984 write_frame(s, &pkt, enc, ost->bitstream_filters);
986 ost->sync_opts += enc->frame_size;
990 av_init_packet(&pkt);
992 ost->sync_opts += size_out / (osize * enc->channels);
994 /* output a pcm frame */
995 /* determine the size of the coded buffer */
998 size_out = size_out*coded_bps/8;
1000 if(size_out > audio_out_size){
1001 av_log(NULL, AV_LOG_FATAL, "Internal error, buffer size too small\n");
1005 //FIXME pass ost->sync_opts as AVFrame.pts in avcodec_encode_audio()
1006 ret = avcodec_encode_audio(enc, audio_out, size_out,
1009 av_log(NULL, AV_LOG_FATAL, "Audio encoding failed\n");
1013 pkt.stream_index= ost->index;
1014 pkt.data= audio_out;
1016 if(enc->coded_frame && enc->coded_frame->pts != AV_NOPTS_VALUE)
1017 pkt.pts= av_rescale_q(enc->coded_frame->pts, enc->time_base, ost->st->time_base);
1018 pkt.flags |= AV_PKT_FLAG_KEY;
1019 write_frame(s, &pkt, enc, ost->bitstream_filters);
1023 static void pre_process_video_frame(InputStream *ist, AVPicture *picture, void **bufp)
1025 AVCodecContext *dec;
1026 AVPicture *picture2;
1027 AVPicture picture_tmp;
1030 dec = ist->st->codec;
1032 /* deinterlace : must be done before any resize */
1033 if (do_deinterlace) {
1036 /* create temporary picture */
1037 size = avpicture_get_size(dec->pix_fmt, dec->width, dec->height);
1038 buf = av_malloc(size);
1042 picture2 = &picture_tmp;
1043 avpicture_fill(picture2, buf, dec->pix_fmt, dec->width, dec->height);
1045 if(avpicture_deinterlace(picture2, picture,
1046 dec->pix_fmt, dec->width, dec->height) < 0) {
1047 /* if error, do not deinterlace */
1048 av_log(NULL, AV_LOG_WARNING, "Deinterlacing failed\n");
1057 if (picture != picture2)
1058 *picture = *picture2;
1062 static void do_subtitle_out(AVFormatContext *s,
1068 static uint8_t *subtitle_out = NULL;
1069 int subtitle_out_max_size = 1024 * 1024;
1070 int subtitle_out_size, nb, i;
1071 AVCodecContext *enc;
1074 if (pts == AV_NOPTS_VALUE) {
1075 av_log(NULL, AV_LOG_ERROR, "Subtitle packets must have a pts\n");
1081 enc = ost->st->codec;
1083 if (!subtitle_out) {
1084 subtitle_out = av_malloc(subtitle_out_max_size);
1087 /* Note: DVB subtitle need one packet to draw them and one other
1088 packet to clear them */
1089 /* XXX: signal it in the codec context ? */
1090 if (enc->codec_id == CODEC_ID_DVB_SUBTITLE)
1095 for(i = 0; i < nb; i++) {
1096 sub->pts = av_rescale_q(pts, ist->st->time_base, AV_TIME_BASE_Q);
1097 // start_display_time is required to be 0
1098 sub->pts += av_rescale_q(sub->start_display_time, (AVRational){1, 1000}, AV_TIME_BASE_Q);
1099 sub->end_display_time -= sub->start_display_time;
1100 sub->start_display_time = 0;
1101 subtitle_out_size = avcodec_encode_subtitle(enc, subtitle_out,
1102 subtitle_out_max_size, sub);
1103 if (subtitle_out_size < 0) {
1104 av_log(NULL, AV_LOG_FATAL, "Subtitle encoding failed\n");
1108 av_init_packet(&pkt);
1109 pkt.stream_index = ost->index;
1110 pkt.data = subtitle_out;
1111 pkt.size = subtitle_out_size;
1112 pkt.pts = av_rescale_q(sub->pts, AV_TIME_BASE_Q, ost->st->time_base);
1113 if (enc->codec_id == CODEC_ID_DVB_SUBTITLE) {
1114 /* XXX: the pts correction is handled here. Maybe handling
1115 it in the codec would be better */
1117 pkt.pts += 90 * sub->start_display_time;
1119 pkt.pts += 90 * sub->end_display_time;
1121 write_frame(s, &pkt, ost->st->codec, ost->bitstream_filters);
1125 static int bit_buffer_size= 1024*256;
1126 static uint8_t *bit_buffer= NULL;
1128 static void do_video_resample(OutputStream *ost,
1130 AVFrame *in_picture,
1131 AVFrame **out_picture)
1133 int resample_changed = 0;
1134 AVCodecContext *dec = ist->st->codec;
1135 AVCodecContext *enc = ost->st->codec;
1136 *out_picture = in_picture;
1138 resample_changed = ost->resample_width != dec->width ||
1139 ost->resample_height != dec->height ||
1140 ost->resample_pix_fmt != dec->pix_fmt;
1142 #if !CONFIG_AVFILTER
1143 if (resample_changed) {
1144 av_log(NULL, AV_LOG_INFO,
1145 "Input stream #%d:%d frame changed from size:%dx%d fmt:%s to size:%dx%d fmt:%s\n",
1146 ist->file_index, ist->st->index,
1147 ost->resample_width, ost->resample_height, av_get_pix_fmt_name(ost->resample_pix_fmt),
1148 dec->width , dec->height , av_get_pix_fmt_name(dec->pix_fmt));
1149 ost->resample_width = dec->width;
1150 ost->resample_height = dec->height;
1151 ost->resample_pix_fmt = dec->pix_fmt;
1154 ost->video_resample = dec->width != enc->width ||
1155 dec->height != enc->height ||
1156 dec->pix_fmt != enc->pix_fmt;
1158 if (ost->video_resample) {
1159 *out_picture = &ost->resample_frame;
1160 if (!ost->img_resample_ctx || resample_changed) {
1161 /* initialize the destination picture */
1162 if (!ost->resample_frame.data[0]) {
1163 avcodec_get_frame_defaults(&ost->resample_frame);
1164 if (avpicture_alloc((AVPicture *)&ost->resample_frame, enc->pix_fmt,
1165 enc->width, enc->height)) {
1166 fprintf(stderr, "Cannot allocate temp picture, check pix fmt\n");
1170 /* initialize a new scaler context */
1171 sws_freeContext(ost->img_resample_ctx);
1172 ost->img_resample_ctx = sws_getContext(dec->width, dec->height, dec->pix_fmt,
1173 enc->width, enc->height, enc->pix_fmt,
1174 ost->sws_flags, NULL, NULL, NULL);
1175 if (ost->img_resample_ctx == NULL) {
1176 av_log(NULL, AV_LOG_FATAL, "Cannot get resampling context\n");
1180 sws_scale(ost->img_resample_ctx, in_picture->data, in_picture->linesize,
1181 0, ost->resample_height, (*out_picture)->data, (*out_picture)->linesize);
1184 if (resample_changed) {
1185 avfilter_graph_free(&ost->graph);
1186 if (configure_video_filters(ist, ost)) {
1187 av_log(NULL, AV_LOG_FATAL, "Error reinitializing filters!\n");
1192 if (resample_changed) {
1193 ost->resample_width = dec->width;
1194 ost->resample_height = dec->height;
1195 ost->resample_pix_fmt = dec->pix_fmt;
1200 static void do_video_out(AVFormatContext *s,
1203 AVFrame *in_picture,
1204 int *frame_size, float quality)
1206 int nb_frames, i, ret, format_video_sync;
1207 AVFrame *final_picture;
1208 AVCodecContext *enc;
1211 enc = ost->st->codec;
1213 sync_ipts = get_sync_ipts(ost) / av_q2d(enc->time_base);
1215 /* by default, we output a single frame */
1220 format_video_sync = video_sync_method;
1221 if (format_video_sync < 0)
1222 format_video_sync = (s->oformat->flags & AVFMT_NOTIMESTAMPS) ? 0 :
1223 (s->oformat->flags & AVFMT_VARIABLE_FPS) ? 2 : 1;
1225 if (format_video_sync) {
1226 double vdelta = sync_ipts - ost->sync_opts;
1227 //FIXME set to 0.5 after we fix some dts/pts bugs like in avidec.c
1230 else if (format_video_sync == 2) {
1233 }else if(vdelta>0.6)
1234 ost->sync_opts= lrintf(sync_ipts);
1235 }else if (vdelta > 1.1)
1236 nb_frames = lrintf(vdelta);
1237 //fprintf(stderr, "vdelta:%f, ost->sync_opts:%"PRId64", ost->sync_ipts:%f nb_frames:%d\n", vdelta, ost->sync_opts, get_sync_ipts(ost), nb_frames);
1238 if (nb_frames == 0){
1240 av_log(NULL, AV_LOG_VERBOSE, "*** drop!\n");
1241 }else if (nb_frames > 1) {
1242 nb_frames_dup += nb_frames - 1;
1243 av_log(NULL, AV_LOG_VERBOSE, "*** %d dup!\n", nb_frames-1);
1246 ost->sync_opts= lrintf(sync_ipts);
1248 nb_frames = FFMIN(nb_frames, ost->max_frames - ost->frame_number);
1252 do_video_resample(ost, ist, in_picture, &final_picture);
1254 /* duplicates frame if needed */
1255 for(i=0;i<nb_frames;i++) {
1257 av_init_packet(&pkt);
1258 pkt.stream_index= ost->index;
1260 if (s->oformat->flags & AVFMT_RAWPICTURE) {
1261 /* raw pictures are written as AVPicture structure to
1262 avoid any copies. We support temporarily the older
1264 enc->coded_frame->interlaced_frame = in_picture->interlaced_frame;
1265 enc->coded_frame->top_field_first = in_picture->top_field_first;
1266 pkt.data= (uint8_t *)final_picture;
1267 pkt.size= sizeof(AVPicture);
1268 pkt.pts= av_rescale_q(ost->sync_opts, enc->time_base, ost->st->time_base);
1269 pkt.flags |= AV_PKT_FLAG_KEY;
1271 write_frame(s, &pkt, ost->st->codec, ost->bitstream_filters);
1273 AVFrame big_picture;
1275 big_picture= *final_picture;
1276 /* better than nothing: use input picture interlaced
1278 big_picture.interlaced_frame = in_picture->interlaced_frame;
1279 if (ost->st->codec->flags & (CODEC_FLAG_INTERLACED_DCT|CODEC_FLAG_INTERLACED_ME)) {
1280 if (ost->top_field_first == -1)
1281 big_picture.top_field_first = in_picture->top_field_first;
1283 big_picture.top_field_first = !!ost->top_field_first;
1286 /* handles same_quant here. This is not correct because it may
1287 not be a global option */
1288 big_picture.quality = quality;
1289 if (!enc->me_threshold)
1290 big_picture.pict_type = 0;
1291 // big_picture.pts = AV_NOPTS_VALUE;
1292 big_picture.pts= ost->sync_opts;
1293 // big_picture.pts= av_rescale(ost->sync_opts, AV_TIME_BASE*(int64_t)enc->time_base.num, enc->time_base.den);
1294 //av_log(NULL, AV_LOG_DEBUG, "%"PRId64" -> encoder\n", ost->sync_opts);
1295 if (ost->forced_kf_index < ost->forced_kf_count &&
1296 big_picture.pts >= ost->forced_kf_pts[ost->forced_kf_index]) {
1297 big_picture.pict_type = AV_PICTURE_TYPE_I;
1298 ost->forced_kf_index++;
1300 ret = avcodec_encode_video(enc,
1301 bit_buffer, bit_buffer_size,
1304 av_log(NULL, AV_LOG_FATAL, "Video encoding failed\n");
1309 pkt.data= bit_buffer;
1311 if(enc->coded_frame->pts != AV_NOPTS_VALUE)
1312 pkt.pts= av_rescale_q(enc->coded_frame->pts, enc->time_base, ost->st->time_base);
1313 /*av_log(NULL, AV_LOG_DEBUG, "encoder -> %"PRId64"/%"PRId64"\n",
1314 pkt.pts != AV_NOPTS_VALUE ? av_rescale(pkt.pts, enc->time_base.den, AV_TIME_BASE*(int64_t)enc->time_base.num) : -1,
1315 pkt.dts != AV_NOPTS_VALUE ? av_rescale(pkt.dts, enc->time_base.den, AV_TIME_BASE*(int64_t)enc->time_base.num) : -1);*/
1317 if(enc->coded_frame->key_frame)
1318 pkt.flags |= AV_PKT_FLAG_KEY;
1319 write_frame(s, &pkt, ost->st->codec, ost->bitstream_filters);
1322 //fprintf(stderr,"\nFrame: %3d size: %5d type: %d",
1323 // enc->frame_number-1, ret, enc->pict_type);
1324 /* if two pass, output log */
1325 if (ost->logfile && enc->stats_out) {
1326 fprintf(ost->logfile, "%s", enc->stats_out);
1331 ost->frame_number++;
1335 static double psnr(double d){
1336 return -10.0*log(d)/log(10.0);
1339 static void do_video_stats(AVFormatContext *os, OutputStream *ost,
1342 AVCodecContext *enc;
1344 double ti1, bitrate, avg_bitrate;
1346 /* this is executed just the first time do_video_stats is called */
1348 vstats_file = fopen(vstats_filename, "w");
1355 enc = ost->st->codec;
1356 if (enc->codec_type == AVMEDIA_TYPE_VIDEO) {
1357 frame_number = ost->frame_number;
1358 fprintf(vstats_file, "frame= %5d q= %2.1f ", frame_number, enc->coded_frame->quality/(float)FF_QP2LAMBDA);
1359 if (enc->flags&CODEC_FLAG_PSNR)
1360 fprintf(vstats_file, "PSNR= %6.2f ", psnr(enc->coded_frame->error[0]/(enc->width*enc->height*255.0*255.0)));
1362 fprintf(vstats_file,"f_size= %6d ", frame_size);
1363 /* compute pts value */
1364 ti1 = ost->sync_opts * av_q2d(enc->time_base);
1368 bitrate = (frame_size * 8) / av_q2d(enc->time_base) / 1000.0;
1369 avg_bitrate = (double)(video_size * 8) / ti1 / 1000.0;
1370 fprintf(vstats_file, "s_size= %8.0fkB time= %0.3f br= %7.1fkbits/s avg_br= %7.1fkbits/s ",
1371 (double)video_size / 1024, ti1, bitrate, avg_bitrate);
1372 fprintf(vstats_file, "type= %c\n", av_get_picture_type_char(enc->coded_frame->pict_type));
1376 static void print_report(OutputFile *output_files,
1377 OutputStream *ost_table, int nb_ostreams,
1378 int is_last_report, int64_t timer_start)
1382 AVFormatContext *oc;
1384 AVCodecContext *enc;
1385 int frame_number, vid, i;
1387 int64_t pts = INT64_MAX;
1388 static int64_t last_time = -1;
1389 static int qp_histogram[52];
1390 int hours, mins, secs, us;
1392 if (!print_stats && !is_last_report)
1395 if (!is_last_report) {
1397 /* display the report every 0.5 seconds */
1398 cur_time = av_gettime();
1399 if (last_time == -1) {
1400 last_time = cur_time;
1403 if ((cur_time - last_time) < 500000)
1405 last_time = cur_time;
1409 oc = output_files[0].ctx;
1411 total_size = avio_size(oc->pb);
1412 if(total_size<0) // FIXME improve avio_size() so it works with non seekable output too
1413 total_size= avio_tell(oc->pb);
1417 for(i=0;i<nb_ostreams;i++) {
1419 ost = &ost_table[i];
1420 enc = ost->st->codec;
1421 if (!ost->stream_copy && enc->coded_frame)
1422 q = enc->coded_frame->quality/(float)FF_QP2LAMBDA;
1423 if (vid && enc->codec_type == AVMEDIA_TYPE_VIDEO) {
1424 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "q=%2.1f ", q);
1426 if (!vid && enc->codec_type == AVMEDIA_TYPE_VIDEO) {
1427 float t = (av_gettime()-timer_start) / 1000000.0;
1429 frame_number = ost->frame_number;
1430 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "frame=%5d fps=%3d q=%3.1f ",
1431 frame_number, (t>1)?(int)(frame_number/t+0.5) : 0, q);
1433 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "L");
1437 if(qp>=0 && qp<FF_ARRAY_ELEMS(qp_histogram))
1440 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "%X", (int)lrintf(log(qp_histogram[j]+1)/log(2)));
1442 if (enc->flags&CODEC_FLAG_PSNR){
1444 double error, error_sum=0;
1445 double scale, scale_sum=0;
1446 char type[3]= {'Y','U','V'};
1447 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "PSNR=");
1450 error= enc->error[j];
1451 scale= enc->width*enc->height*255.0*255.0*frame_number;
1453 error= enc->coded_frame->error[j];
1454 scale= enc->width*enc->height*255.0*255.0;
1459 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "%c:%2.2f ", type[j], psnr(error/scale));
1461 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "*:%2.2f ", psnr(error_sum/scale_sum));
1465 /* compute min output value */
1466 pts = FFMIN(pts, av_rescale_q(ost->st->pts.val,
1467 ost->st->time_base, AV_TIME_BASE_Q));
1470 secs = pts / AV_TIME_BASE;
1471 us = pts % AV_TIME_BASE;
1477 bitrate = pts ? total_size * 8 / (pts / 1000.0) : 0;
1479 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
1480 "size=%8.0fkB time=", total_size / 1024.0);
1481 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
1482 "%02d:%02d:%02d.%02d ", hours, mins, secs,
1483 (100 * us) / AV_TIME_BASE);
1484 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
1485 "bitrate=%6.1fkbits/s", bitrate);
1487 if (nb_frames_dup || nb_frames_drop)
1488 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), " dup=%d drop=%d",
1489 nb_frames_dup, nb_frames_drop);
1491 av_log(NULL, AV_LOG_INFO, "%s \r", buf);
1495 if (is_last_report) {
1496 int64_t raw= audio_size + video_size + extra_size;
1497 av_log(NULL, AV_LOG_INFO, "\n");
1498 av_log(NULL, AV_LOG_INFO, "video:%1.0fkB audio:%1.0fkB global headers:%1.0fkB muxing overhead %f%%\n",
1502 100.0*(total_size - raw)/raw
1507 static void generate_silence(uint8_t* buf, enum AVSampleFormat sample_fmt, size_t size)
1509 int fill_char = 0x00;
1510 if (sample_fmt == AV_SAMPLE_FMT_U8)
1512 memset(buf, fill_char, size);
1515 static void flush_encoders(OutputStream *ost_table, int nb_ostreams)
1519 for (i = 0; i < nb_ostreams; i++) {
1520 OutputStream *ost = &ost_table[i];
1521 AVCodecContext *enc = ost->st->codec;
1522 AVFormatContext *os = output_files[ost->file_index].ctx;
1524 if (!ost->encoding_needed)
1527 if (ost->st->codec->codec_type == AVMEDIA_TYPE_AUDIO && enc->frame_size <=1)
1529 if (ost->st->codec->codec_type == AVMEDIA_TYPE_VIDEO && (os->oformat->flags & AVFMT_RAWPICTURE))
1535 av_init_packet(&pkt);
1536 pkt.stream_index= ost->index;
1538 switch (ost->st->codec->codec_type) {
1539 case AVMEDIA_TYPE_AUDIO:
1540 fifo_bytes = av_fifo_size(ost->fifo);
1542 /* encode any samples remaining in fifo */
1543 if (fifo_bytes > 0) {
1544 int osize = av_get_bytes_per_sample(enc->sample_fmt);
1545 int fs_tmp = enc->frame_size;
1547 av_fifo_generic_read(ost->fifo, audio_buf, fifo_bytes, NULL);
1548 if (enc->codec->capabilities & CODEC_CAP_SMALL_LAST_FRAME) {
1549 enc->frame_size = fifo_bytes / (osize * enc->channels);
1551 int frame_bytes = enc->frame_size*osize*enc->channels;
1552 if (allocated_audio_buf_size < frame_bytes)
1554 generate_silence(audio_buf+fifo_bytes, enc->sample_fmt, frame_bytes - fifo_bytes);
1557 ret = avcodec_encode_audio(enc, bit_buffer, bit_buffer_size, (short *)audio_buf);
1558 pkt.duration = av_rescale((int64_t)enc->frame_size*ost->st->time_base.den,
1559 ost->st->time_base.num, enc->sample_rate);
1560 enc->frame_size = fs_tmp;
1563 ret = avcodec_encode_audio(enc, bit_buffer, bit_buffer_size, NULL);
1566 av_log(NULL, AV_LOG_FATAL, "Audio encoding failed\n");
1570 pkt.flags |= AV_PKT_FLAG_KEY;
1572 case AVMEDIA_TYPE_VIDEO:
1573 ret = avcodec_encode_video(enc, bit_buffer, bit_buffer_size, NULL);
1575 av_log(NULL, AV_LOG_FATAL, "Video encoding failed\n");
1579 if(enc->coded_frame && enc->coded_frame->key_frame)
1580 pkt.flags |= AV_PKT_FLAG_KEY;
1581 if (ost->logfile && enc->stats_out) {
1582 fprintf(ost->logfile, "%s", enc->stats_out);
1591 pkt.data = bit_buffer;
1593 if (enc->coded_frame && enc->coded_frame->pts != AV_NOPTS_VALUE)
1594 pkt.pts= av_rescale_q(enc->coded_frame->pts, enc->time_base, ost->st->time_base);
1595 write_frame(os, &pkt, ost->st->codec, ost->bitstream_filters);
1601 * Check whether a packet from ist should be written into ost at this time
1603 static int check_output_constraints(InputStream *ist, OutputStream *ost)
1605 OutputFile *of = &output_files[ost->file_index];
1606 int ist_index = ist - input_streams;
1608 if (ost->source_index != ist_index)
1611 if (of->start_time && ist->pts < of->start_time)
1614 if (of->recording_time != INT64_MAX &&
1615 av_compare_ts(ist->pts, AV_TIME_BASE_Q, of->recording_time + of->start_time,
1616 (AVRational){1, 1000000}) >= 0) {
1617 ost->is_past_recording_time = 1;
1624 static void do_streamcopy(InputStream *ist, OutputStream *ost, const AVPacket *pkt)
1626 OutputFile *of = &output_files[ost->file_index];
1627 int64_t ost_tb_start_time = av_rescale_q(of->start_time, AV_TIME_BASE_Q, ost->st->time_base);
1631 av_init_packet(&opkt);
1633 if ((!ost->frame_number && !(pkt->flags & AV_PKT_FLAG_KEY)) &&
1634 !ost->copy_initial_nonkeyframes)
1637 /* force the input stream PTS */
1638 if (ost->st->codec->codec_type == AVMEDIA_TYPE_AUDIO)
1639 audio_size += pkt->size;
1640 else if (ost->st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
1641 video_size += pkt->size;
1645 opkt.stream_index = ost->index;
1646 if (pkt->pts != AV_NOPTS_VALUE)
1647 opkt.pts = av_rescale_q(pkt->pts, ist->st->time_base, ost->st->time_base) - ost_tb_start_time;
1649 opkt.pts = AV_NOPTS_VALUE;
1651 if (pkt->dts == AV_NOPTS_VALUE)
1652 opkt.dts = av_rescale_q(ist->pts, AV_TIME_BASE_Q, ost->st->time_base);
1654 opkt.dts = av_rescale_q(pkt->dts, ist->st->time_base, ost->st->time_base);
1655 opkt.dts -= ost_tb_start_time;
1657 opkt.duration = av_rescale_q(pkt->duration, ist->st->time_base, ost->st->time_base);
1658 opkt.flags = pkt->flags;
1660 //FIXME remove the following 2 lines they shall be replaced by the bitstream filters
1661 if( ost->st->codec->codec_id != CODEC_ID_H264
1662 && ost->st->codec->codec_id != CODEC_ID_MPEG1VIDEO
1663 && ost->st->codec->codec_id != CODEC_ID_MPEG2VIDEO
1665 if (av_parser_change(ist->st->parser, ost->st->codec, &opkt.data, &opkt.size, pkt->data, pkt->size, pkt->flags & AV_PKT_FLAG_KEY))
1666 opkt.destruct = av_destruct_packet;
1668 opkt.data = pkt->data;
1669 opkt.size = pkt->size;
1671 if (of->ctx->oformat->flags & AVFMT_RAWPICTURE) {
1672 /* store AVPicture in AVPacket, as expected by the output format */
1673 avpicture_fill(&pict, opkt.data, ost->st->codec->pix_fmt, ost->st->codec->width, ost->st->codec->height);
1674 opkt.data = (uint8_t *)&pict;
1675 opkt.size = sizeof(AVPicture);
1676 opkt.flags |= AV_PKT_FLAG_KEY;
1679 write_frame(of->ctx, &opkt, ost->st->codec, ost->bitstream_filters);
1680 ost->st->codec->frame_number++;
1681 ost->frame_number++;
1682 av_free_packet(&opkt);
1685 static void rate_emu_sleep(InputStream *ist)
1687 if (input_files[ist->file_index].rate_emu) {
1688 int64_t pts = av_rescale(ist->pts, 1000000, AV_TIME_BASE);
1689 int64_t now = av_gettime() - ist->start;
1695 static int transcode_audio(InputStream *ist, AVPacket *pkt, int *got_output)
1697 static unsigned int samples_size = 0;
1698 int bps = av_get_bytes_per_sample(ist->st->codec->sample_fmt);
1699 uint8_t *decoded_data_buf = NULL;
1700 int decoded_data_size = 0;
1703 if (pkt && samples_size < FFMAX(pkt->size * bps, AVCODEC_MAX_AUDIO_FRAME_SIZE)) {
1705 samples_size = FFMAX(pkt->size * bps, AVCODEC_MAX_AUDIO_FRAME_SIZE);
1706 samples = av_malloc(samples_size);
1708 decoded_data_size = samples_size;
1710 ret = avcodec_decode_audio3(ist->st->codec, samples, &decoded_data_size,
1714 *got_output = decoded_data_size > 0;
1716 /* Some bug in mpeg audio decoder gives */
1717 /* decoded_data_size < 0, it seems they are overflows */
1719 /* no audio frame */
1723 decoded_data_buf = (uint8_t *)samples;
1724 ist->next_pts += ((int64_t)AV_TIME_BASE/bps * decoded_data_size) /
1725 (ist->st->codec->sample_rate * ist->st->codec->channels);
1727 // preprocess audio (volume)
1728 if (audio_volume != 256) {
1729 switch (ist->st->codec->sample_fmt) {
1730 case AV_SAMPLE_FMT_U8:
1732 uint8_t *volp = samples;
1733 for (i = 0; i < (decoded_data_size / sizeof(*volp)); i++) {
1734 int v = (((*volp - 128) * audio_volume + 128) >> 8) + 128;
1735 *volp++ = av_clip_uint8(v);
1739 case AV_SAMPLE_FMT_S16:
1741 int16_t *volp = samples;
1742 for (i = 0; i < (decoded_data_size / sizeof(*volp)); i++) {
1743 int v = ((*volp) * audio_volume + 128) >> 8;
1744 *volp++ = av_clip_int16(v);
1748 case AV_SAMPLE_FMT_S32:
1750 int32_t *volp = samples;
1751 for (i = 0; i < (decoded_data_size / sizeof(*volp)); i++) {
1752 int64_t v = (((int64_t)*volp * audio_volume + 128) >> 8);
1753 *volp++ = av_clipl_int32(v);
1757 case AV_SAMPLE_FMT_FLT:
1759 float *volp = samples;
1760 float scale = audio_volume / 256.f;
1761 for (i = 0; i < (decoded_data_size / sizeof(*volp)); i++) {
1766 case AV_SAMPLE_FMT_DBL:
1768 double *volp = samples;
1769 double scale = audio_volume / 256.;
1770 for (i = 0; i < (decoded_data_size / sizeof(*volp)); i++) {
1776 av_log(NULL, AV_LOG_FATAL,
1777 "Audio volume adjustment on sample format %s is not supported.\n",
1778 av_get_sample_fmt_name(ist->st->codec->sample_fmt));
1783 rate_emu_sleep(ist);
1785 for (i = 0; i < nb_output_streams; i++) {
1786 OutputStream *ost = &output_streams[i];
1788 if (!check_output_constraints(ist, ost) || !ost->encoding_needed)
1790 do_audio_out(output_files[ost->file_index].ctx, ost, ist,
1791 decoded_data_buf, decoded_data_size);
1796 static int transcode_video(InputStream *ist, AVPacket *pkt, int *got_output, int64_t *pkt_pts)
1798 AVFrame *decoded_frame, *filtered_frame = NULL;
1799 void *buffer_to_free = NULL;
1803 int frame_available = 1;
1806 if (!(decoded_frame = avcodec_alloc_frame()))
1807 return AVERROR(ENOMEM);
1808 pkt->pts = *pkt_pts;
1809 pkt->dts = ist->pts;
1810 *pkt_pts = AV_NOPTS_VALUE;
1812 ret = avcodec_decode_video2(ist->st->codec,
1813 decoded_frame, got_output, pkt);
1817 quality = same_quant ? decoded_frame->quality : 0;
1819 /* no picture yet */
1820 av_freep(&decoded_frame);
1823 ist->next_pts = ist->pts = decoded_frame->best_effort_timestamp;
1824 if (ist->st->codec->time_base.num != 0) {
1825 int ticks = ist->st->parser ? ist->st->parser->repeat_pict + 1 :
1826 ist->st->codec->ticks_per_frame;
1827 ist->next_pts += ((int64_t)AV_TIME_BASE *
1828 ist->st->codec->time_base.num * ticks) /
1829 ist->st->codec->time_base.den;
1832 pre_process_video_frame(ist, (AVPicture *)decoded_frame, &buffer_to_free);
1834 rate_emu_sleep(ist);
1836 for (i = 0; i < nb_output_streams; i++) {
1837 OutputStream *ost = &output_streams[i];
1840 if (!check_output_constraints(ist, ost) || !ost->encoding_needed)
1844 if (ost->input_video_filter) {
1845 if (!decoded_frame->sample_aspect_ratio.num)
1846 decoded_frame->sample_aspect_ratio = ist->st->sample_aspect_ratio;
1847 decoded_frame->pts = ist->pts;
1849 av_vsrc_buffer_add_frame(ost->input_video_filter, decoded_frame, AV_VSRC_BUF_FLAG_OVERWRITE);
1850 if (!(filtered_frame = avcodec_alloc_frame())) {
1851 ret = AVERROR(ENOMEM);
1854 frame_available = avfilter_poll_frame(ost->output_video_filter->inputs[0]);
1856 while (frame_available) {
1857 if (ost->output_video_filter) {
1858 AVRational ist_pts_tb = ost->output_video_filter->inputs[0]->time_base;
1859 if (av_buffersink_get_buffer_ref(ost->output_video_filter, &ost->picref, 0) < 0)
1862 avfilter_fill_frame_from_video_buffer_ref(filtered_frame, ost->picref);
1863 ist->pts = av_rescale_q(ost->picref->pts, ist_pts_tb, AV_TIME_BASE_Q);
1866 if (ost->picref->video && !ost->frame_aspect_ratio)
1867 ost->st->codec->sample_aspect_ratio = ost->picref->video->sample_aspect_ratio;
1869 filtered_frame = decoded_frame;
1872 do_video_out(output_files[ost->file_index].ctx, ost, ist, filtered_frame, &frame_size,
1873 same_quant ? quality : ost->st->codec->global_quality);
1874 if (vstats_filename && frame_size)
1875 do_video_stats(output_files[ost->file_index].ctx, ost, frame_size);
1878 frame_available = ost->output_video_filter && avfilter_poll_frame(ost->output_video_filter->inputs[0]);
1880 avfilter_unref_buffer(ost->picref);
1882 av_freep(&filtered_frame);
1887 av_free(buffer_to_free);
1888 av_freep(&decoded_frame);
1892 static int transcode_subtitles(InputStream *ist, AVPacket *pkt, int *got_output)
1894 AVSubtitle subtitle;
1895 int i, ret = avcodec_decode_subtitle2(ist->st->codec,
1896 &subtitle, got_output, pkt);
1902 rate_emu_sleep(ist);
1904 for (i = 0; i < nb_output_streams; i++) {
1905 OutputStream *ost = &output_streams[i];
1907 if (!check_output_constraints(ist, ost) || !ost->encoding_needed)
1910 do_subtitle_out(output_files[ost->file_index].ctx, ost, ist, &subtitle, pkt->pts);
1913 avsubtitle_free(&subtitle);
1917 /* pkt = NULL means EOF (needed to flush decoder buffers) */
1918 static int output_packet(InputStream *ist,
1919 OutputStream *ost_table, int nb_ostreams,
1920 const AVPacket *pkt)
1924 int64_t pkt_pts = AV_NOPTS_VALUE;
1927 if (ist->next_pts == AV_NOPTS_VALUE)
1928 ist->next_pts = ist->pts;
1932 av_init_packet(&avpkt);
1940 if(pkt->dts != AV_NOPTS_VALUE)
1941 ist->next_pts = ist->pts = av_rescale_q(pkt->dts, ist->st->time_base, AV_TIME_BASE_Q);
1942 if(pkt->pts != AV_NOPTS_VALUE)
1943 pkt_pts = av_rescale_q(pkt->pts, ist->st->time_base, AV_TIME_BASE_Q);
1945 //while we have more to decode or while the decoder did output something on EOF
1946 while (ist->decoding_needed && (avpkt.size > 0 || (!pkt && got_output))) {
1950 ist->pts = ist->next_pts;
1952 if (avpkt.size && avpkt.size != pkt->size) {
1953 av_log(NULL, ist->showed_multi_packet_warning ? AV_LOG_VERBOSE : AV_LOG_WARNING,
1954 "Multiple frames in a packet from stream %d\n", pkt->stream_index);
1955 ist->showed_multi_packet_warning = 1;
1958 switch(ist->st->codec->codec_type) {
1959 case AVMEDIA_TYPE_AUDIO:
1960 ret = transcode_audio (ist, &avpkt, &got_output);
1962 case AVMEDIA_TYPE_VIDEO:
1963 ret = transcode_video (ist, &avpkt, &got_output, &pkt_pts);
1965 case AVMEDIA_TYPE_SUBTITLE:
1966 ret = transcode_subtitles(ist, &avpkt, &got_output);
1974 // touch data and size only if not EOF
1984 /* handle stream copy */
1985 if (!ist->decoding_needed) {
1986 rate_emu_sleep(ist);
1987 switch (ist->st->codec->codec_type) {
1988 case AVMEDIA_TYPE_AUDIO:
1989 ist->next_pts += ((int64_t)AV_TIME_BASE * ist->st->codec->frame_size) /
1990 ist->st->codec->sample_rate;
1992 case AVMEDIA_TYPE_VIDEO:
1993 if (ist->st->codec->time_base.num != 0) {
1994 int ticks = ist->st->parser ? ist->st->parser->repeat_pict+1 : ist->st->codec->ticks_per_frame;
1995 ist->next_pts += ((int64_t)AV_TIME_BASE *
1996 ist->st->codec->time_base.num * ticks) /
1997 ist->st->codec->time_base.den;
2002 for (i = 0; pkt && i < nb_ostreams; i++) {
2003 OutputStream *ost = &ost_table[i];
2005 if (!check_output_constraints(ist, ost) || ost->encoding_needed)
2008 do_streamcopy(ist, ost, pkt);
2014 static void print_sdp(OutputFile *output_files, int n)
2018 AVFormatContext **avc = av_malloc(sizeof(*avc)*n);
2022 for (i = 0; i < n; i++)
2023 avc[i] = output_files[i].ctx;
2025 av_sdp_create(avc, n, sdp, sizeof(sdp));
2026 printf("SDP:\n%s\n", sdp);
2031 static int init_input_stream(int ist_index, OutputStream *output_streams, int nb_output_streams,
2032 char *error, int error_len)
2035 InputStream *ist = &input_streams[ist_index];
2036 if (ist->decoding_needed) {
2037 AVCodec *codec = ist->dec;
2039 snprintf(error, error_len, "Decoder (codec id %d) not found for input stream #%d:%d",
2040 ist->st->codec->codec_id, ist->file_index, ist->st->index);
2041 return AVERROR(EINVAL);
2044 if (avcodec_open2(ist->st->codec, codec, &ist->opts) < 0) {
2045 snprintf(error, error_len, "Error while opening decoder for input stream #%d:%d",
2046 ist->file_index, ist->st->index);
2047 return AVERROR(EINVAL);
2049 assert_codec_experimental(ist->st->codec, 0);
2050 assert_avoptions(ist->opts);
2053 ist->pts = ist->st->avg_frame_rate.num ? - ist->st->codec->has_b_frames*AV_TIME_BASE / av_q2d(ist->st->avg_frame_rate) : 0;
2054 ist->next_pts = AV_NOPTS_VALUE;
2060 static int transcode_init(OutputFile *output_files,
2061 int nb_output_files,
2062 InputFile *input_files,
2065 int ret = 0, i, j, k;
2066 AVFormatContext *oc;
2067 AVCodecContext *codec, *icodec;
2073 /* init framerate emulation */
2074 for (i = 0; i < nb_input_files; i++) {
2075 InputFile *ifile = &input_files[i];
2076 if (ifile->rate_emu)
2077 for (j = 0; j < ifile->nb_streams; j++)
2078 input_streams[j + ifile->ist_index].start = av_gettime();
2081 /* output stream init */
2082 for (i = 0; i < nb_output_files; i++) {
2083 oc = output_files[i].ctx;
2084 if (!oc->nb_streams && !(oc->oformat->flags & AVFMT_NOSTREAMS)) {
2085 av_dump_format(oc, i, oc->filename, 1);
2086 av_log(NULL, AV_LOG_ERROR, "Output file #%d does not contain any stream\n", i);
2087 return AVERROR(EINVAL);
2091 /* for each output stream, we compute the right encoding parameters */
2092 for (i = 0; i < nb_output_streams; i++) {
2093 ost = &output_streams[i];
2094 oc = output_files[ost->file_index].ctx;
2095 ist = &input_streams[ost->source_index];
2097 if (ost->attachment_filename)
2100 codec = ost->st->codec;
2101 icodec = ist->st->codec;
2103 ost->st->disposition = ist->st->disposition;
2104 codec->bits_per_raw_sample = icodec->bits_per_raw_sample;
2105 codec->chroma_sample_location = icodec->chroma_sample_location;
2107 if (ost->stream_copy) {
2108 uint64_t extra_size = (uint64_t)icodec->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE;
2110 if (extra_size > INT_MAX) {
2111 return AVERROR(EINVAL);
2114 /* if stream_copy is selected, no need to decode or encode */
2115 codec->codec_id = icodec->codec_id;
2116 codec->codec_type = icodec->codec_type;
2118 if (!codec->codec_tag) {
2119 if (!oc->oformat->codec_tag ||
2120 av_codec_get_id (oc->oformat->codec_tag, icodec->codec_tag) == codec->codec_id ||
2121 av_codec_get_tag(oc->oformat->codec_tag, icodec->codec_id) <= 0)
2122 codec->codec_tag = icodec->codec_tag;
2125 codec->bit_rate = icodec->bit_rate;
2126 codec->rc_max_rate = icodec->rc_max_rate;
2127 codec->rc_buffer_size = icodec->rc_buffer_size;
2128 codec->extradata = av_mallocz(extra_size);
2129 if (!codec->extradata) {
2130 return AVERROR(ENOMEM);
2132 memcpy(codec->extradata, icodec->extradata, icodec->extradata_size);
2133 codec->extradata_size= icodec->extradata_size;
2135 codec->time_base = ist->st->time_base;
2136 if(!strcmp(oc->oformat->name, "avi")) {
2138 av_q2d(icodec->time_base)*icodec->ticks_per_frame > 2*av_q2d(ist->st->time_base) &&
2139 av_q2d(ist->st->time_base) < 1.0/500){
2140 codec->time_base = icodec->time_base;
2141 codec->time_base.num *= icodec->ticks_per_frame;
2142 codec->time_base.den *= 2;
2144 } else if(!(oc->oformat->flags & AVFMT_VARIABLE_FPS)) {
2145 if(!copy_tb && av_q2d(icodec->time_base)*icodec->ticks_per_frame > av_q2d(ist->st->time_base) && av_q2d(ist->st->time_base) < 1.0/500){
2146 codec->time_base = icodec->time_base;
2147 codec->time_base.num *= icodec->ticks_per_frame;
2150 av_reduce(&codec->time_base.num, &codec->time_base.den,
2151 codec->time_base.num, codec->time_base.den, INT_MAX);
2153 switch(codec->codec_type) {
2154 case AVMEDIA_TYPE_AUDIO:
2155 if(audio_volume != 256) {
2156 av_log(NULL, AV_LOG_FATAL, "-acodec copy and -vol are incompatible (frames are not decoded)\n");
2159 codec->channel_layout = icodec->channel_layout;
2160 codec->sample_rate = icodec->sample_rate;
2161 codec->channels = icodec->channels;
2162 codec->frame_size = icodec->frame_size;
2163 codec->audio_service_type = icodec->audio_service_type;
2164 codec->block_align = icodec->block_align;
2166 case AVMEDIA_TYPE_VIDEO:
2167 codec->pix_fmt = icodec->pix_fmt;
2168 codec->width = icodec->width;
2169 codec->height = icodec->height;
2170 codec->has_b_frames = icodec->has_b_frames;
2171 if (!codec->sample_aspect_ratio.num) {
2172 codec->sample_aspect_ratio =
2173 ost->st->sample_aspect_ratio =
2174 ist->st->sample_aspect_ratio.num ? ist->st->sample_aspect_ratio :
2175 ist->st->codec->sample_aspect_ratio.num ?
2176 ist->st->codec->sample_aspect_ratio : (AVRational){0, 1};
2179 case AVMEDIA_TYPE_SUBTITLE:
2180 codec->width = icodec->width;
2181 codec->height = icodec->height;
2183 case AVMEDIA_TYPE_DATA:
2184 case AVMEDIA_TYPE_ATTACHMENT:
2191 ost->enc = avcodec_find_encoder(ost->st->codec->codec_id);
2193 ist->decoding_needed = 1;
2194 ost->encoding_needed = 1;
2196 switch(codec->codec_type) {
2197 case AVMEDIA_TYPE_AUDIO:
2198 ost->fifo = av_fifo_alloc(1024);
2200 return AVERROR(ENOMEM);
2202 ost->reformat_pair = MAKE_SFMT_PAIR(AV_SAMPLE_FMT_NONE,AV_SAMPLE_FMT_NONE);
2204 if (!codec->sample_rate)
2205 codec->sample_rate = icodec->sample_rate;
2206 choose_sample_rate(ost->st, ost->enc);
2207 codec->time_base = (AVRational){1, codec->sample_rate};
2209 if (codec->sample_fmt == AV_SAMPLE_FMT_NONE)
2210 codec->sample_fmt = icodec->sample_fmt;
2211 choose_sample_fmt(ost->st, ost->enc);
2213 if (!codec->channels) {
2214 codec->channels = icodec->channels;
2215 codec->channel_layout = icodec->channel_layout;
2217 if (av_get_channel_layout_nb_channels(codec->channel_layout) != codec->channels)
2218 codec->channel_layout = 0;
2220 ost->audio_resample = codec-> sample_rate != icodec->sample_rate || audio_sync_method > 1;
2221 icodec->request_channels = codec-> channels;
2222 ost->resample_sample_fmt = icodec->sample_fmt;
2223 ost->resample_sample_rate = icodec->sample_rate;
2224 ost->resample_channels = icodec->channels;
2226 case AVMEDIA_TYPE_VIDEO:
2227 if (codec->pix_fmt == PIX_FMT_NONE)
2228 codec->pix_fmt = icodec->pix_fmt;
2229 choose_pixel_fmt(ost->st, ost->enc);
2231 if (ost->st->codec->pix_fmt == PIX_FMT_NONE) {
2232 av_log(NULL, AV_LOG_FATAL, "Video pixel format is unknown, stream cannot be encoded\n");
2236 if (!codec->width || !codec->height) {
2237 codec->width = icodec->width;
2238 codec->height = icodec->height;
2241 ost->video_resample = codec->width != icodec->width ||
2242 codec->height != icodec->height ||
2243 codec->pix_fmt != icodec->pix_fmt;
2244 if (ost->video_resample) {
2245 codec->bits_per_raw_sample= frame_bits_per_raw_sample;
2248 ost->resample_height = icodec->height;
2249 ost->resample_width = icodec->width;
2250 ost->resample_pix_fmt = icodec->pix_fmt;
2252 if (!ost->frame_rate.num)
2253 ost->frame_rate = ist->st->r_frame_rate.num ? ist->st->r_frame_rate : (AVRational){25,1};
2254 if (ost->enc && ost->enc->supported_framerates && !ost->force_fps) {
2255 int idx = av_find_nearest_q_idx(ost->frame_rate, ost->enc->supported_framerates);
2256 ost->frame_rate = ost->enc->supported_framerates[idx];
2258 codec->time_base = (AVRational){ost->frame_rate.den, ost->frame_rate.num};
2259 if( av_q2d(codec->time_base) < 0.001 && video_sync_method
2260 && (video_sync_method==1 || (video_sync_method<0 && !(oc->oformat->flags & AVFMT_VARIABLE_FPS)))){
2261 av_log(oc, AV_LOG_WARNING, "Frame rate very high for a muxer not effciciently supporting it.\n"
2262 "Please consider specifiying a lower framerate, a different muxer or -vsync 2\n");
2266 if (configure_video_filters(ist, ost)) {
2267 av_log(NULL, AV_LOG_FATAL, "Error opening filters!\n");
2272 case AVMEDIA_TYPE_SUBTITLE:
2279 if (codec->codec_id != CODEC_ID_H264 &&
2280 (codec->flags & (CODEC_FLAG_PASS1 | CODEC_FLAG_PASS2))) {
2281 char logfilename[1024];
2284 snprintf(logfilename, sizeof(logfilename), "%s-%d.log",
2285 pass_logfilename_prefix ? pass_logfilename_prefix : DEFAULT_PASS_LOGFILENAME_PREFIX,
2287 if (codec->flags & CODEC_FLAG_PASS1) {
2288 f = fopen(logfilename, "wb");
2290 av_log(NULL, AV_LOG_FATAL, "Cannot write log file '%s' for pass-1 encoding: %s\n",
2291 logfilename, strerror(errno));
2297 size_t logbuffer_size;
2298 if (cmdutils_read_file(logfilename, &logbuffer, &logbuffer_size) < 0) {
2299 av_log(NULL, AV_LOG_FATAL, "Error reading log file '%s' for pass-2 encoding\n",
2303 codec->stats_in = logbuffer;
2307 if(codec->codec_type == AVMEDIA_TYPE_VIDEO){
2308 /* maximum video buffer size is 6-bytes per pixel, plus DPX header size */
2309 int size = codec->width * codec->height;
2310 bit_buffer_size = FFMAX(bit_buffer_size, 6*size + 1664);
2315 bit_buffer = av_malloc(bit_buffer_size);
2317 av_log(NULL, AV_LOG_ERROR, "Cannot allocate %d bytes output buffer\n",
2319 return AVERROR(ENOMEM);
2322 /* open each encoder */
2323 for (i = 0; i < nb_output_streams; i++) {
2324 ost = &output_streams[i];
2325 if (ost->encoding_needed) {
2326 AVCodec *codec = ost->enc;
2327 AVCodecContext *dec = input_streams[ost->source_index].st->codec;
2329 snprintf(error, sizeof(error), "Encoder (codec id %d) not found for output stream #%d:%d",
2330 ost->st->codec->codec_id, ost->file_index, ost->index);
2331 ret = AVERROR(EINVAL);
2334 if (dec->subtitle_header) {
2335 ost->st->codec->subtitle_header = av_malloc(dec->subtitle_header_size);
2336 if (!ost->st->codec->subtitle_header) {
2337 ret = AVERROR(ENOMEM);
2340 memcpy(ost->st->codec->subtitle_header, dec->subtitle_header, dec->subtitle_header_size);
2341 ost->st->codec->subtitle_header_size = dec->subtitle_header_size;
2343 if (avcodec_open2(ost->st->codec, codec, &ost->opts) < 0) {
2344 snprintf(error, sizeof(error), "Error while opening encoder for output stream #%d:%d - maybe incorrect parameters such as bit_rate, rate, width or height",
2345 ost->file_index, ost->index);
2346 ret = AVERROR(EINVAL);
2349 assert_codec_experimental(ost->st->codec, 1);
2350 assert_avoptions(ost->opts);
2351 if (ost->st->codec->bit_rate && ost->st->codec->bit_rate < 1000)
2352 av_log(NULL, AV_LOG_WARNING, "The bitrate parameter is set too low."
2353 "It takes bits/s as argument, not kbits/s\n");
2354 extra_size += ost->st->codec->extradata_size;
2356 if (ost->st->codec->me_threshold)
2357 input_streams[ost->source_index].st->codec->debug |= FF_DEBUG_MV;
2361 /* init input streams */
2362 for (i = 0; i < nb_input_streams; i++)
2363 if ((ret = init_input_stream(i, output_streams, nb_output_streams, error, sizeof(error))) < 0)
2366 /* discard unused programs */
2367 for (i = 0; i < nb_input_files; i++) {
2368 InputFile *ifile = &input_files[i];
2369 for (j = 0; j < ifile->ctx->nb_programs; j++) {
2370 AVProgram *p = ifile->ctx->programs[j];
2371 int discard = AVDISCARD_ALL;
2373 for (k = 0; k < p->nb_stream_indexes; k++)
2374 if (!input_streams[ifile->ist_index + p->stream_index[k]].discard) {
2375 discard = AVDISCARD_DEFAULT;
2378 p->discard = discard;
2382 /* open files and write file headers */
2383 for (i = 0; i < nb_output_files; i++) {
2384 oc = output_files[i].ctx;
2385 oc->interrupt_callback = int_cb;
2386 if (avformat_write_header(oc, &output_files[i].opts) < 0) {
2387 snprintf(error, sizeof(error), "Could not write header for output file #%d (incorrect codec parameters ?)", i);
2388 ret = AVERROR(EINVAL);
2391 // assert_avoptions(output_files[i].opts);
2392 if (strcmp(oc->oformat->name, "rtp")) {
2398 /* dump the file output parameters - cannot be done before in case
2400 for (i = 0; i < nb_output_files; i++) {
2401 av_dump_format(output_files[i].ctx, i, output_files[i].ctx->filename, 1);
2404 /* dump the stream mapping */
2405 av_log(NULL, AV_LOG_INFO, "Stream mapping:\n");
2406 for (i = 0; i < nb_output_streams; i++) {
2407 ost = &output_streams[i];
2409 if (ost->attachment_filename) {
2410 /* an attached file */
2411 av_log(NULL, AV_LOG_INFO, " File %s -> Stream #%d:%d\n",
2412 ost->attachment_filename, ost->file_index, ost->index);
2415 av_log(NULL, AV_LOG_INFO, " Stream #%d:%d -> #%d:%d",
2416 input_streams[ost->source_index].file_index,
2417 input_streams[ost->source_index].st->index,
2420 if (ost->sync_ist != &input_streams[ost->source_index])
2421 av_log(NULL, AV_LOG_INFO, " [sync #%d:%d]",
2422 ost->sync_ist->file_index,
2423 ost->sync_ist->st->index);
2424 if (ost->stream_copy)
2425 av_log(NULL, AV_LOG_INFO, " (copy)");
2427 av_log(NULL, AV_LOG_INFO, " (%s -> %s)", input_streams[ost->source_index].dec ?
2428 input_streams[ost->source_index].dec->name : "?",
2429 ost->enc ? ost->enc->name : "?");
2430 av_log(NULL, AV_LOG_INFO, "\n");
2434 av_log(NULL, AV_LOG_ERROR, "%s\n", error);
2439 print_sdp(output_files, nb_output_files);
2446 * The following code is the main loop of the file converter
2448 static int transcode(OutputFile *output_files,
2449 int nb_output_files,
2450 InputFile *input_files,
2454 AVFormatContext *is, *os;
2458 int no_packet_count=0;
2459 int64_t timer_start;
2462 if (!(no_packet = av_mallocz(nb_input_files)))
2465 ret = transcode_init(output_files, nb_output_files, input_files, nb_input_files);
2470 av_log(NULL, AV_LOG_INFO, "Press [q] to stop, [?] for help\n");
2471 avio_set_interrupt_cb(decode_interrupt_cb);
2475 timer_start = av_gettime();
2477 for(; received_sigterm == 0;) {
2478 int file_index, ist_index;
2483 ipts_min = INT64_MAX;
2485 /* if 'q' pressed, exits */
2489 /* read_key() returns 0 on EOF */
2493 if (key == '+') av_log_set_level(av_log_get_level()+10);
2494 if (key == '-') av_log_set_level(av_log_get_level()-10);
2495 if (key == 's') qp_hist ^= 1;
2498 do_hex_dump = do_pkt_dump = 0;
2499 } else if(do_pkt_dump){
2503 av_log_set_level(AV_LOG_DEBUG);
2505 if (key == 'd' || key == 'D'){
2508 debug = input_streams[0].st->codec->debug<<1;
2509 if(!debug) debug = 1;
2510 while(debug & (FF_DEBUG_DCT_COEFF|FF_DEBUG_VIS_QP|FF_DEBUG_VIS_MB_TYPE)) //unsupported, would just crash
2513 scanf("%d", &debug);
2514 for(i=0;i<nb_input_streams;i++) {
2515 input_streams[i].st->codec->debug = debug;
2517 for(i=0;i<nb_output_streams;i++) {
2518 ost = &output_streams[i];
2519 ost->st->codec->debug = debug;
2521 if(debug) av_log_set_level(AV_LOG_DEBUG);
2522 fprintf(stderr,"debug=%d\n", debug);
2525 fprintf(stderr, "key function\n"
2526 "? show this help\n"
2527 "+ increase verbosity\n"
2528 "- decrease verbosity\n"
2529 "D cycle through available debug modes\n"
2530 "h dump packets/hex press to cycle through the 3 states\n"
2532 "s Show QP histogram\n"
2537 /* select the stream that we must read now by looking at the
2538 smallest output pts */
2540 for (i = 0; i < nb_output_streams; i++) {
2544 ost = &output_streams[i];
2545 of = &output_files[ost->file_index];
2546 os = output_files[ost->file_index].ctx;
2547 ist = &input_streams[ost->source_index];
2548 if (ost->is_past_recording_time || no_packet[ist->file_index] ||
2549 (os->pb && avio_tell(os->pb) >= of->limit_filesize))
2551 opts = ost->st->pts.val * av_q2d(ost->st->time_base);
2553 if (!input_files[ist->file_index].eof_reached){
2554 if(ipts < ipts_min) {
2556 if(input_sync ) file_index = ist->file_index;
2558 if(opts < opts_min) {
2560 if(!input_sync) file_index = ist->file_index;
2563 if (ost->frame_number >= ost->max_frames) {
2565 for (j = 0; j < of->ctx->nb_streams; j++)
2566 output_streams[of->ost_index + j].is_past_recording_time = 1;
2570 /* if none, if is finished */
2571 if (file_index < 0) {
2572 if(no_packet_count){
2574 memset(no_packet, 0, nb_input_files);
2581 /* read a frame from it and output it in the fifo */
2582 is = input_files[file_index].ctx;
2583 ret= av_read_frame(is, &pkt);
2584 if(ret == AVERROR(EAGAIN)){
2585 no_packet[file_index]=1;
2590 input_files[file_index].eof_reached = 1;
2598 memset(no_packet, 0, nb_input_files);
2601 av_pkt_dump_log2(NULL, AV_LOG_DEBUG, &pkt, do_hex_dump,
2602 is->streams[pkt.stream_index]);
2604 /* the following test is needed in case new streams appear
2605 dynamically in stream : we ignore them */
2606 if (pkt.stream_index >= input_files[file_index].nb_streams)
2607 goto discard_packet;
2608 ist_index = input_files[file_index].ist_index + pkt.stream_index;
2609 ist = &input_streams[ist_index];
2611 goto discard_packet;
2613 if (pkt.dts != AV_NOPTS_VALUE)
2614 pkt.dts += av_rescale_q(input_files[ist->file_index].ts_offset, AV_TIME_BASE_Q, ist->st->time_base);
2615 if (pkt.pts != AV_NOPTS_VALUE)
2616 pkt.pts += av_rescale_q(input_files[ist->file_index].ts_offset, AV_TIME_BASE_Q, ist->st->time_base);
2618 if(pkt.pts != AV_NOPTS_VALUE)
2619 pkt.pts *= ist->ts_scale;
2620 if(pkt.dts != AV_NOPTS_VALUE)
2621 pkt.dts *= ist->ts_scale;
2623 // fprintf(stderr, "next:%"PRId64" dts:%"PRId64" off:%"PRId64" %d\n", ist->next_pts, pkt.dts, input_files[ist->file_index].ts_offset, ist->st->codec->codec_type);
2624 if (pkt.dts != AV_NOPTS_VALUE && ist->next_pts != AV_NOPTS_VALUE
2625 && (is->iformat->flags & AVFMT_TS_DISCONT)) {
2626 int64_t pkt_dts= av_rescale_q(pkt.dts, ist->st->time_base, AV_TIME_BASE_Q);
2627 int64_t delta= pkt_dts - ist->next_pts;
2628 if((FFABS(delta) > 1LL*dts_delta_threshold*AV_TIME_BASE || pkt_dts+1<ist->pts)&& !copy_ts){
2629 input_files[ist->file_index].ts_offset -= delta;
2630 av_log(NULL, AV_LOG_DEBUG, "timestamp discontinuity %"PRId64", new offset= %"PRId64"\n",
2631 delta, input_files[ist->file_index].ts_offset);
2632 pkt.dts-= av_rescale_q(delta, AV_TIME_BASE_Q, ist->st->time_base);
2633 if(pkt.pts != AV_NOPTS_VALUE)
2634 pkt.pts-= av_rescale_q(delta, AV_TIME_BASE_Q, ist->st->time_base);
2638 //fprintf(stderr,"read #%d.%d size=%d\n", ist->file_index, ist->st->index, pkt.size);
2639 if (output_packet(ist, output_streams, nb_output_streams, &pkt) < 0) {
2641 av_log(NULL, AV_LOG_ERROR, "Error while decoding stream #%d:%d\n",
2642 ist->file_index, ist->st->index);
2645 av_free_packet(&pkt);
2650 av_free_packet(&pkt);
2652 /* dump report by using the output first video and audio streams */
2653 print_report(output_files, output_streams, nb_output_streams, 0, timer_start);
2656 /* at the end of stream, we must flush the decoder buffers */
2657 for (i = 0; i < nb_input_streams; i++) {
2658 ist = &input_streams[i];
2659 if (ist->decoding_needed) {
2660 output_packet(ist, output_streams, nb_output_streams, NULL);
2663 flush_encoders(output_streams, nb_output_streams);
2667 /* write the trailer if needed and close file */
2668 for(i=0;i<nb_output_files;i++) {
2669 os = output_files[i].ctx;
2670 av_write_trailer(os);
2673 /* dump report by using the first video and audio streams */
2674 print_report(output_files, output_streams, nb_output_streams, 1, timer_start);
2676 /* close each encoder */
2677 for (i = 0; i < nb_output_streams; i++) {
2678 ost = &output_streams[i];
2679 if (ost->encoding_needed) {
2680 av_freep(&ost->st->codec->stats_in);
2681 avcodec_close(ost->st->codec);
2684 avfilter_graph_free(&ost->graph);
2688 /* close each decoder */
2689 for (i = 0; i < nb_input_streams; i++) {
2690 ist = &input_streams[i];
2691 if (ist->decoding_needed) {
2692 avcodec_close(ist->st->codec);
2700 av_freep(&bit_buffer);
2701 av_freep(&no_packet);
2703 if (output_streams) {
2704 for (i = 0; i < nb_output_streams; i++) {
2705 ost = &output_streams[i];
2707 if (ost->stream_copy)
2708 av_freep(&ost->st->codec->extradata);
2710 fclose(ost->logfile);
2711 ost->logfile = NULL;
2713 av_fifo_free(ost->fifo); /* works even if fifo is not
2714 initialized but set to zero */
2715 av_freep(&ost->st->codec->subtitle_header);
2716 av_free(ost->resample_frame.data[0]);
2717 av_free(ost->forced_kf_pts);
2718 if (ost->video_resample)
2719 sws_freeContext(ost->img_resample_ctx);
2721 audio_resample_close(ost->resample);
2722 if (ost->reformat_ctx)
2723 av_audio_convert_free(ost->reformat_ctx);
2724 av_dict_free(&ost->opts);
2731 static double parse_frame_aspect_ratio(const char *arg)
2738 p = strchr(arg, ':');
2740 x = strtol(arg, &end, 10);
2742 y = strtol(end+1, &end, 10);
2744 ar = (double)x / (double)y;
2746 ar = strtod(arg, NULL);
2749 av_log(NULL, AV_LOG_FATAL, "Incorrect aspect ratio specification.\n");
2755 static int opt_audio_codec(OptionsContext *o, const char *opt, const char *arg)
2757 return parse_option(o, "codec:a", arg, options);
2760 static int opt_video_codec(OptionsContext *o, const char *opt, const char *arg)
2762 return parse_option(o, "codec:v", arg, options);
2765 static int opt_subtitle_codec(OptionsContext *o, const char *opt, const char *arg)
2767 return parse_option(o, "codec:s", arg, options);
2770 static int opt_data_codec(OptionsContext *o, const char *opt, const char *arg)
2772 return parse_option(o, "codec:d", arg, options);
2775 static int opt_map(OptionsContext *o, const char *opt, const char *arg)
2777 StreamMap *m = NULL;
2778 int i, negative = 0, file_idx;
2779 int sync_file_idx = -1, sync_stream_idx;
2787 map = av_strdup(arg);
2789 /* parse sync stream first, just pick first matching stream */
2790 if (sync = strchr(map, ',')) {
2792 sync_file_idx = strtol(sync + 1, &sync, 0);
2793 if (sync_file_idx >= nb_input_files || sync_file_idx < 0) {
2794 av_log(NULL, AV_LOG_FATAL, "Invalid sync file index: %d.\n", sync_file_idx);
2799 for (i = 0; i < input_files[sync_file_idx].nb_streams; i++)
2800 if (check_stream_specifier(input_files[sync_file_idx].ctx,
2801 input_files[sync_file_idx].ctx->streams[i], sync) == 1) {
2802 sync_stream_idx = i;
2805 if (i == input_files[sync_file_idx].nb_streams) {
2806 av_log(NULL, AV_LOG_FATAL, "Sync stream specification in map %s does not "
2807 "match any streams.\n", arg);
2813 file_idx = strtol(map, &p, 0);
2814 if (file_idx >= nb_input_files || file_idx < 0) {
2815 av_log(NULL, AV_LOG_FATAL, "Invalid input file index: %d.\n", file_idx);
2819 /* disable some already defined maps */
2820 for (i = 0; i < o->nb_stream_maps; i++) {
2821 m = &o->stream_maps[i];
2822 if (file_idx == m->file_index &&
2823 check_stream_specifier(input_files[m->file_index].ctx,
2824 input_files[m->file_index].ctx->streams[m->stream_index],
2825 *p == ':' ? p + 1 : p) > 0)
2829 for (i = 0; i < input_files[file_idx].nb_streams; i++) {
2830 if (check_stream_specifier(input_files[file_idx].ctx, input_files[file_idx].ctx->streams[i],
2831 *p == ':' ? p + 1 : p) <= 0)
2833 o->stream_maps = grow_array(o->stream_maps, sizeof(*o->stream_maps),
2834 &o->nb_stream_maps, o->nb_stream_maps + 1);
2835 m = &o->stream_maps[o->nb_stream_maps - 1];
2837 m->file_index = file_idx;
2838 m->stream_index = i;
2840 if (sync_file_idx >= 0) {
2841 m->sync_file_index = sync_file_idx;
2842 m->sync_stream_index = sync_stream_idx;
2844 m->sync_file_index = file_idx;
2845 m->sync_stream_index = i;
2850 av_log(NULL, AV_LOG_FATAL, "Stream map '%s' matches no streams.\n", arg);
2858 static int opt_attach(OptionsContext *o, const char *opt, const char *arg)
2860 o->attachments = grow_array(o->attachments, sizeof(*o->attachments),
2861 &o->nb_attachments, o->nb_attachments + 1);
2862 o->attachments[o->nb_attachments - 1] = arg;
2866 static void parse_meta_type(char *arg, char *type, int *index)
2876 if (*(++arg) == ':')
2877 *index = strtol(++arg, NULL, 0);
2880 av_log(NULL, AV_LOG_FATAL, "Invalid metadata type %c.\n", *arg);
2887 static int opt_map_metadata(OptionsContext *o, const char *opt, const char *arg)
2889 MetadataMap *m, *m1;
2892 o->meta_data_maps = grow_array(o->meta_data_maps, sizeof(*o->meta_data_maps),
2893 &o->nb_meta_data_maps, o->nb_meta_data_maps + 1);
2895 m = &o->meta_data_maps[o->nb_meta_data_maps - 1][1];
2896 m->file = strtol(arg, &p, 0);
2897 parse_meta_type(*p ? p + 1 : p, &m->type, &m->index);
2899 m1 = &o->meta_data_maps[o->nb_meta_data_maps - 1][0];
2900 if (p = strchr(opt, ':'))
2901 parse_meta_type(p + 1, &m1->type, &m1->index);
2905 if (m->type == 'g' || m1->type == 'g')
2906 o->metadata_global_manual = 1;
2907 if (m->type == 's' || m1->type == 's')
2908 o->metadata_streams_manual = 1;
2909 if (m->type == 'c' || m1->type == 'c')
2910 o->metadata_chapters_manual = 1;
2915 static AVCodec *find_codec_or_die(const char *name, enum AVMediaType type, int encoder)
2917 const char *codec_string = encoder ? "encoder" : "decoder";
2921 avcodec_find_encoder_by_name(name) :
2922 avcodec_find_decoder_by_name(name);
2924 av_log(NULL, AV_LOG_FATAL, "Unknown %s '%s'\n", codec_string, name);
2927 if(codec->type != type) {
2928 av_log(NULL, AV_LOG_FATAL, "Invalid %s type '%s'\n", codec_string, name);
2934 static AVCodec *choose_decoder(OptionsContext *o, AVFormatContext *s, AVStream *st)
2936 char *codec_name = NULL;
2938 MATCH_PER_STREAM_OPT(codec_names, str, codec_name, s, st);
2940 AVCodec *codec = find_codec_or_die(codec_name, st->codec->codec_type, 0);
2941 st->codec->codec_id = codec->id;
2944 return avcodec_find_decoder(st->codec->codec_id);
2948 * Add all the streams from the given input file to the global
2949 * list of input streams.
2951 static void add_input_streams(OptionsContext *o, AVFormatContext *ic)
2953 int i, rfps, rfps_base;
2955 for (i = 0; i < ic->nb_streams; i++) {
2956 AVStream *st = ic->streams[i];
2957 AVCodecContext *dec = st->codec;
2960 input_streams = grow_array(input_streams, sizeof(*input_streams), &nb_input_streams, nb_input_streams + 1);
2961 ist = &input_streams[nb_input_streams - 1];
2963 ist->file_index = nb_input_files;
2965 ist->opts = filter_codec_opts(codec_opts, ist->st->codec->codec_id, ic, st);
2967 ist->ts_scale = 1.0;
2968 MATCH_PER_STREAM_OPT(ts_scale, dbl, ist->ts_scale, ic, st);
2970 ist->dec = choose_decoder(o, ic, st);
2972 switch (dec->codec_type) {
2973 case AVMEDIA_TYPE_AUDIO:
2975 ist->dec = avcodec_find_decoder(dec->codec_id);
2976 if(o->audio_disable)
2977 st->discard= AVDISCARD_ALL;
2979 case AVMEDIA_TYPE_VIDEO:
2981 ist->dec = avcodec_find_decoder(dec->codec_id);
2982 rfps = ic->streams[i]->r_frame_rate.num;
2983 rfps_base = ic->streams[i]->r_frame_rate.den;
2985 dec->flags |= CODEC_FLAG_EMU_EDGE;
2988 if (dec->time_base.den != rfps*dec->ticks_per_frame || dec->time_base.num != rfps_base) {
2990 av_log(NULL, AV_LOG_INFO,"\nSeems stream %d codec frame rate differs from container frame rate: %2.2f (%d/%d) -> %2.2f (%d/%d)\n",
2991 i, (float)dec->time_base.den / dec->time_base.num, dec->time_base.den, dec->time_base.num,
2992 (float)rfps / rfps_base, rfps, rfps_base);
2995 if (o->video_disable)
2996 st->discard= AVDISCARD_ALL;
2997 else if(video_discard)
2998 st->discard= video_discard;
3000 case AVMEDIA_TYPE_DATA:
3002 case AVMEDIA_TYPE_SUBTITLE:
3004 ist->dec = avcodec_find_decoder(dec->codec_id);
3005 if(o->subtitle_disable)
3006 st->discard = AVDISCARD_ALL;
3008 case AVMEDIA_TYPE_ATTACHMENT:
3009 case AVMEDIA_TYPE_UNKNOWN:
3017 static void assert_file_overwrite(const char *filename)
3019 if (!file_overwrite &&
3020 (strchr(filename, ':') == NULL || filename[1] == ':' ||
3021 av_strstart(filename, "file:", NULL))) {
3022 if (avio_check(filename, 0) == 0) {
3024 fprintf(stderr,"File '%s' already exists. Overwrite ? [y/N] ", filename);
3026 if (!read_yesno()) {
3027 fprintf(stderr, "Not overwriting - exiting\n");
3032 fprintf(stderr,"File '%s' already exists. Exiting.\n", filename);
3039 static void dump_attachment(AVStream *st, const char *filename)
3042 AVIOContext *out = NULL;
3043 AVDictionaryEntry *e;
3045 if (!st->codec->extradata_size) {
3046 av_log(NULL, AV_LOG_WARNING, "No extradata to dump in stream #%d:%d.\n",
3047 nb_input_files - 1, st->index);
3050 if (!*filename && (e = av_dict_get(st->metadata, "filename", NULL, 0)))
3051 filename = e->value;
3053 av_log(NULL, AV_LOG_FATAL, "No filename specified and no 'filename' tag"
3054 "in stream #%d:%d.\n", nb_input_files - 1, st->index);
3058 assert_file_overwrite(filename);
3060 if ((ret = avio_open2(&out, filename, AVIO_FLAG_WRITE, &int_cb, NULL)) < 0) {
3061 av_log(NULL, AV_LOG_FATAL, "Could not open file %s for writing.\n",
3066 avio_write(out, st->codec->extradata, st->codec->extradata_size);
3071 static int opt_input_file(OptionsContext *o, const char *opt, const char *filename)
3073 AVFormatContext *ic;
3074 AVInputFormat *file_iformat = NULL;
3078 AVDictionary **opts;
3079 int orig_nb_streams; // number of streams before avformat_find_stream_info
3082 if (!(file_iformat = av_find_input_format(o->format))) {
3083 av_log(NULL, AV_LOG_FATAL, "Unknown input format: '%s'\n", o->format);
3088 if (!strcmp(filename, "-"))
3091 using_stdin |= !strncmp(filename, "pipe:", 5) ||
3092 !strcmp(filename, "/dev/stdin");
3094 /* get default parameters from command line */
3095 ic = avformat_alloc_context();
3097 print_error(filename, AVERROR(ENOMEM));
3100 if (o->nb_audio_sample_rate) {
3101 snprintf(buf, sizeof(buf), "%d", o->audio_sample_rate[o->nb_audio_sample_rate - 1].u.i);
3102 av_dict_set(&format_opts, "sample_rate", buf, 0);
3104 if (o->nb_audio_channels) {
3105 snprintf(buf, sizeof(buf), "%d", o->audio_channels[o->nb_audio_channels - 1].u.i);
3106 av_dict_set(&format_opts, "channels", buf, 0);
3108 if (o->nb_frame_rates) {
3109 av_dict_set(&format_opts, "framerate", o->frame_rates[o->nb_frame_rates - 1].u.str, 0);
3111 if (o->nb_frame_sizes) {
3112 av_dict_set(&format_opts, "video_size", o->frame_sizes[o->nb_frame_sizes - 1].u.str, 0);
3114 if (o->nb_frame_pix_fmts)
3115 av_dict_set(&format_opts, "pixel_format", o->frame_pix_fmts[o->nb_frame_pix_fmts - 1].u.str, 0);
3117 ic->flags |= AVFMT_FLAG_NONBLOCK;
3118 ic->interrupt_callback = int_cb;
3120 /* open the input file with generic libav function */
3121 err = avformat_open_input(&ic, filename, file_iformat, &format_opts);
3123 print_error(filename, err);
3126 assert_avoptions(format_opts);
3128 /* apply forced codec ids */
3129 for (i = 0; i < ic->nb_streams; i++)
3130 choose_decoder(o, ic, ic->streams[i]);
3132 /* Set AVCodecContext options for avformat_find_stream_info */
3133 opts = setup_find_stream_info_opts(ic, codec_opts);
3134 orig_nb_streams = ic->nb_streams;
3136 /* If not enough info to get the stream parameters, we decode the
3137 first frames to get it. (used in mpeg case for example) */
3138 ret = avformat_find_stream_info(ic, opts);
3140 av_log(NULL, AV_LOG_FATAL, "%s: could not find codec parameters\n", filename);
3141 av_close_input_file(ic);
3145 timestamp = o->start_time;
3146 /* add the stream start time */
3147 if (ic->start_time != AV_NOPTS_VALUE)
3148 timestamp += ic->start_time;
3150 /* if seeking requested, we execute it */
3151 if (o->start_time != 0) {
3152 ret = av_seek_frame(ic, -1, timestamp, AVSEEK_FLAG_BACKWARD);
3154 av_log(NULL, AV_LOG_WARNING, "%s: could not seek to position %0.3f\n",
3155 filename, (double)timestamp / AV_TIME_BASE);
3159 /* update the current parameters so that they match the one of the input stream */
3160 add_input_streams(o, ic);
3162 /* dump the file content */
3163 av_dump_format(ic, nb_input_files, filename, 0);
3165 input_files = grow_array(input_files, sizeof(*input_files), &nb_input_files, nb_input_files + 1);
3166 input_files[nb_input_files - 1].ctx = ic;
3167 input_files[nb_input_files - 1].ist_index = nb_input_streams - ic->nb_streams;
3168 input_files[nb_input_files - 1].ts_offset = o->input_ts_offset - (copy_ts ? 0 : timestamp);
3169 input_files[nb_input_files - 1].nb_streams = ic->nb_streams;
3170 input_files[nb_input_files - 1].rate_emu = o->rate_emu;
3172 for (i = 0; i < o->nb_dump_attachment; i++) {
3175 for (j = 0; j < ic->nb_streams; j++) {
3176 AVStream *st = ic->streams[j];
3178 if (check_stream_specifier(ic, st, o->dump_attachment[i].specifier) == 1)
3179 dump_attachment(st, o->dump_attachment[i].u.str);
3183 for (i = 0; i < orig_nb_streams; i++)
3184 av_dict_free(&opts[i]);
3191 static void parse_forced_key_frames(char *kf, OutputStream *ost,
3192 AVCodecContext *avctx)
3198 for (p = kf; *p; p++)
3201 ost->forced_kf_count = n;
3202 ost->forced_kf_pts = av_malloc(sizeof(*ost->forced_kf_pts) * n);
3203 if (!ost->forced_kf_pts) {
3204 av_log(NULL, AV_LOG_FATAL, "Could not allocate forced key frames array.\n");
3207 for (i = 0; i < n; i++) {
3208 p = i ? strchr(p, ',') + 1 : kf;
3209 t = parse_time_or_die("force_key_frames", p, 1);
3210 ost->forced_kf_pts[i] = av_rescale_q(t, AV_TIME_BASE_Q, avctx->time_base);
3214 static uint8_t *get_line(AVIOContext *s)
3220 if (avio_open_dyn_buf(&line) < 0) {
3221 av_log(NULL, AV_LOG_FATAL, "Could not alloc buffer for reading preset.\n");
3225 while ((c = avio_r8(s)) && c != '\n')
3228 avio_close_dyn_buf(line, &buf);
3233 static int get_preset_file_2(const char *preset_name, const char *codec_name, AVIOContext **s)
3236 char filename[1000];
3237 const char *base[3] = { getenv("AVCONV_DATADIR"),
3242 for (i = 0; i < FF_ARRAY_ELEMS(base) && ret; i++) {
3246 snprintf(filename, sizeof(filename), "%s%s/%s-%s.avpreset", base[i],
3247 i != 1 ? "" : "/.avconv", codec_name, preset_name);
3248 ret = avio_open2(s, filename, AVIO_FLAG_READ, &int_cb, NULL);
3251 snprintf(filename, sizeof(filename), "%s%s/%s.avpreset", base[i],
3252 i != 1 ? "" : "/.avconv", preset_name);
3253 ret = avio_open2(s, filename, AVIO_FLAG_READ, &int_cb, NULL);
3259 static void choose_encoder(OptionsContext *o, AVFormatContext *s, OutputStream *ost)
3261 char *codec_name = NULL;
3263 MATCH_PER_STREAM_OPT(codec_names, str, codec_name, s, ost->st);
3265 ost->st->codec->codec_id = av_guess_codec(s->oformat, NULL, s->filename,
3266 NULL, ost->st->codec->codec_type);
3267 ost->enc = avcodec_find_encoder(ost->st->codec->codec_id);
3268 } else if (!strcmp(codec_name, "copy"))
3269 ost->stream_copy = 1;
3271 ost->enc = find_codec_or_die(codec_name, ost->st->codec->codec_type, 1);
3272 ost->st->codec->codec_id = ost->enc->id;
3276 static OutputStream *new_output_stream(OptionsContext *o, AVFormatContext *oc, enum AVMediaType type)
3279 AVStream *st = avformat_new_stream(oc, NULL);
3280 int idx = oc->nb_streams - 1, ret = 0;
3281 char *bsf = NULL, *next, *codec_tag = NULL;
3282 AVBitStreamFilterContext *bsfc, *bsfc_prev = NULL;
3284 char *buf = NULL, *arg = NULL, *preset = NULL;
3285 AVIOContext *s = NULL;
3288 av_log(NULL, AV_LOG_FATAL, "Could not alloc stream.\n");
3292 if (oc->nb_streams - 1 < o->nb_streamid_map)
3293 st->id = o->streamid_map[oc->nb_streams - 1];
3295 output_streams = grow_array(output_streams, sizeof(*output_streams), &nb_output_streams,
3296 nb_output_streams + 1);
3297 ost = &output_streams[nb_output_streams - 1];
3298 ost->file_index = nb_output_files;
3301 st->codec->codec_type = type;
3302 choose_encoder(o, oc, ost);
3304 ost->opts = filter_codec_opts(codec_opts, ost->enc->id, oc, st);
3307 avcodec_get_context_defaults3(st->codec, ost->enc);
3308 st->codec->codec_type = type; // XXX hack, avcodec_get_context_defaults2() sets type to unknown for stream copy
3310 MATCH_PER_STREAM_OPT(presets, str, preset, oc, st);
3311 if (preset && (!(ret = get_preset_file_2(preset, ost->enc->name, &s)))) {
3314 if (!buf[0] || buf[0] == '#') {
3318 if (!(arg = strchr(buf, '='))) {
3319 av_log(NULL, AV_LOG_FATAL, "Invalid line found in the preset file.\n");
3323 av_dict_set(&ost->opts, buf, arg, AV_DICT_DONT_OVERWRITE);
3325 } while (!s->eof_reached);
3329 av_log(NULL, AV_LOG_FATAL,
3330 "Preset %s specified for stream %d:%d, but could not be opened.\n",
3331 preset, ost->file_index, ost->index);
3335 ost->max_frames = INT64_MAX;
3336 MATCH_PER_STREAM_OPT(max_frames, i64, ost->max_frames, oc, st);
3338 MATCH_PER_STREAM_OPT(bitstream_filters, str, bsf, oc, st);
3340 if (next = strchr(bsf, ','))
3342 if (!(bsfc = av_bitstream_filter_init(bsf))) {
3343 av_log(NULL, AV_LOG_FATAL, "Unknown bitstream filter %s\n", bsf);
3347 bsfc_prev->next = bsfc;
3349 ost->bitstream_filters = bsfc;
3355 MATCH_PER_STREAM_OPT(codec_tags, str, codec_tag, oc, st);
3357 uint32_t tag = strtol(codec_tag, &next, 0);
3359 tag = AV_RL32(codec_tag);
3360 st->codec->codec_tag = tag;
3363 MATCH_PER_STREAM_OPT(qscale, dbl, qscale, oc, st);
3364 if (qscale >= 0 || same_quant) {
3365 st->codec->flags |= CODEC_FLAG_QSCALE;
3366 st->codec->global_quality = FF_QP2LAMBDA * qscale;
3369 if (oc->oformat->flags & AVFMT_GLOBALHEADER)
3370 st->codec->flags |= CODEC_FLAG_GLOBAL_HEADER;
3372 av_opt_get_int(sws_opts, "sws_flags", 0, &ost->sws_flags);
3376 static void parse_matrix_coeffs(uint16_t *dest, const char *str)
3379 const char *p = str;
3386 av_log(NULL, AV_LOG_FATAL, "Syntax error in matrix \"%s\" at coeff %d\n", str, i);
3393 static OutputStream *new_video_stream(OptionsContext *o, AVFormatContext *oc)
3397 AVCodecContext *video_enc;
3399 ost = new_output_stream(o, oc, AVMEDIA_TYPE_VIDEO);
3401 video_enc = st->codec;
3403 if (!ost->stream_copy) {
3404 const char *p = NULL;
3405 char *forced_key_frames = NULL, *frame_rate = NULL, *frame_size = NULL;
3406 char *frame_aspect_ratio = NULL, *frame_pix_fmt = NULL;
3407 char *intra_matrix = NULL, *inter_matrix = NULL, *filters = NULL;
3410 MATCH_PER_STREAM_OPT(frame_rates, str, frame_rate, oc, st);
3411 if (frame_rate && av_parse_video_rate(&ost->frame_rate, frame_rate) < 0) {
3412 av_log(NULL, AV_LOG_FATAL, "Invalid framerate value: %s\n", frame_rate);
3416 MATCH_PER_STREAM_OPT(frame_sizes, str, frame_size, oc, st);
3417 if (frame_size && av_parse_video_size(&video_enc->width, &video_enc->height, frame_size) < 0) {
3418 av_log(NULL, AV_LOG_FATAL, "Invalid frame size: %s.\n", frame_size);
3422 MATCH_PER_STREAM_OPT(frame_aspect_ratios, str, frame_aspect_ratio, oc, st);
3423 if (frame_aspect_ratio)
3424 ost->frame_aspect_ratio = parse_frame_aspect_ratio(frame_aspect_ratio);
3426 MATCH_PER_STREAM_OPT(frame_pix_fmts, str, frame_pix_fmt, oc, st);
3427 if (frame_pix_fmt && (video_enc->pix_fmt = av_get_pix_fmt(frame_pix_fmt)) == PIX_FMT_NONE) {
3428 av_log(NULL, AV_LOG_FATAL, "Unknown pixel format requested: %s.\n", frame_pix_fmt);
3431 st->sample_aspect_ratio = video_enc->sample_aspect_ratio;
3433 MATCH_PER_STREAM_OPT(intra_matrices, str, intra_matrix, oc, st);
3435 if (!(video_enc->intra_matrix = av_mallocz(sizeof(*video_enc->intra_matrix) * 64))) {
3436 av_log(NULL, AV_LOG_FATAL, "Could not allocate memory for intra matrix.\n");
3439 parse_matrix_coeffs(video_enc->intra_matrix, intra_matrix);
3441 MATCH_PER_STREAM_OPT(inter_matrices, str, inter_matrix, oc, st);
3443 if (!(video_enc->inter_matrix = av_mallocz(sizeof(*video_enc->inter_matrix) * 64))) {
3444 av_log(NULL, AV_LOG_FATAL, "Could not allocate memory for inter matrix.\n");
3447 parse_matrix_coeffs(video_enc->inter_matrix, inter_matrix);
3450 MATCH_PER_STREAM_OPT(rc_overrides, str, p, oc, st);
3453 int e=sscanf(p, "%d,%d,%d", &start, &end, &q);
3455 av_log(NULL, AV_LOG_FATAL, "error parsing rc_override\n");
3458 video_enc->rc_override=
3459 av_realloc(video_enc->rc_override,
3460 sizeof(RcOverride)*(i+1));
3461 video_enc->rc_override[i].start_frame= start;
3462 video_enc->rc_override[i].end_frame = end;
3464 video_enc->rc_override[i].qscale= q;
3465 video_enc->rc_override[i].quality_factor= 1.0;
3468 video_enc->rc_override[i].qscale= 0;
3469 video_enc->rc_override[i].quality_factor= -q/100.0;
3474 video_enc->rc_override_count=i;
3475 if (!video_enc->rc_initial_buffer_occupancy)
3476 video_enc->rc_initial_buffer_occupancy = video_enc->rc_buffer_size*3/4;
3477 video_enc->intra_dc_precision= intra_dc_precision - 8;
3482 video_enc->flags |= CODEC_FLAG_PASS1;
3484 video_enc->flags |= CODEC_FLAG_PASS2;
3488 MATCH_PER_STREAM_OPT(forced_key_frames, str, forced_key_frames, oc, st);
3489 if (forced_key_frames)
3490 parse_forced_key_frames(forced_key_frames, ost, video_enc);
3492 MATCH_PER_STREAM_OPT(force_fps, i, ost->force_fps, oc, st);
3494 ost->top_field_first = -1;
3495 MATCH_PER_STREAM_OPT(top_field_first, i, ost->top_field_first, oc, st);
3497 MATCH_PER_STREAM_OPT(copy_initial_nonkeyframes, i, ost->copy_initial_nonkeyframes, oc ,st);
3500 MATCH_PER_STREAM_OPT(filters, str, filters, oc, st);
3502 ost->avfilter = av_strdup(filters);
3509 static OutputStream *new_audio_stream(OptionsContext *o, AVFormatContext *oc)
3513 AVCodecContext *audio_enc;
3515 ost = new_output_stream(o, oc, AVMEDIA_TYPE_AUDIO);
3518 audio_enc = st->codec;
3519 audio_enc->codec_type = AVMEDIA_TYPE_AUDIO;
3521 if (!ost->stream_copy) {
3522 char *sample_fmt = NULL;
3524 MATCH_PER_STREAM_OPT(audio_channels, i, audio_enc->channels, oc, st);
3526 MATCH_PER_STREAM_OPT(sample_fmts, str, sample_fmt, oc, st);
3528 (audio_enc->sample_fmt = av_get_sample_fmt(sample_fmt)) == AV_SAMPLE_FMT_NONE) {
3529 av_log(NULL, AV_LOG_FATAL, "Invalid sample format '%s'\n", sample_fmt);
3533 MATCH_PER_STREAM_OPT(audio_sample_rate, i, audio_enc->sample_rate, oc, st);
3539 static OutputStream *new_data_stream(OptionsContext *o, AVFormatContext *oc)
3543 ost = new_output_stream(o, oc, AVMEDIA_TYPE_DATA);
3544 if (!ost->stream_copy) {
3545 av_log(NULL, AV_LOG_FATAL, "Data stream encoding not supported yet (only streamcopy)\n");
3552 static OutputStream *new_attachment_stream(OptionsContext *o, AVFormatContext *oc)
3554 OutputStream *ost = new_output_stream(o, oc, AVMEDIA_TYPE_ATTACHMENT);
3555 ost->stream_copy = 1;
3559 static OutputStream *new_subtitle_stream(OptionsContext *o, AVFormatContext *oc)
3563 AVCodecContext *subtitle_enc;
3565 ost = new_output_stream(o, oc, AVMEDIA_TYPE_SUBTITLE);
3567 subtitle_enc = st->codec;
3569 subtitle_enc->codec_type = AVMEDIA_TYPE_SUBTITLE;
3574 /* arg format is "output-stream-index:streamid-value". */
3575 static int opt_streamid(OptionsContext *o, const char *opt, const char *arg)
3581 av_strlcpy(idx_str, arg, sizeof(idx_str));
3582 p = strchr(idx_str, ':');
3584 av_log(NULL, AV_LOG_FATAL,
3585 "Invalid value '%s' for option '%s', required syntax is 'index:value'\n",
3590 idx = parse_number_or_die(opt, idx_str, OPT_INT, 0, MAX_STREAMS-1);
3591 o->streamid_map = grow_array(o->streamid_map, sizeof(*o->streamid_map), &o->nb_streamid_map, idx+1);
3592 o->streamid_map[idx] = parse_number_or_die(opt, p, OPT_INT, 0, INT_MAX);
3596 static int copy_chapters(InputFile *ifile, OutputFile *ofile, int copy_metadata)
3598 AVFormatContext *is = ifile->ctx;
3599 AVFormatContext *os = ofile->ctx;
3602 for (i = 0; i < is->nb_chapters; i++) {
3603 AVChapter *in_ch = is->chapters[i], *out_ch;
3604 int64_t ts_off = av_rescale_q(ofile->start_time - ifile->ts_offset,
3605 AV_TIME_BASE_Q, in_ch->time_base);
3606 int64_t rt = (ofile->recording_time == INT64_MAX) ? INT64_MAX :
3607 av_rescale_q(ofile->recording_time, AV_TIME_BASE_Q, in_ch->time_base);
3610 if (in_ch->end < ts_off)
3612 if (rt != INT64_MAX && in_ch->start > rt + ts_off)
3615 out_ch = av_mallocz(sizeof(AVChapter));
3617 return AVERROR(ENOMEM);
3619 out_ch->id = in_ch->id;
3620 out_ch->time_base = in_ch->time_base;
3621 out_ch->start = FFMAX(0, in_ch->start - ts_off);
3622 out_ch->end = FFMIN(rt, in_ch->end - ts_off);
3625 av_dict_copy(&out_ch->metadata, in_ch->metadata, 0);
3628 os->chapters = av_realloc(os->chapters, sizeof(AVChapter)*os->nb_chapters);
3630 return AVERROR(ENOMEM);
3631 os->chapters[os->nb_chapters - 1] = out_ch;
3636 static int read_ffserver_streams(OptionsContext *o, AVFormatContext *s, const char *filename)
3639 AVFormatContext *ic = avformat_alloc_context();
3641 ic->interrupt_callback = int_cb;
3642 err = avformat_open_input(&ic, filename, NULL, NULL);
3645 /* copy stream format */
3646 for(i=0;i<ic->nb_streams;i++) {
3651 codec = avcodec_find_encoder(ic->streams[i]->codec->codec_id);
3652 ost = new_output_stream(o, s, codec->type);
3655 // FIXME: a more elegant solution is needed
3656 memcpy(st, ic->streams[i], sizeof(AVStream));
3657 st->info = av_malloc(sizeof(*st->info));
3658 memcpy(st->info, ic->streams[i]->info, sizeof(*st->info));
3659 avcodec_copy_context(st->codec, ic->streams[i]->codec);
3661 if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO && !ost->stream_copy)
3662 choose_sample_fmt(st, codec);
3663 else if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO && !ost->stream_copy)
3664 choose_pixel_fmt(st, codec);
3667 av_close_input_file(ic);
3671 static void opt_output_file(void *optctx, const char *filename)
3673 OptionsContext *o = optctx;
3674 AVFormatContext *oc;
3676 AVOutputFormat *file_oformat;
3680 if (!strcmp(filename, "-"))
3683 err = avformat_alloc_output_context2(&oc, NULL, o->format, filename);
3685 print_error(filename, err);
3689 file_oformat= oc->oformat;
3690 oc->interrupt_callback = int_cb;
3692 if (!strcmp(file_oformat->name, "ffm") &&
3693 av_strstart(filename, "http:", NULL)) {
3694 /* special case for files sent to ffserver: we get the stream
3695 parameters from ffserver */
3696 int err = read_ffserver_streams(o, oc, filename);
3698 print_error(filename, err);
3701 } else if (!o->nb_stream_maps) {
3702 /* pick the "best" stream of each type */
3703 #define NEW_STREAM(type, index)\
3705 ost = new_ ## type ## _stream(o, oc);\
3706 ost->source_index = index;\
3707 ost->sync_ist = &input_streams[index];\
3708 input_streams[index].discard = 0;\
3711 /* video: highest resolution */
3712 if (!o->video_disable && oc->oformat->video_codec != CODEC_ID_NONE) {
3713 int area = 0, idx = -1;
3714 for (i = 0; i < nb_input_streams; i++) {
3715 ist = &input_streams[i];
3716 if (ist->st->codec->codec_type == AVMEDIA_TYPE_VIDEO &&
3717 ist->st->codec->width * ist->st->codec->height > area) {
3718 area = ist->st->codec->width * ist->st->codec->height;
3722 NEW_STREAM(video, idx);
3725 /* audio: most channels */
3726 if (!o->audio_disable && oc->oformat->audio_codec != CODEC_ID_NONE) {
3727 int channels = 0, idx = -1;
3728 for (i = 0; i < nb_input_streams; i++) {
3729 ist = &input_streams[i];
3730 if (ist->st->codec->codec_type == AVMEDIA_TYPE_AUDIO &&
3731 ist->st->codec->channels > channels) {
3732 channels = ist->st->codec->channels;
3736 NEW_STREAM(audio, idx);
3739 /* subtitles: pick first */
3740 if (!o->subtitle_disable && oc->oformat->subtitle_codec != CODEC_ID_NONE) {
3741 for (i = 0; i < nb_input_streams; i++)
3742 if (input_streams[i].st->codec->codec_type == AVMEDIA_TYPE_SUBTITLE) {
3743 NEW_STREAM(subtitle, i);
3747 /* do something with data? */
3749 for (i = 0; i < o->nb_stream_maps; i++) {
3750 StreamMap *map = &o->stream_maps[i];
3755 ist = &input_streams[input_files[map->file_index].ist_index + map->stream_index];
3756 switch (ist->st->codec->codec_type) {
3757 case AVMEDIA_TYPE_VIDEO: ost = new_video_stream(o, oc); break;
3758 case AVMEDIA_TYPE_AUDIO: ost = new_audio_stream(o, oc); break;
3759 case AVMEDIA_TYPE_SUBTITLE: ost = new_subtitle_stream(o, oc); break;
3760 case AVMEDIA_TYPE_DATA: ost = new_data_stream(o, oc); break;
3761 case AVMEDIA_TYPE_ATTACHMENT: ost = new_attachment_stream(o, oc); break;
3763 av_log(NULL, AV_LOG_FATAL, "Cannot map stream #%d:%d - unsupported type.\n",
3764 map->file_index, map->stream_index);
3768 ost->source_index = input_files[map->file_index].ist_index + map->stream_index;
3769 ost->sync_ist = &input_streams[input_files[map->sync_file_index].ist_index +
3770 map->sync_stream_index];
3775 /* handle attached files */
3776 for (i = 0; i < o->nb_attachments; i++) {
3778 uint8_t *attachment;
3782 if ((err = avio_open2(&pb, o->attachments[i], AVIO_FLAG_READ, &int_cb, NULL)) < 0) {
3783 av_log(NULL, AV_LOG_FATAL, "Could not open attachment file %s.\n",
3787 if ((len = avio_size(pb)) <= 0) {
3788 av_log(NULL, AV_LOG_FATAL, "Could not get size of the attachment %s.\n",
3792 if (!(attachment = av_malloc(len))) {
3793 av_log(NULL, AV_LOG_FATAL, "Attachment %s too large to fit into memory.\n",
3797 avio_read(pb, attachment, len);
3799 ost = new_attachment_stream(o, oc);
3800 ost->stream_copy = 0;
3801 ost->source_index = -1;
3802 ost->attachment_filename = o->attachments[i];
3803 ost->st->codec->extradata = attachment;
3804 ost->st->codec->extradata_size = len;
3806 p = strrchr(o->attachments[i], '/');
3807 av_dict_set(&ost->st->metadata, "filename", (p && *p) ? p + 1 : o->attachments[i], AV_DICT_DONT_OVERWRITE);
3811 output_files = grow_array(output_files, sizeof(*output_files), &nb_output_files, nb_output_files + 1);
3812 output_files[nb_output_files - 1].ctx = oc;
3813 output_files[nb_output_files - 1].ost_index = nb_output_streams - oc->nb_streams;
3814 output_files[nb_output_files - 1].recording_time = o->recording_time;
3815 output_files[nb_output_files - 1].start_time = o->start_time;
3816 output_files[nb_output_files - 1].limit_filesize = o->limit_filesize;
3817 av_dict_copy(&output_files[nb_output_files - 1].opts, format_opts, 0);
3819 /* check filename in case of an image number is expected */
3820 if (oc->oformat->flags & AVFMT_NEEDNUMBER) {
3821 if (!av_filename_number_test(oc->filename)) {
3822 print_error(oc->filename, AVERROR(EINVAL));
3827 if (!(oc->oformat->flags & AVFMT_NOFILE)) {
3828 /* test if it already exists to avoid loosing precious files */
3829 assert_file_overwrite(filename);
3832 if ((err = avio_open2(&oc->pb, filename, AVIO_FLAG_WRITE,
3833 &oc->interrupt_callback,
3834 &output_files[nb_output_files - 1].opts)) < 0) {
3835 print_error(filename, err);
3840 if (o->mux_preload) {
3842 snprintf(buf, sizeof(buf), "%d", (int)(o->mux_preload*AV_TIME_BASE));
3843 av_dict_set(&output_files[nb_output_files - 1].opts, "preload", buf, 0);
3845 oc->max_delay = (int)(o->mux_max_delay * AV_TIME_BASE);
3848 if (o->chapters_input_file >= nb_input_files) {
3849 if (o->chapters_input_file == INT_MAX) {
3850 /* copy chapters from the first input file that has them*/
3851 o->chapters_input_file = -1;
3852 for (i = 0; i < nb_input_files; i++)
3853 if (input_files[i].ctx->nb_chapters) {
3854 o->chapters_input_file = i;
3858 av_log(NULL, AV_LOG_FATAL, "Invalid input file index %d in chapter mapping.\n",
3859 o->chapters_input_file);
3863 if (o->chapters_input_file >= 0)
3864 copy_chapters(&input_files[o->chapters_input_file], &output_files[nb_output_files - 1],
3865 !o->metadata_chapters_manual);
3868 for (i = 0; i < o->nb_meta_data_maps; i++) {
3869 AVFormatContext *files[2];
3870 AVDictionary **meta[2];
3873 #define METADATA_CHECK_INDEX(index, nb_elems, desc)\
3874 if ((index) < 0 || (index) >= (nb_elems)) {\
3875 av_log(NULL, AV_LOG_FATAL, "Invalid %s index %d while processing metadata maps\n",\
3880 int in_file_index = o->meta_data_maps[i][1].file;
3881 if (in_file_index < 0)
3883 METADATA_CHECK_INDEX(in_file_index, nb_input_files, "input file")
3886 files[1] = input_files[in_file_index].ctx;
3888 for (j = 0; j < 2; j++) {
3889 MetadataMap *map = &o->meta_data_maps[i][j];
3891 switch (map->type) {
3893 meta[j] = &files[j]->metadata;
3896 METADATA_CHECK_INDEX(map->index, files[j]->nb_streams, "stream")
3897 meta[j] = &files[j]->streams[map->index]->metadata;
3900 METADATA_CHECK_INDEX(map->index, files[j]->nb_chapters, "chapter")
3901 meta[j] = &files[j]->chapters[map->index]->metadata;
3904 METADATA_CHECK_INDEX(map->index, files[j]->nb_programs, "program")
3905 meta[j] = &files[j]->programs[map->index]->metadata;
3910 av_dict_copy(meta[0], *meta[1], AV_DICT_DONT_OVERWRITE);
3913 /* copy global metadata by default */
3914 if (!o->metadata_global_manual && nb_input_files)
3915 av_dict_copy(&oc->metadata, input_files[0].ctx->metadata,
3916 AV_DICT_DONT_OVERWRITE);
3917 if (!o->metadata_streams_manual)
3918 for (i = output_files[nb_output_files - 1].ost_index; i < nb_output_streams; i++) {
3920 if (output_streams[i].source_index < 0) /* this is true e.g. for attached files */
3922 ist = &input_streams[output_streams[i].source_index];
3923 av_dict_copy(&output_streams[i].st->metadata, ist->st->metadata, AV_DICT_DONT_OVERWRITE);
3926 /* process manually set metadata */
3927 for (i = 0; i < o->nb_metadata; i++) {
3932 val = strchr(o->metadata[i].u.str, '=');
3934 av_log(NULL, AV_LOG_FATAL, "No '=' character in metadata string %s.\n",
3935 o->metadata[i].u.str);
3940 parse_meta_type(o->metadata[i].specifier, &type, &index);
3946 if (index < 0 || index >= oc->nb_streams) {
3947 av_log(NULL, AV_LOG_FATAL, "Invalid stream index %d in metadata specifier.\n", index);
3950 m = &oc->streams[index]->metadata;
3953 if (index < 0 || index >= oc->nb_chapters) {
3954 av_log(NULL, AV_LOG_FATAL, "Invalid chapter index %d in metadata specifier.\n", index);
3957 m = &oc->chapters[index]->metadata;
3960 av_log(NULL, AV_LOG_FATAL, "Invalid metadata specifier %s.\n", o->metadata[i].specifier);
3964 av_dict_set(m, o->metadata[i].u.str, *val ? val : NULL, 0);
3970 /* same option as mencoder */
3971 static int opt_pass(const char *opt, const char *arg)
3973 do_pass = parse_number_or_die(opt, arg, OPT_INT, 1, 2);
3977 static int64_t getutime(void)
3980 struct rusage rusage;
3982 getrusage(RUSAGE_SELF, &rusage);
3983 return (rusage.ru_utime.tv_sec * 1000000LL) + rusage.ru_utime.tv_usec;
3984 #elif HAVE_GETPROCESSTIMES
3986 FILETIME c, e, k, u;
3987 proc = GetCurrentProcess();
3988 GetProcessTimes(proc, &c, &e, &k, &u);
3989 return ((int64_t) u.dwHighDateTime << 32 | u.dwLowDateTime) / 10;
3991 return av_gettime();
3995 static int64_t getmaxrss(void)
3997 #if HAVE_GETRUSAGE && HAVE_STRUCT_RUSAGE_RU_MAXRSS
3998 struct rusage rusage;
3999 getrusage(RUSAGE_SELF, &rusage);
4000 return (int64_t)rusage.ru_maxrss * 1024;
4001 #elif HAVE_GETPROCESSMEMORYINFO
4003 PROCESS_MEMORY_COUNTERS memcounters;
4004 proc = GetCurrentProcess();
4005 memcounters.cb = sizeof(memcounters);
4006 GetProcessMemoryInfo(proc, &memcounters, sizeof(memcounters));
4007 return memcounters.PeakPagefileUsage;
4013 static int opt_audio_qscale(OptionsContext *o, const char *opt, const char *arg)
4015 return parse_option(o, "q:a", arg, options);
4018 static void show_usage(void)
4020 printf("Hyper fast Audio and Video encoder\n");
4021 printf("usage: %s [options] [[infile options] -i infile]... {[outfile options] outfile}...\n", program_name);
4025 static int opt_help(const char *opt, const char *arg)
4027 int flags = AV_OPT_FLAG_DECODING_PARAM | AV_OPT_FLAG_ENCODING_PARAM;
4028 av_log_set_callback(log_callback_help);
4030 show_help_options(options, "Main options:\n",
4031 OPT_EXPERT | OPT_AUDIO | OPT_VIDEO | OPT_SUBTITLE | OPT_GRAB, 0);
4032 show_help_options(options, "\nAdvanced options:\n",
4033 OPT_EXPERT | OPT_AUDIO | OPT_VIDEO | OPT_SUBTITLE | OPT_GRAB,
4035 show_help_options(options, "\nVideo options:\n",
4036 OPT_EXPERT | OPT_AUDIO | OPT_VIDEO | OPT_GRAB,
4038 show_help_options(options, "\nAdvanced Video options:\n",
4039 OPT_EXPERT | OPT_AUDIO | OPT_VIDEO | OPT_GRAB,
4040 OPT_VIDEO | OPT_EXPERT);
4041 show_help_options(options, "\nAudio options:\n",
4042 OPT_EXPERT | OPT_AUDIO | OPT_VIDEO | OPT_GRAB,
4044 show_help_options(options, "\nAdvanced Audio options:\n",
4045 OPT_EXPERT | OPT_AUDIO | OPT_VIDEO | OPT_GRAB,
4046 OPT_AUDIO | OPT_EXPERT);
4047 show_help_options(options, "\nSubtitle options:\n",
4048 OPT_SUBTITLE | OPT_GRAB,
4050 show_help_options(options, "\nAudio/Video grab options:\n",
4054 show_help_children(avcodec_get_class(), flags);
4055 show_help_children(avformat_get_class(), flags);
4056 show_help_children(sws_get_class(), flags);
4061 static int opt_target(OptionsContext *o, const char *opt, const char *arg)
4063 enum { PAL, NTSC, FILM, UNKNOWN } norm = UNKNOWN;
4064 static const char *const frame_rates[] = {"25", "30000/1001", "24000/1001"};
4066 if(!strncmp(arg, "pal-", 4)) {
4069 } else if(!strncmp(arg, "ntsc-", 5)) {
4072 } else if(!strncmp(arg, "film-", 5)) {
4076 /* Try to determine PAL/NTSC by peeking in the input files */
4077 if(nb_input_files) {
4079 for (j = 0; j < nb_input_files; j++) {
4080 for (i = 0; i < input_files[j].nb_streams; i++) {
4081 AVCodecContext *c = input_files[j].ctx->streams[i]->codec;
4082 if(c->codec_type != AVMEDIA_TYPE_VIDEO)
4084 fr = c->time_base.den * 1000 / c->time_base.num;
4088 } else if((fr == 29970) || (fr == 23976)) {
4097 if (norm != UNKNOWN)
4098 av_log(NULL, AV_LOG_INFO, "Assuming %s for target.\n", norm == PAL ? "PAL" : "NTSC");
4101 if(norm == UNKNOWN) {
4102 av_log(NULL, AV_LOG_FATAL, "Could not determine norm (PAL/NTSC/NTSC-Film) for target.\n");
4103 av_log(NULL, AV_LOG_FATAL, "Please prefix target with \"pal-\", \"ntsc-\" or \"film-\",\n");
4104 av_log(NULL, AV_LOG_FATAL, "or set a framerate with \"-r xxx\".\n");
4108 if(!strcmp(arg, "vcd")) {
4109 opt_video_codec(o, "c:v", "mpeg1video");
4110 opt_audio_codec(o, "c:a", "mp2");
4111 parse_option(o, "f", "vcd", options);
4113 parse_option(o, "s", norm == PAL ? "352x288" : "352x240", options);
4114 parse_option(o, "r", frame_rates[norm], options);
4115 opt_default("g", norm == PAL ? "15" : "18");
4117 opt_default("b", "1150000");
4118 opt_default("maxrate", "1150000");
4119 opt_default("minrate", "1150000");
4120 opt_default("bufsize", "327680"); // 40*1024*8;
4122 opt_default("b:a", "224000");
4123 parse_option(o, "ar", "44100", options);
4124 parse_option(o, "ac", "2", options);
4126 opt_default("packetsize", "2324");
4127 opt_default("muxrate", "1411200"); // 2352 * 75 * 8;
4129 /* We have to offset the PTS, so that it is consistent with the SCR.
4130 SCR starts at 36000, but the first two packs contain only padding
4131 and the first pack from the other stream, respectively, may also have
4132 been written before.
4133 So the real data starts at SCR 36000+3*1200. */
4134 o->mux_preload = (36000+3*1200) / 90000.0; //0.44
4135 } else if(!strcmp(arg, "svcd")) {
4137 opt_video_codec(o, "c:v", "mpeg2video");
4138 opt_audio_codec(o, "c:a", "mp2");
4139 parse_option(o, "f", "svcd", options);
4141 parse_option(o, "s", norm == PAL ? "480x576" : "480x480", options);
4142 parse_option(o, "r", frame_rates[norm], options);
4143 opt_default("g", norm == PAL ? "15" : "18");
4145 opt_default("b", "2040000");
4146 opt_default("maxrate", "2516000");
4147 opt_default("minrate", "0"); //1145000;
4148 opt_default("bufsize", "1835008"); //224*1024*8;
4149 opt_default("flags", "+scan_offset");
4152 opt_default("b:a", "224000");
4153 parse_option(o, "ar", "44100", options);
4155 opt_default("packetsize", "2324");
4157 } else if(!strcmp(arg, "dvd")) {
4159 opt_video_codec(o, "c:v", "mpeg2video");
4160 opt_audio_codec(o, "c:a", "ac3");
4161 parse_option(o, "f", "dvd", options);
4163 parse_option(o, "s", norm == PAL ? "720x576" : "720x480", options);
4164 parse_option(o, "r", frame_rates[norm], options);
4165 opt_default("g", norm == PAL ? "15" : "18");
4167 opt_default("b", "6000000");
4168 opt_default("maxrate", "9000000");
4169 opt_default("minrate", "0"); //1500000;
4170 opt_default("bufsize", "1835008"); //224*1024*8;
4172 opt_default("packetsize", "2048"); // from www.mpucoder.com: DVD sectors contain 2048 bytes of data, this is also the size of one pack.
4173 opt_default("muxrate", "10080000"); // from mplex project: data_rate = 1260000. mux_rate = data_rate * 8
4175 opt_default("b:a", "448000");
4176 parse_option(o, "ar", "48000", options);
4178 } else if(!strncmp(arg, "dv", 2)) {
4180 parse_option(o, "f", "dv", options);
4182 parse_option(o, "s", norm == PAL ? "720x576" : "720x480", options);
4183 parse_option(o, "pix_fmt", !strncmp(arg, "dv50", 4) ? "yuv422p" :
4184 norm == PAL ? "yuv420p" : "yuv411p", options);
4185 parse_option(o, "r", frame_rates[norm], options);
4187 parse_option(o, "ar", "48000", options);
4188 parse_option(o, "ac", "2", options);
4191 av_log(NULL, AV_LOG_ERROR, "Unknown target: %s\n", arg);
4192 return AVERROR(EINVAL);
4197 static int opt_vstats_file(const char *opt, const char *arg)
4199 av_free (vstats_filename);
4200 vstats_filename=av_strdup (arg);
4204 static int opt_vstats(const char *opt, const char *arg)
4207 time_t today2 = time(NULL);
4208 struct tm *today = localtime(&today2);
4210 snprintf(filename, sizeof(filename), "vstats_%02d%02d%02d.log", today->tm_hour, today->tm_min,
4212 return opt_vstats_file(opt, filename);
4215 static int opt_video_frames(OptionsContext *o, const char *opt, const char *arg)
4217 return parse_option(o, "frames:v", arg, options);
4220 static int opt_audio_frames(OptionsContext *o, const char *opt, const char *arg)
4222 return parse_option(o, "frames:a", arg, options);
4225 static int opt_data_frames(OptionsContext *o, const char *opt, const char *arg)
4227 return parse_option(o, "frames:d", arg, options);
4230 static void log_callback_null(void* ptr, int level, const char* fmt, va_list vl)
4234 static int opt_passlogfile(const char *opt, const char *arg)
4236 pass_logfilename_prefix = arg;
4237 #if CONFIG_LIBX264_ENCODER
4238 return opt_default("passlogfile", arg);
4244 static int opt_video_tag(OptionsContext *o, const char *opt, const char *arg)
4246 return parse_option(o, "tag:v", arg, options);
4249 static int opt_audio_tag(OptionsContext *o, const char *opt, const char *arg)
4251 return parse_option(o, "tag:a", arg, options);
4254 static int opt_subtitle_tag(OptionsContext *o, const char *opt, const char *arg)
4256 return parse_option(o, "tag:s", arg, options);
4259 static int opt_video_filters(OptionsContext *o, const char *opt, const char *arg)
4261 return parse_option(o, "filter:v", arg, options);
4264 #define OFFSET(x) offsetof(OptionsContext, x)
4265 static const OptionDef options[] = {
4267 #include "cmdutils_common_opts.h"
4268 { "f", HAS_ARG | OPT_STRING | OPT_OFFSET, {.off = OFFSET(format)}, "force format", "fmt" },
4269 { "i", HAS_ARG | OPT_FUNC2, {(void*)opt_input_file}, "input file name", "filename" },
4270 { "y", OPT_BOOL, {(void*)&file_overwrite}, "overwrite output files" },
4271 { "c", HAS_ARG | OPT_STRING | OPT_SPEC, {.off = OFFSET(codec_names)}, "codec name", "codec" },
4272 { "codec", HAS_ARG | OPT_STRING | OPT_SPEC, {.off = OFFSET(codec_names)}, "codec name", "codec" },
4273 { "pre", HAS_ARG | OPT_STRING | OPT_SPEC, {.off = OFFSET(presets)}, "preset name", "preset" },
4274 { "map", HAS_ARG | OPT_EXPERT | OPT_FUNC2, {(void*)opt_map}, "set input stream mapping", "file.stream[:syncfile.syncstream]" },
4275 { "map_metadata", HAS_ARG | OPT_EXPERT | OPT_FUNC2, {(void*)opt_map_metadata}, "set metadata information of outfile from infile",
4276 "outfile[,metadata]:infile[,metadata]" },
4277 { "map_chapters", OPT_INT | HAS_ARG | OPT_EXPERT | OPT_OFFSET, {.off = OFFSET(chapters_input_file)}, "set chapters mapping", "input_file_index" },
4278 { "t", HAS_ARG | OPT_TIME | OPT_OFFSET, {.off = OFFSET(recording_time)}, "record or transcode \"duration\" seconds of audio/video", "duration" },
4279 { "fs", HAS_ARG | OPT_INT64 | OPT_OFFSET, {.off = OFFSET(limit_filesize)}, "set the limit file size in bytes", "limit_size" }, //
4280 { "ss", HAS_ARG | OPT_TIME | OPT_OFFSET, {.off = OFFSET(start_time)}, "set the start time offset", "time_off" },
4281 { "itsoffset", HAS_ARG | OPT_TIME | OPT_OFFSET, {.off = OFFSET(input_ts_offset)}, "set the input ts offset", "time_off" },
4282 { "itsscale", HAS_ARG | OPT_DOUBLE | OPT_SPEC, {.off = OFFSET(ts_scale)}, "set the input ts scale", "scale" },
4283 { "metadata", HAS_ARG | OPT_STRING | OPT_SPEC, {.off = OFFSET(metadata)}, "add metadata", "string=string" },
4284 { "dframes", HAS_ARG | OPT_FUNC2, {(void*)opt_data_frames}, "set the number of data frames to record", "number" },
4285 { "benchmark", OPT_BOOL | OPT_EXPERT, {(void*)&do_benchmark},
4286 "add timings for benchmarking" },
4287 { "timelimit", HAS_ARG, {(void*)opt_timelimit}, "set max runtime in seconds", "limit" },
4288 { "dump", OPT_BOOL | OPT_EXPERT, {(void*)&do_pkt_dump},
4289 "dump each input packet" },
4290 { "hex", OPT_BOOL | OPT_EXPERT, {(void*)&do_hex_dump},
4291 "when dumping packets, also dump the payload" },
4292 { "re", OPT_BOOL | OPT_EXPERT | OPT_OFFSET, {.off = OFFSET(rate_emu)}, "read input at native frame rate", "" },
4293 { "target", HAS_ARG | OPT_FUNC2, {(void*)opt_target}, "specify target file type (\"vcd\", \"svcd\", \"dvd\", \"dv\", \"dv50\", \"pal-vcd\", \"ntsc-svcd\", ...)", "type" },
4294 { "vsync", HAS_ARG | OPT_INT | OPT_EXPERT, {(void*)&video_sync_method}, "video sync method", "" },
4295 { "async", HAS_ARG | OPT_INT | OPT_EXPERT, {(void*)&audio_sync_method}, "audio sync method", "" },
4296 { "adrift_threshold", HAS_ARG | OPT_FLOAT | OPT_EXPERT, {(void*)&audio_drift_threshold}, "audio drift threshold", "threshold" },
4297 { "copyts", OPT_BOOL | OPT_EXPERT, {(void*)©_ts}, "copy timestamps" },
4298 { "copytb", OPT_BOOL | OPT_EXPERT, {(void*)©_tb}, "copy input stream time base when stream copying" },
4299 { "shortest", OPT_BOOL | OPT_EXPERT, {(void*)&opt_shortest}, "finish encoding within shortest input" }, //
4300 { "dts_delta_threshold", HAS_ARG | OPT_FLOAT | OPT_EXPERT, {(void*)&dts_delta_threshold}, "timestamp discontinuity delta threshold", "threshold" },
4301 { "xerror", OPT_BOOL, {(void*)&exit_on_error}, "exit on error", "error" },
4302 { "copyinkf", OPT_BOOL | OPT_EXPERT | OPT_SPEC, {.off = OFFSET(copy_initial_nonkeyframes)}, "copy initial non-keyframes" },
4303 { "frames", OPT_INT64 | HAS_ARG | OPT_SPEC, {.off = OFFSET(max_frames)}, "set the number of frames to record", "number" },
4304 { "tag", OPT_STRING | HAS_ARG | OPT_SPEC, {.off = OFFSET(codec_tags)}, "force codec tag/fourcc", "fourcc/tag" },
4305 { "q", HAS_ARG | OPT_EXPERT | OPT_DOUBLE | OPT_SPEC, {.off = OFFSET(qscale)}, "use fixed quality scale (VBR)", "q" },
4306 { "qscale", HAS_ARG | OPT_EXPERT | OPT_DOUBLE | OPT_SPEC, {.off = OFFSET(qscale)}, "use fixed quality scale (VBR)", "q" },
4308 { "filter", HAS_ARG | OPT_STRING | OPT_SPEC, {.off = OFFSET(filters)}, "set stream filterchain", "filter_list" },
4310 { "stats", OPT_BOOL, {&print_stats}, "print progress report during encoding", },
4311 { "attach", HAS_ARG | OPT_FUNC2, {(void*)opt_attach}, "add an attachment to the output file", "filename" },
4312 { "dump_attachment", HAS_ARG | OPT_STRING | OPT_SPEC, {.off = OFFSET(dump_attachment)}, "extract an attachment into a file", "filename" },
4315 { "vframes", HAS_ARG | OPT_VIDEO | OPT_FUNC2, {(void*)opt_video_frames}, "set the number of video frames to record", "number" },
4316 { "r", HAS_ARG | OPT_VIDEO | OPT_STRING | OPT_SPEC, {.off = OFFSET(frame_rates)}, "set frame rate (Hz value, fraction or abbreviation)", "rate" },
4317 { "s", HAS_ARG | OPT_VIDEO | OPT_STRING | OPT_SPEC, {.off = OFFSET(frame_sizes)}, "set frame size (WxH or abbreviation)", "size" },
4318 { "aspect", HAS_ARG | OPT_VIDEO | OPT_STRING | OPT_SPEC, {.off = OFFSET(frame_aspect_ratios)}, "set aspect ratio (4:3, 16:9 or 1.3333, 1.7777)", "aspect" },
4319 { "pix_fmt", HAS_ARG | OPT_EXPERT | OPT_VIDEO | OPT_STRING | OPT_SPEC, {.off = OFFSET(frame_pix_fmts)}, "set pixel format", "format" },
4320 { "bits_per_raw_sample", OPT_INT | HAS_ARG | OPT_VIDEO, {(void*)&frame_bits_per_raw_sample}, "set the number of bits per raw sample", "number" },
4321 { "vn", OPT_BOOL | OPT_VIDEO | OPT_OFFSET, {.off = OFFSET(video_disable)}, "disable video" },
4322 { "vdt", OPT_INT | HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)&video_discard}, "discard threshold", "n" },
4323 { "rc_override", HAS_ARG | OPT_EXPERT | OPT_VIDEO | OPT_STRING | OPT_SPEC, {.off = OFFSET(rc_overrides)}, "rate control override for specific intervals", "override" },
4324 { "vcodec", HAS_ARG | OPT_VIDEO | OPT_FUNC2, {(void*)opt_video_codec}, "force video codec ('copy' to copy stream)", "codec" },
4325 { "same_quant", OPT_BOOL | OPT_VIDEO, {(void*)&same_quant},
4326 "use same quantizer as source (implies VBR)" },
4327 { "pass", HAS_ARG | OPT_VIDEO, {(void*)opt_pass}, "select the pass number (1 or 2)", "n" },
4328 { "passlogfile", HAS_ARG | OPT_VIDEO, {(void*)&opt_passlogfile}, "select two pass log file name prefix", "prefix" },
4329 { "deinterlace", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, {(void*)&do_deinterlace},
4330 "deinterlace pictures" },
4331 { "vstats", OPT_EXPERT | OPT_VIDEO, {(void*)&opt_vstats}, "dump video coding statistics to file" },
4332 { "vstats_file", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_vstats_file}, "dump video coding statistics to file", "file" },
4334 { "vf", HAS_ARG | OPT_VIDEO | OPT_FUNC2, {(void*)opt_video_filters}, "video filters", "filter list" },
4336 { "intra_matrix", HAS_ARG | OPT_EXPERT | OPT_VIDEO | OPT_STRING | OPT_SPEC, {.off = OFFSET(intra_matrices)}, "specify intra matrix coeffs", "matrix" },
4337 { "inter_matrix", HAS_ARG | OPT_EXPERT | OPT_VIDEO | OPT_STRING | OPT_SPEC, {.off = OFFSET(inter_matrices)}, "specify inter matrix coeffs", "matrix" },
4338 { "top", HAS_ARG | OPT_EXPERT | OPT_VIDEO | OPT_INT| OPT_SPEC, {.off = OFFSET(top_field_first)}, "top=1/bottom=0/auto=-1 field first", "" },
4339 { "dc", OPT_INT | HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)&intra_dc_precision}, "intra_dc_precision", "precision" },
4340 { "vtag", HAS_ARG | OPT_EXPERT | OPT_VIDEO | OPT_FUNC2, {(void*)opt_video_tag}, "force video tag/fourcc", "fourcc/tag" },
4341 { "qphist", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, { (void *)&qp_hist }, "show QP histogram" },
4342 { "force_fps", OPT_BOOL | OPT_EXPERT | OPT_VIDEO | OPT_SPEC, {.off = OFFSET(force_fps)}, "force the selected framerate, disable the best supported framerate selection" },
4343 { "streamid", HAS_ARG | OPT_EXPERT | OPT_FUNC2, {(void*)opt_streamid}, "set the value of an outfile streamid", "streamIndex:value" },
4344 { "force_key_frames", OPT_STRING | HAS_ARG | OPT_EXPERT | OPT_VIDEO | OPT_SPEC, {.off = OFFSET(forced_key_frames)}, "force key frames at specified timestamps", "timestamps" },
4347 { "aframes", HAS_ARG | OPT_AUDIO | OPT_FUNC2, {(void*)opt_audio_frames}, "set the number of audio frames to record", "number" },
4348 { "aq", HAS_ARG | OPT_AUDIO | OPT_FUNC2, {(void*)opt_audio_qscale}, "set audio quality (codec-specific)", "quality", },
4349 { "ar", HAS_ARG | OPT_AUDIO | OPT_INT | OPT_SPEC, {.off = OFFSET(audio_sample_rate)}, "set audio sampling rate (in Hz)", "rate" },
4350 { "ac", HAS_ARG | OPT_AUDIO | OPT_INT | OPT_SPEC, {.off = OFFSET(audio_channels)}, "set number of audio channels", "channels" },
4351 { "an", OPT_BOOL | OPT_AUDIO | OPT_OFFSET, {.off = OFFSET(audio_disable)}, "disable audio" },
4352 { "acodec", HAS_ARG | OPT_AUDIO | OPT_FUNC2, {(void*)opt_audio_codec}, "force audio codec ('copy' to copy stream)", "codec" },
4353 { "atag", HAS_ARG | OPT_EXPERT | OPT_AUDIO | OPT_FUNC2, {(void*)opt_audio_tag}, "force audio tag/fourcc", "fourcc/tag" },
4354 { "vol", OPT_INT | HAS_ARG | OPT_AUDIO, {(void*)&audio_volume}, "change audio volume (256=normal)" , "volume" }, //
4355 { "sample_fmt", HAS_ARG | OPT_EXPERT | OPT_AUDIO | OPT_SPEC | OPT_STRING, {.off = OFFSET(sample_fmts)}, "set sample format", "format" },
4357 /* subtitle options */
4358 { "sn", OPT_BOOL | OPT_SUBTITLE | OPT_OFFSET, {.off = OFFSET(subtitle_disable)}, "disable subtitle" },
4359 { "scodec", HAS_ARG | OPT_SUBTITLE | OPT_FUNC2, {(void*)opt_subtitle_codec}, "force subtitle codec ('copy' to copy stream)", "codec" },
4360 { "stag", HAS_ARG | OPT_EXPERT | OPT_SUBTITLE | OPT_FUNC2, {(void*)opt_subtitle_tag}, "force subtitle tag/fourcc", "fourcc/tag" },
4363 { "isync", OPT_BOOL | OPT_EXPERT | OPT_GRAB, {(void*)&input_sync}, "sync read on input", "" },
4366 { "muxdelay", OPT_FLOAT | HAS_ARG | OPT_EXPERT | OPT_OFFSET, {.off = OFFSET(mux_max_delay)}, "set the maximum demux-decode delay", "seconds" },
4367 { "muxpreload", OPT_FLOAT | HAS_ARG | OPT_EXPERT | OPT_OFFSET, {.off = OFFSET(mux_preload)}, "set the initial demux-decode delay", "seconds" },
4369 { "bsf", HAS_ARG | OPT_STRING | OPT_SPEC, {.off = OFFSET(bitstream_filters)}, "A comma-separated list of bitstream filters", "bitstream_filters" },
4371 /* data codec support */
4372 { "dcodec", HAS_ARG | OPT_DATA | OPT_FUNC2, {(void*)opt_data_codec}, "force data codec ('copy' to copy stream)", "codec" },
4374 { "default", HAS_ARG | OPT_AUDIO | OPT_VIDEO | OPT_EXPERT, {(void*)opt_default}, "generic catch all option", "" },
4378 int main(int argc, char **argv)
4380 OptionsContext o = { 0 };
4385 av_log_set_flags(AV_LOG_SKIP_REPEATED);
4386 parse_loglevel(argc, argv, options);
4388 if(argc>1 && !strcmp(argv[1], "-d")){
4390 av_log_set_callback(log_callback_null);
4395 avcodec_register_all();
4397 avdevice_register_all();
4400 avfilter_register_all();
4403 avformat_network_init();
4408 parse_options(&o, argc, argv, options, opt_output_file);
4410 if(nb_output_files <= 0 && nb_input_files == 0) {
4412 av_log(NULL, AV_LOG_WARNING, "Use -h to get full help or, even better, run 'man %s'\n", program_name);
4416 /* file converter / grab */
4417 if (nb_output_files <= 0) {
4418 fprintf(stderr, "At least one output file must be specified\n");
4422 if (nb_input_files == 0) {
4423 av_log(NULL, AV_LOG_FATAL, "At least one input file must be specified\n");
4428 if (transcode(output_files, nb_output_files, input_files, nb_input_files) < 0)
4430 ti = getutime() - ti;
4432 int maxrss = getmaxrss() / 1024;
4433 printf("bench: utime=%0.3fs maxrss=%ikB\n", ti / 1000000.0, maxrss);