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 no_file_overwrite = 0;
123 static int do_benchmark = 0;
124 static int do_hex_dump = 0;
125 static int do_pkt_dump = 0;
126 static int do_pass = 0;
127 static const char *pass_logfilename_prefix;
128 static int video_sync_method= -1;
129 static int audio_sync_method= 0;
130 static float audio_drift_threshold= 0.1;
131 static int copy_ts= 0;
132 static int copy_tb = 1;
133 static int opt_shortest = 0;
134 static char *vstats_filename;
135 static FILE *vstats_file;
137 static int audio_volume = 256;
139 static int exit_on_error = 0;
140 static int using_stdin = 0;
141 static int run_as_daemon = 0;
142 static int q_pressed = 0;
143 static int64_t video_size = 0;
144 static int64_t audio_size = 0;
145 static int64_t extra_size = 0;
146 static int nb_frames_dup = 0;
147 static int nb_frames_drop = 0;
148 static int input_sync;
150 static float dts_delta_threshold = 10;
152 static int print_stats = 1;
154 static uint8_t *audio_buf;
155 static uint8_t *audio_out;
156 static unsigned int allocated_audio_out_size, allocated_audio_buf_size;
158 #define DEFAULT_PASS_LOGFILENAME_PREFIX "av2pass"
160 typedef struct InputStream {
163 int discard; /* true if stream data should be discarded */
164 int decoding_needed; /* true if the packets must be decoded in 'raw_fifo' */
166 AVFrame *decoded_frame;
167 AVFrame *filtered_frame;
169 int64_t start; /* time when read started */
170 int64_t next_pts; /* synthetic pts for cases where pkt.pts
172 int64_t pts; /* current pts */
174 int is_start; /* is 1 at the start and after a discontinuity */
175 int showed_multi_packet_warning;
179 typedef struct InputFile {
180 AVFormatContext *ctx;
181 int eof_reached; /* true if eof reached */
182 int ist_index; /* index of first stream in ist_table */
183 int buffer_size; /* current total buffer size */
185 int nb_streams; /* number of stream that avconv is aware of; may be different
186 from ctx.nb_streams if new streams appear during av_read_frame() */
190 typedef struct OutputStream {
191 int file_index; /* file index */
192 int index; /* stream index in the output file */
193 int source_index; /* InputStream index */
194 AVStream *st; /* stream in the output file */
195 int encoding_needed; /* true if encoding needed for this stream */
197 /* input pts and corresponding output pts
199 //double sync_ipts; /* dts from the AVPacket of the demuxer in second units */
200 struct InputStream *sync_ist; /* input stream to sync against */
201 int64_t sync_opts; /* output frame counter, could be changed to some true timestamp */ //FIXME look at frame_number
202 AVBitStreamFilterContext *bitstream_filters;
208 AVFrame resample_frame; /* temporary frame for image resampling */
209 struct SwsContext *img_resample_ctx; /* for image resampling */
212 int resample_pix_fmt;
213 AVRational frame_rate;
217 float frame_aspect_ratio;
219 /* forced key frames */
220 int64_t *forced_kf_pts;
226 ReSampleContext *resample; /* for audio resampling */
227 int resample_sample_fmt;
228 int resample_channels;
229 int resample_sample_rate;
231 AVAudioConvert *reformat_ctx;
232 AVFifoBuffer *fifo; /* for compression: one audio fifo per codec */
236 AVFilterContext *output_video_filter;
237 AVFilterContext *input_video_filter;
238 AVFilterBufferRef *picref;
240 AVFilterGraph *graph;
245 int is_past_recording_time;
247 const char *attachment_filename;
248 int copy_initial_nonkeyframes;
253 /* init terminal so that we can grab keys */
254 static struct termios oldtty;
257 typedef struct OutputFile {
258 AVFormatContext *ctx;
260 int ost_index; /* index of the first stream in output_streams */
261 int64_t recording_time; /* desired length of the resulting file in microseconds */
262 int64_t start_time; /* start time in microseconds */
263 uint64_t limit_filesize;
266 static InputStream *input_streams = NULL;
267 static int nb_input_streams = 0;
268 static InputFile *input_files = NULL;
269 static int nb_input_files = 0;
271 static OutputStream *output_streams = NULL;
272 static int nb_output_streams = 0;
273 static OutputFile *output_files = NULL;
274 static int nb_output_files = 0;
276 typedef struct OptionsContext {
277 /* input/output options */
281 SpecifierOpt *codec_names;
283 SpecifierOpt *audio_channels;
284 int nb_audio_channels;
285 SpecifierOpt *audio_sample_rate;
286 int nb_audio_sample_rate;
287 SpecifierOpt *frame_rates;
289 SpecifierOpt *frame_sizes;
291 SpecifierOpt *frame_pix_fmts;
292 int nb_frame_pix_fmts;
295 int64_t input_ts_offset;
298 SpecifierOpt *ts_scale;
300 SpecifierOpt *dump_attachment;
301 int nb_dump_attachment;
304 StreamMap *stream_maps;
306 /* first item specifies output metadata, second is input */
307 MetadataMap (*meta_data_maps)[2];
308 int nb_meta_data_maps;
309 int metadata_global_manual;
310 int metadata_streams_manual;
311 int metadata_chapters_manual;
312 const char **attachments;
315 int chapters_input_file;
317 int64_t recording_time;
318 uint64_t limit_filesize;
324 int subtitle_disable;
327 /* indexed by output file stream index */
331 SpecifierOpt *metadata;
333 SpecifierOpt *max_frames;
335 SpecifierOpt *bitstream_filters;
336 int nb_bitstream_filters;
337 SpecifierOpt *codec_tags;
339 SpecifierOpt *sample_fmts;
341 SpecifierOpt *qscale;
343 SpecifierOpt *forced_key_frames;
344 int nb_forced_key_frames;
345 SpecifierOpt *force_fps;
347 SpecifierOpt *frame_aspect_ratios;
348 int nb_frame_aspect_ratios;
349 SpecifierOpt *rc_overrides;
351 SpecifierOpt *intra_matrices;
352 int nb_intra_matrices;
353 SpecifierOpt *inter_matrices;
354 int nb_inter_matrices;
355 SpecifierOpt *top_field_first;
356 int nb_top_field_first;
357 SpecifierOpt *presets;
359 SpecifierOpt *copy_initial_nonkeyframes;
360 int nb_copy_initial_nonkeyframes;
362 SpecifierOpt *filters;
367 #define MATCH_PER_STREAM_OPT(name, type, outvar, fmtctx, st)\
370 for (i = 0; i < o->nb_ ## name; i++) {\
371 char *spec = o->name[i].specifier;\
372 if ((ret = check_stream_specifier(fmtctx, st, spec)) > 0)\
373 outvar = o->name[i].u.type;\
379 static void reset_options(OptionsContext *o)
381 const OptionDef *po = options;
383 /* all OPT_SPEC and OPT_STRING can be freed in generic way */
385 void *dst = (uint8_t*)o + po->u.off;
387 if (po->flags & OPT_SPEC) {
388 SpecifierOpt **so = dst;
389 int i, *count = (int*)(so + 1);
390 for (i = 0; i < *count; i++) {
391 av_freep(&(*so)[i].specifier);
392 if (po->flags & OPT_STRING)
393 av_freep(&(*so)[i].u.str);
397 } else if (po->flags & OPT_OFFSET && po->flags & OPT_STRING)
402 av_freep(&o->stream_maps);
403 av_freep(&o->meta_data_maps);
404 av_freep(&o->streamid_map);
406 memset(o, 0, sizeof(*o));
408 o->mux_max_delay = 0.7;
409 o->recording_time = INT64_MAX;
410 o->limit_filesize = UINT64_MAX;
411 o->chapters_input_file = INT_MAX;
419 static int configure_video_filters(InputStream *ist, OutputStream *ost)
421 AVFilterContext *last_filter, *filter;
422 /** filter graph containing all filters including input & output */
423 AVCodecContext *codec = ost->st->codec;
424 AVCodecContext *icodec = ist->st->codec;
425 enum PixelFormat pix_fmts[] = { codec->pix_fmt, PIX_FMT_NONE };
426 AVBufferSinkParams *buffersink_params = av_buffersink_params_alloc();
427 AVRational sample_aspect_ratio;
431 ost->graph = avfilter_graph_alloc();
433 if (ist->st->sample_aspect_ratio.num){
434 sample_aspect_ratio = ist->st->sample_aspect_ratio;
436 sample_aspect_ratio = ist->st->codec->sample_aspect_ratio;
438 snprintf(args, 255, "%d:%d:%d:%d:%d:%d:%d", ist->st->codec->width,
439 ist->st->codec->height, ist->st->codec->pix_fmt, 1, AV_TIME_BASE,
440 sample_aspect_ratio.num, sample_aspect_ratio.den);
442 ret = avfilter_graph_create_filter(&ost->input_video_filter, avfilter_get_by_name("buffer"),
443 "src", args, NULL, ost->graph);
446 #if FF_API_OLD_VSINK_API
447 ret = avfilter_graph_create_filter(&ost->output_video_filter, avfilter_get_by_name("buffersink"),
448 "out", NULL, pix_fmts, ost->graph);
450 buffersink_params->pixel_fmts = pix_fmts;
451 ret = avfilter_graph_create_filter(&ost->output_video_filter, avfilter_get_by_name("buffersink"),
452 "out", NULL, buffersink_params, ost->graph);
454 av_freep(&buffersink_params);
457 last_filter = ost->input_video_filter;
459 if (codec->width != icodec->width || codec->height != icodec->height) {
460 snprintf(args, 255, "%d:%d:flags=0x%X",
463 (unsigned)ost->sws_flags);
464 if ((ret = avfilter_graph_create_filter(&filter, avfilter_get_by_name("scale"),
465 NULL, args, NULL, ost->graph)) < 0)
467 if ((ret = avfilter_link(last_filter, 0, filter, 0)) < 0)
469 last_filter = filter;
472 snprintf(args, sizeof(args), "flags=0x%X", (unsigned)ost->sws_flags);
473 ost->graph->scale_sws_opts = av_strdup(args);
476 AVFilterInOut *outputs = avfilter_inout_alloc();
477 AVFilterInOut *inputs = avfilter_inout_alloc();
479 outputs->name = av_strdup("in");
480 outputs->filter_ctx = last_filter;
481 outputs->pad_idx = 0;
482 outputs->next = NULL;
484 inputs->name = av_strdup("out");
485 inputs->filter_ctx = ost->output_video_filter;
489 if ((ret = avfilter_graph_parse(ost->graph, ost->avfilter, &inputs, &outputs, NULL)) < 0)
491 av_freep(&ost->avfilter);
493 if ((ret = avfilter_link(last_filter, 0, ost->output_video_filter, 0)) < 0)
497 if ((ret = avfilter_graph_config(ost->graph, NULL)) < 0)
500 codec->width = ost->output_video_filter->inputs[0]->w;
501 codec->height = ost->output_video_filter->inputs[0]->h;
502 codec->sample_aspect_ratio = ost->st->sample_aspect_ratio =
503 ost->frame_aspect_ratio ? // overridden by the -aspect cli option
504 av_d2q(ost->frame_aspect_ratio*codec->height/codec->width, 255) :
505 ost->output_video_filter->inputs[0]->sample_aspect_ratio;
509 #endif /* CONFIG_AVFILTER */
511 static void term_exit(void)
513 av_log(NULL, AV_LOG_QUIET, "%s", "");
516 tcsetattr (0, TCSANOW, &oldtty);
520 static volatile int received_sigterm = 0;
523 sigterm_handler(int sig)
525 received_sigterm = sig;
530 static void term_init(void)
540 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
541 |INLCR|IGNCR|ICRNL|IXON);
542 tty.c_oflag |= OPOST;
543 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
544 tty.c_cflag &= ~(CSIZE|PARENB);
549 tcsetattr (0, TCSANOW, &tty);
550 signal(SIGQUIT, sigterm_handler); /* Quit (POSIX). */
554 signal(SIGINT , sigterm_handler); /* Interrupt (ANSI). */
555 signal(SIGTERM, sigterm_handler); /* Termination (ANSI). */
557 signal(SIGXCPU, sigterm_handler);
561 /* read a key without blocking */
562 static int read_key(void)
577 n = select(1, &rfds, NULL, NULL, &tv);
592 static int decode_interrupt_cb(void *ctx)
594 q_pressed += read_key() == 'q';
595 return q_pressed > 1;
598 static const AVIOInterruptCB int_cb = { decode_interrupt_cb, NULL };
600 void exit_program(int ret)
605 for(i=0;i<nb_output_files;i++) {
606 AVFormatContext *s = output_files[i].ctx;
607 if (!(s->oformat->flags & AVFMT_NOFILE) && s->pb)
609 avformat_free_context(s);
610 av_dict_free(&output_files[i].opts);
612 for(i=0;i<nb_input_files;i++) {
613 av_close_input_file(input_files[i].ctx);
615 for (i = 0; i < nb_input_streams; i++) {
616 av_freep(&input_streams[i].decoded_frame);
617 av_freep(&input_streams[i].filtered_frame);
618 av_dict_free(&input_streams[i].opts);
623 av_free(vstats_filename);
625 av_freep(&input_streams);
626 av_freep(&input_files);
627 av_freep(&output_streams);
628 av_freep(&output_files);
633 allocated_audio_buf_size= allocated_audio_out_size= 0;
638 avformat_network_deinit();
640 if (received_sigterm) {
641 av_log(NULL, AV_LOG_INFO, "Received signal %d: terminating.\n",
642 (int) received_sigterm);
649 static void assert_avoptions(AVDictionary *m)
651 AVDictionaryEntry *t;
652 if ((t = av_dict_get(m, "", NULL, AV_DICT_IGNORE_SUFFIX))) {
653 av_log(NULL, AV_LOG_FATAL, "Option %s not found.\n", t->key);
658 static void assert_codec_experimental(AVCodecContext *c, int encoder)
660 const char *codec_string = encoder ? "encoder" : "decoder";
662 if (c->codec->capabilities & CODEC_CAP_EXPERIMENTAL &&
663 c->strict_std_compliance > FF_COMPLIANCE_EXPERIMENTAL) {
664 av_log(NULL, AV_LOG_FATAL, "%s '%s' is experimental and might produce bad "
665 "results.\nAdd '-strict experimental' if you want to use it.\n",
666 codec_string, c->codec->name);
667 codec = encoder ? avcodec_find_encoder(c->codec->id) : avcodec_find_decoder(c->codec->id);
668 if (!(codec->capabilities & CODEC_CAP_EXPERIMENTAL))
669 av_log(NULL, AV_LOG_FATAL, "Or use the non experimental %s '%s'.\n",
670 codec_string, codec->name);
675 static void choose_sample_fmt(AVStream *st, AVCodec *codec)
677 if(codec && codec->sample_fmts){
678 const enum AVSampleFormat *p= codec->sample_fmts;
680 if(*p == st->codec->sample_fmt)
684 if((codec->capabilities & CODEC_CAP_LOSSLESS) && av_get_sample_fmt_name(st->codec->sample_fmt) > av_get_sample_fmt_name(codec->sample_fmts[0]))
685 av_log(NULL, AV_LOG_ERROR, "Convertion will not be lossless'\n");
686 if(av_get_sample_fmt_name(st->codec->sample_fmt))
687 av_log(NULL, AV_LOG_WARNING,
688 "Incompatible sample format '%s' for codec '%s', auto-selecting format '%s'\n",
689 av_get_sample_fmt_name(st->codec->sample_fmt),
691 av_get_sample_fmt_name(codec->sample_fmts[0]));
692 st->codec->sample_fmt = codec->sample_fmts[0];
697 static void choose_sample_rate(AVStream *st, AVCodec *codec)
699 if(codec && codec->supported_samplerates){
700 const int *p= codec->supported_samplerates;
702 int best_dist=INT_MAX;
704 int dist= abs(st->codec->sample_rate - *p);
705 if(dist < best_dist){
711 av_log(st->codec, AV_LOG_WARNING, "Requested sampling rate unsupported using closest supported (%d)\n", best);
713 st->codec->sample_rate= best;
717 static void choose_pixel_fmt(AVStream *st, AVCodec *codec)
719 if(codec && codec->pix_fmts){
720 const enum PixelFormat *p= codec->pix_fmts;
721 if(st->codec->strict_std_compliance <= FF_COMPLIANCE_UNOFFICIAL){
722 if(st->codec->codec_id==CODEC_ID_MJPEG){
723 p= (const enum PixelFormat[]){PIX_FMT_YUVJ420P, PIX_FMT_YUVJ422P, PIX_FMT_YUV420P, PIX_FMT_YUV422P, PIX_FMT_NONE};
724 }else if(st->codec->codec_id==CODEC_ID_LJPEG){
725 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};
728 for (; *p != PIX_FMT_NONE; p++) {
729 if(*p == st->codec->pix_fmt)
732 if (*p == PIX_FMT_NONE) {
733 if(st->codec->pix_fmt != PIX_FMT_NONE)
734 av_log(NULL, AV_LOG_WARNING,
735 "Incompatible pixel format '%s' for codec '%s', auto-selecting format '%s'\n",
736 av_pix_fmt_descriptors[st->codec->pix_fmt].name,
738 av_pix_fmt_descriptors[codec->pix_fmts[0]].name);
739 st->codec->pix_fmt = codec->pix_fmts[0];
745 get_sync_ipts(const OutputStream *ost)
747 const InputStream *ist = ost->sync_ist;
748 OutputFile *of = &output_files[ost->file_index];
749 return (double)(ist->pts - of->start_time)/AV_TIME_BASE;
752 static void write_frame(AVFormatContext *s, AVPacket *pkt, AVCodecContext *avctx, AVBitStreamFilterContext *bsfc){
756 AVPacket new_pkt= *pkt;
757 int a= av_bitstream_filter_filter(bsfc, avctx, NULL,
758 &new_pkt.data, &new_pkt.size,
759 pkt->data, pkt->size,
760 pkt->flags & AV_PKT_FLAG_KEY);
763 new_pkt.destruct= av_destruct_packet;
765 av_log(NULL, AV_LOG_ERROR, "%s failed for stream %d, codec %s",
766 bsfc->filter->name, pkt->stream_index,
767 avctx->codec ? avctx->codec->name : "copy");
777 ret= av_interleaved_write_frame(s, pkt);
779 print_error("av_interleaved_write_frame()", ret);
784 static void generate_silence(uint8_t* buf, enum AVSampleFormat sample_fmt, size_t size)
786 int fill_char = 0x00;
787 if (sample_fmt == AV_SAMPLE_FMT_U8)
789 memset(buf, fill_char, size);
792 static void do_audio_out(AVFormatContext *s, OutputStream *ost,
793 InputStream *ist, AVFrame *decoded_frame)
796 int64_t audio_out_size, audio_buf_size;
798 int size_out, frame_bytes, ret, resample_changed;
799 AVCodecContext *enc= ost->st->codec;
800 AVCodecContext *dec= ist->st->codec;
801 int osize = av_get_bytes_per_sample(enc->sample_fmt);
802 int isize = av_get_bytes_per_sample(dec->sample_fmt);
803 const int coded_bps = av_get_bits_per_sample(enc->codec->id);
804 uint8_t *buf = decoded_frame->data[0];
805 int size = decoded_frame->nb_samples * dec->channels * isize;
806 int64_t allocated_for_size = size;
809 audio_buf_size= (allocated_for_size + isize*dec->channels - 1) / (isize*dec->channels);
810 audio_buf_size= (audio_buf_size*enc->sample_rate + dec->sample_rate) / dec->sample_rate;
811 audio_buf_size= audio_buf_size*2 + 10000; //safety factors for the deprecated resampling API
812 audio_buf_size= FFMAX(audio_buf_size, enc->frame_size);
813 audio_buf_size*= osize*enc->channels;
815 audio_out_size= FFMAX(audio_buf_size, enc->frame_size * osize * enc->channels);
816 if(coded_bps > 8*osize)
817 audio_out_size= audio_out_size * coded_bps / (8*osize);
818 audio_out_size += FF_MIN_BUFFER_SIZE;
820 if(audio_out_size > INT_MAX || audio_buf_size > INT_MAX){
821 av_log(NULL, AV_LOG_FATAL, "Buffer sizes too large\n");
825 av_fast_malloc(&audio_buf, &allocated_audio_buf_size, audio_buf_size);
826 av_fast_malloc(&audio_out, &allocated_audio_out_size, audio_out_size);
827 if (!audio_buf || !audio_out){
828 av_log(NULL, AV_LOG_FATAL, "Out of memory in do_audio_out\n");
832 if (enc->channels != dec->channels)
833 ost->audio_resample = 1;
835 resample_changed = ost->resample_sample_fmt != dec->sample_fmt ||
836 ost->resample_channels != dec->channels ||
837 ost->resample_sample_rate != dec->sample_rate;
839 if ((ost->audio_resample && !ost->resample) || resample_changed) {
840 if (resample_changed) {
841 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",
842 ist->file_index, ist->st->index,
843 ost->resample_sample_rate, av_get_sample_fmt_name(ost->resample_sample_fmt), ost->resample_channels,
844 dec->sample_rate, av_get_sample_fmt_name(dec->sample_fmt), dec->channels);
845 ost->resample_sample_fmt = dec->sample_fmt;
846 ost->resample_channels = dec->channels;
847 ost->resample_sample_rate = dec->sample_rate;
849 audio_resample_close(ost->resample);
851 /* if audio_sync_method is >1 the resampler is needed for audio drift compensation */
852 if (audio_sync_method <= 1 &&
853 ost->resample_sample_fmt == enc->sample_fmt &&
854 ost->resample_channels == enc->channels &&
855 ost->resample_sample_rate == enc->sample_rate) {
856 ost->resample = NULL;
857 ost->audio_resample = 0;
859 if (dec->sample_fmt != AV_SAMPLE_FMT_S16)
860 av_log(NULL, AV_LOG_WARNING, "Using s16 intermediate sample format for resampling\n");
861 ost->resample = av_audio_resample_init(enc->channels, dec->channels,
862 enc->sample_rate, dec->sample_rate,
863 enc->sample_fmt, dec->sample_fmt,
865 if (!ost->resample) {
866 av_log(NULL, AV_LOG_FATAL, "Can not resample %d channels @ %d Hz to %d channels @ %d Hz\n",
867 dec->channels, dec->sample_rate,
868 enc->channels, enc->sample_rate);
874 #define MAKE_SFMT_PAIR(a,b) ((a)+AV_SAMPLE_FMT_NB*(b))
875 if (!ost->audio_resample && dec->sample_fmt!=enc->sample_fmt &&
876 MAKE_SFMT_PAIR(enc->sample_fmt,dec->sample_fmt)!=ost->reformat_pair) {
877 if (ost->reformat_ctx)
878 av_audio_convert_free(ost->reformat_ctx);
879 ost->reformat_ctx = av_audio_convert_alloc(enc->sample_fmt, 1,
880 dec->sample_fmt, 1, NULL, 0);
881 if (!ost->reformat_ctx) {
882 av_log(NULL, AV_LOG_FATAL, "Cannot convert %s sample format to %s sample format\n",
883 av_get_sample_fmt_name(dec->sample_fmt),
884 av_get_sample_fmt_name(enc->sample_fmt));
887 ost->reformat_pair=MAKE_SFMT_PAIR(enc->sample_fmt,dec->sample_fmt);
890 if(audio_sync_method){
891 double delta = get_sync_ipts(ost) * enc->sample_rate - ost->sync_opts
892 - av_fifo_size(ost->fifo)/(enc->channels * osize);
893 int idelta = delta * dec->sample_rate / enc->sample_rate;
894 int byte_delta = idelta * isize * dec->channels;
896 //FIXME resample delay
897 if(fabs(delta) > 50){
898 if(ist->is_start || fabs(delta) > audio_drift_threshold*enc->sample_rate){
900 byte_delta= FFMAX(byte_delta, -size);
903 av_log(NULL, AV_LOG_VERBOSE, "discarding %d audio samples\n",
904 -byte_delta / (isize * dec->channels));
909 static uint8_t *input_tmp= NULL;
910 input_tmp= av_realloc(input_tmp, byte_delta + size);
912 if(byte_delta > allocated_for_size - size){
913 allocated_for_size= byte_delta + (int64_t)size;
918 generate_silence(input_tmp, dec->sample_fmt, byte_delta);
919 memcpy(input_tmp + byte_delta, buf, size);
922 av_log(NULL, AV_LOG_VERBOSE, "adding %d audio samples of silence\n", idelta);
924 }else if(audio_sync_method>1){
925 int comp= av_clip(delta, -audio_sync_method, audio_sync_method);
926 av_assert0(ost->audio_resample);
927 av_log(NULL, AV_LOG_VERBOSE, "compensating audio timestamp drift:%f compensation:%d in:%d\n",
928 delta, comp, enc->sample_rate);
929 // 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));
930 av_resample_compensate(*(struct AVResampleContext**)ost->resample, comp, enc->sample_rate);
934 ost->sync_opts= lrintf(get_sync_ipts(ost) * enc->sample_rate)
935 - av_fifo_size(ost->fifo)/(enc->channels * osize); //FIXME wrong
937 if (ost->audio_resample) {
939 size_out = audio_resample(ost->resample,
940 (short *)buftmp, (short *)buf,
941 size / (dec->channels * isize));
942 size_out = size_out * enc->channels * osize;
948 if (!ost->audio_resample && dec->sample_fmt!=enc->sample_fmt) {
949 const void *ibuf[6]= {buftmp};
950 void *obuf[6]= {audio_buf};
951 int istride[6]= {isize};
952 int ostride[6]= {osize};
953 int len= size_out/istride[0];
954 if (av_audio_convert(ost->reformat_ctx, obuf, ostride, ibuf, istride, len)<0) {
955 printf("av_audio_convert() failed\n");
961 size_out = len*osize;
964 /* now encode as many frames as possible */
965 if (enc->frame_size > 1) {
966 /* output resampled raw samples */
967 if (av_fifo_realloc2(ost->fifo, av_fifo_size(ost->fifo) + size_out) < 0) {
968 av_log(NULL, AV_LOG_FATAL, "av_fifo_realloc2() failed\n");
971 av_fifo_generic_write(ost->fifo, buftmp, size_out, NULL);
973 frame_bytes = enc->frame_size * osize * enc->channels;
975 while (av_fifo_size(ost->fifo) >= frame_bytes) {
977 av_init_packet(&pkt);
979 av_fifo_generic_read(ost->fifo, audio_buf, frame_bytes, NULL);
981 //FIXME pass ost->sync_opts as AVFrame.pts in avcodec_encode_audio()
983 ret = avcodec_encode_audio(enc, audio_out, audio_out_size,
986 av_log(NULL, AV_LOG_FATAL, "Audio encoding failed\n");
990 pkt.stream_index= ost->index;
993 if(enc->coded_frame && enc->coded_frame->pts != AV_NOPTS_VALUE)
994 pkt.pts= av_rescale_q(enc->coded_frame->pts, enc->time_base, ost->st->time_base);
995 pkt.flags |= AV_PKT_FLAG_KEY;
996 write_frame(s, &pkt, enc, ost->bitstream_filters);
998 ost->sync_opts += enc->frame_size;
1002 av_init_packet(&pkt);
1004 ost->sync_opts += size_out / (osize * enc->channels);
1006 /* output a pcm frame */
1007 /* determine the size of the coded buffer */
1010 size_out = size_out*coded_bps/8;
1012 if(size_out > audio_out_size){
1013 av_log(NULL, AV_LOG_FATAL, "Internal error, buffer size too small\n");
1017 //FIXME pass ost->sync_opts as AVFrame.pts in avcodec_encode_audio()
1018 ret = avcodec_encode_audio(enc, audio_out, size_out,
1021 av_log(NULL, AV_LOG_FATAL, "Audio encoding failed\n");
1025 pkt.stream_index= ost->index;
1026 pkt.data= audio_out;
1028 if(enc->coded_frame && enc->coded_frame->pts != AV_NOPTS_VALUE)
1029 pkt.pts= av_rescale_q(enc->coded_frame->pts, enc->time_base, ost->st->time_base);
1030 pkt.flags |= AV_PKT_FLAG_KEY;
1031 write_frame(s, &pkt, enc, ost->bitstream_filters);
1035 static void pre_process_video_frame(InputStream *ist, AVPicture *picture, void **bufp)
1037 AVCodecContext *dec;
1038 AVPicture *picture2;
1039 AVPicture picture_tmp;
1042 dec = ist->st->codec;
1044 /* deinterlace : must be done before any resize */
1045 if (do_deinterlace) {
1048 /* create temporary picture */
1049 size = avpicture_get_size(dec->pix_fmt, dec->width, dec->height);
1050 buf = av_malloc(size);
1054 picture2 = &picture_tmp;
1055 avpicture_fill(picture2, buf, dec->pix_fmt, dec->width, dec->height);
1057 if(avpicture_deinterlace(picture2, picture,
1058 dec->pix_fmt, dec->width, dec->height) < 0) {
1059 /* if error, do not deinterlace */
1060 av_log(NULL, AV_LOG_WARNING, "Deinterlacing failed\n");
1069 if (picture != picture2)
1070 *picture = *picture2;
1074 static void do_subtitle_out(AVFormatContext *s,
1080 static uint8_t *subtitle_out = NULL;
1081 int subtitle_out_max_size = 1024 * 1024;
1082 int subtitle_out_size, nb, i;
1083 AVCodecContext *enc;
1086 if (pts == AV_NOPTS_VALUE) {
1087 av_log(NULL, AV_LOG_ERROR, "Subtitle packets must have a pts\n");
1093 enc = ost->st->codec;
1095 if (!subtitle_out) {
1096 subtitle_out = av_malloc(subtitle_out_max_size);
1099 /* Note: DVB subtitle need one packet to draw them and one other
1100 packet to clear them */
1101 /* XXX: signal it in the codec context ? */
1102 if (enc->codec_id == CODEC_ID_DVB_SUBTITLE)
1107 for(i = 0; i < nb; i++) {
1108 sub->pts = av_rescale_q(pts, ist->st->time_base, AV_TIME_BASE_Q);
1109 // start_display_time is required to be 0
1110 sub->pts += av_rescale_q(sub->start_display_time, (AVRational){1, 1000}, AV_TIME_BASE_Q);
1111 sub->end_display_time -= sub->start_display_time;
1112 sub->start_display_time = 0;
1113 subtitle_out_size = avcodec_encode_subtitle(enc, subtitle_out,
1114 subtitle_out_max_size, sub);
1115 if (subtitle_out_size < 0) {
1116 av_log(NULL, AV_LOG_FATAL, "Subtitle encoding failed\n");
1120 av_init_packet(&pkt);
1121 pkt.stream_index = ost->index;
1122 pkt.data = subtitle_out;
1123 pkt.size = subtitle_out_size;
1124 pkt.pts = av_rescale_q(sub->pts, AV_TIME_BASE_Q, ost->st->time_base);
1125 if (enc->codec_id == CODEC_ID_DVB_SUBTITLE) {
1126 /* XXX: the pts correction is handled here. Maybe handling
1127 it in the codec would be better */
1129 pkt.pts += 90 * sub->start_display_time;
1131 pkt.pts += 90 * sub->end_display_time;
1133 write_frame(s, &pkt, ost->st->codec, ost->bitstream_filters);
1137 static int bit_buffer_size= 1024*256;
1138 static uint8_t *bit_buffer= NULL;
1140 static void do_video_resample(OutputStream *ost,
1142 AVFrame *in_picture,
1143 AVFrame **out_picture)
1145 int resample_changed = 0;
1146 AVCodecContext *dec = ist->st->codec;
1147 AVCodecContext *enc = ost->st->codec;
1148 *out_picture = in_picture;
1150 resample_changed = ost->resample_width != dec->width ||
1151 ost->resample_height != dec->height ||
1152 ost->resample_pix_fmt != dec->pix_fmt;
1154 #if !CONFIG_AVFILTER
1155 if (resample_changed) {
1156 av_log(NULL, AV_LOG_INFO,
1157 "Input stream #%d:%d frame changed from size:%dx%d fmt:%s to size:%dx%d fmt:%s\n",
1158 ist->file_index, ist->st->index,
1159 ost->resample_width, ost->resample_height, av_get_pix_fmt_name(ost->resample_pix_fmt),
1160 dec->width , dec->height , av_get_pix_fmt_name(dec->pix_fmt));
1161 ost->resample_width = dec->width;
1162 ost->resample_height = dec->height;
1163 ost->resample_pix_fmt = dec->pix_fmt;
1166 ost->video_resample = dec->width != enc->width ||
1167 dec->height != enc->height ||
1168 dec->pix_fmt != enc->pix_fmt;
1170 if (ost->video_resample) {
1171 *out_picture = &ost->resample_frame;
1172 if (!ost->img_resample_ctx || resample_changed) {
1173 /* initialize the destination picture */
1174 if (!ost->resample_frame.data[0]) {
1175 avcodec_get_frame_defaults(&ost->resample_frame);
1176 if (avpicture_alloc((AVPicture *)&ost->resample_frame, enc->pix_fmt,
1177 enc->width, enc->height)) {
1178 fprintf(stderr, "Cannot allocate temp picture, check pix fmt\n");
1182 /* initialize a new scaler context */
1183 sws_freeContext(ost->img_resample_ctx);
1184 ost->img_resample_ctx = sws_getContext(dec->width, dec->height, dec->pix_fmt,
1185 enc->width, enc->height, enc->pix_fmt,
1186 ost->sws_flags, NULL, NULL, NULL);
1187 if (ost->img_resample_ctx == NULL) {
1188 av_log(NULL, AV_LOG_FATAL, "Cannot get resampling context\n");
1192 sws_scale(ost->img_resample_ctx, in_picture->data, in_picture->linesize,
1193 0, ost->resample_height, (*out_picture)->data, (*out_picture)->linesize);
1196 if (resample_changed) {
1197 avfilter_graph_free(&ost->graph);
1198 if (configure_video_filters(ist, ost)) {
1199 av_log(NULL, AV_LOG_FATAL, "Error reinitializing filters!\n");
1204 if (resample_changed) {
1205 ost->resample_width = dec->width;
1206 ost->resample_height = dec->height;
1207 ost->resample_pix_fmt = dec->pix_fmt;
1212 static void do_video_out(AVFormatContext *s,
1215 AVFrame *in_picture,
1216 int *frame_size, float quality)
1218 int nb_frames, i, ret, format_video_sync;
1219 AVFrame *final_picture;
1220 AVCodecContext *enc;
1223 enc = ost->st->codec;
1225 sync_ipts = get_sync_ipts(ost) / av_q2d(enc->time_base);
1227 /* by default, we output a single frame */
1232 format_video_sync = video_sync_method;
1233 if (format_video_sync < 0)
1234 format_video_sync = (s->oformat->flags & AVFMT_NOTIMESTAMPS) ? 0 :
1235 (s->oformat->flags & AVFMT_VARIABLE_FPS) ? 2 : 1;
1237 if (format_video_sync) {
1238 double vdelta = sync_ipts - ost->sync_opts;
1239 //FIXME set to 0.5 after we fix some dts/pts bugs like in avidec.c
1242 else if (format_video_sync == 2) {
1245 }else if(vdelta>0.6)
1246 ost->sync_opts= lrintf(sync_ipts);
1247 }else if (vdelta > 1.1)
1248 nb_frames = lrintf(vdelta);
1249 //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);
1250 if (nb_frames == 0){
1252 av_log(NULL, AV_LOG_VERBOSE, "*** drop!\n");
1253 }else if (nb_frames > 1) {
1254 nb_frames_dup += nb_frames - 1;
1255 av_log(NULL, AV_LOG_VERBOSE, "*** %d dup!\n", nb_frames-1);
1258 ost->sync_opts= lrintf(sync_ipts);
1260 nb_frames = FFMIN(nb_frames, ost->max_frames - ost->frame_number);
1264 do_video_resample(ost, ist, in_picture, &final_picture);
1266 /* duplicates frame if needed */
1267 for(i=0;i<nb_frames;i++) {
1269 av_init_packet(&pkt);
1270 pkt.stream_index= ost->index;
1272 if (s->oformat->flags & AVFMT_RAWPICTURE &&
1273 enc->codec->id == CODEC_ID_RAWVIDEO) {
1274 /* raw pictures are written as AVPicture structure to
1275 avoid any copies. We support temporarily the older
1277 enc->coded_frame->interlaced_frame = in_picture->interlaced_frame;
1278 enc->coded_frame->top_field_first = in_picture->top_field_first;
1279 pkt.data= (uint8_t *)final_picture;
1280 pkt.size= sizeof(AVPicture);
1281 pkt.pts= av_rescale_q(ost->sync_opts, enc->time_base, ost->st->time_base);
1282 pkt.flags |= AV_PKT_FLAG_KEY;
1284 write_frame(s, &pkt, ost->st->codec, ost->bitstream_filters);
1286 AVFrame big_picture;
1288 big_picture= *final_picture;
1289 /* better than nothing: use input picture interlaced
1291 big_picture.interlaced_frame = in_picture->interlaced_frame;
1292 if (ost->st->codec->flags & (CODEC_FLAG_INTERLACED_DCT|CODEC_FLAG_INTERLACED_ME)) {
1293 if (ost->top_field_first == -1)
1294 big_picture.top_field_first = in_picture->top_field_first;
1296 big_picture.top_field_first = !!ost->top_field_first;
1299 /* handles same_quant here. This is not correct because it may
1300 not be a global option */
1301 big_picture.quality = quality;
1302 if (!enc->me_threshold)
1303 big_picture.pict_type = 0;
1304 // big_picture.pts = AV_NOPTS_VALUE;
1305 big_picture.pts= ost->sync_opts;
1306 // big_picture.pts= av_rescale(ost->sync_opts, AV_TIME_BASE*(int64_t)enc->time_base.num, enc->time_base.den);
1307 //av_log(NULL, AV_LOG_DEBUG, "%"PRId64" -> encoder\n", ost->sync_opts);
1308 if (ost->forced_kf_index < ost->forced_kf_count &&
1309 big_picture.pts >= ost->forced_kf_pts[ost->forced_kf_index]) {
1310 big_picture.pict_type = AV_PICTURE_TYPE_I;
1311 ost->forced_kf_index++;
1313 ret = avcodec_encode_video(enc,
1314 bit_buffer, bit_buffer_size,
1317 av_log(NULL, AV_LOG_FATAL, "Video encoding failed\n");
1322 pkt.data= bit_buffer;
1324 if(enc->coded_frame->pts != AV_NOPTS_VALUE)
1325 pkt.pts= av_rescale_q(enc->coded_frame->pts, enc->time_base, ost->st->time_base);
1326 /*av_log(NULL, AV_LOG_DEBUG, "encoder -> %"PRId64"/%"PRId64"\n",
1327 pkt.pts != AV_NOPTS_VALUE ? av_rescale(pkt.pts, enc->time_base.den, AV_TIME_BASE*(int64_t)enc->time_base.num) : -1,
1328 pkt.dts != AV_NOPTS_VALUE ? av_rescale(pkt.dts, enc->time_base.den, AV_TIME_BASE*(int64_t)enc->time_base.num) : -1);*/
1330 if(enc->coded_frame->key_frame)
1331 pkt.flags |= AV_PKT_FLAG_KEY;
1332 write_frame(s, &pkt, ost->st->codec, ost->bitstream_filters);
1335 //fprintf(stderr,"\nFrame: %3d size: %5d type: %d",
1336 // enc->frame_number-1, ret, enc->pict_type);
1337 /* if two pass, output log */
1338 if (ost->logfile && enc->stats_out) {
1339 fprintf(ost->logfile, "%s", enc->stats_out);
1344 ost->frame_number++;
1348 static double psnr(double d){
1349 return -10.0*log(d)/log(10.0);
1352 static void do_video_stats(AVFormatContext *os, OutputStream *ost,
1355 AVCodecContext *enc;
1357 double ti1, bitrate, avg_bitrate;
1359 /* this is executed just the first time do_video_stats is called */
1361 vstats_file = fopen(vstats_filename, "w");
1368 enc = ost->st->codec;
1369 if (enc->codec_type == AVMEDIA_TYPE_VIDEO) {
1370 frame_number = ost->frame_number;
1371 fprintf(vstats_file, "frame= %5d q= %2.1f ", frame_number, enc->coded_frame->quality/(float)FF_QP2LAMBDA);
1372 if (enc->flags&CODEC_FLAG_PSNR)
1373 fprintf(vstats_file, "PSNR= %6.2f ", psnr(enc->coded_frame->error[0]/(enc->width*enc->height*255.0*255.0)));
1375 fprintf(vstats_file,"f_size= %6d ", frame_size);
1376 /* compute pts value */
1377 ti1 = ost->sync_opts * av_q2d(enc->time_base);
1381 bitrate = (frame_size * 8) / av_q2d(enc->time_base) / 1000.0;
1382 avg_bitrate = (double)(video_size * 8) / ti1 / 1000.0;
1383 fprintf(vstats_file, "s_size= %8.0fkB time= %0.3f br= %7.1fkbits/s avg_br= %7.1fkbits/s ",
1384 (double)video_size / 1024, ti1, bitrate, avg_bitrate);
1385 fprintf(vstats_file, "type= %c\n", av_get_picture_type_char(enc->coded_frame->pict_type));
1389 static void print_report(OutputFile *output_files,
1390 OutputStream *ost_table, int nb_ostreams,
1391 int is_last_report, int64_t timer_start)
1395 AVFormatContext *oc;
1397 AVCodecContext *enc;
1398 int frame_number, vid, i;
1400 int64_t pts = INT64_MAX;
1401 static int64_t last_time = -1;
1402 static int qp_histogram[52];
1403 int hours, mins, secs, us;
1405 if (!print_stats && !is_last_report)
1408 if (!is_last_report) {
1410 /* display the report every 0.5 seconds */
1411 cur_time = av_gettime();
1412 if (last_time == -1) {
1413 last_time = cur_time;
1416 if ((cur_time - last_time) < 500000)
1418 last_time = cur_time;
1422 oc = output_files[0].ctx;
1424 total_size = avio_size(oc->pb);
1425 if(total_size<0) // FIXME improve avio_size() so it works with non seekable output too
1426 total_size= avio_tell(oc->pb);
1430 for(i=0;i<nb_ostreams;i++) {
1432 ost = &ost_table[i];
1433 enc = ost->st->codec;
1434 if (!ost->stream_copy && enc->coded_frame)
1435 q = enc->coded_frame->quality/(float)FF_QP2LAMBDA;
1436 if (vid && enc->codec_type == AVMEDIA_TYPE_VIDEO) {
1437 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "q=%2.1f ", q);
1439 if (!vid && enc->codec_type == AVMEDIA_TYPE_VIDEO) {
1440 float t = (av_gettime()-timer_start) / 1000000.0;
1442 frame_number = ost->frame_number;
1443 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "frame=%5d fps=%3d q=%3.1f ",
1444 frame_number, (t>1)?(int)(frame_number/t+0.5) : 0, q);
1446 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "L");
1450 if(qp>=0 && qp<FF_ARRAY_ELEMS(qp_histogram))
1453 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "%X", (int)lrintf(log(qp_histogram[j]+1)/log(2)));
1455 if (enc->flags&CODEC_FLAG_PSNR){
1457 double error, error_sum=0;
1458 double scale, scale_sum=0;
1459 char type[3]= {'Y','U','V'};
1460 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "PSNR=");
1463 error= enc->error[j];
1464 scale= enc->width*enc->height*255.0*255.0*frame_number;
1466 error= enc->coded_frame->error[j];
1467 scale= enc->width*enc->height*255.0*255.0;
1472 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "%c:%2.2f ", type[j], psnr(error/scale));
1474 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "*:%2.2f ", psnr(error_sum/scale_sum));
1478 /* compute min output value */
1479 pts = FFMIN(pts, av_rescale_q(ost->st->pts.val,
1480 ost->st->time_base, AV_TIME_BASE_Q));
1483 secs = pts / AV_TIME_BASE;
1484 us = pts % AV_TIME_BASE;
1490 bitrate = pts ? total_size * 8 / (pts / 1000.0) : 0;
1492 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
1493 "size=%8.0fkB time=", total_size / 1024.0);
1494 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
1495 "%02d:%02d:%02d.%02d ", hours, mins, secs,
1496 (100 * us) / AV_TIME_BASE);
1497 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
1498 "bitrate=%6.1fkbits/s", bitrate);
1500 if (nb_frames_dup || nb_frames_drop)
1501 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), " dup=%d drop=%d",
1502 nb_frames_dup, nb_frames_drop);
1504 av_log(NULL, AV_LOG_INFO, "%s \r", buf);
1508 if (is_last_report) {
1509 int64_t raw= audio_size + video_size + extra_size;
1510 av_log(NULL, AV_LOG_INFO, "\n");
1511 av_log(NULL, AV_LOG_INFO, "video:%1.0fkB audio:%1.0fkB global headers:%1.0fkB muxing overhead %f%%\n",
1515 100.0*(total_size - raw)/raw
1520 static void flush_encoders(OutputStream *ost_table, int nb_ostreams)
1524 for (i = 0; i < nb_ostreams; i++) {
1525 OutputStream *ost = &ost_table[i];
1526 AVCodecContext *enc = ost->st->codec;
1527 AVFormatContext *os = output_files[ost->file_index].ctx;
1529 if (!ost->encoding_needed)
1532 if (ost->st->codec->codec_type == AVMEDIA_TYPE_AUDIO && enc->frame_size <=1)
1534 if (ost->st->codec->codec_type == AVMEDIA_TYPE_VIDEO && (os->oformat->flags & AVFMT_RAWPICTURE) && enc->codec->id == CODEC_ID_RAWVIDEO)
1540 av_init_packet(&pkt);
1541 pkt.stream_index= ost->index;
1543 switch (ost->st->codec->codec_type) {
1544 case AVMEDIA_TYPE_AUDIO:
1545 fifo_bytes = av_fifo_size(ost->fifo);
1547 /* encode any samples remaining in fifo */
1548 if (fifo_bytes > 0) {
1549 int osize = av_get_bytes_per_sample(enc->sample_fmt);
1550 int fs_tmp = enc->frame_size;
1552 av_fifo_generic_read(ost->fifo, audio_buf, fifo_bytes, NULL);
1553 if (enc->codec->capabilities & CODEC_CAP_SMALL_LAST_FRAME) {
1554 enc->frame_size = fifo_bytes / (osize * enc->channels);
1556 int frame_bytes = enc->frame_size*osize*enc->channels;
1557 if (allocated_audio_buf_size < frame_bytes)
1559 generate_silence(audio_buf+fifo_bytes, enc->sample_fmt, frame_bytes - fifo_bytes);
1562 ret = avcodec_encode_audio(enc, bit_buffer, bit_buffer_size, (short *)audio_buf);
1563 pkt.duration = av_rescale((int64_t)enc->frame_size*ost->st->time_base.den,
1564 ost->st->time_base.num, enc->sample_rate);
1565 enc->frame_size = fs_tmp;
1568 ret = avcodec_encode_audio(enc, bit_buffer, bit_buffer_size, NULL);
1571 av_log(NULL, AV_LOG_FATAL, "Audio encoding failed\n");
1575 pkt.flags |= AV_PKT_FLAG_KEY;
1577 case AVMEDIA_TYPE_VIDEO:
1578 ret = avcodec_encode_video(enc, bit_buffer, bit_buffer_size, NULL);
1580 av_log(NULL, AV_LOG_FATAL, "Video encoding failed\n");
1584 if(enc->coded_frame && enc->coded_frame->key_frame)
1585 pkt.flags |= AV_PKT_FLAG_KEY;
1586 if (ost->logfile && enc->stats_out) {
1587 fprintf(ost->logfile, "%s", enc->stats_out);
1596 pkt.data = bit_buffer;
1598 if (enc->coded_frame && enc->coded_frame->pts != AV_NOPTS_VALUE)
1599 pkt.pts= av_rescale_q(enc->coded_frame->pts, enc->time_base, ost->st->time_base);
1600 write_frame(os, &pkt, ost->st->codec, ost->bitstream_filters);
1606 * Check whether a packet from ist should be written into ost at this time
1608 static int check_output_constraints(InputStream *ist, OutputStream *ost)
1610 OutputFile *of = &output_files[ost->file_index];
1611 int ist_index = ist - input_streams;
1613 if (ost->source_index != ist_index)
1616 if (of->start_time && ist->pts < of->start_time)
1619 if (of->recording_time != INT64_MAX &&
1620 av_compare_ts(ist->pts, AV_TIME_BASE_Q, of->recording_time + of->start_time,
1621 (AVRational){1, 1000000}) >= 0) {
1622 ost->is_past_recording_time = 1;
1629 static void do_streamcopy(InputStream *ist, OutputStream *ost, const AVPacket *pkt)
1631 OutputFile *of = &output_files[ost->file_index];
1632 int64_t ost_tb_start_time = av_rescale_q(of->start_time, AV_TIME_BASE_Q, ost->st->time_base);
1636 av_init_packet(&opkt);
1638 if ((!ost->frame_number && !(pkt->flags & AV_PKT_FLAG_KEY)) &&
1639 !ost->copy_initial_nonkeyframes)
1642 /* force the input stream PTS */
1643 if (ost->st->codec->codec_type == AVMEDIA_TYPE_AUDIO)
1644 audio_size += pkt->size;
1645 else if (ost->st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
1646 video_size += pkt->size;
1650 opkt.stream_index = ost->index;
1651 if (pkt->pts != AV_NOPTS_VALUE)
1652 opkt.pts = av_rescale_q(pkt->pts, ist->st->time_base, ost->st->time_base) - ost_tb_start_time;
1654 opkt.pts = AV_NOPTS_VALUE;
1656 if (pkt->dts == AV_NOPTS_VALUE)
1657 opkt.dts = av_rescale_q(ist->pts, AV_TIME_BASE_Q, ost->st->time_base);
1659 opkt.dts = av_rescale_q(pkt->dts, ist->st->time_base, ost->st->time_base);
1660 opkt.dts -= ost_tb_start_time;
1662 opkt.duration = av_rescale_q(pkt->duration, ist->st->time_base, ost->st->time_base);
1663 opkt.flags = pkt->flags;
1665 //FIXME remove the following 2 lines they shall be replaced by the bitstream filters
1666 if( ost->st->codec->codec_id != CODEC_ID_H264
1667 && ost->st->codec->codec_id != CODEC_ID_MPEG1VIDEO
1668 && ost->st->codec->codec_id != CODEC_ID_MPEG2VIDEO
1670 if (av_parser_change(ist->st->parser, ost->st->codec, &opkt.data, &opkt.size, pkt->data, pkt->size, pkt->flags & AV_PKT_FLAG_KEY))
1671 opkt.destruct = av_destruct_packet;
1673 opkt.data = pkt->data;
1674 opkt.size = pkt->size;
1676 if (of->ctx->oformat->flags & AVFMT_RAWPICTURE) {
1677 /* store AVPicture in AVPacket, as expected by the output format */
1678 avpicture_fill(&pict, opkt.data, ost->st->codec->pix_fmt, ost->st->codec->width, ost->st->codec->height);
1679 opkt.data = (uint8_t *)&pict;
1680 opkt.size = sizeof(AVPicture);
1681 opkt.flags |= AV_PKT_FLAG_KEY;
1684 write_frame(of->ctx, &opkt, ost->st->codec, ost->bitstream_filters);
1685 ost->st->codec->frame_number++;
1686 ost->frame_number++;
1687 av_free_packet(&opkt);
1690 static void rate_emu_sleep(InputStream *ist)
1692 if (input_files[ist->file_index].rate_emu) {
1693 int64_t pts = av_rescale(ist->pts, 1000000, AV_TIME_BASE);
1694 int64_t now = av_gettime() - ist->start;
1700 static int transcode_audio(InputStream *ist, AVPacket *pkt, int *got_output)
1702 AVFrame *decoded_frame;
1703 AVCodecContext *avctx = ist->st->codec;
1704 int bps = av_get_bytes_per_sample(ist->st->codec->sample_fmt);
1707 if (!ist->decoded_frame && !(ist->decoded_frame = avcodec_alloc_frame()))
1708 return AVERROR(ENOMEM);
1710 avcodec_get_frame_defaults(ist->decoded_frame);
1711 decoded_frame = ist->decoded_frame;
1713 ret = avcodec_decode_audio4(avctx, decoded_frame, got_output, pkt);
1719 /* no audio frame */
1723 /* if the decoder provides a pts, use it instead of the last packet pts.
1724 the decoder could be delaying output by a packet or more. */
1725 if (decoded_frame->pts != AV_NOPTS_VALUE)
1726 ist->next_pts = decoded_frame->pts;
1728 /* increment next_pts to use for the case where the input stream does not
1729 have timestamps or there are multiple frames in the packet */
1730 ist->next_pts += ((int64_t)AV_TIME_BASE * decoded_frame->nb_samples) /
1733 // preprocess audio (volume)
1734 if (audio_volume != 256) {
1735 int decoded_data_size = decoded_frame->nb_samples * avctx->channels * bps;
1736 void *samples = decoded_frame->data[0];
1737 switch (avctx->sample_fmt) {
1738 case AV_SAMPLE_FMT_U8:
1740 uint8_t *volp = samples;
1741 for (i = 0; i < (decoded_data_size / sizeof(*volp)); i++) {
1742 int v = (((*volp - 128) * audio_volume + 128) >> 8) + 128;
1743 *volp++ = av_clip_uint8(v);
1747 case AV_SAMPLE_FMT_S16:
1749 int16_t *volp = samples;
1750 for (i = 0; i < (decoded_data_size / sizeof(*volp)); i++) {
1751 int v = ((*volp) * audio_volume + 128) >> 8;
1752 *volp++ = av_clip_int16(v);
1756 case AV_SAMPLE_FMT_S32:
1758 int32_t *volp = samples;
1759 for (i = 0; i < (decoded_data_size / sizeof(*volp)); i++) {
1760 int64_t v = (((int64_t)*volp * audio_volume + 128) >> 8);
1761 *volp++ = av_clipl_int32(v);
1765 case AV_SAMPLE_FMT_FLT:
1767 float *volp = samples;
1768 float scale = audio_volume / 256.f;
1769 for (i = 0; i < (decoded_data_size / sizeof(*volp)); i++) {
1774 case AV_SAMPLE_FMT_DBL:
1776 double *volp = samples;
1777 double scale = audio_volume / 256.;
1778 for (i = 0; i < (decoded_data_size / sizeof(*volp)); i++) {
1784 av_log(NULL, AV_LOG_FATAL,
1785 "Audio volume adjustment on sample format %s is not supported.\n",
1786 av_get_sample_fmt_name(ist->st->codec->sample_fmt));
1791 rate_emu_sleep(ist);
1793 for (i = 0; i < nb_output_streams; i++) {
1794 OutputStream *ost = &output_streams[i];
1796 if (!check_output_constraints(ist, ost) || !ost->encoding_needed)
1798 do_audio_out(output_files[ost->file_index].ctx, ost, ist, decoded_frame);
1804 static int transcode_video(InputStream *ist, AVPacket *pkt, int *got_output, int64_t *pkt_pts)
1806 AVFrame *decoded_frame, *filtered_frame = NULL;
1807 void *buffer_to_free = NULL;
1811 int frame_available = 1;
1814 if (!ist->decoded_frame && !(ist->decoded_frame = avcodec_alloc_frame()))
1815 return AVERROR(ENOMEM);
1817 avcodec_get_frame_defaults(ist->decoded_frame);
1818 decoded_frame = ist->decoded_frame;
1819 pkt->pts = *pkt_pts;
1820 pkt->dts = ist->pts;
1821 *pkt_pts = AV_NOPTS_VALUE;
1823 ret = avcodec_decode_video2(ist->st->codec,
1824 decoded_frame, got_output, pkt);
1828 quality = same_quant ? decoded_frame->quality : 0;
1830 /* no picture yet */
1833 ist->next_pts = ist->pts = decoded_frame->best_effort_timestamp;
1835 ist->next_pts += av_rescale_q(pkt->duration, ist->st->time_base, AV_TIME_BASE_Q);
1836 else if (ist->st->codec->time_base.num != 0) {
1837 int ticks = ist->st->parser ? ist->st->parser->repeat_pict + 1 :
1838 ist->st->codec->ticks_per_frame;
1839 ist->next_pts += ((int64_t)AV_TIME_BASE *
1840 ist->st->codec->time_base.num * ticks) /
1841 ist->st->codec->time_base.den;
1844 pre_process_video_frame(ist, (AVPicture *)decoded_frame, &buffer_to_free);
1846 rate_emu_sleep(ist);
1848 for (i = 0; i < nb_output_streams; i++) {
1849 OutputStream *ost = &output_streams[i];
1852 if (!check_output_constraints(ist, ost) || !ost->encoding_needed)
1856 if (ost->input_video_filter) {
1857 if (!decoded_frame->sample_aspect_ratio.num)
1858 decoded_frame->sample_aspect_ratio = ist->st->sample_aspect_ratio;
1859 decoded_frame->pts = ist->pts;
1861 av_vsrc_buffer_add_frame(ost->input_video_filter, decoded_frame, AV_VSRC_BUF_FLAG_OVERWRITE);
1862 if (!ist->filtered_frame && !(ist->filtered_frame = avcodec_alloc_frame())) {
1863 av_free(buffer_to_free);
1864 return AVERROR(ENOMEM);
1866 avcodec_get_frame_defaults(ist->filtered_frame);
1867 filtered_frame = ist->filtered_frame;
1868 frame_available = avfilter_poll_frame(ost->output_video_filter->inputs[0]);
1870 while (frame_available) {
1871 if (ost->output_video_filter) {
1872 AVRational ist_pts_tb = ost->output_video_filter->inputs[0]->time_base;
1873 if (av_buffersink_get_buffer_ref(ost->output_video_filter, &ost->picref, 0) < 0)
1876 avfilter_fill_frame_from_video_buffer_ref(filtered_frame, ost->picref);
1877 ist->pts = av_rescale_q(ost->picref->pts, ist_pts_tb, AV_TIME_BASE_Q);
1880 if (ost->picref->video && !ost->frame_aspect_ratio)
1881 ost->st->codec->sample_aspect_ratio = ost->picref->video->sample_aspect_ratio;
1883 filtered_frame = decoded_frame;
1886 do_video_out(output_files[ost->file_index].ctx, ost, ist, filtered_frame, &frame_size,
1887 same_quant ? quality : ost->st->codec->global_quality);
1888 if (vstats_filename && frame_size)
1889 do_video_stats(output_files[ost->file_index].ctx, ost, frame_size);
1892 frame_available = ost->output_video_filter && avfilter_poll_frame(ost->output_video_filter->inputs[0]);
1894 avfilter_unref_buffer(ost->picref);
1899 av_free(buffer_to_free);
1903 static int transcode_subtitles(InputStream *ist, AVPacket *pkt, int *got_output)
1905 AVSubtitle subtitle;
1906 int i, ret = avcodec_decode_subtitle2(ist->st->codec,
1907 &subtitle, got_output, pkt);
1913 rate_emu_sleep(ist);
1915 for (i = 0; i < nb_output_streams; i++) {
1916 OutputStream *ost = &output_streams[i];
1918 if (!check_output_constraints(ist, ost) || !ost->encoding_needed)
1921 do_subtitle_out(output_files[ost->file_index].ctx, ost, ist, &subtitle, pkt->pts);
1924 avsubtitle_free(&subtitle);
1928 /* pkt = NULL means EOF (needed to flush decoder buffers) */
1929 static int output_packet(InputStream *ist,
1930 OutputStream *ost_table, int nb_ostreams,
1931 const AVPacket *pkt)
1935 int64_t pkt_pts = AV_NOPTS_VALUE;
1938 if (ist->next_pts == AV_NOPTS_VALUE)
1939 ist->next_pts = ist->pts;
1943 av_init_packet(&avpkt);
1951 if(pkt->dts != AV_NOPTS_VALUE)
1952 ist->next_pts = ist->pts = av_rescale_q(pkt->dts, ist->st->time_base, AV_TIME_BASE_Q);
1953 if(pkt->pts != AV_NOPTS_VALUE)
1954 pkt_pts = av_rescale_q(pkt->pts, ist->st->time_base, AV_TIME_BASE_Q);
1956 //while we have more to decode or while the decoder did output something on EOF
1957 while (ist->decoding_needed && (avpkt.size > 0 || (!pkt && got_output))) {
1961 ist->pts = ist->next_pts;
1963 if (avpkt.size && avpkt.size != pkt->size) {
1964 av_log(NULL, ist->showed_multi_packet_warning ? AV_LOG_VERBOSE : AV_LOG_WARNING,
1965 "Multiple frames in a packet from stream %d\n", pkt->stream_index);
1966 ist->showed_multi_packet_warning = 1;
1969 switch(ist->st->codec->codec_type) {
1970 case AVMEDIA_TYPE_AUDIO:
1971 ret = transcode_audio (ist, &avpkt, &got_output);
1973 case AVMEDIA_TYPE_VIDEO:
1974 ret = transcode_video (ist, &avpkt, &got_output, &pkt_pts);
1976 case AVMEDIA_TYPE_SUBTITLE:
1977 ret = transcode_subtitles(ist, &avpkt, &got_output);
1985 // touch data and size only if not EOF
1995 /* handle stream copy */
1996 if (!ist->decoding_needed) {
1997 rate_emu_sleep(ist);
1998 ist->pts = ist->next_pts;
1999 switch (ist->st->codec->codec_type) {
2000 case AVMEDIA_TYPE_AUDIO:
2001 ist->next_pts += ((int64_t)AV_TIME_BASE * ist->st->codec->frame_size) /
2002 ist->st->codec->sample_rate;
2004 case AVMEDIA_TYPE_VIDEO:
2005 if (ist->st->codec->time_base.num != 0) {
2006 int ticks = ist->st->parser ? ist->st->parser->repeat_pict+1 : ist->st->codec->ticks_per_frame;
2007 ist->next_pts += ((int64_t)AV_TIME_BASE *
2008 ist->st->codec->time_base.num * ticks) /
2009 ist->st->codec->time_base.den;
2014 for (i = 0; pkt && i < nb_ostreams; i++) {
2015 OutputStream *ost = &ost_table[i];
2017 if (!check_output_constraints(ist, ost) || ost->encoding_needed)
2020 do_streamcopy(ist, ost, pkt);
2026 static void print_sdp(OutputFile *output_files, int n)
2030 AVFormatContext **avc = av_malloc(sizeof(*avc)*n);
2034 for (i = 0; i < n; i++)
2035 avc[i] = output_files[i].ctx;
2037 av_sdp_create(avc, n, sdp, sizeof(sdp));
2038 printf("SDP:\n%s\n", sdp);
2043 static int init_input_stream(int ist_index, OutputStream *output_streams, int nb_output_streams,
2044 char *error, int error_len)
2047 InputStream *ist = &input_streams[ist_index];
2048 if (ist->decoding_needed) {
2049 AVCodec *codec = ist->dec;
2051 snprintf(error, error_len, "Decoder (codec id %d) not found for input stream #%d:%d",
2052 ist->st->codec->codec_id, ist->file_index, ist->st->index);
2053 return AVERROR(EINVAL);
2056 if (avcodec_open2(ist->st->codec, codec, &ist->opts) < 0) {
2057 snprintf(error, error_len, "Error while opening decoder for input stream #%d:%d",
2058 ist->file_index, ist->st->index);
2059 return AVERROR(EINVAL);
2061 assert_codec_experimental(ist->st->codec, 0);
2062 assert_avoptions(ist->opts);
2065 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;
2066 ist->next_pts = AV_NOPTS_VALUE;
2072 static int transcode_init(OutputFile *output_files,
2073 int nb_output_files,
2074 InputFile *input_files,
2077 int ret = 0, i, j, k;
2078 AVFormatContext *oc;
2079 AVCodecContext *codec, *icodec;
2085 /* init framerate emulation */
2086 for (i = 0; i < nb_input_files; i++) {
2087 InputFile *ifile = &input_files[i];
2088 if (ifile->rate_emu)
2089 for (j = 0; j < ifile->nb_streams; j++)
2090 input_streams[j + ifile->ist_index].start = av_gettime();
2093 /* output stream init */
2094 for (i = 0; i < nb_output_files; i++) {
2095 oc = output_files[i].ctx;
2096 if (!oc->nb_streams && !(oc->oformat->flags & AVFMT_NOSTREAMS)) {
2097 av_dump_format(oc, i, oc->filename, 1);
2098 av_log(NULL, AV_LOG_ERROR, "Output file #%d does not contain any stream\n", i);
2099 return AVERROR(EINVAL);
2103 /* for each output stream, we compute the right encoding parameters */
2104 for (i = 0; i < nb_output_streams; i++) {
2105 ost = &output_streams[i];
2106 oc = output_files[ost->file_index].ctx;
2107 ist = &input_streams[ost->source_index];
2109 if (ost->attachment_filename)
2112 codec = ost->st->codec;
2113 icodec = ist->st->codec;
2115 ost->st->disposition = ist->st->disposition;
2116 codec->bits_per_raw_sample = icodec->bits_per_raw_sample;
2117 codec->chroma_sample_location = icodec->chroma_sample_location;
2119 if (ost->stream_copy) {
2120 uint64_t extra_size = (uint64_t)icodec->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE;
2122 if (extra_size > INT_MAX) {
2123 return AVERROR(EINVAL);
2126 /* if stream_copy is selected, no need to decode or encode */
2127 codec->codec_id = icodec->codec_id;
2128 codec->codec_type = icodec->codec_type;
2130 if (!codec->codec_tag) {
2131 if (!oc->oformat->codec_tag ||
2132 av_codec_get_id (oc->oformat->codec_tag, icodec->codec_tag) == codec->codec_id ||
2133 av_codec_get_tag(oc->oformat->codec_tag, icodec->codec_id) <= 0)
2134 codec->codec_tag = icodec->codec_tag;
2137 codec->bit_rate = icodec->bit_rate;
2138 codec->rc_max_rate = icodec->rc_max_rate;
2139 codec->rc_buffer_size = icodec->rc_buffer_size;
2140 codec->extradata = av_mallocz(extra_size);
2141 if (!codec->extradata) {
2142 return AVERROR(ENOMEM);
2144 memcpy(codec->extradata, icodec->extradata, icodec->extradata_size);
2146 codec->extradata_size = icodec->extradata_size;
2148 codec->time_base = icodec->time_base;
2149 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 codec->time_base = ist->st->time_base;
2155 switch(codec->codec_type) {
2156 case AVMEDIA_TYPE_AUDIO:
2157 if(audio_volume != 256) {
2158 av_log(NULL, AV_LOG_FATAL, "-acodec copy and -vol are incompatible (frames are not decoded)\n");
2161 codec->channel_layout = icodec->channel_layout;
2162 codec->sample_rate = icodec->sample_rate;
2163 codec->channels = icodec->channels;
2164 codec->frame_size = icodec->frame_size;
2165 codec->audio_service_type = icodec->audio_service_type;
2166 codec->block_align = icodec->block_align;
2168 case AVMEDIA_TYPE_VIDEO:
2169 codec->pix_fmt = icodec->pix_fmt;
2170 codec->width = icodec->width;
2171 codec->height = icodec->height;
2172 codec->has_b_frames = icodec->has_b_frames;
2173 if (!codec->sample_aspect_ratio.num) {
2174 codec->sample_aspect_ratio =
2175 ost->st->sample_aspect_ratio =
2176 ist->st->sample_aspect_ratio.num ? ist->st->sample_aspect_ratio :
2177 ist->st->codec->sample_aspect_ratio.num ?
2178 ist->st->codec->sample_aspect_ratio : (AVRational){0, 1};
2181 case AVMEDIA_TYPE_SUBTITLE:
2182 codec->width = icodec->width;
2183 codec->height = icodec->height;
2185 case AVMEDIA_TYPE_DATA:
2186 case AVMEDIA_TYPE_ATTACHMENT:
2193 ost->enc = avcodec_find_encoder(ost->st->codec->codec_id);
2195 ist->decoding_needed = 1;
2196 ost->encoding_needed = 1;
2198 switch(codec->codec_type) {
2199 case AVMEDIA_TYPE_AUDIO:
2200 ost->fifo = av_fifo_alloc(1024);
2202 return AVERROR(ENOMEM);
2204 ost->reformat_pair = MAKE_SFMT_PAIR(AV_SAMPLE_FMT_NONE,AV_SAMPLE_FMT_NONE);
2206 if (!codec->sample_rate)
2207 codec->sample_rate = icodec->sample_rate;
2208 choose_sample_rate(ost->st, ost->enc);
2209 codec->time_base = (AVRational){1, codec->sample_rate};
2211 if (codec->sample_fmt == AV_SAMPLE_FMT_NONE)
2212 codec->sample_fmt = icodec->sample_fmt;
2213 choose_sample_fmt(ost->st, ost->enc);
2215 if (!codec->channels) {
2216 codec->channels = icodec->channels;
2217 codec->channel_layout = icodec->channel_layout;
2219 if (av_get_channel_layout_nb_channels(codec->channel_layout) != codec->channels)
2220 codec->channel_layout = 0;
2222 ost->audio_resample = codec-> sample_rate != icodec->sample_rate || audio_sync_method > 1;
2223 icodec->request_channels = codec-> channels;
2224 ost->resample_sample_fmt = icodec->sample_fmt;
2225 ost->resample_sample_rate = icodec->sample_rate;
2226 ost->resample_channels = icodec->channels;
2228 case AVMEDIA_TYPE_VIDEO:
2229 if (codec->pix_fmt == PIX_FMT_NONE)
2230 codec->pix_fmt = icodec->pix_fmt;
2231 choose_pixel_fmt(ost->st, ost->enc);
2233 if (ost->st->codec->pix_fmt == PIX_FMT_NONE) {
2234 av_log(NULL, AV_LOG_FATAL, "Video pixel format is unknown, stream cannot be encoded\n");
2238 if (!codec->width || !codec->height) {
2239 codec->width = icodec->width;
2240 codec->height = icodec->height;
2243 ost->video_resample = codec->width != icodec->width ||
2244 codec->height != icodec->height ||
2245 codec->pix_fmt != icodec->pix_fmt;
2246 if (ost->video_resample) {
2247 codec->bits_per_raw_sample= frame_bits_per_raw_sample;
2250 ost->resample_height = icodec->height;
2251 ost->resample_width = icodec->width;
2252 ost->resample_pix_fmt = icodec->pix_fmt;
2254 if (!ost->frame_rate.num)
2255 ost->frame_rate = ist->st->r_frame_rate.num ? ist->st->r_frame_rate : (AVRational){25,1};
2256 if (ost->enc && ost->enc->supported_framerates && !ost->force_fps) {
2257 int idx = av_find_nearest_q_idx(ost->frame_rate, ost->enc->supported_framerates);
2258 ost->frame_rate = ost->enc->supported_framerates[idx];
2260 codec->time_base = (AVRational){ost->frame_rate.den, ost->frame_rate.num};
2261 if( av_q2d(codec->time_base) < 0.001 && video_sync_method
2262 && (video_sync_method==1 || (video_sync_method<0 && !(oc->oformat->flags & AVFMT_VARIABLE_FPS)))){
2263 av_log(oc, AV_LOG_WARNING, "Frame rate very high for a muxer not effciciently supporting it.\n"
2264 "Please consider specifiying a lower framerate, a different muxer or -vsync 2\n");
2268 if (configure_video_filters(ist, ost)) {
2269 av_log(NULL, AV_LOG_FATAL, "Error opening filters!\n");
2274 case AVMEDIA_TYPE_SUBTITLE:
2281 if (codec->codec_id != CODEC_ID_H264 &&
2282 (codec->flags & (CODEC_FLAG_PASS1 | CODEC_FLAG_PASS2))) {
2283 char logfilename[1024];
2286 snprintf(logfilename, sizeof(logfilename), "%s-%d.log",
2287 pass_logfilename_prefix ? pass_logfilename_prefix : DEFAULT_PASS_LOGFILENAME_PREFIX,
2289 if (codec->flags & CODEC_FLAG_PASS1) {
2290 f = fopen(logfilename, "wb");
2292 av_log(NULL, AV_LOG_FATAL, "Cannot write log file '%s' for pass-1 encoding: %s\n",
2293 logfilename, strerror(errno));
2299 size_t logbuffer_size;
2300 if (cmdutils_read_file(logfilename, &logbuffer, &logbuffer_size) < 0) {
2301 av_log(NULL, AV_LOG_FATAL, "Error reading log file '%s' for pass-2 encoding\n",
2305 codec->stats_in = logbuffer;
2309 if(codec->codec_type == AVMEDIA_TYPE_VIDEO){
2310 /* maximum video buffer size is 6-bytes per pixel, plus DPX header size */
2311 int size = codec->width * codec->height;
2312 bit_buffer_size = FFMAX(bit_buffer_size, 6*size + 1664);
2317 bit_buffer = av_malloc(bit_buffer_size);
2319 av_log(NULL, AV_LOG_ERROR, "Cannot allocate %d bytes output buffer\n",
2321 return AVERROR(ENOMEM);
2324 /* open each encoder */
2325 for (i = 0; i < nb_output_streams; i++) {
2326 ost = &output_streams[i];
2327 if (ost->encoding_needed) {
2328 AVCodec *codec = ost->enc;
2329 AVCodecContext *dec = input_streams[ost->source_index].st->codec;
2331 snprintf(error, sizeof(error), "Encoder (codec id %d) not found for output stream #%d:%d",
2332 ost->st->codec->codec_id, ost->file_index, ost->index);
2333 ret = AVERROR(EINVAL);
2336 if (dec->subtitle_header) {
2337 ost->st->codec->subtitle_header = av_malloc(dec->subtitle_header_size);
2338 if (!ost->st->codec->subtitle_header) {
2339 ret = AVERROR(ENOMEM);
2342 memcpy(ost->st->codec->subtitle_header, dec->subtitle_header, dec->subtitle_header_size);
2343 ost->st->codec->subtitle_header_size = dec->subtitle_header_size;
2345 if (avcodec_open2(ost->st->codec, codec, &ost->opts) < 0) {
2346 snprintf(error, sizeof(error), "Error while opening encoder for output stream #%d:%d - maybe incorrect parameters such as bit_rate, rate, width or height",
2347 ost->file_index, ost->index);
2348 ret = AVERROR(EINVAL);
2351 assert_codec_experimental(ost->st->codec, 1);
2352 assert_avoptions(ost->opts);
2353 if (ost->st->codec->bit_rate && ost->st->codec->bit_rate < 1000)
2354 av_log(NULL, AV_LOG_WARNING, "The bitrate parameter is set too low."
2355 "It takes bits/s as argument, not kbits/s\n");
2356 extra_size += ost->st->codec->extradata_size;
2358 if (ost->st->codec->me_threshold)
2359 input_streams[ost->source_index].st->codec->debug |= FF_DEBUG_MV;
2363 /* init input streams */
2364 for (i = 0; i < nb_input_streams; i++)
2365 if ((ret = init_input_stream(i, output_streams, nb_output_streams, error, sizeof(error))) < 0)
2368 /* discard unused programs */
2369 for (i = 0; i < nb_input_files; i++) {
2370 InputFile *ifile = &input_files[i];
2371 for (j = 0; j < ifile->ctx->nb_programs; j++) {
2372 AVProgram *p = ifile->ctx->programs[j];
2373 int discard = AVDISCARD_ALL;
2375 for (k = 0; k < p->nb_stream_indexes; k++)
2376 if (!input_streams[ifile->ist_index + p->stream_index[k]].discard) {
2377 discard = AVDISCARD_DEFAULT;
2380 p->discard = discard;
2384 /* open files and write file headers */
2385 for (i = 0; i < nb_output_files; i++) {
2386 oc = output_files[i].ctx;
2387 oc->interrupt_callback = int_cb;
2388 if (avformat_write_header(oc, &output_files[i].opts) < 0) {
2389 snprintf(error, sizeof(error), "Could not write header for output file #%d (incorrect codec parameters ?)", i);
2390 ret = AVERROR(EINVAL);
2393 // assert_avoptions(output_files[i].opts);
2394 if (strcmp(oc->oformat->name, "rtp")) {
2400 /* dump the file output parameters - cannot be done before in case
2402 for (i = 0; i < nb_output_files; i++) {
2403 av_dump_format(output_files[i].ctx, i, output_files[i].ctx->filename, 1);
2406 /* dump the stream mapping */
2407 av_log(NULL, AV_LOG_INFO, "Stream mapping:\n");
2408 for (i = 0; i < nb_output_streams; i++) {
2409 ost = &output_streams[i];
2411 if (ost->attachment_filename) {
2412 /* an attached file */
2413 av_log(NULL, AV_LOG_INFO, " File %s -> Stream #%d:%d\n",
2414 ost->attachment_filename, ost->file_index, ost->index);
2417 av_log(NULL, AV_LOG_INFO, " Stream #%d:%d -> #%d:%d",
2418 input_streams[ost->source_index].file_index,
2419 input_streams[ost->source_index].st->index,
2422 if (ost->sync_ist != &input_streams[ost->source_index])
2423 av_log(NULL, AV_LOG_INFO, " [sync #%d:%d]",
2424 ost->sync_ist->file_index,
2425 ost->sync_ist->st->index);
2426 if (ost->stream_copy)
2427 av_log(NULL, AV_LOG_INFO, " (copy)");
2429 av_log(NULL, AV_LOG_INFO, " (%s -> %s)", input_streams[ost->source_index].dec ?
2430 input_streams[ost->source_index].dec->name : "?",
2431 ost->enc ? ost->enc->name : "?");
2432 av_log(NULL, AV_LOG_INFO, "\n");
2436 av_log(NULL, AV_LOG_ERROR, "%s\n", error);
2441 print_sdp(output_files, nb_output_files);
2448 * The following code is the main loop of the file converter
2450 static int transcode(OutputFile *output_files,
2451 int nb_output_files,
2452 InputFile *input_files,
2456 AVFormatContext *is, *os;
2460 int no_packet_count=0;
2461 int64_t timer_start;
2464 if (!(no_packet = av_mallocz(nb_input_files)))
2467 ret = transcode_init(output_files, nb_output_files, input_files, nb_input_files);
2472 av_log(NULL, AV_LOG_INFO, "Press [q] to stop, [?] for help\n");
2473 avio_set_interrupt_cb(decode_interrupt_cb);
2477 timer_start = av_gettime();
2479 for(; received_sigterm == 0;) {
2480 int file_index, ist_index;
2485 ipts_min = INT64_MAX;
2487 /* if 'q' pressed, exits */
2491 /* read_key() returns 0 on EOF */
2495 if (key == '+') av_log_set_level(av_log_get_level()+10);
2496 if (key == '-') av_log_set_level(av_log_get_level()-10);
2497 if (key == 's') qp_hist ^= 1;
2500 do_hex_dump = do_pkt_dump = 0;
2501 } else if(do_pkt_dump){
2505 av_log_set_level(AV_LOG_DEBUG);
2507 if (key == 'd' || key == 'D'){
2510 debug = input_streams[0].st->codec->debug<<1;
2511 if(!debug) debug = 1;
2512 while(debug & (FF_DEBUG_DCT_COEFF|FF_DEBUG_VIS_QP|FF_DEBUG_VIS_MB_TYPE)) //unsupported, would just crash
2515 scanf("%d", &debug);
2516 for(i=0;i<nb_input_streams;i++) {
2517 input_streams[i].st->codec->debug = debug;
2519 for(i=0;i<nb_output_streams;i++) {
2520 ost = &output_streams[i];
2521 ost->st->codec->debug = debug;
2523 if(debug) av_log_set_level(AV_LOG_DEBUG);
2524 fprintf(stderr,"debug=%d\n", debug);
2527 fprintf(stderr, "key function\n"
2528 "? show this help\n"
2529 "+ increase verbosity\n"
2530 "- decrease verbosity\n"
2531 "D cycle through available debug modes\n"
2532 "h dump packets/hex press to cycle through the 3 states\n"
2534 "s Show QP histogram\n"
2539 /* select the stream that we must read now by looking at the
2540 smallest output pts */
2542 for (i = 0; i < nb_output_streams; i++) {
2546 ost = &output_streams[i];
2547 of = &output_files[ost->file_index];
2548 os = output_files[ost->file_index].ctx;
2549 ist = &input_streams[ost->source_index];
2550 if (ost->is_past_recording_time || no_packet[ist->file_index] ||
2551 (os->pb && avio_tell(os->pb) >= of->limit_filesize))
2553 opts = ost->st->pts.val * av_q2d(ost->st->time_base);
2555 if (!input_files[ist->file_index].eof_reached){
2556 if(ipts < ipts_min) {
2558 if(input_sync ) file_index = ist->file_index;
2560 if(opts < opts_min) {
2562 if(!input_sync) file_index = ist->file_index;
2565 if (ost->frame_number >= ost->max_frames) {
2567 for (j = 0; j < of->ctx->nb_streams; j++)
2568 output_streams[of->ost_index + j].is_past_recording_time = 1;
2572 /* if none, if is finished */
2573 if (file_index < 0) {
2574 if(no_packet_count){
2576 memset(no_packet, 0, nb_input_files);
2583 /* read a frame from it and output it in the fifo */
2584 is = input_files[file_index].ctx;
2585 ret= av_read_frame(is, &pkt);
2586 if(ret == AVERROR(EAGAIN)){
2587 no_packet[file_index]=1;
2592 input_files[file_index].eof_reached = 1;
2600 memset(no_packet, 0, nb_input_files);
2603 av_pkt_dump_log2(NULL, AV_LOG_DEBUG, &pkt, do_hex_dump,
2604 is->streams[pkt.stream_index]);
2606 /* the following test is needed in case new streams appear
2607 dynamically in stream : we ignore them */
2608 if (pkt.stream_index >= input_files[file_index].nb_streams)
2609 goto discard_packet;
2610 ist_index = input_files[file_index].ist_index + pkt.stream_index;
2611 ist = &input_streams[ist_index];
2613 goto discard_packet;
2615 if (pkt.dts != AV_NOPTS_VALUE)
2616 pkt.dts += av_rescale_q(input_files[ist->file_index].ts_offset, AV_TIME_BASE_Q, ist->st->time_base);
2617 if (pkt.pts != AV_NOPTS_VALUE)
2618 pkt.pts += av_rescale_q(input_files[ist->file_index].ts_offset, AV_TIME_BASE_Q, ist->st->time_base);
2620 if(pkt.pts != AV_NOPTS_VALUE)
2621 pkt.pts *= ist->ts_scale;
2622 if(pkt.dts != AV_NOPTS_VALUE)
2623 pkt.dts *= ist->ts_scale;
2625 // 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);
2626 if (pkt.dts != AV_NOPTS_VALUE && ist->next_pts != AV_NOPTS_VALUE
2627 && (is->iformat->flags & AVFMT_TS_DISCONT)) {
2628 int64_t pkt_dts= av_rescale_q(pkt.dts, ist->st->time_base, AV_TIME_BASE_Q);
2629 int64_t delta= pkt_dts - ist->next_pts;
2630 if((FFABS(delta) > 1LL*dts_delta_threshold*AV_TIME_BASE || pkt_dts+1<ist->pts)&& !copy_ts){
2631 input_files[ist->file_index].ts_offset -= delta;
2632 av_log(NULL, AV_LOG_DEBUG, "timestamp discontinuity %"PRId64", new offset= %"PRId64"\n",
2633 delta, input_files[ist->file_index].ts_offset);
2634 pkt.dts-= av_rescale_q(delta, AV_TIME_BASE_Q, ist->st->time_base);
2635 if(pkt.pts != AV_NOPTS_VALUE)
2636 pkt.pts-= av_rescale_q(delta, AV_TIME_BASE_Q, ist->st->time_base);
2640 //fprintf(stderr,"read #%d.%d size=%d\n", ist->file_index, ist->st->index, pkt.size);
2641 if (output_packet(ist, output_streams, nb_output_streams, &pkt) < 0) {
2643 av_log(NULL, AV_LOG_ERROR, "Error while decoding stream #%d:%d\n",
2644 ist->file_index, ist->st->index);
2647 av_free_packet(&pkt);
2652 av_free_packet(&pkt);
2654 /* dump report by using the output first video and audio streams */
2655 print_report(output_files, output_streams, nb_output_streams, 0, timer_start);
2658 /* at the end of stream, we must flush the decoder buffers */
2659 for (i = 0; i < nb_input_streams; i++) {
2660 ist = &input_streams[i];
2661 if (ist->decoding_needed) {
2662 output_packet(ist, output_streams, nb_output_streams, NULL);
2665 flush_encoders(output_streams, nb_output_streams);
2669 /* write the trailer if needed and close file */
2670 for(i=0;i<nb_output_files;i++) {
2671 os = output_files[i].ctx;
2672 av_write_trailer(os);
2675 /* dump report by using the first video and audio streams */
2676 print_report(output_files, output_streams, nb_output_streams, 1, timer_start);
2678 /* close each encoder */
2679 for (i = 0; i < nb_output_streams; i++) {
2680 ost = &output_streams[i];
2681 if (ost->encoding_needed) {
2682 av_freep(&ost->st->codec->stats_in);
2683 avcodec_close(ost->st->codec);
2686 avfilter_graph_free(&ost->graph);
2690 /* close each decoder */
2691 for (i = 0; i < nb_input_streams; i++) {
2692 ist = &input_streams[i];
2693 if (ist->decoding_needed) {
2694 avcodec_close(ist->st->codec);
2702 av_freep(&bit_buffer);
2703 av_freep(&no_packet);
2705 if (output_streams) {
2706 for (i = 0; i < nb_output_streams; i++) {
2707 ost = &output_streams[i];
2709 if (ost->stream_copy)
2710 av_freep(&ost->st->codec->extradata);
2712 fclose(ost->logfile);
2713 ost->logfile = NULL;
2715 av_fifo_free(ost->fifo); /* works even if fifo is not
2716 initialized but set to zero */
2717 av_freep(&ost->st->codec->subtitle_header);
2718 av_free(ost->resample_frame.data[0]);
2719 av_free(ost->forced_kf_pts);
2720 if (ost->video_resample)
2721 sws_freeContext(ost->img_resample_ctx);
2723 audio_resample_close(ost->resample);
2724 if (ost->reformat_ctx)
2725 av_audio_convert_free(ost->reformat_ctx);
2726 av_dict_free(&ost->opts);
2733 static double parse_frame_aspect_ratio(const char *arg)
2740 p = strchr(arg, ':');
2742 x = strtol(arg, &end, 10);
2744 y = strtol(end+1, &end, 10);
2746 ar = (double)x / (double)y;
2748 ar = strtod(arg, NULL);
2751 av_log(NULL, AV_LOG_FATAL, "Incorrect aspect ratio specification.\n");
2757 static int opt_audio_codec(OptionsContext *o, const char *opt, const char *arg)
2759 return parse_option(o, "codec:a", arg, options);
2762 static int opt_video_codec(OptionsContext *o, const char *opt, const char *arg)
2764 return parse_option(o, "codec:v", arg, options);
2767 static int opt_subtitle_codec(OptionsContext *o, const char *opt, const char *arg)
2769 return parse_option(o, "codec:s", arg, options);
2772 static int opt_data_codec(OptionsContext *o, const char *opt, const char *arg)
2774 return parse_option(o, "codec:d", arg, options);
2777 static int opt_map(OptionsContext *o, const char *opt, const char *arg)
2779 StreamMap *m = NULL;
2780 int i, negative = 0, file_idx;
2781 int sync_file_idx = -1, sync_stream_idx;
2789 map = av_strdup(arg);
2791 /* parse sync stream first, just pick first matching stream */
2792 if (sync = strchr(map, ',')) {
2794 sync_file_idx = strtol(sync + 1, &sync, 0);
2795 if (sync_file_idx >= nb_input_files || sync_file_idx < 0) {
2796 av_log(NULL, AV_LOG_FATAL, "Invalid sync file index: %d.\n", sync_file_idx);
2801 for (i = 0; i < input_files[sync_file_idx].nb_streams; i++)
2802 if (check_stream_specifier(input_files[sync_file_idx].ctx,
2803 input_files[sync_file_idx].ctx->streams[i], sync) == 1) {
2804 sync_stream_idx = i;
2807 if (i == input_files[sync_file_idx].nb_streams) {
2808 av_log(NULL, AV_LOG_FATAL, "Sync stream specification in map %s does not "
2809 "match any streams.\n", arg);
2815 file_idx = strtol(map, &p, 0);
2816 if (file_idx >= nb_input_files || file_idx < 0) {
2817 av_log(NULL, AV_LOG_FATAL, "Invalid input file index: %d.\n", file_idx);
2821 /* disable some already defined maps */
2822 for (i = 0; i < o->nb_stream_maps; i++) {
2823 m = &o->stream_maps[i];
2824 if (file_idx == m->file_index &&
2825 check_stream_specifier(input_files[m->file_index].ctx,
2826 input_files[m->file_index].ctx->streams[m->stream_index],
2827 *p == ':' ? p + 1 : p) > 0)
2831 for (i = 0; i < input_files[file_idx].nb_streams; i++) {
2832 if (check_stream_specifier(input_files[file_idx].ctx, input_files[file_idx].ctx->streams[i],
2833 *p == ':' ? p + 1 : p) <= 0)
2835 o->stream_maps = grow_array(o->stream_maps, sizeof(*o->stream_maps),
2836 &o->nb_stream_maps, o->nb_stream_maps + 1);
2837 m = &o->stream_maps[o->nb_stream_maps - 1];
2839 m->file_index = file_idx;
2840 m->stream_index = i;
2842 if (sync_file_idx >= 0) {
2843 m->sync_file_index = sync_file_idx;
2844 m->sync_stream_index = sync_stream_idx;
2846 m->sync_file_index = file_idx;
2847 m->sync_stream_index = i;
2852 av_log(NULL, AV_LOG_FATAL, "Stream map '%s' matches no streams.\n", arg);
2860 static int opt_attach(OptionsContext *o, const char *opt, const char *arg)
2862 o->attachments = grow_array(o->attachments, sizeof(*o->attachments),
2863 &o->nb_attachments, o->nb_attachments + 1);
2864 o->attachments[o->nb_attachments - 1] = arg;
2868 static void parse_meta_type(char *arg, char *type, int *index)
2878 if (*(++arg) == ':')
2879 *index = strtol(++arg, NULL, 0);
2882 av_log(NULL, AV_LOG_FATAL, "Invalid metadata type %c.\n", *arg);
2889 static int opt_map_metadata(OptionsContext *o, const char *opt, const char *arg)
2891 MetadataMap *m, *m1;
2894 o->meta_data_maps = grow_array(o->meta_data_maps, sizeof(*o->meta_data_maps),
2895 &o->nb_meta_data_maps, o->nb_meta_data_maps + 1);
2897 m = &o->meta_data_maps[o->nb_meta_data_maps - 1][1];
2898 m->file = strtol(arg, &p, 0);
2899 parse_meta_type(*p ? p + 1 : p, &m->type, &m->index);
2901 m1 = &o->meta_data_maps[o->nb_meta_data_maps - 1][0];
2902 if (p = strchr(opt, ':'))
2903 parse_meta_type(p + 1, &m1->type, &m1->index);
2907 if (m->type == 'g' || m1->type == 'g')
2908 o->metadata_global_manual = 1;
2909 if (m->type == 's' || m1->type == 's')
2910 o->metadata_streams_manual = 1;
2911 if (m->type == 'c' || m1->type == 'c')
2912 o->metadata_chapters_manual = 1;
2917 static AVCodec *find_codec_or_die(const char *name, enum AVMediaType type, int encoder)
2919 const char *codec_string = encoder ? "encoder" : "decoder";
2923 avcodec_find_encoder_by_name(name) :
2924 avcodec_find_decoder_by_name(name);
2926 av_log(NULL, AV_LOG_FATAL, "Unknown %s '%s'\n", codec_string, name);
2929 if(codec->type != type) {
2930 av_log(NULL, AV_LOG_FATAL, "Invalid %s type '%s'\n", codec_string, name);
2936 static AVCodec *choose_decoder(OptionsContext *o, AVFormatContext *s, AVStream *st)
2938 char *codec_name = NULL;
2940 MATCH_PER_STREAM_OPT(codec_names, str, codec_name, s, st);
2942 AVCodec *codec = find_codec_or_die(codec_name, st->codec->codec_type, 0);
2943 st->codec->codec_id = codec->id;
2946 return avcodec_find_decoder(st->codec->codec_id);
2950 * Add all the streams from the given input file to the global
2951 * list of input streams.
2953 static void add_input_streams(OptionsContext *o, AVFormatContext *ic)
2955 int i, rfps, rfps_base;
2957 for (i = 0; i < ic->nb_streams; i++) {
2958 AVStream *st = ic->streams[i];
2959 AVCodecContext *dec = st->codec;
2962 input_streams = grow_array(input_streams, sizeof(*input_streams), &nb_input_streams, nb_input_streams + 1);
2963 ist = &input_streams[nb_input_streams - 1];
2965 ist->file_index = nb_input_files;
2967 ist->opts = filter_codec_opts(codec_opts, choose_decoder(o, ic, st), ic, st);
2969 ist->ts_scale = 1.0;
2970 MATCH_PER_STREAM_OPT(ts_scale, dbl, ist->ts_scale, ic, st);
2972 ist->dec = choose_decoder(o, ic, st);
2974 switch (dec->codec_type) {
2975 case AVMEDIA_TYPE_AUDIO:
2977 ist->dec = avcodec_find_decoder(dec->codec_id);
2978 if(o->audio_disable)
2979 st->discard= AVDISCARD_ALL;
2981 case AVMEDIA_TYPE_VIDEO:
2983 ist->dec = avcodec_find_decoder(dec->codec_id);
2984 rfps = ic->streams[i]->r_frame_rate.num;
2985 rfps_base = ic->streams[i]->r_frame_rate.den;
2987 dec->flags |= CODEC_FLAG_EMU_EDGE;
2990 if (dec->time_base.den != rfps*dec->ticks_per_frame || dec->time_base.num != rfps_base) {
2992 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",
2993 i, (float)dec->time_base.den / dec->time_base.num, dec->time_base.den, dec->time_base.num,
2994 (float)rfps / rfps_base, rfps, rfps_base);
2997 if (o->video_disable)
2998 st->discard= AVDISCARD_ALL;
2999 else if(video_discard)
3000 st->discard= video_discard;
3002 case AVMEDIA_TYPE_DATA:
3004 case AVMEDIA_TYPE_SUBTITLE:
3006 ist->dec = avcodec_find_decoder(dec->codec_id);
3007 if(o->subtitle_disable)
3008 st->discard = AVDISCARD_ALL;
3010 case AVMEDIA_TYPE_ATTACHMENT:
3011 case AVMEDIA_TYPE_UNKNOWN:
3019 static void assert_file_overwrite(const char *filename)
3021 if ((!file_overwrite || no_file_overwrite) &&
3022 (strchr(filename, ':') == NULL || filename[1] == ':' ||
3023 av_strstart(filename, "file:", NULL))) {
3024 if (avio_check(filename, 0) == 0) {
3025 if (!using_stdin && (!no_file_overwrite || file_overwrite)) {
3026 fprintf(stderr,"File '%s' already exists. Overwrite ? [y/N] ", filename);
3028 if (!read_yesno()) {
3029 fprintf(stderr, "Not overwriting - exiting\n");
3034 fprintf(stderr,"File '%s' already exists. Exiting.\n", filename);
3041 static void dump_attachment(AVStream *st, const char *filename)
3044 AVIOContext *out = NULL;
3045 AVDictionaryEntry *e;
3047 if (!st->codec->extradata_size) {
3048 av_log(NULL, AV_LOG_WARNING, "No extradata to dump in stream #%d:%d.\n",
3049 nb_input_files - 1, st->index);
3052 if (!*filename && (e = av_dict_get(st->metadata, "filename", NULL, 0)))
3053 filename = e->value;
3055 av_log(NULL, AV_LOG_FATAL, "No filename specified and no 'filename' tag"
3056 "in stream #%d:%d.\n", nb_input_files - 1, st->index);
3060 assert_file_overwrite(filename);
3062 if ((ret = avio_open2(&out, filename, AVIO_FLAG_WRITE, &int_cb, NULL)) < 0) {
3063 av_log(NULL, AV_LOG_FATAL, "Could not open file %s for writing.\n",
3068 avio_write(out, st->codec->extradata, st->codec->extradata_size);
3073 static int opt_input_file(OptionsContext *o, const char *opt, const char *filename)
3075 AVFormatContext *ic;
3076 AVInputFormat *file_iformat = NULL;
3080 AVDictionary **opts;
3081 int orig_nb_streams; // number of streams before avformat_find_stream_info
3084 if (!(file_iformat = av_find_input_format(o->format))) {
3085 av_log(NULL, AV_LOG_FATAL, "Unknown input format: '%s'\n", o->format);
3090 if (!strcmp(filename, "-"))
3093 using_stdin |= !strncmp(filename, "pipe:", 5) ||
3094 !strcmp(filename, "/dev/stdin");
3096 /* get default parameters from command line */
3097 ic = avformat_alloc_context();
3099 print_error(filename, AVERROR(ENOMEM));
3102 if (o->nb_audio_sample_rate) {
3103 snprintf(buf, sizeof(buf), "%d", o->audio_sample_rate[o->nb_audio_sample_rate - 1].u.i);
3104 av_dict_set(&format_opts, "sample_rate", buf, 0);
3106 if (o->nb_audio_channels) {
3107 snprintf(buf, sizeof(buf), "%d", o->audio_channels[o->nb_audio_channels - 1].u.i);
3108 av_dict_set(&format_opts, "channels", buf, 0);
3110 if (o->nb_frame_rates) {
3111 av_dict_set(&format_opts, "framerate", o->frame_rates[o->nb_frame_rates - 1].u.str, 0);
3113 if (o->nb_frame_sizes) {
3114 av_dict_set(&format_opts, "video_size", o->frame_sizes[o->nb_frame_sizes - 1].u.str, 0);
3116 if (o->nb_frame_pix_fmts)
3117 av_dict_set(&format_opts, "pixel_format", o->frame_pix_fmts[o->nb_frame_pix_fmts - 1].u.str, 0);
3119 ic->flags |= AVFMT_FLAG_NONBLOCK;
3120 ic->interrupt_callback = int_cb;
3122 /* open the input file with generic avformat function */
3123 err = avformat_open_input(&ic, filename, file_iformat, &format_opts);
3125 print_error(filename, err);
3128 assert_avoptions(format_opts);
3130 /* apply forced codec ids */
3131 for (i = 0; i < ic->nb_streams; i++)
3132 choose_decoder(o, ic, ic->streams[i]);
3134 /* Set AVCodecContext options for avformat_find_stream_info */
3135 opts = setup_find_stream_info_opts(ic, codec_opts);
3136 orig_nb_streams = ic->nb_streams;
3138 /* If not enough info to get the stream parameters, we decode the
3139 first frames to get it. (used in mpeg case for example) */
3140 ret = avformat_find_stream_info(ic, opts);
3142 av_log(NULL, AV_LOG_FATAL, "%s: could not find codec parameters\n", filename);
3143 av_close_input_file(ic);
3147 timestamp = o->start_time;
3148 /* add the stream start time */
3149 if (ic->start_time != AV_NOPTS_VALUE)
3150 timestamp += ic->start_time;
3152 /* if seeking requested, we execute it */
3153 if (o->start_time != 0) {
3154 ret = av_seek_frame(ic, -1, timestamp, AVSEEK_FLAG_BACKWARD);
3156 av_log(NULL, AV_LOG_WARNING, "%s: could not seek to position %0.3f\n",
3157 filename, (double)timestamp / AV_TIME_BASE);
3161 /* update the current parameters so that they match the one of the input stream */
3162 add_input_streams(o, ic);
3164 /* dump the file content */
3165 av_dump_format(ic, nb_input_files, filename, 0);
3167 input_files = grow_array(input_files, sizeof(*input_files), &nb_input_files, nb_input_files + 1);
3168 input_files[nb_input_files - 1].ctx = ic;
3169 input_files[nb_input_files - 1].ist_index = nb_input_streams - ic->nb_streams;
3170 input_files[nb_input_files - 1].ts_offset = o->input_ts_offset - (copy_ts ? 0 : timestamp);
3171 input_files[nb_input_files - 1].nb_streams = ic->nb_streams;
3172 input_files[nb_input_files - 1].rate_emu = o->rate_emu;
3174 for (i = 0; i < o->nb_dump_attachment; i++) {
3177 for (j = 0; j < ic->nb_streams; j++) {
3178 AVStream *st = ic->streams[j];
3180 if (check_stream_specifier(ic, st, o->dump_attachment[i].specifier) == 1)
3181 dump_attachment(st, o->dump_attachment[i].u.str);
3185 for (i = 0; i < orig_nb_streams; i++)
3186 av_dict_free(&opts[i]);
3193 static void parse_forced_key_frames(char *kf, OutputStream *ost,
3194 AVCodecContext *avctx)
3200 for (p = kf; *p; p++)
3203 ost->forced_kf_count = n;
3204 ost->forced_kf_pts = av_malloc(sizeof(*ost->forced_kf_pts) * n);
3205 if (!ost->forced_kf_pts) {
3206 av_log(NULL, AV_LOG_FATAL, "Could not allocate forced key frames array.\n");
3209 for (i = 0; i < n; i++) {
3210 p = i ? strchr(p, ',') + 1 : kf;
3211 t = parse_time_or_die("force_key_frames", p, 1);
3212 ost->forced_kf_pts[i] = av_rescale_q(t, AV_TIME_BASE_Q, avctx->time_base);
3216 static uint8_t *get_line(AVIOContext *s)
3222 if (avio_open_dyn_buf(&line) < 0) {
3223 av_log(NULL, AV_LOG_FATAL, "Could not alloc buffer for reading preset.\n");
3227 while ((c = avio_r8(s)) && c != '\n')
3230 avio_close_dyn_buf(line, &buf);
3235 static int get_preset_file_2(const char *preset_name, const char *codec_name, AVIOContext **s)
3238 char filename[1000];
3239 const char *base[3] = { getenv("AVCONV_DATADIR"),
3244 for (i = 0; i < FF_ARRAY_ELEMS(base) && ret; i++) {
3248 snprintf(filename, sizeof(filename), "%s%s/%s-%s.avpreset", base[i],
3249 i != 1 ? "" : "/.avconv", codec_name, preset_name);
3250 ret = avio_open2(s, filename, AVIO_FLAG_READ, &int_cb, NULL);
3253 snprintf(filename, sizeof(filename), "%s%s/%s.avpreset", base[i],
3254 i != 1 ? "" : "/.avconv", preset_name);
3255 ret = avio_open2(s, filename, AVIO_FLAG_READ, &int_cb, NULL);
3261 static void choose_encoder(OptionsContext *o, AVFormatContext *s, OutputStream *ost)
3263 char *codec_name = NULL;
3265 MATCH_PER_STREAM_OPT(codec_names, str, codec_name, s, ost->st);
3267 ost->st->codec->codec_id = av_guess_codec(s->oformat, NULL, s->filename,
3268 NULL, ost->st->codec->codec_type);
3269 ost->enc = avcodec_find_encoder(ost->st->codec->codec_id);
3270 } else if (!strcmp(codec_name, "copy"))
3271 ost->stream_copy = 1;
3273 ost->enc = find_codec_or_die(codec_name, ost->st->codec->codec_type, 1);
3274 ost->st->codec->codec_id = ost->enc->id;
3278 static OutputStream *new_output_stream(OptionsContext *o, AVFormatContext *oc, enum AVMediaType type)
3281 AVStream *st = avformat_new_stream(oc, NULL);
3282 int idx = oc->nb_streams - 1, ret = 0;
3283 char *bsf = NULL, *next, *codec_tag = NULL;
3284 AVBitStreamFilterContext *bsfc, *bsfc_prev = NULL;
3286 char *buf = NULL, *arg = NULL, *preset = NULL;
3287 AVIOContext *s = NULL;
3290 av_log(NULL, AV_LOG_FATAL, "Could not alloc stream.\n");
3294 if (oc->nb_streams - 1 < o->nb_streamid_map)
3295 st->id = o->streamid_map[oc->nb_streams - 1];
3297 output_streams = grow_array(output_streams, sizeof(*output_streams), &nb_output_streams,
3298 nb_output_streams + 1);
3299 ost = &output_streams[nb_output_streams - 1];
3300 ost->file_index = nb_output_files;
3303 st->codec->codec_type = type;
3304 choose_encoder(o, oc, ost);
3306 ost->opts = filter_codec_opts(codec_opts, ost->enc, oc, st);
3309 avcodec_get_context_defaults3(st->codec, ost->enc);
3310 st->codec->codec_type = type; // XXX hack, avcodec_get_context_defaults2() sets type to unknown for stream copy
3312 MATCH_PER_STREAM_OPT(presets, str, preset, oc, st);
3313 if (preset && (!(ret = get_preset_file_2(preset, ost->enc->name, &s)))) {
3316 if (!buf[0] || buf[0] == '#') {
3320 if (!(arg = strchr(buf, '='))) {
3321 av_log(NULL, AV_LOG_FATAL, "Invalid line found in the preset file.\n");
3325 av_dict_set(&ost->opts, buf, arg, AV_DICT_DONT_OVERWRITE);
3327 } while (!s->eof_reached);
3331 av_log(NULL, AV_LOG_FATAL,
3332 "Preset %s specified for stream %d:%d, but could not be opened.\n",
3333 preset, ost->file_index, ost->index);
3337 ost->max_frames = INT64_MAX;
3338 MATCH_PER_STREAM_OPT(max_frames, i64, ost->max_frames, oc, st);
3340 MATCH_PER_STREAM_OPT(bitstream_filters, str, bsf, oc, st);
3342 if (next = strchr(bsf, ','))
3344 if (!(bsfc = av_bitstream_filter_init(bsf))) {
3345 av_log(NULL, AV_LOG_FATAL, "Unknown bitstream filter %s\n", bsf);
3349 bsfc_prev->next = bsfc;
3351 ost->bitstream_filters = bsfc;
3357 MATCH_PER_STREAM_OPT(codec_tags, str, codec_tag, oc, st);
3359 uint32_t tag = strtol(codec_tag, &next, 0);
3361 tag = AV_RL32(codec_tag);
3362 st->codec->codec_tag = tag;
3365 MATCH_PER_STREAM_OPT(qscale, dbl, qscale, oc, st);
3366 if (qscale >= 0 || same_quant) {
3367 st->codec->flags |= CODEC_FLAG_QSCALE;
3368 st->codec->global_quality = FF_QP2LAMBDA * qscale;
3371 if (oc->oformat->flags & AVFMT_GLOBALHEADER)
3372 st->codec->flags |= CODEC_FLAG_GLOBAL_HEADER;
3374 av_opt_get_int(sws_opts, "sws_flags", 0, &ost->sws_flags);
3378 static void parse_matrix_coeffs(uint16_t *dest, const char *str)
3381 const char *p = str;
3388 av_log(NULL, AV_LOG_FATAL, "Syntax error in matrix \"%s\" at coeff %d\n", str, i);
3395 static OutputStream *new_video_stream(OptionsContext *o, AVFormatContext *oc)
3399 AVCodecContext *video_enc;
3401 ost = new_output_stream(o, oc, AVMEDIA_TYPE_VIDEO);
3403 video_enc = st->codec;
3405 if (!ost->stream_copy) {
3406 const char *p = NULL;
3407 char *forced_key_frames = NULL, *frame_rate = NULL, *frame_size = NULL;
3408 char *frame_aspect_ratio = NULL, *frame_pix_fmt = NULL;
3409 char *intra_matrix = NULL, *inter_matrix = NULL, *filters = NULL;
3412 MATCH_PER_STREAM_OPT(frame_rates, str, frame_rate, oc, st);
3413 if (frame_rate && av_parse_video_rate(&ost->frame_rate, frame_rate) < 0) {
3414 av_log(NULL, AV_LOG_FATAL, "Invalid framerate value: %s\n", frame_rate);
3418 MATCH_PER_STREAM_OPT(frame_sizes, str, frame_size, oc, st);
3419 if (frame_size && av_parse_video_size(&video_enc->width, &video_enc->height, frame_size) < 0) {
3420 av_log(NULL, AV_LOG_FATAL, "Invalid frame size: %s.\n", frame_size);
3424 MATCH_PER_STREAM_OPT(frame_aspect_ratios, str, frame_aspect_ratio, oc, st);
3425 if (frame_aspect_ratio)
3426 ost->frame_aspect_ratio = parse_frame_aspect_ratio(frame_aspect_ratio);
3428 MATCH_PER_STREAM_OPT(frame_pix_fmts, str, frame_pix_fmt, oc, st);
3429 if (frame_pix_fmt && (video_enc->pix_fmt = av_get_pix_fmt(frame_pix_fmt)) == PIX_FMT_NONE) {
3430 av_log(NULL, AV_LOG_FATAL, "Unknown pixel format requested: %s.\n", frame_pix_fmt);
3433 st->sample_aspect_ratio = video_enc->sample_aspect_ratio;
3435 MATCH_PER_STREAM_OPT(intra_matrices, str, intra_matrix, oc, st);
3437 if (!(video_enc->intra_matrix = av_mallocz(sizeof(*video_enc->intra_matrix) * 64))) {
3438 av_log(NULL, AV_LOG_FATAL, "Could not allocate memory for intra matrix.\n");
3441 parse_matrix_coeffs(video_enc->intra_matrix, intra_matrix);
3443 MATCH_PER_STREAM_OPT(inter_matrices, str, inter_matrix, oc, st);
3445 if (!(video_enc->inter_matrix = av_mallocz(sizeof(*video_enc->inter_matrix) * 64))) {
3446 av_log(NULL, AV_LOG_FATAL, "Could not allocate memory for inter matrix.\n");
3449 parse_matrix_coeffs(video_enc->inter_matrix, inter_matrix);
3452 MATCH_PER_STREAM_OPT(rc_overrides, str, p, oc, st);
3455 int e=sscanf(p, "%d,%d,%d", &start, &end, &q);
3457 av_log(NULL, AV_LOG_FATAL, "error parsing rc_override\n");
3460 video_enc->rc_override=
3461 av_realloc(video_enc->rc_override,
3462 sizeof(RcOverride)*(i+1));
3463 video_enc->rc_override[i].start_frame= start;
3464 video_enc->rc_override[i].end_frame = end;
3466 video_enc->rc_override[i].qscale= q;
3467 video_enc->rc_override[i].quality_factor= 1.0;
3470 video_enc->rc_override[i].qscale= 0;
3471 video_enc->rc_override[i].quality_factor= -q/100.0;
3476 video_enc->rc_override_count=i;
3477 if (!video_enc->rc_initial_buffer_occupancy)
3478 video_enc->rc_initial_buffer_occupancy = video_enc->rc_buffer_size*3/4;
3479 video_enc->intra_dc_precision= intra_dc_precision - 8;
3484 video_enc->flags |= CODEC_FLAG_PASS1;
3486 video_enc->flags |= CODEC_FLAG_PASS2;
3490 MATCH_PER_STREAM_OPT(forced_key_frames, str, forced_key_frames, oc, st);
3491 if (forced_key_frames)
3492 parse_forced_key_frames(forced_key_frames, ost, video_enc);
3494 MATCH_PER_STREAM_OPT(force_fps, i, ost->force_fps, oc, st);
3496 ost->top_field_first = -1;
3497 MATCH_PER_STREAM_OPT(top_field_first, i, ost->top_field_first, oc, st);
3499 MATCH_PER_STREAM_OPT(copy_initial_nonkeyframes, i, ost->copy_initial_nonkeyframes, oc ,st);
3502 MATCH_PER_STREAM_OPT(filters, str, filters, oc, st);
3504 ost->avfilter = av_strdup(filters);
3511 static OutputStream *new_audio_stream(OptionsContext *o, AVFormatContext *oc)
3515 AVCodecContext *audio_enc;
3517 ost = new_output_stream(o, oc, AVMEDIA_TYPE_AUDIO);
3520 audio_enc = st->codec;
3521 audio_enc->codec_type = AVMEDIA_TYPE_AUDIO;
3523 if (!ost->stream_copy) {
3524 char *sample_fmt = NULL;
3526 MATCH_PER_STREAM_OPT(audio_channels, i, audio_enc->channels, oc, st);
3528 MATCH_PER_STREAM_OPT(sample_fmts, str, sample_fmt, oc, st);
3530 (audio_enc->sample_fmt = av_get_sample_fmt(sample_fmt)) == AV_SAMPLE_FMT_NONE) {
3531 av_log(NULL, AV_LOG_FATAL, "Invalid sample format '%s'\n", sample_fmt);
3535 MATCH_PER_STREAM_OPT(audio_sample_rate, i, audio_enc->sample_rate, oc, st);
3541 static OutputStream *new_data_stream(OptionsContext *o, AVFormatContext *oc)
3545 ost = new_output_stream(o, oc, AVMEDIA_TYPE_DATA);
3546 if (!ost->stream_copy) {
3547 av_log(NULL, AV_LOG_FATAL, "Data stream encoding not supported yet (only streamcopy)\n");
3554 static OutputStream *new_attachment_stream(OptionsContext *o, AVFormatContext *oc)
3556 OutputStream *ost = new_output_stream(o, oc, AVMEDIA_TYPE_ATTACHMENT);
3557 ost->stream_copy = 1;
3561 static OutputStream *new_subtitle_stream(OptionsContext *o, AVFormatContext *oc)
3565 AVCodecContext *subtitle_enc;
3567 ost = new_output_stream(o, oc, AVMEDIA_TYPE_SUBTITLE);
3569 subtitle_enc = st->codec;
3571 subtitle_enc->codec_type = AVMEDIA_TYPE_SUBTITLE;
3576 /* arg format is "output-stream-index:streamid-value". */
3577 static int opt_streamid(OptionsContext *o, const char *opt, const char *arg)
3583 av_strlcpy(idx_str, arg, sizeof(idx_str));
3584 p = strchr(idx_str, ':');
3586 av_log(NULL, AV_LOG_FATAL,
3587 "Invalid value '%s' for option '%s', required syntax is 'index:value'\n",
3592 idx = parse_number_or_die(opt, idx_str, OPT_INT, 0, MAX_STREAMS-1);
3593 o->streamid_map = grow_array(o->streamid_map, sizeof(*o->streamid_map), &o->nb_streamid_map, idx+1);
3594 o->streamid_map[idx] = parse_number_or_die(opt, p, OPT_INT, 0, INT_MAX);
3598 static int copy_chapters(InputFile *ifile, OutputFile *ofile, int copy_metadata)
3600 AVFormatContext *is = ifile->ctx;
3601 AVFormatContext *os = ofile->ctx;
3604 for (i = 0; i < is->nb_chapters; i++) {
3605 AVChapter *in_ch = is->chapters[i], *out_ch;
3606 int64_t ts_off = av_rescale_q(ofile->start_time - ifile->ts_offset,
3607 AV_TIME_BASE_Q, in_ch->time_base);
3608 int64_t rt = (ofile->recording_time == INT64_MAX) ? INT64_MAX :
3609 av_rescale_q(ofile->recording_time, AV_TIME_BASE_Q, in_ch->time_base);
3612 if (in_ch->end < ts_off)
3614 if (rt != INT64_MAX && in_ch->start > rt + ts_off)
3617 out_ch = av_mallocz(sizeof(AVChapter));
3619 return AVERROR(ENOMEM);
3621 out_ch->id = in_ch->id;
3622 out_ch->time_base = in_ch->time_base;
3623 out_ch->start = FFMAX(0, in_ch->start - ts_off);
3624 out_ch->end = FFMIN(rt, in_ch->end - ts_off);
3627 av_dict_copy(&out_ch->metadata, in_ch->metadata, 0);
3630 os->chapters = av_realloc(os->chapters, sizeof(AVChapter)*os->nb_chapters);
3632 return AVERROR(ENOMEM);
3633 os->chapters[os->nb_chapters - 1] = out_ch;
3638 static void opt_output_file(void *optctx, const char *filename)
3640 OptionsContext *o = optctx;
3641 AVFormatContext *oc;
3643 AVOutputFormat *file_oformat;
3647 if (!strcmp(filename, "-"))
3650 err = avformat_alloc_output_context2(&oc, NULL, o->format, filename);
3652 print_error(filename, err);
3656 file_oformat= oc->oformat;
3657 oc->interrupt_callback = int_cb;
3659 if (!o->nb_stream_maps) {
3660 /* pick the "best" stream of each type */
3661 #define NEW_STREAM(type, index)\
3663 ost = new_ ## type ## _stream(o, oc);\
3664 ost->source_index = index;\
3665 ost->sync_ist = &input_streams[index];\
3666 input_streams[index].discard = 0;\
3669 /* video: highest resolution */
3670 if (!o->video_disable && oc->oformat->video_codec != CODEC_ID_NONE) {
3671 int area = 0, idx = -1;
3672 for (i = 0; i < nb_input_streams; i++) {
3673 ist = &input_streams[i];
3674 if (ist->st->codec->codec_type == AVMEDIA_TYPE_VIDEO &&
3675 ist->st->codec->width * ist->st->codec->height > area) {
3676 area = ist->st->codec->width * ist->st->codec->height;
3680 NEW_STREAM(video, idx);
3683 /* audio: most channels */
3684 if (!o->audio_disable && oc->oformat->audio_codec != CODEC_ID_NONE) {
3685 int channels = 0, idx = -1;
3686 for (i = 0; i < nb_input_streams; i++) {
3687 ist = &input_streams[i];
3688 if (ist->st->codec->codec_type == AVMEDIA_TYPE_AUDIO &&
3689 ist->st->codec->channels > channels) {
3690 channels = ist->st->codec->channels;
3694 NEW_STREAM(audio, idx);
3697 /* subtitles: pick first */
3698 if (!o->subtitle_disable && oc->oformat->subtitle_codec != CODEC_ID_NONE) {
3699 for (i = 0; i < nb_input_streams; i++)
3700 if (input_streams[i].st->codec->codec_type == AVMEDIA_TYPE_SUBTITLE) {
3701 NEW_STREAM(subtitle, i);
3705 /* do something with data? */
3707 for (i = 0; i < o->nb_stream_maps; i++) {
3708 StreamMap *map = &o->stream_maps[i];
3713 ist = &input_streams[input_files[map->file_index].ist_index + map->stream_index];
3714 switch (ist->st->codec->codec_type) {
3715 case AVMEDIA_TYPE_VIDEO: ost = new_video_stream(o, oc); break;
3716 case AVMEDIA_TYPE_AUDIO: ost = new_audio_stream(o, oc); break;
3717 case AVMEDIA_TYPE_SUBTITLE: ost = new_subtitle_stream(o, oc); break;
3718 case AVMEDIA_TYPE_DATA: ost = new_data_stream(o, oc); break;
3719 case AVMEDIA_TYPE_ATTACHMENT: ost = new_attachment_stream(o, oc); break;
3721 av_log(NULL, AV_LOG_FATAL, "Cannot map stream #%d:%d - unsupported type.\n",
3722 map->file_index, map->stream_index);
3726 ost->source_index = input_files[map->file_index].ist_index + map->stream_index;
3727 ost->sync_ist = &input_streams[input_files[map->sync_file_index].ist_index +
3728 map->sync_stream_index];
3733 /* handle attached files */
3734 for (i = 0; i < o->nb_attachments; i++) {
3736 uint8_t *attachment;
3740 if ((err = avio_open2(&pb, o->attachments[i], AVIO_FLAG_READ, &int_cb, NULL)) < 0) {
3741 av_log(NULL, AV_LOG_FATAL, "Could not open attachment file %s.\n",
3745 if ((len = avio_size(pb)) <= 0) {
3746 av_log(NULL, AV_LOG_FATAL, "Could not get size of the attachment %s.\n",
3750 if (!(attachment = av_malloc(len))) {
3751 av_log(NULL, AV_LOG_FATAL, "Attachment %s too large to fit into memory.\n",
3755 avio_read(pb, attachment, len);
3757 ost = new_attachment_stream(o, oc);
3758 ost->stream_copy = 0;
3759 ost->source_index = -1;
3760 ost->attachment_filename = o->attachments[i];
3761 ost->st->codec->extradata = attachment;
3762 ost->st->codec->extradata_size = len;
3764 p = strrchr(o->attachments[i], '/');
3765 av_dict_set(&ost->st->metadata, "filename", (p && *p) ? p + 1 : o->attachments[i], AV_DICT_DONT_OVERWRITE);
3769 output_files = grow_array(output_files, sizeof(*output_files), &nb_output_files, nb_output_files + 1);
3770 output_files[nb_output_files - 1].ctx = oc;
3771 output_files[nb_output_files - 1].ost_index = nb_output_streams - oc->nb_streams;
3772 output_files[nb_output_files - 1].recording_time = o->recording_time;
3773 output_files[nb_output_files - 1].start_time = o->start_time;
3774 output_files[nb_output_files - 1].limit_filesize = o->limit_filesize;
3775 av_dict_copy(&output_files[nb_output_files - 1].opts, format_opts, 0);
3777 /* check filename in case of an image number is expected */
3778 if (oc->oformat->flags & AVFMT_NEEDNUMBER) {
3779 if (!av_filename_number_test(oc->filename)) {
3780 print_error(oc->filename, AVERROR(EINVAL));
3785 if (!(oc->oformat->flags & AVFMT_NOFILE)) {
3786 /* test if it already exists to avoid losing precious files */
3787 assert_file_overwrite(filename);
3790 if ((err = avio_open2(&oc->pb, filename, AVIO_FLAG_WRITE,
3791 &oc->interrupt_callback,
3792 &output_files[nb_output_files - 1].opts)) < 0) {
3793 print_error(filename, err);
3798 if (o->mux_preload) {
3800 snprintf(buf, sizeof(buf), "%d", (int)(o->mux_preload*AV_TIME_BASE));
3801 av_dict_set(&output_files[nb_output_files - 1].opts, "preload", buf, 0);
3803 oc->max_delay = (int)(o->mux_max_delay * AV_TIME_BASE);
3806 if (o->chapters_input_file >= nb_input_files) {
3807 if (o->chapters_input_file == INT_MAX) {
3808 /* copy chapters from the first input file that has them*/
3809 o->chapters_input_file = -1;
3810 for (i = 0; i < nb_input_files; i++)
3811 if (input_files[i].ctx->nb_chapters) {
3812 o->chapters_input_file = i;
3816 av_log(NULL, AV_LOG_FATAL, "Invalid input file index %d in chapter mapping.\n",
3817 o->chapters_input_file);
3821 if (o->chapters_input_file >= 0)
3822 copy_chapters(&input_files[o->chapters_input_file], &output_files[nb_output_files - 1],
3823 !o->metadata_chapters_manual);
3826 for (i = 0; i < o->nb_meta_data_maps; i++) {
3827 AVFormatContext *files[2];
3828 AVDictionary **meta[2];
3831 #define METADATA_CHECK_INDEX(index, nb_elems, desc)\
3832 if ((index) < 0 || (index) >= (nb_elems)) {\
3833 av_log(NULL, AV_LOG_FATAL, "Invalid %s index %d while processing metadata maps\n",\
3838 int in_file_index = o->meta_data_maps[i][1].file;
3839 if (in_file_index < 0)
3841 METADATA_CHECK_INDEX(in_file_index, nb_input_files, "input file")
3844 files[1] = input_files[in_file_index].ctx;
3846 for (j = 0; j < 2; j++) {
3847 MetadataMap *map = &o->meta_data_maps[i][j];
3849 switch (map->type) {
3851 meta[j] = &files[j]->metadata;
3854 METADATA_CHECK_INDEX(map->index, files[j]->nb_streams, "stream")
3855 meta[j] = &files[j]->streams[map->index]->metadata;
3858 METADATA_CHECK_INDEX(map->index, files[j]->nb_chapters, "chapter")
3859 meta[j] = &files[j]->chapters[map->index]->metadata;
3862 METADATA_CHECK_INDEX(map->index, files[j]->nb_programs, "program")
3863 meta[j] = &files[j]->programs[map->index]->metadata;
3868 av_dict_copy(meta[0], *meta[1], AV_DICT_DONT_OVERWRITE);
3871 /* copy global metadata by default */
3872 if (!o->metadata_global_manual && nb_input_files)
3873 av_dict_copy(&oc->metadata, input_files[0].ctx->metadata,
3874 AV_DICT_DONT_OVERWRITE);
3875 if (!o->metadata_streams_manual)
3876 for (i = output_files[nb_output_files - 1].ost_index; i < nb_output_streams; i++) {
3878 if (output_streams[i].source_index < 0) /* this is true e.g. for attached files */
3880 ist = &input_streams[output_streams[i].source_index];
3881 av_dict_copy(&output_streams[i].st->metadata, ist->st->metadata, AV_DICT_DONT_OVERWRITE);
3884 /* process manually set metadata */
3885 for (i = 0; i < o->nb_metadata; i++) {
3890 val = strchr(o->metadata[i].u.str, '=');
3892 av_log(NULL, AV_LOG_FATAL, "No '=' character in metadata string %s.\n",
3893 o->metadata[i].u.str);
3898 parse_meta_type(o->metadata[i].specifier, &type, &index);
3904 if (index < 0 || index >= oc->nb_streams) {
3905 av_log(NULL, AV_LOG_FATAL, "Invalid stream index %d in metadata specifier.\n", index);
3908 m = &oc->streams[index]->metadata;
3911 if (index < 0 || index >= oc->nb_chapters) {
3912 av_log(NULL, AV_LOG_FATAL, "Invalid chapter index %d in metadata specifier.\n", index);
3915 m = &oc->chapters[index]->metadata;
3918 av_log(NULL, AV_LOG_FATAL, "Invalid metadata specifier %s.\n", o->metadata[i].specifier);
3922 av_dict_set(m, o->metadata[i].u.str, *val ? val : NULL, 0);
3928 /* same option as mencoder */
3929 static int opt_pass(const char *opt, const char *arg)
3931 do_pass = parse_number_or_die(opt, arg, OPT_INT, 1, 2);
3935 static int64_t getutime(void)
3938 struct rusage rusage;
3940 getrusage(RUSAGE_SELF, &rusage);
3941 return (rusage.ru_utime.tv_sec * 1000000LL) + rusage.ru_utime.tv_usec;
3942 #elif HAVE_GETPROCESSTIMES
3944 FILETIME c, e, k, u;
3945 proc = GetCurrentProcess();
3946 GetProcessTimes(proc, &c, &e, &k, &u);
3947 return ((int64_t) u.dwHighDateTime << 32 | u.dwLowDateTime) / 10;
3949 return av_gettime();
3953 static int64_t getmaxrss(void)
3955 #if HAVE_GETRUSAGE && HAVE_STRUCT_RUSAGE_RU_MAXRSS
3956 struct rusage rusage;
3957 getrusage(RUSAGE_SELF, &rusage);
3958 return (int64_t)rusage.ru_maxrss * 1024;
3959 #elif HAVE_GETPROCESSMEMORYINFO
3961 PROCESS_MEMORY_COUNTERS memcounters;
3962 proc = GetCurrentProcess();
3963 memcounters.cb = sizeof(memcounters);
3964 GetProcessMemoryInfo(proc, &memcounters, sizeof(memcounters));
3965 return memcounters.PeakPagefileUsage;
3971 static int opt_audio_qscale(OptionsContext *o, const char *opt, const char *arg)
3973 return parse_option(o, "q:a", arg, options);
3976 static void show_usage(void)
3978 printf("Hyper fast Audio and Video encoder\n");
3979 printf("usage: %s [options] [[infile options] -i infile]... {[outfile options] outfile}...\n", program_name);
3983 static int opt_help(const char *opt, const char *arg)
3985 int flags = AV_OPT_FLAG_DECODING_PARAM | AV_OPT_FLAG_ENCODING_PARAM;
3986 av_log_set_callback(log_callback_help);
3988 show_help_options(options, "Main options:\n",
3989 OPT_EXPERT | OPT_AUDIO | OPT_VIDEO | OPT_SUBTITLE | OPT_GRAB, 0);
3990 show_help_options(options, "\nAdvanced options:\n",
3991 OPT_EXPERT | OPT_AUDIO | OPT_VIDEO | OPT_SUBTITLE | OPT_GRAB,
3993 show_help_options(options, "\nVideo options:\n",
3994 OPT_EXPERT | OPT_AUDIO | OPT_VIDEO | OPT_GRAB,
3996 show_help_options(options, "\nAdvanced Video options:\n",
3997 OPT_EXPERT | OPT_AUDIO | OPT_VIDEO | OPT_GRAB,
3998 OPT_VIDEO | OPT_EXPERT);
3999 show_help_options(options, "\nAudio options:\n",
4000 OPT_EXPERT | OPT_AUDIO | OPT_VIDEO | OPT_GRAB,
4002 show_help_options(options, "\nAdvanced Audio options:\n",
4003 OPT_EXPERT | OPT_AUDIO | OPT_VIDEO | OPT_GRAB,
4004 OPT_AUDIO | OPT_EXPERT);
4005 show_help_options(options, "\nSubtitle options:\n",
4006 OPT_SUBTITLE | OPT_GRAB,
4008 show_help_options(options, "\nAudio/Video grab options:\n",
4012 show_help_children(avcodec_get_class(), flags);
4013 show_help_children(avformat_get_class(), flags);
4014 show_help_children(sws_get_class(), flags);
4019 static int opt_target(OptionsContext *o, const char *opt, const char *arg)
4021 enum { PAL, NTSC, FILM, UNKNOWN } norm = UNKNOWN;
4022 static const char *const frame_rates[] = {"25", "30000/1001", "24000/1001"};
4024 if(!strncmp(arg, "pal-", 4)) {
4027 } else if(!strncmp(arg, "ntsc-", 5)) {
4030 } else if(!strncmp(arg, "film-", 5)) {
4034 /* Try to determine PAL/NTSC by peeking in the input files */
4035 if(nb_input_files) {
4037 for (j = 0; j < nb_input_files; j++) {
4038 for (i = 0; i < input_files[j].nb_streams; i++) {
4039 AVCodecContext *c = input_files[j].ctx->streams[i]->codec;
4040 if(c->codec_type != AVMEDIA_TYPE_VIDEO)
4042 fr = c->time_base.den * 1000 / c->time_base.num;
4046 } else if((fr == 29970) || (fr == 23976)) {
4055 if (norm != UNKNOWN)
4056 av_log(NULL, AV_LOG_INFO, "Assuming %s for target.\n", norm == PAL ? "PAL" : "NTSC");
4059 if(norm == UNKNOWN) {
4060 av_log(NULL, AV_LOG_FATAL, "Could not determine norm (PAL/NTSC/NTSC-Film) for target.\n");
4061 av_log(NULL, AV_LOG_FATAL, "Please prefix target with \"pal-\", \"ntsc-\" or \"film-\",\n");
4062 av_log(NULL, AV_LOG_FATAL, "or set a framerate with \"-r xxx\".\n");
4066 if(!strcmp(arg, "vcd")) {
4067 opt_video_codec(o, "c:v", "mpeg1video");
4068 opt_audio_codec(o, "c:a", "mp2");
4069 parse_option(o, "f", "vcd", options);
4071 parse_option(o, "s", norm == PAL ? "352x288" : "352x240", options);
4072 parse_option(o, "r", frame_rates[norm], options);
4073 opt_default("g", norm == PAL ? "15" : "18");
4075 opt_default("b", "1150000");
4076 opt_default("maxrate", "1150000");
4077 opt_default("minrate", "1150000");
4078 opt_default("bufsize", "327680"); // 40*1024*8;
4080 opt_default("b:a", "224000");
4081 parse_option(o, "ar", "44100", options);
4082 parse_option(o, "ac", "2", options);
4084 opt_default("packetsize", "2324");
4085 opt_default("muxrate", "1411200"); // 2352 * 75 * 8;
4087 /* We have to offset the PTS, so that it is consistent with the SCR.
4088 SCR starts at 36000, but the first two packs contain only padding
4089 and the first pack from the other stream, respectively, may also have
4090 been written before.
4091 So the real data starts at SCR 36000+3*1200. */
4092 o->mux_preload = (36000+3*1200) / 90000.0; //0.44
4093 } else if(!strcmp(arg, "svcd")) {
4095 opt_video_codec(o, "c:v", "mpeg2video");
4096 opt_audio_codec(o, "c:a", "mp2");
4097 parse_option(o, "f", "svcd", options);
4099 parse_option(o, "s", norm == PAL ? "480x576" : "480x480", options);
4100 parse_option(o, "r", frame_rates[norm], options);
4101 opt_default("g", norm == PAL ? "15" : "18");
4103 opt_default("b", "2040000");
4104 opt_default("maxrate", "2516000");
4105 opt_default("minrate", "0"); //1145000;
4106 opt_default("bufsize", "1835008"); //224*1024*8;
4107 opt_default("flags", "+scan_offset");
4110 opt_default("b:a", "224000");
4111 parse_option(o, "ar", "44100", options);
4113 opt_default("packetsize", "2324");
4115 } else if(!strcmp(arg, "dvd")) {
4117 opt_video_codec(o, "c:v", "mpeg2video");
4118 opt_audio_codec(o, "c:a", "ac3");
4119 parse_option(o, "f", "dvd", options);
4121 parse_option(o, "s", norm == PAL ? "720x576" : "720x480", options);
4122 parse_option(o, "r", frame_rates[norm], options);
4123 opt_default("g", norm == PAL ? "15" : "18");
4125 opt_default("b", "6000000");
4126 opt_default("maxrate", "9000000");
4127 opt_default("minrate", "0"); //1500000;
4128 opt_default("bufsize", "1835008"); //224*1024*8;
4130 opt_default("packetsize", "2048"); // from www.mpucoder.com: DVD sectors contain 2048 bytes of data, this is also the size of one pack.
4131 opt_default("muxrate", "10080000"); // from mplex project: data_rate = 1260000. mux_rate = data_rate * 8
4133 opt_default("b:a", "448000");
4134 parse_option(o, "ar", "48000", options);
4136 } else if(!strncmp(arg, "dv", 2)) {
4138 parse_option(o, "f", "dv", options);
4140 parse_option(o, "s", norm == PAL ? "720x576" : "720x480", options);
4141 parse_option(o, "pix_fmt", !strncmp(arg, "dv50", 4) ? "yuv422p" :
4142 norm == PAL ? "yuv420p" : "yuv411p", options);
4143 parse_option(o, "r", frame_rates[norm], options);
4145 parse_option(o, "ar", "48000", options);
4146 parse_option(o, "ac", "2", options);
4149 av_log(NULL, AV_LOG_ERROR, "Unknown target: %s\n", arg);
4150 return AVERROR(EINVAL);
4155 static int opt_vstats_file(const char *opt, const char *arg)
4157 av_free (vstats_filename);
4158 vstats_filename=av_strdup (arg);
4162 static int opt_vstats(const char *opt, const char *arg)
4165 time_t today2 = time(NULL);
4166 struct tm *today = localtime(&today2);
4168 snprintf(filename, sizeof(filename), "vstats_%02d%02d%02d.log", today->tm_hour, today->tm_min,
4170 return opt_vstats_file(opt, filename);
4173 static int opt_video_frames(OptionsContext *o, const char *opt, const char *arg)
4175 return parse_option(o, "frames:v", arg, options);
4178 static int opt_audio_frames(OptionsContext *o, const char *opt, const char *arg)
4180 return parse_option(o, "frames:a", arg, options);
4183 static int opt_data_frames(OptionsContext *o, const char *opt, const char *arg)
4185 return parse_option(o, "frames:d", arg, options);
4188 static void log_callback_null(void* ptr, int level, const char* fmt, va_list vl)
4192 static int opt_passlogfile(const char *opt, const char *arg)
4194 pass_logfilename_prefix = arg;
4195 #if CONFIG_LIBX264_ENCODER
4196 return opt_default("passlogfile", arg);
4202 static int opt_video_tag(OptionsContext *o, const char *opt, const char *arg)
4204 return parse_option(o, "tag:v", arg, options);
4207 static int opt_audio_tag(OptionsContext *o, const char *opt, const char *arg)
4209 return parse_option(o, "tag:a", arg, options);
4212 static int opt_subtitle_tag(OptionsContext *o, const char *opt, const char *arg)
4214 return parse_option(o, "tag:s", arg, options);
4217 static int opt_video_filters(OptionsContext *o, const char *opt, const char *arg)
4219 return parse_option(o, "filter:v", arg, options);
4222 #define OFFSET(x) offsetof(OptionsContext, x)
4223 static const OptionDef options[] = {
4225 #include "cmdutils_common_opts.h"
4226 { "f", HAS_ARG | OPT_STRING | OPT_OFFSET, {.off = OFFSET(format)}, "force format", "fmt" },
4227 { "i", HAS_ARG | OPT_FUNC2, {(void*)opt_input_file}, "input file name", "filename" },
4228 { "y", OPT_BOOL, {(void*)&file_overwrite}, "overwrite output files" },
4229 { "n", OPT_BOOL, {(void*)&no_file_overwrite}, "do not overwrite output files" },
4230 { "c", HAS_ARG | OPT_STRING | OPT_SPEC, {.off = OFFSET(codec_names)}, "codec name", "codec" },
4231 { "codec", HAS_ARG | OPT_STRING | OPT_SPEC, {.off = OFFSET(codec_names)}, "codec name", "codec" },
4232 { "pre", HAS_ARG | OPT_STRING | OPT_SPEC, {.off = OFFSET(presets)}, "preset name", "preset" },
4233 { "map", HAS_ARG | OPT_EXPERT | OPT_FUNC2, {(void*)opt_map}, "set input stream mapping", "file.stream[:syncfile.syncstream]" },
4234 { "map_metadata", HAS_ARG | OPT_EXPERT | OPT_FUNC2, {(void*)opt_map_metadata}, "set metadata information of outfile from infile",
4235 "outfile[,metadata]:infile[,metadata]" },
4236 { "map_chapters", OPT_INT | HAS_ARG | OPT_EXPERT | OPT_OFFSET, {.off = OFFSET(chapters_input_file)}, "set chapters mapping", "input_file_index" },
4237 { "t", HAS_ARG | OPT_TIME | OPT_OFFSET, {.off = OFFSET(recording_time)}, "record or transcode \"duration\" seconds of audio/video", "duration" },
4238 { "fs", HAS_ARG | OPT_INT64 | OPT_OFFSET, {.off = OFFSET(limit_filesize)}, "set the limit file size in bytes", "limit_size" }, //
4239 { "ss", HAS_ARG | OPT_TIME | OPT_OFFSET, {.off = OFFSET(start_time)}, "set the start time offset", "time_off" },
4240 { "itsoffset", HAS_ARG | OPT_TIME | OPT_OFFSET, {.off = OFFSET(input_ts_offset)}, "set the input ts offset", "time_off" },
4241 { "itsscale", HAS_ARG | OPT_DOUBLE | OPT_SPEC, {.off = OFFSET(ts_scale)}, "set the input ts scale", "scale" },
4242 { "metadata", HAS_ARG | OPT_STRING | OPT_SPEC, {.off = OFFSET(metadata)}, "add metadata", "string=string" },
4243 { "dframes", HAS_ARG | OPT_FUNC2, {(void*)opt_data_frames}, "set the number of data frames to record", "number" },
4244 { "benchmark", OPT_BOOL | OPT_EXPERT, {(void*)&do_benchmark},
4245 "add timings for benchmarking" },
4246 { "timelimit", HAS_ARG, {(void*)opt_timelimit}, "set max runtime in seconds", "limit" },
4247 { "dump", OPT_BOOL | OPT_EXPERT, {(void*)&do_pkt_dump},
4248 "dump each input packet" },
4249 { "hex", OPT_BOOL | OPT_EXPERT, {(void*)&do_hex_dump},
4250 "when dumping packets, also dump the payload" },
4251 { "re", OPT_BOOL | OPT_EXPERT | OPT_OFFSET, {.off = OFFSET(rate_emu)}, "read input at native frame rate", "" },
4252 { "target", HAS_ARG | OPT_FUNC2, {(void*)opt_target}, "specify target file type (\"vcd\", \"svcd\", \"dvd\", \"dv\", \"dv50\", \"pal-vcd\", \"ntsc-svcd\", ...)", "type" },
4253 { "vsync", HAS_ARG | OPT_INT | OPT_EXPERT, {(void*)&video_sync_method}, "video sync method", "" },
4254 { "async", HAS_ARG | OPT_INT | OPT_EXPERT, {(void*)&audio_sync_method}, "audio sync method", "" },
4255 { "adrift_threshold", HAS_ARG | OPT_FLOAT | OPT_EXPERT, {(void*)&audio_drift_threshold}, "audio drift threshold", "threshold" },
4256 { "copyts", OPT_BOOL | OPT_EXPERT, {(void*)©_ts}, "copy timestamps" },
4257 { "copytb", OPT_BOOL | OPT_EXPERT, {(void*)©_tb}, "copy input stream time base when stream copying" },
4258 { "shortest", OPT_BOOL | OPT_EXPERT, {(void*)&opt_shortest}, "finish encoding within shortest input" }, //
4259 { "dts_delta_threshold", HAS_ARG | OPT_FLOAT | OPT_EXPERT, {(void*)&dts_delta_threshold}, "timestamp discontinuity delta threshold", "threshold" },
4260 { "xerror", OPT_BOOL, {(void*)&exit_on_error}, "exit on error", "error" },
4261 { "copyinkf", OPT_BOOL | OPT_EXPERT | OPT_SPEC, {.off = OFFSET(copy_initial_nonkeyframes)}, "copy initial non-keyframes" },
4262 { "frames", OPT_INT64 | HAS_ARG | OPT_SPEC, {.off = OFFSET(max_frames)}, "set the number of frames to record", "number" },
4263 { "tag", OPT_STRING | HAS_ARG | OPT_SPEC, {.off = OFFSET(codec_tags)}, "force codec tag/fourcc", "fourcc/tag" },
4264 { "q", HAS_ARG | OPT_EXPERT | OPT_DOUBLE | OPT_SPEC, {.off = OFFSET(qscale)}, "use fixed quality scale (VBR)", "q" },
4265 { "qscale", HAS_ARG | OPT_EXPERT | OPT_DOUBLE | OPT_SPEC, {.off = OFFSET(qscale)}, "use fixed quality scale (VBR)", "q" },
4267 { "filter", HAS_ARG | OPT_STRING | OPT_SPEC, {.off = OFFSET(filters)}, "set stream filterchain", "filter_list" },
4269 { "stats", OPT_BOOL, {&print_stats}, "print progress report during encoding", },
4270 { "attach", HAS_ARG | OPT_FUNC2, {(void*)opt_attach}, "add an attachment to the output file", "filename" },
4271 { "dump_attachment", HAS_ARG | OPT_STRING | OPT_SPEC, {.off = OFFSET(dump_attachment)}, "extract an attachment into a file", "filename" },
4274 { "vframes", HAS_ARG | OPT_VIDEO | OPT_FUNC2, {(void*)opt_video_frames}, "set the number of video frames to record", "number" },
4275 { "r", HAS_ARG | OPT_VIDEO | OPT_STRING | OPT_SPEC, {.off = OFFSET(frame_rates)}, "set frame rate (Hz value, fraction or abbreviation)", "rate" },
4276 { "s", HAS_ARG | OPT_VIDEO | OPT_STRING | OPT_SPEC, {.off = OFFSET(frame_sizes)}, "set frame size (WxH or abbreviation)", "size" },
4277 { "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" },
4278 { "pix_fmt", HAS_ARG | OPT_EXPERT | OPT_VIDEO | OPT_STRING | OPT_SPEC, {.off = OFFSET(frame_pix_fmts)}, "set pixel format", "format" },
4279 { "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" },
4280 { "vn", OPT_BOOL | OPT_VIDEO | OPT_OFFSET, {.off = OFFSET(video_disable)}, "disable video" },
4281 { "vdt", OPT_INT | HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)&video_discard}, "discard threshold", "n" },
4282 { "rc_override", HAS_ARG | OPT_EXPERT | OPT_VIDEO | OPT_STRING | OPT_SPEC, {.off = OFFSET(rc_overrides)}, "rate control override for specific intervals", "override" },
4283 { "vcodec", HAS_ARG | OPT_VIDEO | OPT_FUNC2, {(void*)opt_video_codec}, "force video codec ('copy' to copy stream)", "codec" },
4284 { "same_quant", OPT_BOOL | OPT_VIDEO, {(void*)&same_quant},
4285 "use same quantizer as source (implies VBR)" },
4286 { "pass", HAS_ARG | OPT_VIDEO, {(void*)opt_pass}, "select the pass number (1 or 2)", "n" },
4287 { "passlogfile", HAS_ARG | OPT_VIDEO, {(void*)&opt_passlogfile}, "select two pass log file name prefix", "prefix" },
4288 { "deinterlace", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, {(void*)&do_deinterlace},
4289 "deinterlace pictures" },
4290 { "vstats", OPT_EXPERT | OPT_VIDEO, {(void*)&opt_vstats}, "dump video coding statistics to file" },
4291 { "vstats_file", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_vstats_file}, "dump video coding statistics to file", "file" },
4293 { "vf", HAS_ARG | OPT_VIDEO | OPT_FUNC2, {(void*)opt_video_filters}, "video filters", "filter list" },
4295 { "intra_matrix", HAS_ARG | OPT_EXPERT | OPT_VIDEO | OPT_STRING | OPT_SPEC, {.off = OFFSET(intra_matrices)}, "specify intra matrix coeffs", "matrix" },
4296 { "inter_matrix", HAS_ARG | OPT_EXPERT | OPT_VIDEO | OPT_STRING | OPT_SPEC, {.off = OFFSET(inter_matrices)}, "specify inter matrix coeffs", "matrix" },
4297 { "top", HAS_ARG | OPT_EXPERT | OPT_VIDEO | OPT_INT| OPT_SPEC, {.off = OFFSET(top_field_first)}, "top=1/bottom=0/auto=-1 field first", "" },
4298 { "dc", OPT_INT | HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)&intra_dc_precision}, "intra_dc_precision", "precision" },
4299 { "vtag", HAS_ARG | OPT_EXPERT | OPT_VIDEO | OPT_FUNC2, {(void*)opt_video_tag}, "force video tag/fourcc", "fourcc/tag" },
4300 { "qphist", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, { (void *)&qp_hist }, "show QP histogram" },
4301 { "force_fps", OPT_BOOL | OPT_EXPERT | OPT_VIDEO | OPT_SPEC, {.off = OFFSET(force_fps)}, "force the selected framerate, disable the best supported framerate selection" },
4302 { "streamid", HAS_ARG | OPT_EXPERT | OPT_FUNC2, {(void*)opt_streamid}, "set the value of an outfile streamid", "streamIndex:value" },
4303 { "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" },
4306 { "aframes", HAS_ARG | OPT_AUDIO | OPT_FUNC2, {(void*)opt_audio_frames}, "set the number of audio frames to record", "number" },
4307 { "aq", HAS_ARG | OPT_AUDIO | OPT_FUNC2, {(void*)opt_audio_qscale}, "set audio quality (codec-specific)", "quality", },
4308 { "ar", HAS_ARG | OPT_AUDIO | OPT_INT | OPT_SPEC, {.off = OFFSET(audio_sample_rate)}, "set audio sampling rate (in Hz)", "rate" },
4309 { "ac", HAS_ARG | OPT_AUDIO | OPT_INT | OPT_SPEC, {.off = OFFSET(audio_channels)}, "set number of audio channels", "channels" },
4310 { "an", OPT_BOOL | OPT_AUDIO | OPT_OFFSET, {.off = OFFSET(audio_disable)}, "disable audio" },
4311 { "acodec", HAS_ARG | OPT_AUDIO | OPT_FUNC2, {(void*)opt_audio_codec}, "force audio codec ('copy' to copy stream)", "codec" },
4312 { "atag", HAS_ARG | OPT_EXPERT | OPT_AUDIO | OPT_FUNC2, {(void*)opt_audio_tag}, "force audio tag/fourcc", "fourcc/tag" },
4313 { "vol", OPT_INT | HAS_ARG | OPT_AUDIO, {(void*)&audio_volume}, "change audio volume (256=normal)" , "volume" }, //
4314 { "sample_fmt", HAS_ARG | OPT_EXPERT | OPT_AUDIO | OPT_SPEC | OPT_STRING, {.off = OFFSET(sample_fmts)}, "set sample format", "format" },
4316 /* subtitle options */
4317 { "sn", OPT_BOOL | OPT_SUBTITLE | OPT_OFFSET, {.off = OFFSET(subtitle_disable)}, "disable subtitle" },
4318 { "scodec", HAS_ARG | OPT_SUBTITLE | OPT_FUNC2, {(void*)opt_subtitle_codec}, "force subtitle codec ('copy' to copy stream)", "codec" },
4319 { "stag", HAS_ARG | OPT_EXPERT | OPT_SUBTITLE | OPT_FUNC2, {(void*)opt_subtitle_tag}, "force subtitle tag/fourcc", "fourcc/tag" },
4322 { "isync", OPT_BOOL | OPT_EXPERT | OPT_GRAB, {(void*)&input_sync}, "sync read on input", "" },
4325 { "muxdelay", OPT_FLOAT | HAS_ARG | OPT_EXPERT | OPT_OFFSET, {.off = OFFSET(mux_max_delay)}, "set the maximum demux-decode delay", "seconds" },
4326 { "muxpreload", OPT_FLOAT | HAS_ARG | OPT_EXPERT | OPT_OFFSET, {.off = OFFSET(mux_preload)}, "set the initial demux-decode delay", "seconds" },
4328 { "bsf", HAS_ARG | OPT_STRING | OPT_SPEC, {.off = OFFSET(bitstream_filters)}, "A comma-separated list of bitstream filters", "bitstream_filters" },
4330 /* data codec support */
4331 { "dcodec", HAS_ARG | OPT_DATA | OPT_FUNC2, {(void*)opt_data_codec}, "force data codec ('copy' to copy stream)", "codec" },
4333 { "default", HAS_ARG | OPT_AUDIO | OPT_VIDEO | OPT_EXPERT, {(void*)opt_default}, "generic catch all option", "" },
4337 int main(int argc, char **argv)
4339 OptionsContext o = { 0 };
4344 av_log_set_flags(AV_LOG_SKIP_REPEATED);
4345 parse_loglevel(argc, argv, options);
4347 if(argc>1 && !strcmp(argv[1], "-d")){
4349 av_log_set_callback(log_callback_null);
4354 avcodec_register_all();
4356 avdevice_register_all();
4359 avfilter_register_all();
4362 avformat_network_init();
4367 parse_options(&o, argc, argv, options, opt_output_file);
4369 if(nb_output_files <= 0 && nb_input_files == 0) {
4371 av_log(NULL, AV_LOG_WARNING, "Use -h to get full help or, even better, run 'man %s'\n", program_name);
4375 /* file converter / grab */
4376 if (nb_output_files <= 0) {
4377 fprintf(stderr, "At least one output file must be specified\n");
4381 if (nb_input_files == 0) {
4382 av_log(NULL, AV_LOG_FATAL, "At least one input file must be specified\n");
4387 if (transcode(output_files, nb_output_files, input_files, nb_input_files) < 0)
4389 ti = getutime() - ti;
4391 int maxrss = getmaxrss() / 1024;
4392 printf("bench: utime=%0.3fs maxrss=%ikB\n", ti / 1000000.0, maxrss);