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= 0;
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 static void *samples;
160 #define DEFAULT_PASS_LOGFILENAME_PREFIX "av2pass"
162 typedef struct InputStream {
165 int discard; /* true if stream data should be discarded */
166 int decoding_needed; /* true if the packets must be decoded in 'raw_fifo' */
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_dict_free(&input_streams[i].opts);
620 av_free(vstats_filename);
622 av_freep(&input_streams);
623 av_freep(&input_files);
624 av_freep(&output_streams);
625 av_freep(&output_files);
630 allocated_audio_buf_size= allocated_audio_out_size= 0;
636 avformat_network_deinit();
638 if (received_sigterm) {
639 av_log(NULL, AV_LOG_INFO, "Received signal %d: terminating.\n",
640 (int) received_sigterm);
644 exit(ret); /* not all OS-es handle main() return value */
647 static void assert_avoptions(AVDictionary *m)
649 AVDictionaryEntry *t;
650 if ((t = av_dict_get(m, "", NULL, AV_DICT_IGNORE_SUFFIX))) {
651 av_log(NULL, AV_LOG_FATAL, "Option %s not found.\n", t->key);
656 static void assert_codec_experimental(AVCodecContext *c, int encoder)
658 const char *codec_string = encoder ? "encoder" : "decoder";
660 if (c->codec->capabilities & CODEC_CAP_EXPERIMENTAL &&
661 c->strict_std_compliance > FF_COMPLIANCE_EXPERIMENTAL) {
662 av_log(NULL, AV_LOG_FATAL, "%s '%s' is experimental and might produce bad "
663 "results.\nAdd '-strict experimental' if you want to use it.\n",
664 codec_string, c->codec->name);
665 codec = encoder ? avcodec_find_encoder(c->codec->id) : avcodec_find_decoder(c->codec->id);
666 if (!(codec->capabilities & CODEC_CAP_EXPERIMENTAL))
667 av_log(NULL, AV_LOG_FATAL, "Or use the non experimental %s '%s'.\n",
668 codec_string, codec->name);
673 static void choose_sample_fmt(AVStream *st, AVCodec *codec)
675 if(codec && codec->sample_fmts){
676 const enum AVSampleFormat *p= codec->sample_fmts;
678 if(*p == st->codec->sample_fmt)
682 if((codec->capabilities & CODEC_CAP_LOSSLESS) && av_get_sample_fmt_name(st->codec->sample_fmt) > av_get_sample_fmt_name(codec->sample_fmts[0]))
683 av_log(NULL, AV_LOG_ERROR, "Convertion will not be lossless'\n");
684 if(av_get_sample_fmt_name(st->codec->sample_fmt))
685 av_log(NULL, AV_LOG_WARNING,
686 "Incompatible sample format '%s' for codec '%s', auto-selecting format '%s'\n",
687 av_get_sample_fmt_name(st->codec->sample_fmt),
689 av_get_sample_fmt_name(codec->sample_fmts[0]));
690 st->codec->sample_fmt = codec->sample_fmts[0];
695 static void choose_sample_rate(AVStream *st, AVCodec *codec)
697 if(codec && codec->supported_samplerates){
698 const int *p= codec->supported_samplerates;
700 int best_dist=INT_MAX;
702 int dist= abs(st->codec->sample_rate - *p);
703 if(dist < best_dist){
709 av_log(st->codec, AV_LOG_WARNING, "Requested sampling rate unsupported using closest supported (%d)\n", best);
711 st->codec->sample_rate= best;
715 static void choose_pixel_fmt(AVStream *st, AVCodec *codec)
717 if(codec && codec->pix_fmts){
718 const enum PixelFormat *p= codec->pix_fmts;
719 if(st->codec->strict_std_compliance <= FF_COMPLIANCE_UNOFFICIAL){
720 if(st->codec->codec_id==CODEC_ID_MJPEG){
721 p= (const enum PixelFormat[]){PIX_FMT_YUVJ420P, PIX_FMT_YUVJ422P, PIX_FMT_YUV420P, PIX_FMT_YUV422P, PIX_FMT_NONE};
722 }else if(st->codec->codec_id==CODEC_ID_LJPEG){
723 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};
726 for (; *p != PIX_FMT_NONE; p++) {
727 if(*p == st->codec->pix_fmt)
730 if (*p == PIX_FMT_NONE) {
731 if(st->codec->pix_fmt != PIX_FMT_NONE)
732 av_log(NULL, AV_LOG_WARNING,
733 "Incompatible pixel format '%s' for codec '%s', auto-selecting format '%s'\n",
734 av_pix_fmt_descriptors[st->codec->pix_fmt].name,
736 av_pix_fmt_descriptors[codec->pix_fmts[0]].name);
737 st->codec->pix_fmt = codec->pix_fmts[0];
743 get_sync_ipts(const OutputStream *ost)
745 const InputStream *ist = ost->sync_ist;
746 OutputFile *of = &output_files[ost->file_index];
747 return (double)(ist->pts - of->start_time)/AV_TIME_BASE;
750 static void write_frame(AVFormatContext *s, AVPacket *pkt, AVCodecContext *avctx, AVBitStreamFilterContext *bsfc){
754 AVPacket new_pkt= *pkt;
755 int a= av_bitstream_filter_filter(bsfc, avctx, NULL,
756 &new_pkt.data, &new_pkt.size,
757 pkt->data, pkt->size,
758 pkt->flags & AV_PKT_FLAG_KEY);
761 new_pkt.destruct= av_destruct_packet;
763 av_log(NULL, AV_LOG_ERROR, "%s failed for stream %d, codec %s",
764 bsfc->filter->name, pkt->stream_index,
765 avctx->codec ? avctx->codec->name : "copy");
775 ret= av_interleaved_write_frame(s, pkt);
777 print_error("av_interleaved_write_frame()", ret);
782 static void do_audio_out(AVFormatContext *s,
785 unsigned char *buf, int size)
788 int64_t audio_out_size, audio_buf_size;
789 int64_t allocated_for_size= size;
791 int size_out, frame_bytes, ret, resample_changed;
792 AVCodecContext *enc= ost->st->codec;
793 AVCodecContext *dec= ist->st->codec;
794 int osize = av_get_bytes_per_sample(enc->sample_fmt);
795 int isize = av_get_bytes_per_sample(dec->sample_fmt);
796 const int coded_bps = av_get_bits_per_sample(enc->codec->id);
799 audio_buf_size= (allocated_for_size + isize*dec->channels - 1) / (isize*dec->channels);
800 audio_buf_size= (audio_buf_size*enc->sample_rate + dec->sample_rate) / dec->sample_rate;
801 audio_buf_size= audio_buf_size*2 + 10000; //safety factors for the deprecated resampling API
802 audio_buf_size= FFMAX(audio_buf_size, enc->frame_size);
803 audio_buf_size*= osize*enc->channels;
805 audio_out_size= FFMAX(audio_buf_size, enc->frame_size * osize * enc->channels);
806 if(coded_bps > 8*osize)
807 audio_out_size= audio_out_size * coded_bps / (8*osize);
808 audio_out_size += FF_MIN_BUFFER_SIZE;
810 if(audio_out_size > INT_MAX || audio_buf_size > INT_MAX){
811 av_log(NULL, AV_LOG_FATAL, "Buffer sizes too large\n");
815 av_fast_malloc(&audio_buf, &allocated_audio_buf_size, audio_buf_size);
816 av_fast_malloc(&audio_out, &allocated_audio_out_size, audio_out_size);
817 if (!audio_buf || !audio_out){
818 av_log(NULL, AV_LOG_FATAL, "Out of memory in do_audio_out\n");
822 if (enc->channels != dec->channels)
823 ost->audio_resample = 1;
825 resample_changed = ost->resample_sample_fmt != dec->sample_fmt ||
826 ost->resample_channels != dec->channels ||
827 ost->resample_sample_rate != dec->sample_rate;
829 if ((ost->audio_resample && !ost->resample) || resample_changed) {
830 if (resample_changed) {
831 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",
832 ist->file_index, ist->st->index,
833 ost->resample_sample_rate, av_get_sample_fmt_name(ost->resample_sample_fmt), ost->resample_channels,
834 dec->sample_rate, av_get_sample_fmt_name(dec->sample_fmt), dec->channels);
835 ost->resample_sample_fmt = dec->sample_fmt;
836 ost->resample_channels = dec->channels;
837 ost->resample_sample_rate = dec->sample_rate;
839 audio_resample_close(ost->resample);
841 /* if audio_sync_method is >1 the resampler is needed for audio drift compensation */
842 if (audio_sync_method <= 1 &&
843 ost->resample_sample_fmt == enc->sample_fmt &&
844 ost->resample_channels == enc->channels &&
845 ost->resample_sample_rate == enc->sample_rate) {
846 ost->resample = NULL;
847 ost->audio_resample = 0;
849 if (dec->sample_fmt != AV_SAMPLE_FMT_S16)
850 av_log(NULL, AV_LOG_WARNING, "Using s16 intermediate sample format for resampling\n");
851 ost->resample = av_audio_resample_init(enc->channels, dec->channels,
852 enc->sample_rate, dec->sample_rate,
853 enc->sample_fmt, dec->sample_fmt,
855 if (!ost->resample) {
856 av_log(NULL, AV_LOG_FATAL, "Can not resample %d channels @ %d Hz to %d channels @ %d Hz\n",
857 dec->channels, dec->sample_rate,
858 enc->channels, enc->sample_rate);
864 #define MAKE_SFMT_PAIR(a,b) ((a)+AV_SAMPLE_FMT_NB*(b))
865 if (!ost->audio_resample && dec->sample_fmt!=enc->sample_fmt &&
866 MAKE_SFMT_PAIR(enc->sample_fmt,dec->sample_fmt)!=ost->reformat_pair) {
867 if (ost->reformat_ctx)
868 av_audio_convert_free(ost->reformat_ctx);
869 ost->reformat_ctx = av_audio_convert_alloc(enc->sample_fmt, 1,
870 dec->sample_fmt, 1, NULL, 0);
871 if (!ost->reformat_ctx) {
872 av_log(NULL, AV_LOG_FATAL, "Cannot convert %s sample format to %s sample format\n",
873 av_get_sample_fmt_name(dec->sample_fmt),
874 av_get_sample_fmt_name(enc->sample_fmt));
877 ost->reformat_pair=MAKE_SFMT_PAIR(enc->sample_fmt,dec->sample_fmt);
880 if(audio_sync_method){
881 double delta = get_sync_ipts(ost) * enc->sample_rate - ost->sync_opts
882 - av_fifo_size(ost->fifo)/(enc->channels * 2);
883 double idelta= delta*dec->sample_rate / enc->sample_rate;
884 int byte_delta= ((int)idelta)*2*dec->channels;
886 //FIXME resample delay
887 if(fabs(delta) > 50){
888 if(ist->is_start || fabs(delta) > audio_drift_threshold*enc->sample_rate){
890 byte_delta= FFMAX(byte_delta, -size);
893 av_log(NULL, AV_LOG_VERBOSE, "discarding %d audio samples\n", (int)-delta);
898 static uint8_t *input_tmp= NULL;
899 input_tmp= av_realloc(input_tmp, byte_delta + size);
901 if(byte_delta > allocated_for_size - size){
902 allocated_for_size= byte_delta + (int64_t)size;
907 memset(input_tmp, 0, byte_delta);
908 memcpy(input_tmp + byte_delta, buf, size);
911 av_log(NULL, AV_LOG_VERBOSE, "adding %d audio samples of silence\n", (int)delta);
913 }else if(audio_sync_method>1){
914 int comp= av_clip(delta, -audio_sync_method, audio_sync_method);
915 av_assert0(ost->audio_resample);
916 av_log(NULL, AV_LOG_VERBOSE, "compensating audio timestamp drift:%f compensation:%d in:%d\n",
917 delta, comp, enc->sample_rate);
918 // 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));
919 av_resample_compensate(*(struct AVResampleContext**)ost->resample, comp, enc->sample_rate);
923 ost->sync_opts= lrintf(get_sync_ipts(ost) * enc->sample_rate)
924 - av_fifo_size(ost->fifo)/(enc->channels * 2); //FIXME wrong
926 if (ost->audio_resample) {
928 size_out = audio_resample(ost->resample,
929 (short *)buftmp, (short *)buf,
930 size / (dec->channels * isize));
931 size_out = size_out * enc->channels * osize;
937 if (!ost->audio_resample && dec->sample_fmt!=enc->sample_fmt) {
938 const void *ibuf[6]= {buftmp};
939 void *obuf[6]= {audio_buf};
940 int istride[6]= {isize};
941 int ostride[6]= {osize};
942 int len= size_out/istride[0];
943 if (av_audio_convert(ost->reformat_ctx, obuf, ostride, ibuf, istride, len)<0) {
944 printf("av_audio_convert() failed\n");
950 size_out = len*osize;
953 /* now encode as many frames as possible */
954 if (enc->frame_size > 1) {
955 /* output resampled raw samples */
956 if (av_fifo_realloc2(ost->fifo, av_fifo_size(ost->fifo) + size_out) < 0) {
957 av_log(NULL, AV_LOG_FATAL, "av_fifo_realloc2() failed\n");
960 av_fifo_generic_write(ost->fifo, buftmp, size_out, NULL);
962 frame_bytes = enc->frame_size * osize * enc->channels;
964 while (av_fifo_size(ost->fifo) >= frame_bytes) {
966 av_init_packet(&pkt);
968 av_fifo_generic_read(ost->fifo, audio_buf, frame_bytes, NULL);
970 //FIXME pass ost->sync_opts as AVFrame.pts in avcodec_encode_audio()
972 ret = avcodec_encode_audio(enc, audio_out, audio_out_size,
975 av_log(NULL, AV_LOG_FATAL, "Audio encoding failed\n");
979 pkt.stream_index= ost->index;
982 if(enc->coded_frame && enc->coded_frame->pts != AV_NOPTS_VALUE)
983 pkt.pts= av_rescale_q(enc->coded_frame->pts, enc->time_base, ost->st->time_base);
984 pkt.flags |= AV_PKT_FLAG_KEY;
985 write_frame(s, &pkt, enc, ost->bitstream_filters);
987 ost->sync_opts += enc->frame_size;
991 av_init_packet(&pkt);
993 ost->sync_opts += size_out / (osize * enc->channels);
995 /* output a pcm frame */
996 /* determine the size of the coded buffer */
999 size_out = size_out*coded_bps/8;
1001 if(size_out > audio_out_size){
1002 av_log(NULL, AV_LOG_FATAL, "Internal error, buffer size too small\n");
1006 //FIXME pass ost->sync_opts as AVFrame.pts in avcodec_encode_audio()
1007 ret = avcodec_encode_audio(enc, audio_out, size_out,
1010 av_log(NULL, AV_LOG_FATAL, "Audio encoding failed\n");
1014 pkt.stream_index= ost->index;
1015 pkt.data= audio_out;
1017 if(enc->coded_frame && enc->coded_frame->pts != AV_NOPTS_VALUE)
1018 pkt.pts= av_rescale_q(enc->coded_frame->pts, enc->time_base, ost->st->time_base);
1019 pkt.flags |= AV_PKT_FLAG_KEY;
1020 write_frame(s, &pkt, enc, ost->bitstream_filters);
1024 static void pre_process_video_frame(InputStream *ist, AVPicture *picture, void **bufp)
1026 AVCodecContext *dec;
1027 AVPicture *picture2;
1028 AVPicture picture_tmp;
1031 dec = ist->st->codec;
1033 /* deinterlace : must be done before any resize */
1034 if (do_deinterlace) {
1037 /* create temporary picture */
1038 size = avpicture_get_size(dec->pix_fmt, dec->width, dec->height);
1039 buf = av_malloc(size);
1043 picture2 = &picture_tmp;
1044 avpicture_fill(picture2, buf, dec->pix_fmt, dec->width, dec->height);
1046 if(avpicture_deinterlace(picture2, picture,
1047 dec->pix_fmt, dec->width, dec->height) < 0) {
1048 /* if error, do not deinterlace */
1049 av_log(NULL, AV_LOG_WARNING, "Deinterlacing failed\n");
1058 if (picture != picture2)
1059 *picture = *picture2;
1063 static void do_subtitle_out(AVFormatContext *s,
1069 static uint8_t *subtitle_out = NULL;
1070 int subtitle_out_max_size = 1024 * 1024;
1071 int subtitle_out_size, nb, i;
1072 AVCodecContext *enc;
1075 if (pts == AV_NOPTS_VALUE) {
1076 av_log(NULL, AV_LOG_ERROR, "Subtitle packets must have a pts\n");
1082 enc = ost->st->codec;
1084 if (!subtitle_out) {
1085 subtitle_out = av_malloc(subtitle_out_max_size);
1088 /* Note: DVB subtitle need one packet to draw them and one other
1089 packet to clear them */
1090 /* XXX: signal it in the codec context ? */
1091 if (enc->codec_id == CODEC_ID_DVB_SUBTITLE)
1096 for(i = 0; i < nb; i++) {
1097 sub->pts = av_rescale_q(pts, ist->st->time_base, AV_TIME_BASE_Q);
1098 // start_display_time is required to be 0
1099 sub->pts += av_rescale_q(sub->start_display_time, (AVRational){1, 1000}, AV_TIME_BASE_Q);
1100 sub->end_display_time -= sub->start_display_time;
1101 sub->start_display_time = 0;
1102 subtitle_out_size = avcodec_encode_subtitle(enc, subtitle_out,
1103 subtitle_out_max_size, sub);
1104 if (subtitle_out_size < 0) {
1105 av_log(NULL, AV_LOG_FATAL, "Subtitle encoding failed\n");
1109 av_init_packet(&pkt);
1110 pkt.stream_index = ost->index;
1111 pkt.data = subtitle_out;
1112 pkt.size = subtitle_out_size;
1113 pkt.pts = av_rescale_q(sub->pts, AV_TIME_BASE_Q, ost->st->time_base);
1114 if (enc->codec_id == CODEC_ID_DVB_SUBTITLE) {
1115 /* XXX: the pts correction is handled here. Maybe handling
1116 it in the codec would be better */
1118 pkt.pts += 90 * sub->start_display_time;
1120 pkt.pts += 90 * sub->end_display_time;
1122 write_frame(s, &pkt, ost->st->codec, ost->bitstream_filters);
1126 static int bit_buffer_size= 1024*256;
1127 static uint8_t *bit_buffer= NULL;
1129 static void do_video_resample(OutputStream *ost,
1131 AVFrame *in_picture,
1132 AVFrame **out_picture)
1134 int resample_changed = 0;
1135 AVCodecContext *dec = ist->st->codec;
1136 AVCodecContext *enc = ost->st->codec;
1137 *out_picture = in_picture;
1139 resample_changed = ost->resample_width != dec->width ||
1140 ost->resample_height != dec->height ||
1141 ost->resample_pix_fmt != dec->pix_fmt;
1143 #if !CONFIG_AVFILTER
1144 if (resample_changed) {
1145 av_log(NULL, AV_LOG_INFO,
1146 "Input stream #%d:%d frame changed from size:%dx%d fmt:%s to size:%dx%d fmt:%s\n",
1147 ist->file_index, ist->st->index,
1148 ost->resample_width, ost->resample_height, av_get_pix_fmt_name(ost->resample_pix_fmt),
1149 dec->width , dec->height , av_get_pix_fmt_name(dec->pix_fmt));
1150 ost->resample_width = dec->width;
1151 ost->resample_height = dec->height;
1152 ost->resample_pix_fmt = dec->pix_fmt;
1155 ost->video_resample = dec->width != enc->width ||
1156 dec->height != enc->height ||
1157 dec->pix_fmt != enc->pix_fmt;
1159 if (ost->video_resample) {
1160 *out_picture = &ost->resample_frame;
1161 if (!ost->img_resample_ctx || resample_changed) {
1162 /* initialize the destination picture */
1163 if (!ost->resample_frame.data[0]) {
1164 avcodec_get_frame_defaults(&ost->resample_frame);
1165 if (avpicture_alloc((AVPicture *)&ost->resample_frame, enc->pix_fmt,
1166 enc->width, enc->height)) {
1167 fprintf(stderr, "Cannot allocate temp picture, check pix fmt\n");
1171 /* initialize a new scaler context */
1172 sws_freeContext(ost->img_resample_ctx);
1173 ost->img_resample_ctx = sws_getContext(dec->width, dec->height, dec->pix_fmt,
1174 enc->width, enc->height, enc->pix_fmt,
1175 ost->sws_flags, NULL, NULL, NULL);
1176 if (ost->img_resample_ctx == NULL) {
1177 av_log(NULL, AV_LOG_FATAL, "Cannot get resampling context\n");
1181 sws_scale(ost->img_resample_ctx, in_picture->data, in_picture->linesize,
1182 0, ost->resample_height, (*out_picture)->data, (*out_picture)->linesize);
1185 if (resample_changed) {
1186 avfilter_graph_free(&ost->graph);
1187 if (configure_video_filters(ist, ost)) {
1188 av_log(NULL, AV_LOG_FATAL, "Error reinitializing filters!\n");
1193 if (resample_changed) {
1194 ost->resample_width = dec->width;
1195 ost->resample_height = dec->height;
1196 ost->resample_pix_fmt = dec->pix_fmt;
1201 static void do_video_out(AVFormatContext *s,
1204 AVFrame *in_picture,
1205 int *frame_size, float quality)
1207 int nb_frames, i, ret, format_video_sync;
1208 AVFrame *final_picture;
1209 AVCodecContext *enc;
1212 enc = ost->st->codec;
1214 sync_ipts = get_sync_ipts(ost) / av_q2d(enc->time_base);
1216 /* by default, we output a single frame */
1221 format_video_sync = video_sync_method;
1222 if (format_video_sync < 0)
1223 format_video_sync = (s->oformat->flags & AVFMT_NOTIMESTAMPS) ? 0 :
1224 (s->oformat->flags & AVFMT_VARIABLE_FPS) ? 2 : 1;
1226 if (format_video_sync) {
1227 double vdelta = sync_ipts - ost->sync_opts;
1228 //FIXME set to 0.5 after we fix some dts/pts bugs like in avidec.c
1231 else if (format_video_sync == 2) {
1234 }else if(vdelta>0.6)
1235 ost->sync_opts= lrintf(sync_ipts);
1236 }else if (vdelta > 1.1)
1237 nb_frames = lrintf(vdelta);
1238 //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);
1239 if (nb_frames == 0){
1241 av_log(NULL, AV_LOG_VERBOSE, "*** drop!\n");
1242 }else if (nb_frames > 1) {
1243 nb_frames_dup += nb_frames - 1;
1244 av_log(NULL, AV_LOG_VERBOSE, "*** %d dup!\n", nb_frames-1);
1247 ost->sync_opts= lrintf(sync_ipts);
1249 nb_frames = FFMIN(nb_frames, ost->max_frames - ost->frame_number);
1253 do_video_resample(ost, ist, in_picture, &final_picture);
1255 /* duplicates frame if needed */
1256 for(i=0;i<nb_frames;i++) {
1258 av_init_packet(&pkt);
1259 pkt.stream_index= ost->index;
1261 if (s->oformat->flags & AVFMT_RAWPICTURE) {
1262 /* raw pictures are written as AVPicture structure to
1263 avoid any copies. We support temporarily the older
1265 enc->coded_frame->interlaced_frame = in_picture->interlaced_frame;
1266 enc->coded_frame->top_field_first = in_picture->top_field_first;
1267 pkt.data= (uint8_t *)final_picture;
1268 pkt.size= sizeof(AVPicture);
1269 pkt.pts= av_rescale_q(ost->sync_opts, enc->time_base, ost->st->time_base);
1270 pkt.flags |= AV_PKT_FLAG_KEY;
1272 write_frame(s, &pkt, ost->st->codec, ost->bitstream_filters);
1274 AVFrame big_picture;
1276 big_picture= *final_picture;
1277 /* better than nothing: use input picture interlaced
1279 big_picture.interlaced_frame = in_picture->interlaced_frame;
1280 if (ost->st->codec->flags & (CODEC_FLAG_INTERLACED_DCT|CODEC_FLAG_INTERLACED_ME)) {
1281 if (ost->top_field_first == -1)
1282 big_picture.top_field_first = in_picture->top_field_first;
1284 big_picture.top_field_first = !!ost->top_field_first;
1287 /* handles same_quant here. This is not correct because it may
1288 not be a global option */
1289 big_picture.quality = quality;
1290 if (!enc->me_threshold)
1291 big_picture.pict_type = 0;
1292 // big_picture.pts = AV_NOPTS_VALUE;
1293 big_picture.pts= ost->sync_opts;
1294 // big_picture.pts= av_rescale(ost->sync_opts, AV_TIME_BASE*(int64_t)enc->time_base.num, enc->time_base.den);
1295 //av_log(NULL, AV_LOG_DEBUG, "%"PRId64" -> encoder\n", ost->sync_opts);
1296 if (ost->forced_kf_index < ost->forced_kf_count &&
1297 big_picture.pts >= ost->forced_kf_pts[ost->forced_kf_index]) {
1298 big_picture.pict_type = AV_PICTURE_TYPE_I;
1299 ost->forced_kf_index++;
1301 ret = avcodec_encode_video(enc,
1302 bit_buffer, bit_buffer_size,
1305 av_log(NULL, AV_LOG_FATAL, "Video encoding failed\n");
1310 pkt.data= bit_buffer;
1312 if(enc->coded_frame->pts != AV_NOPTS_VALUE)
1313 pkt.pts= av_rescale_q(enc->coded_frame->pts, enc->time_base, ost->st->time_base);
1314 /*av_log(NULL, AV_LOG_DEBUG, "encoder -> %"PRId64"/%"PRId64"\n",
1315 pkt.pts != AV_NOPTS_VALUE ? av_rescale(pkt.pts, enc->time_base.den, AV_TIME_BASE*(int64_t)enc->time_base.num) : -1,
1316 pkt.dts != AV_NOPTS_VALUE ? av_rescale(pkt.dts, enc->time_base.den, AV_TIME_BASE*(int64_t)enc->time_base.num) : -1);*/
1318 if(enc->coded_frame->key_frame)
1319 pkt.flags |= AV_PKT_FLAG_KEY;
1320 write_frame(s, &pkt, ost->st->codec, ost->bitstream_filters);
1323 //fprintf(stderr,"\nFrame: %3d size: %5d type: %d",
1324 // enc->frame_number-1, ret, enc->pict_type);
1325 /* if two pass, output log */
1326 if (ost->logfile && enc->stats_out) {
1327 fprintf(ost->logfile, "%s", enc->stats_out);
1332 ost->frame_number++;
1336 static double psnr(double d){
1337 return -10.0*log(d)/log(10.0);
1340 static void do_video_stats(AVFormatContext *os, OutputStream *ost,
1343 AVCodecContext *enc;
1345 double ti1, bitrate, avg_bitrate;
1347 /* this is executed just the first time do_video_stats is called */
1349 vstats_file = fopen(vstats_filename, "w");
1356 enc = ost->st->codec;
1357 if (enc->codec_type == AVMEDIA_TYPE_VIDEO) {
1358 frame_number = ost->frame_number;
1359 fprintf(vstats_file, "frame= %5d q= %2.1f ", frame_number, enc->coded_frame->quality/(float)FF_QP2LAMBDA);
1360 if (enc->flags&CODEC_FLAG_PSNR)
1361 fprintf(vstats_file, "PSNR= %6.2f ", psnr(enc->coded_frame->error[0]/(enc->width*enc->height*255.0*255.0)));
1363 fprintf(vstats_file,"f_size= %6d ", frame_size);
1364 /* compute pts value */
1365 ti1 = ost->sync_opts * av_q2d(enc->time_base);
1369 bitrate = (frame_size * 8) / av_q2d(enc->time_base) / 1000.0;
1370 avg_bitrate = (double)(video_size * 8) / ti1 / 1000.0;
1371 fprintf(vstats_file, "s_size= %8.0fkB time= %0.3f br= %7.1fkbits/s avg_br= %7.1fkbits/s ",
1372 (double)video_size / 1024, ti1, bitrate, avg_bitrate);
1373 fprintf(vstats_file, "type= %c\n", av_get_picture_type_char(enc->coded_frame->pict_type));
1377 static void print_report(OutputFile *output_files,
1378 OutputStream *ost_table, int nb_ostreams,
1379 int is_last_report, int64_t timer_start)
1383 AVFormatContext *oc;
1385 AVCodecContext *enc;
1386 int frame_number, vid, i;
1388 int64_t pts = INT64_MAX;
1389 static int64_t last_time = -1;
1390 static int qp_histogram[52];
1391 int hours, mins, secs, us;
1393 if (!print_stats && !is_last_report)
1396 if (!is_last_report) {
1398 /* display the report every 0.5 seconds */
1399 cur_time = av_gettime();
1400 if (last_time == -1) {
1401 last_time = cur_time;
1404 if ((cur_time - last_time) < 500000)
1406 last_time = cur_time;
1410 oc = output_files[0].ctx;
1412 total_size = avio_size(oc->pb);
1413 if(total_size<0) // FIXME improve avio_size() so it works with non seekable output too
1414 total_size= avio_tell(oc->pb);
1418 for(i=0;i<nb_ostreams;i++) {
1420 ost = &ost_table[i];
1421 enc = ost->st->codec;
1422 if (!ost->stream_copy && enc->coded_frame)
1423 q = enc->coded_frame->quality/(float)FF_QP2LAMBDA;
1424 if (vid && enc->codec_type == AVMEDIA_TYPE_VIDEO) {
1425 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "q=%2.1f ", q);
1427 if (!vid && enc->codec_type == AVMEDIA_TYPE_VIDEO) {
1428 float t = (av_gettime()-timer_start) / 1000000.0;
1430 frame_number = ost->frame_number;
1431 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "frame=%5d fps=%3d q=%3.1f ",
1432 frame_number, (t>1)?(int)(frame_number/t+0.5) : 0, q);
1434 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "L");
1438 if(qp>=0 && qp<FF_ARRAY_ELEMS(qp_histogram))
1441 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "%X", (int)lrintf(log(qp_histogram[j]+1)/log(2)));
1443 if (enc->flags&CODEC_FLAG_PSNR){
1445 double error, error_sum=0;
1446 double scale, scale_sum=0;
1447 char type[3]= {'Y','U','V'};
1448 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "PSNR=");
1451 error= enc->error[j];
1452 scale= enc->width*enc->height*255.0*255.0*frame_number;
1454 error= enc->coded_frame->error[j];
1455 scale= enc->width*enc->height*255.0*255.0;
1460 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "%c:%2.2f ", type[j], psnr(error/scale));
1462 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "*:%2.2f ", psnr(error_sum/scale_sum));
1466 /* compute min output value */
1467 pts = FFMIN(pts, av_rescale_q(ost->st->pts.val,
1468 ost->st->time_base, AV_TIME_BASE_Q));
1471 secs = pts / AV_TIME_BASE;
1472 us = pts % AV_TIME_BASE;
1478 bitrate = pts ? total_size * 8 / (pts / 1000.0) : 0;
1480 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
1481 "size=%8.0fkB time=", total_size / 1024.0);
1482 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
1483 "%02d:%02d:%02d.%02d ", hours, mins, secs,
1484 (100 * us) / AV_TIME_BASE);
1485 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
1486 "bitrate=%6.1fkbits/s", bitrate);
1488 if (nb_frames_dup || nb_frames_drop)
1489 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), " dup=%d drop=%d",
1490 nb_frames_dup, nb_frames_drop);
1492 av_log(NULL, AV_LOG_INFO, "%s \r", buf);
1496 if (is_last_report) {
1497 int64_t raw= audio_size + video_size + extra_size;
1498 av_log(NULL, AV_LOG_INFO, "\n");
1499 av_log(NULL, AV_LOG_INFO, "video:%1.0fkB audio:%1.0fkB global headers:%1.0fkB muxing overhead %f%%\n",
1503 100.0*(total_size - raw)/raw
1508 static void generate_silence(uint8_t* buf, enum AVSampleFormat sample_fmt, size_t size)
1510 int fill_char = 0x00;
1511 if (sample_fmt == AV_SAMPLE_FMT_U8)
1513 memset(buf, fill_char, size);
1516 static void flush_encoders(OutputStream *ost_table, int nb_ostreams)
1520 for (i = 0; i < nb_ostreams; i++) {
1521 OutputStream *ost = &ost_table[i];
1522 AVCodecContext *enc = ost->st->codec;
1523 AVFormatContext *os = output_files[ost->file_index].ctx;
1525 if (!ost->encoding_needed)
1528 if (ost->st->codec->codec_type == AVMEDIA_TYPE_AUDIO && enc->frame_size <=1)
1530 if (ost->st->codec->codec_type == AVMEDIA_TYPE_VIDEO && (os->oformat->flags & AVFMT_RAWPICTURE))
1536 av_init_packet(&pkt);
1537 pkt.stream_index= ost->index;
1539 switch (ost->st->codec->codec_type) {
1540 case AVMEDIA_TYPE_AUDIO:
1541 fifo_bytes = av_fifo_size(ost->fifo);
1543 /* encode any samples remaining in fifo */
1544 if (fifo_bytes > 0) {
1545 int osize = av_get_bytes_per_sample(enc->sample_fmt);
1546 int fs_tmp = enc->frame_size;
1548 av_fifo_generic_read(ost->fifo, audio_buf, fifo_bytes, NULL);
1549 if (enc->codec->capabilities & CODEC_CAP_SMALL_LAST_FRAME) {
1550 enc->frame_size = fifo_bytes / (osize * enc->channels);
1552 int frame_bytes = enc->frame_size*osize*enc->channels;
1553 if (allocated_audio_buf_size < frame_bytes)
1555 generate_silence(audio_buf+fifo_bytes, enc->sample_fmt, frame_bytes - fifo_bytes);
1558 ret = avcodec_encode_audio(enc, bit_buffer, bit_buffer_size, (short *)audio_buf);
1559 pkt.duration = av_rescale((int64_t)enc->frame_size*ost->st->time_base.den,
1560 ost->st->time_base.num, enc->sample_rate);
1561 enc->frame_size = fs_tmp;
1564 ret = avcodec_encode_audio(enc, bit_buffer, bit_buffer_size, NULL);
1567 av_log(NULL, AV_LOG_FATAL, "Audio encoding failed\n");
1571 pkt.flags |= AV_PKT_FLAG_KEY;
1573 case AVMEDIA_TYPE_VIDEO:
1574 ret = avcodec_encode_video(enc, bit_buffer, bit_buffer_size, NULL);
1576 av_log(NULL, AV_LOG_FATAL, "Video encoding failed\n");
1580 if(enc->coded_frame && enc->coded_frame->key_frame)
1581 pkt.flags |= AV_PKT_FLAG_KEY;
1582 if (ost->logfile && enc->stats_out) {
1583 fprintf(ost->logfile, "%s", enc->stats_out);
1592 pkt.data = bit_buffer;
1594 if (enc->coded_frame && enc->coded_frame->pts != AV_NOPTS_VALUE)
1595 pkt.pts= av_rescale_q(enc->coded_frame->pts, enc->time_base, ost->st->time_base);
1596 write_frame(os, &pkt, ost->st->codec, ost->bitstream_filters);
1602 * Check whether a packet from ist should be written into ost at this time
1604 static int check_output_constraints(InputStream *ist, OutputStream *ost)
1606 OutputFile *of = &output_files[ost->file_index];
1607 int ist_index = ist - input_streams;
1609 if (ost->source_index != ist_index)
1612 if (of->start_time && ist->pts < of->start_time)
1615 if (of->recording_time != INT64_MAX &&
1616 av_compare_ts(ist->pts, AV_TIME_BASE_Q, of->recording_time + of->start_time,
1617 (AVRational){1, 1000000}) >= 0) {
1618 ost->is_past_recording_time = 1;
1625 static void do_streamcopy(InputStream *ist, OutputStream *ost, const AVPacket *pkt)
1627 OutputFile *of = &output_files[ost->file_index];
1628 int64_t ost_tb_start_time = av_rescale_q(of->start_time, AV_TIME_BASE_Q, ost->st->time_base);
1632 av_init_packet(&opkt);
1634 if ((!ost->frame_number && !(pkt->flags & AV_PKT_FLAG_KEY)) &&
1635 !ost->copy_initial_nonkeyframes)
1638 /* force the input stream PTS */
1639 if (ost->st->codec->codec_type == AVMEDIA_TYPE_AUDIO)
1640 audio_size += pkt->size;
1641 else if (ost->st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
1642 video_size += pkt->size;
1646 opkt.stream_index = ost->index;
1647 if (pkt->pts != AV_NOPTS_VALUE)
1648 opkt.pts = av_rescale_q(pkt->pts, ist->st->time_base, ost->st->time_base) - ost_tb_start_time;
1650 opkt.pts = AV_NOPTS_VALUE;
1652 if (pkt->dts == AV_NOPTS_VALUE)
1653 opkt.dts = av_rescale_q(ist->pts, AV_TIME_BASE_Q, ost->st->time_base);
1655 opkt.dts = av_rescale_q(pkt->dts, ist->st->time_base, ost->st->time_base);
1656 opkt.dts -= ost_tb_start_time;
1658 opkt.duration = av_rescale_q(pkt->duration, ist->st->time_base, ost->st->time_base);
1659 opkt.flags = pkt->flags;
1661 //FIXME remove the following 2 lines they shall be replaced by the bitstream filters
1662 if( ost->st->codec->codec_id != CODEC_ID_H264
1663 && ost->st->codec->codec_id != CODEC_ID_MPEG1VIDEO
1664 && ost->st->codec->codec_id != CODEC_ID_MPEG2VIDEO
1666 if (av_parser_change(ist->st->parser, ost->st->codec, &opkt.data, &opkt.size, pkt->data, pkt->size, pkt->flags & AV_PKT_FLAG_KEY))
1667 opkt.destruct = av_destruct_packet;
1669 opkt.data = pkt->data;
1670 opkt.size = pkt->size;
1672 if (of->ctx->oformat->flags & AVFMT_RAWPICTURE) {
1673 /* store AVPicture in AVPacket, as expected by the output format */
1674 avpicture_fill(&pict, opkt.data, ost->st->codec->pix_fmt, ost->st->codec->width, ost->st->codec->height);
1675 opkt.data = (uint8_t *)&pict;
1676 opkt.size = sizeof(AVPicture);
1677 opkt.flags |= AV_PKT_FLAG_KEY;
1680 write_frame(of->ctx, &opkt, ost->st->codec, ost->bitstream_filters);
1681 ost->st->codec->frame_number++;
1682 ost->frame_number++;
1683 av_free_packet(&opkt);
1686 static void rate_emu_sleep(InputStream *ist)
1688 if (input_files[ist->file_index].rate_emu) {
1689 int64_t pts = av_rescale(ist->pts, 1000000, AV_TIME_BASE);
1690 int64_t now = av_gettime() - ist->start;
1696 static int transcode_audio(InputStream *ist, AVPacket *pkt, int *got_output)
1698 static unsigned int samples_size = 0;
1699 int bps = av_get_bytes_per_sample(ist->st->codec->sample_fmt);
1700 uint8_t *decoded_data_buf = NULL;
1701 int decoded_data_size = 0;
1704 if (pkt && samples_size < FFMAX(pkt->size * bps, AVCODEC_MAX_AUDIO_FRAME_SIZE)) {
1706 samples_size = FFMAX(pkt->size * bps, AVCODEC_MAX_AUDIO_FRAME_SIZE);
1707 samples = av_malloc(samples_size);
1709 decoded_data_size = samples_size;
1711 ret = avcodec_decode_audio3(ist->st->codec, samples, &decoded_data_size,
1715 *got_output = decoded_data_size > 0;
1717 /* Some bug in mpeg audio decoder gives */
1718 /* decoded_data_size < 0, it seems they are overflows */
1720 /* no audio frame */
1724 decoded_data_buf = (uint8_t *)samples;
1725 ist->next_pts += ((int64_t)AV_TIME_BASE/bps * decoded_data_size) /
1726 (ist->st->codec->sample_rate * ist->st->codec->channels);
1728 // preprocess audio (volume)
1729 if (audio_volume != 256) {
1730 switch (ist->st->codec->sample_fmt) {
1731 case AV_SAMPLE_FMT_U8:
1733 uint8_t *volp = samples;
1734 for (i = 0; i < (decoded_data_size / sizeof(*volp)); i++) {
1735 int v = (((*volp - 128) * audio_volume + 128) >> 8) + 128;
1736 *volp++ = av_clip_uint8(v);
1740 case AV_SAMPLE_FMT_S16:
1742 int16_t *volp = samples;
1743 for (i = 0; i < (decoded_data_size / sizeof(*volp)); i++) {
1744 int v = ((*volp) * audio_volume + 128) >> 8;
1745 *volp++ = av_clip_int16(v);
1749 case AV_SAMPLE_FMT_S32:
1751 int32_t *volp = samples;
1752 for (i = 0; i < (decoded_data_size / sizeof(*volp)); i++) {
1753 int64_t v = (((int64_t)*volp * audio_volume + 128) >> 8);
1754 *volp++ = av_clipl_int32(v);
1758 case AV_SAMPLE_FMT_FLT:
1760 float *volp = samples;
1761 float scale = audio_volume / 256.f;
1762 for (i = 0; i < (decoded_data_size / sizeof(*volp)); i++) {
1767 case AV_SAMPLE_FMT_DBL:
1769 double *volp = samples;
1770 double scale = audio_volume / 256.;
1771 for (i = 0; i < (decoded_data_size / sizeof(*volp)); i++) {
1777 av_log(NULL, AV_LOG_FATAL,
1778 "Audio volume adjustment on sample format %s is not supported.\n",
1779 av_get_sample_fmt_name(ist->st->codec->sample_fmt));
1784 rate_emu_sleep(ist);
1786 for (i = 0; i < nb_output_streams; i++) {
1787 OutputStream *ost = &output_streams[i];
1789 if (!check_output_constraints(ist, ost) || !ost->encoding_needed)
1791 do_audio_out(output_files[ost->file_index].ctx, ost, ist,
1792 decoded_data_buf, decoded_data_size);
1797 static int transcode_video(InputStream *ist, AVPacket *pkt, int *got_output, int64_t *pkt_pts)
1799 AVFrame *decoded_frame, *filtered_frame = NULL;
1800 void *buffer_to_free = NULL;
1804 int frame_available = 1;
1807 if (!(decoded_frame = avcodec_alloc_frame()))
1808 return AVERROR(ENOMEM);
1809 pkt->pts = *pkt_pts;
1810 pkt->dts = ist->pts;
1811 *pkt_pts = AV_NOPTS_VALUE;
1813 ret = avcodec_decode_video2(ist->st->codec,
1814 decoded_frame, got_output, pkt);
1818 quality = same_quant ? decoded_frame->quality : 0;
1820 /* no picture yet */
1821 av_freep(&decoded_frame);
1824 ist->next_pts = ist->pts = decoded_frame->best_effort_timestamp;
1825 if (ist->st->codec->time_base.num != 0) {
1826 int ticks = ist->st->parser ? ist->st->parser->repeat_pict + 1 :
1827 ist->st->codec->ticks_per_frame;
1828 ist->next_pts += ((int64_t)AV_TIME_BASE *
1829 ist->st->codec->time_base.num * ticks) /
1830 ist->st->codec->time_base.den;
1833 pre_process_video_frame(ist, (AVPicture *)decoded_frame, &buffer_to_free);
1835 rate_emu_sleep(ist);
1837 for (i = 0; i < nb_output_streams; i++) {
1838 OutputStream *ost = &output_streams[i];
1841 if (!check_output_constraints(ist, ost) || !ost->encoding_needed)
1845 if (ost->input_video_filter) {
1846 if (!decoded_frame->sample_aspect_ratio.num)
1847 decoded_frame->sample_aspect_ratio = ist->st->sample_aspect_ratio;
1848 decoded_frame->pts = ist->pts;
1850 av_vsrc_buffer_add_frame(ost->input_video_filter, decoded_frame, AV_VSRC_BUF_FLAG_OVERWRITE);
1851 if (!(filtered_frame = avcodec_alloc_frame())) {
1852 ret = AVERROR(ENOMEM);
1855 frame_available = avfilter_poll_frame(ost->output_video_filter->inputs[0]);
1857 while (frame_available) {
1858 if (ost->output_video_filter) {
1859 AVRational ist_pts_tb = ost->output_video_filter->inputs[0]->time_base;
1860 if (av_buffersink_get_buffer_ref(ost->output_video_filter, &ost->picref, 0) < 0)
1863 avfilter_fill_frame_from_video_buffer_ref(filtered_frame, ost->picref);
1864 ist->pts = av_rescale_q(ost->picref->pts, ist_pts_tb, AV_TIME_BASE_Q);
1867 if (ost->picref->video && !ost->frame_aspect_ratio)
1868 ost->st->codec->sample_aspect_ratio = ost->picref->video->sample_aspect_ratio;
1870 filtered_frame = decoded_frame;
1873 do_video_out(output_files[ost->file_index].ctx, ost, ist, filtered_frame, &frame_size,
1874 same_quant ? quality : ost->st->codec->global_quality);
1875 if (vstats_filename && frame_size)
1876 do_video_stats(output_files[ost->file_index].ctx, ost, frame_size);
1879 frame_available = ost->output_video_filter && avfilter_poll_frame(ost->output_video_filter->inputs[0]);
1881 avfilter_unref_buffer(ost->picref);
1883 av_freep(&filtered_frame);
1888 av_free(buffer_to_free);
1889 av_freep(&decoded_frame);
1893 static int transcode_subtitles(InputStream *ist, AVPacket *pkt, int *got_output)
1895 AVSubtitle subtitle;
1896 int i, ret = avcodec_decode_subtitle2(ist->st->codec,
1897 &subtitle, got_output, pkt);
1903 rate_emu_sleep(ist);
1905 for (i = 0; i < nb_output_streams; i++) {
1906 OutputStream *ost = &output_streams[i];
1908 if (!check_output_constraints(ist, ost) || !ost->encoding_needed)
1911 do_subtitle_out(output_files[ost->file_index].ctx, ost, ist, &subtitle, pkt->pts);
1914 avsubtitle_free(&subtitle);
1918 /* pkt = NULL means EOF (needed to flush decoder buffers) */
1919 static int output_packet(InputStream *ist,
1920 OutputStream *ost_table, int nb_ostreams,
1921 const AVPacket *pkt)
1925 int64_t pkt_pts = AV_NOPTS_VALUE;
1928 if (ist->next_pts == AV_NOPTS_VALUE)
1929 ist->next_pts = ist->pts;
1933 av_init_packet(&avpkt);
1941 if(pkt->dts != AV_NOPTS_VALUE)
1942 ist->next_pts = ist->pts = av_rescale_q(pkt->dts, ist->st->time_base, AV_TIME_BASE_Q);
1943 if(pkt->pts != AV_NOPTS_VALUE)
1944 pkt_pts = av_rescale_q(pkt->pts, ist->st->time_base, AV_TIME_BASE_Q);
1946 //while we have more to decode or while the decoder did output something on EOF
1947 while (ist->decoding_needed && (avpkt.size > 0 || (!pkt && got_output))) {
1951 ist->pts = ist->next_pts;
1953 if (avpkt.size && avpkt.size != pkt->size) {
1954 av_log(NULL, ist->showed_multi_packet_warning ? AV_LOG_VERBOSE : AV_LOG_WARNING,
1955 "Multiple frames in a packet from stream %d\n", pkt->stream_index);
1956 ist->showed_multi_packet_warning = 1;
1959 switch(ist->st->codec->codec_type) {
1960 case AVMEDIA_TYPE_AUDIO:
1961 ret = transcode_audio (ist, &avpkt, &got_output);
1963 case AVMEDIA_TYPE_VIDEO:
1964 ret = transcode_video (ist, &avpkt, &got_output, &pkt_pts);
1966 case AVMEDIA_TYPE_SUBTITLE:
1967 ret = transcode_subtitles(ist, &avpkt, &got_output);
1975 // touch data and size only if not EOF
1985 /* handle stream copy */
1986 if (!ist->decoding_needed) {
1987 rate_emu_sleep(ist);
1988 switch (ist->st->codec->codec_type) {
1989 case AVMEDIA_TYPE_AUDIO:
1990 ist->next_pts += ((int64_t)AV_TIME_BASE * ist->st->codec->frame_size) /
1991 ist->st->codec->sample_rate;
1993 case AVMEDIA_TYPE_VIDEO:
1994 if (ist->st->codec->time_base.num != 0) {
1995 int ticks = ist->st->parser ? ist->st->parser->repeat_pict+1 : ist->st->codec->ticks_per_frame;
1996 ist->next_pts += ((int64_t)AV_TIME_BASE *
1997 ist->st->codec->time_base.num * ticks) /
1998 ist->st->codec->time_base.den;
2003 for (i = 0; pkt && i < nb_ostreams; i++) {
2004 OutputStream *ost = &ost_table[i];
2006 if (!check_output_constraints(ist, ost) || ost->encoding_needed)
2009 do_streamcopy(ist, ost, pkt);
2015 static void print_sdp(OutputFile *output_files, int n)
2019 AVFormatContext **avc = av_malloc(sizeof(*avc)*n);
2023 for (i = 0; i < n; i++)
2024 avc[i] = output_files[i].ctx;
2026 av_sdp_create(avc, n, sdp, sizeof(sdp));
2027 printf("SDP:\n%s\n", sdp);
2032 static int init_input_stream(int ist_index, OutputStream *output_streams, int nb_output_streams,
2033 char *error, int error_len)
2036 InputStream *ist = &input_streams[ist_index];
2037 if (ist->decoding_needed) {
2038 AVCodec *codec = ist->dec;
2040 snprintf(error, error_len, "Decoder (codec id %d) not found for input stream #%d:%d",
2041 ist->st->codec->codec_id, ist->file_index, ist->st->index);
2042 return AVERROR(EINVAL);
2045 if (avcodec_open2(ist->st->codec, codec, &ist->opts) < 0) {
2046 snprintf(error, error_len, "Error while opening decoder for input stream #%d:%d",
2047 ist->file_index, ist->st->index);
2048 return AVERROR(EINVAL);
2050 assert_codec_experimental(ist->st->codec, 0);
2051 assert_avoptions(ist->opts);
2054 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;
2055 ist->next_pts = AV_NOPTS_VALUE;
2061 static int transcode_init(OutputFile *output_files,
2062 int nb_output_files,
2063 InputFile *input_files,
2066 int ret = 0, i, j, k;
2067 AVFormatContext *oc;
2068 AVCodecContext *codec, *icodec;
2074 /* init framerate emulation */
2075 for (i = 0; i < nb_input_files; i++) {
2076 InputFile *ifile = &input_files[i];
2077 if (ifile->rate_emu)
2078 for (j = 0; j < ifile->nb_streams; j++)
2079 input_streams[j + ifile->ist_index].start = av_gettime();
2082 /* output stream init */
2083 for (i = 0; i < nb_output_files; i++) {
2084 oc = output_files[i].ctx;
2085 if (!oc->nb_streams && !(oc->oformat->flags & AVFMT_NOSTREAMS)) {
2086 av_dump_format(oc, i, oc->filename, 1);
2087 av_log(NULL, AV_LOG_ERROR, "Output file #%d does not contain any stream\n", i);
2088 return AVERROR(EINVAL);
2092 /* for each output stream, we compute the right encoding parameters */
2093 for (i = 0; i < nb_output_streams; i++) {
2094 ost = &output_streams[i];
2095 oc = output_files[ost->file_index].ctx;
2096 ist = &input_streams[ost->source_index];
2098 if (ost->attachment_filename)
2101 codec = ost->st->codec;
2102 icodec = ist->st->codec;
2104 ost->st->disposition = ist->st->disposition;
2105 codec->bits_per_raw_sample = icodec->bits_per_raw_sample;
2106 codec->chroma_sample_location = icodec->chroma_sample_location;
2108 if (ost->stream_copy) {
2109 uint64_t extra_size = (uint64_t)icodec->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE;
2111 if (extra_size > INT_MAX) {
2112 return AVERROR(EINVAL);
2115 /* if stream_copy is selected, no need to decode or encode */
2116 codec->codec_id = icodec->codec_id;
2117 codec->codec_type = icodec->codec_type;
2119 if (!codec->codec_tag) {
2120 if (!oc->oformat->codec_tag ||
2121 av_codec_get_id (oc->oformat->codec_tag, icodec->codec_tag) == codec->codec_id ||
2122 av_codec_get_tag(oc->oformat->codec_tag, icodec->codec_id) <= 0)
2123 codec->codec_tag = icodec->codec_tag;
2126 codec->bit_rate = icodec->bit_rate;
2127 codec->rc_max_rate = icodec->rc_max_rate;
2128 codec->rc_buffer_size = icodec->rc_buffer_size;
2129 codec->extradata = av_mallocz(extra_size);
2130 if (!codec->extradata) {
2131 return AVERROR(ENOMEM);
2133 memcpy(codec->extradata, icodec->extradata, icodec->extradata_size);
2134 codec->extradata_size= icodec->extradata_size;
2136 codec->time_base = ist->st->time_base;
2137 if(!strcmp(oc->oformat->name, "avi")) {
2139 av_q2d(icodec->time_base)*icodec->ticks_per_frame > 2*av_q2d(ist->st->time_base) &&
2140 av_q2d(ist->st->time_base) < 1.0/500){
2141 codec->time_base = icodec->time_base;
2142 codec->time_base.num *= icodec->ticks_per_frame;
2143 codec->time_base.den *= 2;
2145 } else if(!(oc->oformat->flags & AVFMT_VARIABLE_FPS)) {
2146 if(!copy_tb && av_q2d(icodec->time_base)*icodec->ticks_per_frame > av_q2d(ist->st->time_base) && av_q2d(ist->st->time_base) < 1.0/500){
2147 codec->time_base = icodec->time_base;
2148 codec->time_base.num *= icodec->ticks_per_frame;
2151 av_reduce(&codec->time_base.num, &codec->time_base.den,
2152 codec->time_base.num, codec->time_base.den, INT_MAX);
2154 switch(codec->codec_type) {
2155 case AVMEDIA_TYPE_AUDIO:
2156 if(audio_volume != 256) {
2157 av_log(NULL, AV_LOG_FATAL, "-acodec copy and -vol are incompatible (frames are not decoded)\n");
2160 codec->channel_layout = icodec->channel_layout;
2161 codec->sample_rate = icodec->sample_rate;
2162 codec->channels = icodec->channels;
2163 codec->frame_size = icodec->frame_size;
2164 codec->audio_service_type = icodec->audio_service_type;
2165 codec->block_align = icodec->block_align;
2167 case AVMEDIA_TYPE_VIDEO:
2168 codec->pix_fmt = icodec->pix_fmt;
2169 codec->width = icodec->width;
2170 codec->height = icodec->height;
2171 codec->has_b_frames = icodec->has_b_frames;
2172 if (!codec->sample_aspect_ratio.num) {
2173 codec->sample_aspect_ratio =
2174 ost->st->sample_aspect_ratio =
2175 ist->st->sample_aspect_ratio.num ? ist->st->sample_aspect_ratio :
2176 ist->st->codec->sample_aspect_ratio.num ?
2177 ist->st->codec->sample_aspect_ratio : (AVRational){0, 1};
2180 case AVMEDIA_TYPE_SUBTITLE:
2181 codec->width = icodec->width;
2182 codec->height = icodec->height;
2184 case AVMEDIA_TYPE_DATA:
2185 case AVMEDIA_TYPE_ATTACHMENT:
2192 ost->enc = avcodec_find_encoder(ost->st->codec->codec_id);
2194 ist->decoding_needed = 1;
2195 ost->encoding_needed = 1;
2197 switch(codec->codec_type) {
2198 case AVMEDIA_TYPE_AUDIO:
2199 ost->fifo = av_fifo_alloc(1024);
2201 return AVERROR(ENOMEM);
2203 ost->reformat_pair = MAKE_SFMT_PAIR(AV_SAMPLE_FMT_NONE,AV_SAMPLE_FMT_NONE);
2205 if (!codec->sample_rate)
2206 codec->sample_rate = icodec->sample_rate;
2207 choose_sample_rate(ost->st, ost->enc);
2208 codec->time_base = (AVRational){1, codec->sample_rate};
2210 if (codec->sample_fmt == AV_SAMPLE_FMT_NONE)
2211 codec->sample_fmt = icodec->sample_fmt;
2212 choose_sample_fmt(ost->st, ost->enc);
2214 if (!codec->channels) {
2215 codec->channels = icodec->channels;
2216 codec->channel_layout = icodec->channel_layout;
2218 if (av_get_channel_layout_nb_channels(codec->channel_layout) != codec->channels)
2219 codec->channel_layout = 0;
2221 ost->audio_resample = codec-> sample_rate != icodec->sample_rate || audio_sync_method > 1;
2222 icodec->request_channels = codec-> channels;
2223 ost->resample_sample_fmt = icodec->sample_fmt;
2224 ost->resample_sample_rate = icodec->sample_rate;
2225 ost->resample_channels = icodec->channels;
2227 case AVMEDIA_TYPE_VIDEO:
2228 if (codec->pix_fmt == PIX_FMT_NONE)
2229 codec->pix_fmt = icodec->pix_fmt;
2230 choose_pixel_fmt(ost->st, ost->enc);
2232 if (ost->st->codec->pix_fmt == PIX_FMT_NONE) {
2233 av_log(NULL, AV_LOG_FATAL, "Video pixel format is unknown, stream cannot be encoded\n");
2237 if (!codec->width || !codec->height) {
2238 codec->width = icodec->width;
2239 codec->height = icodec->height;
2242 ost->video_resample = codec->width != icodec->width ||
2243 codec->height != icodec->height ||
2244 codec->pix_fmt != icodec->pix_fmt;
2245 if (ost->video_resample) {
2246 codec->bits_per_raw_sample= frame_bits_per_raw_sample;
2249 ost->resample_height = icodec->height;
2250 ost->resample_width = icodec->width;
2251 ost->resample_pix_fmt = icodec->pix_fmt;
2253 if (!ost->frame_rate.num)
2254 ost->frame_rate = ist->st->r_frame_rate.num ? ist->st->r_frame_rate : (AVRational){25,1};
2255 if (ost->enc && ost->enc->supported_framerates && !ost->force_fps) {
2256 int idx = av_find_nearest_q_idx(ost->frame_rate, ost->enc->supported_framerates);
2257 ost->frame_rate = ost->enc->supported_framerates[idx];
2259 codec->time_base = (AVRational){ost->frame_rate.den, ost->frame_rate.num};
2260 if( av_q2d(codec->time_base) < 0.001 && video_sync_method
2261 && (video_sync_method==1 || (video_sync_method<0 && !(oc->oformat->flags & AVFMT_VARIABLE_FPS)))){
2262 av_log(oc, AV_LOG_WARNING, "Frame rate very high for a muxer not effciciently supporting it.\n"
2263 "Please consider specifiying a lower framerate, a different muxer or -vsync 2\n");
2267 if (configure_video_filters(ist, ost)) {
2268 av_log(NULL, AV_LOG_FATAL, "Error opening filters!\n");
2273 case AVMEDIA_TYPE_SUBTITLE:
2280 if (codec->codec_id != CODEC_ID_H264 &&
2281 (codec->flags & (CODEC_FLAG_PASS1 | CODEC_FLAG_PASS2))) {
2282 char logfilename[1024];
2285 snprintf(logfilename, sizeof(logfilename), "%s-%d.log",
2286 pass_logfilename_prefix ? pass_logfilename_prefix : DEFAULT_PASS_LOGFILENAME_PREFIX,
2288 if (codec->flags & CODEC_FLAG_PASS1) {
2289 f = fopen(logfilename, "wb");
2291 av_log(NULL, AV_LOG_FATAL, "Cannot write log file '%s' for pass-1 encoding: %s\n",
2292 logfilename, strerror(errno));
2298 size_t logbuffer_size;
2299 if (cmdutils_read_file(logfilename, &logbuffer, &logbuffer_size) < 0) {
2300 av_log(NULL, AV_LOG_FATAL, "Error reading log file '%s' for pass-2 encoding\n",
2304 codec->stats_in = logbuffer;
2308 if(codec->codec_type == AVMEDIA_TYPE_VIDEO){
2309 /* maximum video buffer size is 6-bytes per pixel, plus DPX header size */
2310 int size = codec->width * codec->height;
2311 bit_buffer_size = FFMAX(bit_buffer_size, 6*size + 1664);
2316 bit_buffer = av_malloc(bit_buffer_size);
2318 av_log(NULL, AV_LOG_ERROR, "Cannot allocate %d bytes output buffer\n",
2320 return AVERROR(ENOMEM);
2323 /* open each encoder */
2324 for (i = 0; i < nb_output_streams; i++) {
2325 ost = &output_streams[i];
2326 if (ost->encoding_needed) {
2327 AVCodec *codec = ost->enc;
2328 AVCodecContext *dec = input_streams[ost->source_index].st->codec;
2330 snprintf(error, sizeof(error), "Encoder (codec id %d) not found for output stream #%d:%d",
2331 ost->st->codec->codec_id, ost->file_index, ost->index);
2332 ret = AVERROR(EINVAL);
2335 if (dec->subtitle_header) {
2336 ost->st->codec->subtitle_header = av_malloc(dec->subtitle_header_size);
2337 if (!ost->st->codec->subtitle_header) {
2338 ret = AVERROR(ENOMEM);
2341 memcpy(ost->st->codec->subtitle_header, dec->subtitle_header, dec->subtitle_header_size);
2342 ost->st->codec->subtitle_header_size = dec->subtitle_header_size;
2344 if (avcodec_open2(ost->st->codec, codec, &ost->opts) < 0) {
2345 snprintf(error, sizeof(error), "Error while opening encoder for output stream #%d:%d - maybe incorrect parameters such as bit_rate, rate, width or height",
2346 ost->file_index, ost->index);
2347 ret = AVERROR(EINVAL);
2350 assert_codec_experimental(ost->st->codec, 1);
2351 assert_avoptions(ost->opts);
2352 if (ost->st->codec->bit_rate && ost->st->codec->bit_rate < 1000)
2353 av_log(NULL, AV_LOG_WARNING, "The bitrate parameter is set too low."
2354 "It takes bits/s as argument, not kbits/s\n");
2355 extra_size += ost->st->codec->extradata_size;
2357 if (ost->st->codec->me_threshold)
2358 input_streams[ost->source_index].st->codec->debug |= FF_DEBUG_MV;
2362 /* init input streams */
2363 for (i = 0; i < nb_input_streams; i++)
2364 if ((ret = init_input_stream(i, output_streams, nb_output_streams, error, sizeof(error))) < 0)
2367 /* discard unused programs */
2368 for (i = 0; i < nb_input_files; i++) {
2369 InputFile *ifile = &input_files[i];
2370 for (j = 0; j < ifile->ctx->nb_programs; j++) {
2371 AVProgram *p = ifile->ctx->programs[j];
2372 int discard = AVDISCARD_ALL;
2374 for (k = 0; k < p->nb_stream_indexes; k++)
2375 if (!input_streams[ifile->ist_index + p->stream_index[k]].discard) {
2376 discard = AVDISCARD_DEFAULT;
2379 p->discard = discard;
2383 /* open files and write file headers */
2384 for (i = 0; i < nb_output_files; i++) {
2385 oc = output_files[i].ctx;
2386 oc->interrupt_callback = int_cb;
2387 if (avformat_write_header(oc, &output_files[i].opts) < 0) {
2388 snprintf(error, sizeof(error), "Could not write header for output file #%d (incorrect codec parameters ?)", i);
2389 ret = AVERROR(EINVAL);
2392 // assert_avoptions(output_files[i].opts);
2393 if (strcmp(oc->oformat->name, "rtp")) {
2399 /* dump the file output parameters - cannot be done before in case
2401 for (i = 0; i < nb_output_files; i++) {
2402 av_dump_format(output_files[i].ctx, i, output_files[i].ctx->filename, 1);
2405 /* dump the stream mapping */
2406 av_log(NULL, AV_LOG_INFO, "Stream mapping:\n");
2407 for (i = 0; i < nb_output_streams; i++) {
2408 ost = &output_streams[i];
2410 if (ost->attachment_filename) {
2411 /* an attached file */
2412 av_log(NULL, AV_LOG_INFO, " File %s -> Stream #%d:%d\n",
2413 ost->attachment_filename, ost->file_index, ost->index);
2416 av_log(NULL, AV_LOG_INFO, " Stream #%d:%d -> #%d:%d",
2417 input_streams[ost->source_index].file_index,
2418 input_streams[ost->source_index].st->index,
2421 if (ost->sync_ist != &input_streams[ost->source_index])
2422 av_log(NULL, AV_LOG_INFO, " [sync #%d:%d]",
2423 ost->sync_ist->file_index,
2424 ost->sync_ist->st->index);
2425 if (ost->stream_copy)
2426 av_log(NULL, AV_LOG_INFO, " (copy)");
2428 av_log(NULL, AV_LOG_INFO, " (%s -> %s)", input_streams[ost->source_index].dec ?
2429 input_streams[ost->source_index].dec->name : "?",
2430 ost->enc ? ost->enc->name : "?");
2431 av_log(NULL, AV_LOG_INFO, "\n");
2435 av_log(NULL, AV_LOG_ERROR, "%s\n", error);
2440 print_sdp(output_files, nb_output_files);
2447 * The following code is the main loop of the file converter
2449 static int transcode(OutputFile *output_files,
2450 int nb_output_files,
2451 InputFile *input_files,
2455 AVFormatContext *is, *os;
2459 int no_packet_count=0;
2460 int64_t timer_start;
2463 if (!(no_packet = av_mallocz(nb_input_files)))
2466 ret = transcode_init(output_files, nb_output_files, input_files, nb_input_files);
2471 av_log(NULL, AV_LOG_INFO, "Press [q] to stop, [?] for help\n");
2472 avio_set_interrupt_cb(decode_interrupt_cb);
2476 timer_start = av_gettime();
2478 for(; received_sigterm == 0;) {
2479 int file_index, ist_index;
2484 ipts_min = INT64_MAX;
2486 /* if 'q' pressed, exits */
2490 /* read_key() returns 0 on EOF */
2494 if (key == '+') av_log_set_level(av_log_get_level()+10);
2495 if (key == '-') av_log_set_level(av_log_get_level()-10);
2496 if (key == 's') qp_hist ^= 1;
2499 do_hex_dump = do_pkt_dump = 0;
2500 } else if(do_pkt_dump){
2504 av_log_set_level(AV_LOG_DEBUG);
2506 if (key == 'd' || key == 'D'){
2509 debug = input_streams[0].st->codec->debug<<1;
2510 if(!debug) debug = 1;
2511 while(debug & (FF_DEBUG_DCT_COEFF|FF_DEBUG_VIS_QP|FF_DEBUG_VIS_MB_TYPE)) //unsupported, would just crash
2514 scanf("%d", &debug);
2515 for(i=0;i<nb_input_streams;i++) {
2516 input_streams[i].st->codec->debug = debug;
2518 for(i=0;i<nb_output_streams;i++) {
2519 ost = &output_streams[i];
2520 ost->st->codec->debug = debug;
2522 if(debug) av_log_set_level(AV_LOG_DEBUG);
2523 fprintf(stderr,"debug=%d\n", debug);
2526 fprintf(stderr, "key function\n"
2527 "? show this help\n"
2528 "+ increase verbosity\n"
2529 "- decrease verbosity\n"
2530 "D cycle through available debug modes\n"
2531 "h dump packets/hex press to cycle through the 3 states\n"
2533 "s Show QP histogram\n"
2538 /* select the stream that we must read now by looking at the
2539 smallest output pts */
2541 for (i = 0; i < nb_output_streams; i++) {
2545 ost = &output_streams[i];
2546 of = &output_files[ost->file_index];
2547 os = output_files[ost->file_index].ctx;
2548 ist = &input_streams[ost->source_index];
2549 if (ost->is_past_recording_time || no_packet[ist->file_index] ||
2550 (os->pb && avio_tell(os->pb) >= of->limit_filesize))
2552 opts = ost->st->pts.val * av_q2d(ost->st->time_base);
2554 if (!input_files[ist->file_index].eof_reached){
2555 if(ipts < ipts_min) {
2557 if(input_sync ) file_index = ist->file_index;
2559 if(opts < opts_min) {
2561 if(!input_sync) file_index = ist->file_index;
2564 if (ost->frame_number >= ost->max_frames) {
2566 for (j = 0; j < of->ctx->nb_streams; j++)
2567 output_streams[of->ost_index + j].is_past_recording_time = 1;
2571 /* if none, if is finished */
2572 if (file_index < 0) {
2573 if(no_packet_count){
2575 memset(no_packet, 0, nb_input_files);
2582 /* read a frame from it and output it in the fifo */
2583 is = input_files[file_index].ctx;
2584 ret= av_read_frame(is, &pkt);
2585 if(ret == AVERROR(EAGAIN)){
2586 no_packet[file_index]=1;
2591 input_files[file_index].eof_reached = 1;
2599 memset(no_packet, 0, nb_input_files);
2602 av_pkt_dump_log2(NULL, AV_LOG_DEBUG, &pkt, do_hex_dump,
2603 is->streams[pkt.stream_index]);
2605 /* the following test is needed in case new streams appear
2606 dynamically in stream : we ignore them */
2607 if (pkt.stream_index >= input_files[file_index].nb_streams)
2608 goto discard_packet;
2609 ist_index = input_files[file_index].ist_index + pkt.stream_index;
2610 ist = &input_streams[ist_index];
2612 goto discard_packet;
2614 if (pkt.dts != AV_NOPTS_VALUE)
2615 pkt.dts += av_rescale_q(input_files[ist->file_index].ts_offset, AV_TIME_BASE_Q, ist->st->time_base);
2616 if (pkt.pts != AV_NOPTS_VALUE)
2617 pkt.pts += av_rescale_q(input_files[ist->file_index].ts_offset, AV_TIME_BASE_Q, ist->st->time_base);
2619 if(pkt.pts != AV_NOPTS_VALUE)
2620 pkt.pts *= ist->ts_scale;
2621 if(pkt.dts != AV_NOPTS_VALUE)
2622 pkt.dts *= ist->ts_scale;
2624 // 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);
2625 if (pkt.dts != AV_NOPTS_VALUE && ist->next_pts != AV_NOPTS_VALUE
2626 && (is->iformat->flags & AVFMT_TS_DISCONT)) {
2627 int64_t pkt_dts= av_rescale_q(pkt.dts, ist->st->time_base, AV_TIME_BASE_Q);
2628 int64_t delta= pkt_dts - ist->next_pts;
2629 if((FFABS(delta) > 1LL*dts_delta_threshold*AV_TIME_BASE || pkt_dts+1<ist->pts)&& !copy_ts){
2630 input_files[ist->file_index].ts_offset -= delta;
2631 av_log(NULL, AV_LOG_DEBUG, "timestamp discontinuity %"PRId64", new offset= %"PRId64"\n",
2632 delta, input_files[ist->file_index].ts_offset);
2633 pkt.dts-= av_rescale_q(delta, AV_TIME_BASE_Q, ist->st->time_base);
2634 if(pkt.pts != AV_NOPTS_VALUE)
2635 pkt.pts-= av_rescale_q(delta, AV_TIME_BASE_Q, ist->st->time_base);
2639 //fprintf(stderr,"read #%d.%d size=%d\n", ist->file_index, ist->st->index, pkt.size);
2640 if (output_packet(ist, output_streams, nb_output_streams, &pkt) < 0) {
2642 av_log(NULL, AV_LOG_ERROR, "Error while decoding stream #%d:%d\n",
2643 ist->file_index, ist->st->index);
2646 av_free_packet(&pkt);
2651 av_free_packet(&pkt);
2653 /* dump report by using the output first video and audio streams */
2654 print_report(output_files, output_streams, nb_output_streams, 0, timer_start);
2657 /* at the end of stream, we must flush the decoder buffers */
2658 for (i = 0; i < nb_input_streams; i++) {
2659 ist = &input_streams[i];
2660 if (ist->decoding_needed) {
2661 output_packet(ist, output_streams, nb_output_streams, NULL);
2664 flush_encoders(output_streams, nb_output_streams);
2668 /* write the trailer if needed and close file */
2669 for(i=0;i<nb_output_files;i++) {
2670 os = output_files[i].ctx;
2671 av_write_trailer(os);
2674 /* dump report by using the first video and audio streams */
2675 print_report(output_files, output_streams, nb_output_streams, 1, timer_start);
2677 /* close each encoder */
2678 for (i = 0; i < nb_output_streams; i++) {
2679 ost = &output_streams[i];
2680 if (ost->encoding_needed) {
2681 av_freep(&ost->st->codec->stats_in);
2682 avcodec_close(ost->st->codec);
2685 avfilter_graph_free(&ost->graph);
2689 /* close each decoder */
2690 for (i = 0; i < nb_input_streams; i++) {
2691 ist = &input_streams[i];
2692 if (ist->decoding_needed) {
2693 avcodec_close(ist->st->codec);
2701 av_freep(&bit_buffer);
2702 av_freep(&no_packet);
2704 if (output_streams) {
2705 for (i = 0; i < nb_output_streams; i++) {
2706 ost = &output_streams[i];
2708 if (ost->stream_copy)
2709 av_freep(&ost->st->codec->extradata);
2711 fclose(ost->logfile);
2712 ost->logfile = NULL;
2714 av_fifo_free(ost->fifo); /* works even if fifo is not
2715 initialized but set to zero */
2716 av_freep(&ost->st->codec->subtitle_header);
2717 av_free(ost->resample_frame.data[0]);
2718 av_free(ost->forced_kf_pts);
2719 if (ost->video_resample)
2720 sws_freeContext(ost->img_resample_ctx);
2722 audio_resample_close(ost->resample);
2723 if (ost->reformat_ctx)
2724 av_audio_convert_free(ost->reformat_ctx);
2725 av_dict_free(&ost->opts);
2732 static double parse_frame_aspect_ratio(const char *arg)
2739 p = strchr(arg, ':');
2741 x = strtol(arg, &end, 10);
2743 y = strtol(end+1, &end, 10);
2745 ar = (double)x / (double)y;
2747 ar = strtod(arg, NULL);
2750 av_log(NULL, AV_LOG_FATAL, "Incorrect aspect ratio specification.\n");
2756 static int opt_audio_codec(OptionsContext *o, const char *opt, const char *arg)
2758 return parse_option(o, "codec:a", arg, options);
2761 static int opt_video_codec(OptionsContext *o, const char *opt, const char *arg)
2763 return parse_option(o, "codec:v", arg, options);
2766 static int opt_subtitle_codec(OptionsContext *o, const char *opt, const char *arg)
2768 return parse_option(o, "codec:s", arg, options);
2771 static int opt_data_codec(OptionsContext *o, const char *opt, const char *arg)
2773 return parse_option(o, "codec:d", arg, options);
2776 static int opt_map(OptionsContext *o, const char *opt, const char *arg)
2778 StreamMap *m = NULL;
2779 int i, negative = 0, file_idx;
2780 int sync_file_idx = -1, sync_stream_idx;
2788 map = av_strdup(arg);
2790 /* parse sync stream first, just pick first matching stream */
2791 if (sync = strchr(map, ',')) {
2793 sync_file_idx = strtol(sync + 1, &sync, 0);
2794 if (sync_file_idx >= nb_input_files || sync_file_idx < 0) {
2795 av_log(NULL, AV_LOG_FATAL, "Invalid sync file index: %d.\n", sync_file_idx);
2800 for (i = 0; i < input_files[sync_file_idx].nb_streams; i++)
2801 if (check_stream_specifier(input_files[sync_file_idx].ctx,
2802 input_files[sync_file_idx].ctx->streams[i], sync) == 1) {
2803 sync_stream_idx = i;
2806 if (i == input_files[sync_file_idx].nb_streams) {
2807 av_log(NULL, AV_LOG_FATAL, "Sync stream specification in map %s does not "
2808 "match any streams.\n", arg);
2814 file_idx = strtol(map, &p, 0);
2815 if (file_idx >= nb_input_files || file_idx < 0) {
2816 av_log(NULL, AV_LOG_FATAL, "Invalid input file index: %d.\n", file_idx);
2820 /* disable some already defined maps */
2821 for (i = 0; i < o->nb_stream_maps; i++) {
2822 m = &o->stream_maps[i];
2823 if (file_idx == m->file_index &&
2824 check_stream_specifier(input_files[m->file_index].ctx,
2825 input_files[m->file_index].ctx->streams[m->stream_index],
2826 *p == ':' ? p + 1 : p) > 0)
2830 for (i = 0; i < input_files[file_idx].nb_streams; i++) {
2831 if (check_stream_specifier(input_files[file_idx].ctx, input_files[file_idx].ctx->streams[i],
2832 *p == ':' ? p + 1 : p) <= 0)
2834 o->stream_maps = grow_array(o->stream_maps, sizeof(*o->stream_maps),
2835 &o->nb_stream_maps, o->nb_stream_maps + 1);
2836 m = &o->stream_maps[o->nb_stream_maps - 1];
2838 m->file_index = file_idx;
2839 m->stream_index = i;
2841 if (sync_file_idx >= 0) {
2842 m->sync_file_index = sync_file_idx;
2843 m->sync_stream_index = sync_stream_idx;
2845 m->sync_file_index = file_idx;
2846 m->sync_stream_index = i;
2851 av_log(NULL, AV_LOG_FATAL, "Stream map '%s' matches no streams.\n", arg);
2859 static int opt_attach(OptionsContext *o, const char *opt, const char *arg)
2861 o->attachments = grow_array(o->attachments, sizeof(*o->attachments),
2862 &o->nb_attachments, o->nb_attachments + 1);
2863 o->attachments[o->nb_attachments - 1] = arg;
2867 static void parse_meta_type(char *arg, char *type, int *index)
2877 if (*(++arg) == ':')
2878 *index = strtol(++arg, NULL, 0);
2881 av_log(NULL, AV_LOG_FATAL, "Invalid metadata type %c.\n", *arg);
2888 static int opt_map_metadata(OptionsContext *o, const char *opt, const char *arg)
2890 MetadataMap *m, *m1;
2893 o->meta_data_maps = grow_array(o->meta_data_maps, sizeof(*o->meta_data_maps),
2894 &o->nb_meta_data_maps, o->nb_meta_data_maps + 1);
2896 m = &o->meta_data_maps[o->nb_meta_data_maps - 1][1];
2897 m->file = strtol(arg, &p, 0);
2898 parse_meta_type(*p ? p + 1 : p, &m->type, &m->index);
2900 m1 = &o->meta_data_maps[o->nb_meta_data_maps - 1][0];
2901 if (p = strchr(opt, ':'))
2902 parse_meta_type(p + 1, &m1->type, &m1->index);
2906 if (m->type == 'g' || m1->type == 'g')
2907 o->metadata_global_manual = 1;
2908 if (m->type == 's' || m1->type == 's')
2909 o->metadata_streams_manual = 1;
2910 if (m->type == 'c' || m1->type == 'c')
2911 o->metadata_chapters_manual = 1;
2916 static AVCodec *find_codec_or_die(const char *name, enum AVMediaType type, int encoder)
2918 const char *codec_string = encoder ? "encoder" : "decoder";
2922 avcodec_find_encoder_by_name(name) :
2923 avcodec_find_decoder_by_name(name);
2925 av_log(NULL, AV_LOG_FATAL, "Unknown %s '%s'\n", codec_string, name);
2928 if(codec->type != type) {
2929 av_log(NULL, AV_LOG_FATAL, "Invalid %s type '%s'\n", codec_string, name);
2935 static AVCodec *choose_decoder(OptionsContext *o, AVFormatContext *s, AVStream *st)
2937 char *codec_name = NULL;
2939 MATCH_PER_STREAM_OPT(codec_names, str, codec_name, s, st);
2941 AVCodec *codec = find_codec_or_die(codec_name, st->codec->codec_type, 0);
2942 st->codec->codec_id = codec->id;
2945 return avcodec_find_decoder(st->codec->codec_id);
2949 * Add all the streams from the given input file to the global
2950 * list of input streams.
2952 static void add_input_streams(OptionsContext *o, AVFormatContext *ic)
2954 int i, rfps, rfps_base;
2956 for (i = 0; i < ic->nb_streams; i++) {
2957 AVStream *st = ic->streams[i];
2958 AVCodecContext *dec = st->codec;
2961 input_streams = grow_array(input_streams, sizeof(*input_streams), &nb_input_streams, nb_input_streams + 1);
2962 ist = &input_streams[nb_input_streams - 1];
2964 ist->file_index = nb_input_files;
2966 ist->opts = filter_codec_opts(codec_opts, ist->st->codec->codec_id, ic, st);
2968 ist->ts_scale = 1.0;
2969 MATCH_PER_STREAM_OPT(ts_scale, dbl, ist->ts_scale, ic, st);
2971 ist->dec = choose_decoder(o, ic, st);
2973 switch (dec->codec_type) {
2974 case AVMEDIA_TYPE_AUDIO:
2976 ist->dec = avcodec_find_decoder(dec->codec_id);
2977 if(o->audio_disable)
2978 st->discard= AVDISCARD_ALL;
2980 case AVMEDIA_TYPE_VIDEO:
2982 ist->dec = avcodec_find_decoder(dec->codec_id);
2983 rfps = ic->streams[i]->r_frame_rate.num;
2984 rfps_base = ic->streams[i]->r_frame_rate.den;
2986 dec->flags |= CODEC_FLAG_EMU_EDGE;
2989 if (dec->time_base.den != rfps*dec->ticks_per_frame || dec->time_base.num != rfps_base) {
2991 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",
2992 i, (float)dec->time_base.den / dec->time_base.num, dec->time_base.den, dec->time_base.num,
2993 (float)rfps / rfps_base, rfps, rfps_base);
2996 if (o->video_disable)
2997 st->discard= AVDISCARD_ALL;
2998 else if(video_discard)
2999 st->discard= video_discard;
3001 case AVMEDIA_TYPE_DATA:
3003 case AVMEDIA_TYPE_SUBTITLE:
3005 ist->dec = avcodec_find_decoder(dec->codec_id);
3006 if(o->subtitle_disable)
3007 st->discard = AVDISCARD_ALL;
3009 case AVMEDIA_TYPE_ATTACHMENT:
3010 case AVMEDIA_TYPE_UNKNOWN:
3018 static void assert_file_overwrite(const char *filename)
3020 if ((!file_overwrite || no_file_overwrite) &&
3021 (strchr(filename, ':') == NULL || filename[1] == ':' ||
3022 av_strstart(filename, "file:", NULL))) {
3023 if (avio_check(filename, 0) == 0) {
3024 if (!using_stdin && (!no_file_overwrite || file_overwrite)) {
3025 fprintf(stderr,"File '%s' already exists. Overwrite ? [y/N] ", filename);
3027 if (!read_yesno()) {
3028 fprintf(stderr, "Not overwriting - exiting\n");
3033 fprintf(stderr,"File '%s' already exists. Exiting.\n", filename);
3040 static void dump_attachment(AVStream *st, const char *filename)
3043 AVIOContext *out = NULL;
3044 AVDictionaryEntry *e;
3046 if (!st->codec->extradata_size) {
3047 av_log(NULL, AV_LOG_WARNING, "No extradata to dump in stream #%d:%d.\n",
3048 nb_input_files - 1, st->index);
3051 if (!*filename && (e = av_dict_get(st->metadata, "filename", NULL, 0)))
3052 filename = e->value;
3054 av_log(NULL, AV_LOG_FATAL, "No filename specified and no 'filename' tag"
3055 "in stream #%d:%d.\n", nb_input_files - 1, st->index);
3059 assert_file_overwrite(filename);
3061 if ((ret = avio_open2(&out, filename, AVIO_FLAG_WRITE, &int_cb, NULL)) < 0) {
3062 av_log(NULL, AV_LOG_FATAL, "Could not open file %s for writing.\n",
3067 avio_write(out, st->codec->extradata, st->codec->extradata_size);
3072 static int opt_input_file(OptionsContext *o, const char *opt, const char *filename)
3074 AVFormatContext *ic;
3075 AVInputFormat *file_iformat = NULL;
3079 AVDictionary **opts;
3080 int orig_nb_streams; // number of streams before avformat_find_stream_info
3083 if (!(file_iformat = av_find_input_format(o->format))) {
3084 av_log(NULL, AV_LOG_FATAL, "Unknown input format: '%s'\n", o->format);
3089 if (!strcmp(filename, "-"))
3092 using_stdin |= !strncmp(filename, "pipe:", 5) ||
3093 !strcmp(filename, "/dev/stdin");
3095 /* get default parameters from command line */
3096 ic = avformat_alloc_context();
3098 print_error(filename, AVERROR(ENOMEM));
3101 if (o->nb_audio_sample_rate) {
3102 snprintf(buf, sizeof(buf), "%d", o->audio_sample_rate[o->nb_audio_sample_rate - 1].u.i);
3103 av_dict_set(&format_opts, "sample_rate", buf, 0);
3105 if (o->nb_audio_channels) {
3106 snprintf(buf, sizeof(buf), "%d", o->audio_channels[o->nb_audio_channels - 1].u.i);
3107 av_dict_set(&format_opts, "channels", buf, 0);
3109 if (o->nb_frame_rates) {
3110 av_dict_set(&format_opts, "framerate", o->frame_rates[o->nb_frame_rates - 1].u.str, 0);
3112 if (o->nb_frame_sizes) {
3113 av_dict_set(&format_opts, "video_size", o->frame_sizes[o->nb_frame_sizes - 1].u.str, 0);
3115 if (o->nb_frame_pix_fmts)
3116 av_dict_set(&format_opts, "pixel_format", o->frame_pix_fmts[o->nb_frame_pix_fmts - 1].u.str, 0);
3118 ic->flags |= AVFMT_FLAG_NONBLOCK;
3119 ic->interrupt_callback = int_cb;
3121 /* open the input file with generic libav function */
3122 err = avformat_open_input(&ic, filename, file_iformat, &format_opts);
3124 print_error(filename, err);
3127 assert_avoptions(format_opts);
3129 /* apply forced codec ids */
3130 for (i = 0; i < ic->nb_streams; i++)
3131 choose_decoder(o, ic, ic->streams[i]);
3133 /* Set AVCodecContext options for avformat_find_stream_info */
3134 opts = setup_find_stream_info_opts(ic, codec_opts);
3135 orig_nb_streams = ic->nb_streams;
3137 /* If not enough info to get the stream parameters, we decode the
3138 first frames to get it. (used in mpeg case for example) */
3139 ret = avformat_find_stream_info(ic, opts);
3141 av_log(NULL, AV_LOG_FATAL, "%s: could not find codec parameters\n", filename);
3142 av_close_input_file(ic);
3146 timestamp = o->start_time;
3147 /* add the stream start time */
3148 if (ic->start_time != AV_NOPTS_VALUE)
3149 timestamp += ic->start_time;
3151 /* if seeking requested, we execute it */
3152 if (o->start_time != 0) {
3153 ret = av_seek_frame(ic, -1, timestamp, AVSEEK_FLAG_BACKWARD);
3155 av_log(NULL, AV_LOG_WARNING, "%s: could not seek to position %0.3f\n",
3156 filename, (double)timestamp / AV_TIME_BASE);
3160 /* update the current parameters so that they match the one of the input stream */
3161 add_input_streams(o, ic);
3163 /* dump the file content */
3164 av_dump_format(ic, nb_input_files, filename, 0);
3166 input_files = grow_array(input_files, sizeof(*input_files), &nb_input_files, nb_input_files + 1);
3167 input_files[nb_input_files - 1].ctx = ic;
3168 input_files[nb_input_files - 1].ist_index = nb_input_streams - ic->nb_streams;
3169 input_files[nb_input_files - 1].ts_offset = o->input_ts_offset - (copy_ts ? 0 : timestamp);
3170 input_files[nb_input_files - 1].nb_streams = ic->nb_streams;
3171 input_files[nb_input_files - 1].rate_emu = o->rate_emu;
3173 for (i = 0; i < o->nb_dump_attachment; i++) {
3176 for (j = 0; j < ic->nb_streams; j++) {
3177 AVStream *st = ic->streams[j];
3179 if (check_stream_specifier(ic, st, o->dump_attachment[i].specifier) == 1)
3180 dump_attachment(st, o->dump_attachment[i].u.str);
3184 for (i = 0; i < orig_nb_streams; i++)
3185 av_dict_free(&opts[i]);
3192 static void parse_forced_key_frames(char *kf, OutputStream *ost,
3193 AVCodecContext *avctx)
3199 for (p = kf; *p; p++)
3202 ost->forced_kf_count = n;
3203 ost->forced_kf_pts = av_malloc(sizeof(*ost->forced_kf_pts) * n);
3204 if (!ost->forced_kf_pts) {
3205 av_log(NULL, AV_LOG_FATAL, "Could not allocate forced key frames array.\n");
3208 for (i = 0; i < n; i++) {
3209 p = i ? strchr(p, ',') + 1 : kf;
3210 t = parse_time_or_die("force_key_frames", p, 1);
3211 ost->forced_kf_pts[i] = av_rescale_q(t, AV_TIME_BASE_Q, avctx->time_base);
3215 static uint8_t *get_line(AVIOContext *s)
3221 if (avio_open_dyn_buf(&line) < 0) {
3222 av_log(NULL, AV_LOG_FATAL, "Could not alloc buffer for reading preset.\n");
3226 while ((c = avio_r8(s)) && c != '\n')
3229 avio_close_dyn_buf(line, &buf);
3234 static int get_preset_file_2(const char *preset_name, const char *codec_name, AVIOContext **s)
3237 char filename[1000];
3238 const char *base[3] = { getenv("AVCONV_DATADIR"),
3243 for (i = 0; i < FF_ARRAY_ELEMS(base) && ret; i++) {
3247 snprintf(filename, sizeof(filename), "%s%s/%s-%s.avpreset", base[i],
3248 i != 1 ? "" : "/.avconv", codec_name, preset_name);
3249 ret = avio_open2(s, filename, AVIO_FLAG_READ, &int_cb, NULL);
3252 snprintf(filename, sizeof(filename), "%s%s/%s.avpreset", base[i],
3253 i != 1 ? "" : "/.avconv", preset_name);
3254 ret = avio_open2(s, filename, AVIO_FLAG_READ, &int_cb, NULL);
3260 static void choose_encoder(OptionsContext *o, AVFormatContext *s, OutputStream *ost)
3262 char *codec_name = NULL;
3264 MATCH_PER_STREAM_OPT(codec_names, str, codec_name, s, ost->st);
3266 ost->st->codec->codec_id = av_guess_codec(s->oformat, NULL, s->filename,
3267 NULL, ost->st->codec->codec_type);
3268 ost->enc = avcodec_find_encoder(ost->st->codec->codec_id);
3269 } else if (!strcmp(codec_name, "copy"))
3270 ost->stream_copy = 1;
3272 ost->enc = find_codec_or_die(codec_name, ost->st->codec->codec_type, 1);
3273 ost->st->codec->codec_id = ost->enc->id;
3277 static OutputStream *new_output_stream(OptionsContext *o, AVFormatContext *oc, enum AVMediaType type)
3280 AVStream *st = avformat_new_stream(oc, NULL);
3281 int idx = oc->nb_streams - 1, ret = 0;
3282 char *bsf = NULL, *next, *codec_tag = NULL;
3283 AVBitStreamFilterContext *bsfc, *bsfc_prev = NULL;
3285 char *buf = NULL, *arg = NULL, *preset = NULL;
3286 AVIOContext *s = NULL;
3289 av_log(NULL, AV_LOG_FATAL, "Could not alloc stream.\n");
3293 if (oc->nb_streams - 1 < o->nb_streamid_map)
3294 st->id = o->streamid_map[oc->nb_streams - 1];
3296 output_streams = grow_array(output_streams, sizeof(*output_streams), &nb_output_streams,
3297 nb_output_streams + 1);
3298 ost = &output_streams[nb_output_streams - 1];
3299 ost->file_index = nb_output_files;
3302 st->codec->codec_type = type;
3303 choose_encoder(o, oc, ost);
3305 ost->opts = filter_codec_opts(codec_opts, ost->enc->id, oc, st);
3308 avcodec_get_context_defaults3(st->codec, ost->enc);
3309 st->codec->codec_type = type; // XXX hack, avcodec_get_context_defaults2() sets type to unknown for stream copy
3311 MATCH_PER_STREAM_OPT(presets, str, preset, oc, st);
3312 if (preset && (!(ret = get_preset_file_2(preset, ost->enc->name, &s)))) {
3315 if (!buf[0] || buf[0] == '#') {
3319 if (!(arg = strchr(buf, '='))) {
3320 av_log(NULL, AV_LOG_FATAL, "Invalid line found in the preset file.\n");
3324 av_dict_set(&ost->opts, buf, arg, AV_DICT_DONT_OVERWRITE);
3326 } while (!s->eof_reached);
3330 av_log(NULL, AV_LOG_FATAL,
3331 "Preset %s specified for stream %d:%d, but could not be opened.\n",
3332 preset, ost->file_index, ost->index);
3336 ost->max_frames = INT64_MAX;
3337 MATCH_PER_STREAM_OPT(max_frames, i64, ost->max_frames, oc, st);
3339 MATCH_PER_STREAM_OPT(bitstream_filters, str, bsf, oc, st);
3341 if (next = strchr(bsf, ','))
3343 if (!(bsfc = av_bitstream_filter_init(bsf))) {
3344 av_log(NULL, AV_LOG_FATAL, "Unknown bitstream filter %s\n", bsf);
3348 bsfc_prev->next = bsfc;
3350 ost->bitstream_filters = bsfc;
3356 MATCH_PER_STREAM_OPT(codec_tags, str, codec_tag, oc, st);
3358 uint32_t tag = strtol(codec_tag, &next, 0);
3360 tag = AV_RL32(codec_tag);
3361 st->codec->codec_tag = tag;
3364 MATCH_PER_STREAM_OPT(qscale, dbl, qscale, oc, st);
3365 if (qscale >= 0 || same_quant) {
3366 st->codec->flags |= CODEC_FLAG_QSCALE;
3367 st->codec->global_quality = FF_QP2LAMBDA * qscale;
3370 if (oc->oformat->flags & AVFMT_GLOBALHEADER)
3371 st->codec->flags |= CODEC_FLAG_GLOBAL_HEADER;
3373 av_opt_get_int(sws_opts, "sws_flags", 0, &ost->sws_flags);
3377 static void parse_matrix_coeffs(uint16_t *dest, const char *str)
3380 const char *p = str;
3387 av_log(NULL, AV_LOG_FATAL, "Syntax error in matrix \"%s\" at coeff %d\n", str, i);
3394 static OutputStream *new_video_stream(OptionsContext *o, AVFormatContext *oc)
3398 AVCodecContext *video_enc;
3400 ost = new_output_stream(o, oc, AVMEDIA_TYPE_VIDEO);
3402 video_enc = st->codec;
3404 if (!ost->stream_copy) {
3405 const char *p = NULL;
3406 char *forced_key_frames = NULL, *frame_rate = NULL, *frame_size = NULL;
3407 char *frame_aspect_ratio = NULL, *frame_pix_fmt = NULL;
3408 char *intra_matrix = NULL, *inter_matrix = NULL, *filters = NULL;
3411 MATCH_PER_STREAM_OPT(frame_rates, str, frame_rate, oc, st);
3412 if (frame_rate && av_parse_video_rate(&ost->frame_rate, frame_rate) < 0) {
3413 av_log(NULL, AV_LOG_FATAL, "Invalid framerate value: %s\n", frame_rate);
3417 MATCH_PER_STREAM_OPT(frame_sizes, str, frame_size, oc, st);
3418 if (frame_size && av_parse_video_size(&video_enc->width, &video_enc->height, frame_size) < 0) {
3419 av_log(NULL, AV_LOG_FATAL, "Invalid frame size: %s.\n", frame_size);
3423 MATCH_PER_STREAM_OPT(frame_aspect_ratios, str, frame_aspect_ratio, oc, st);
3424 if (frame_aspect_ratio)
3425 ost->frame_aspect_ratio = parse_frame_aspect_ratio(frame_aspect_ratio);
3427 MATCH_PER_STREAM_OPT(frame_pix_fmts, str, frame_pix_fmt, oc, st);
3428 if (frame_pix_fmt && (video_enc->pix_fmt = av_get_pix_fmt(frame_pix_fmt)) == PIX_FMT_NONE) {
3429 av_log(NULL, AV_LOG_FATAL, "Unknown pixel format requested: %s.\n", frame_pix_fmt);
3432 st->sample_aspect_ratio = video_enc->sample_aspect_ratio;
3434 MATCH_PER_STREAM_OPT(intra_matrices, str, intra_matrix, oc, st);
3436 if (!(video_enc->intra_matrix = av_mallocz(sizeof(*video_enc->intra_matrix) * 64))) {
3437 av_log(NULL, AV_LOG_FATAL, "Could not allocate memory for intra matrix.\n");
3440 parse_matrix_coeffs(video_enc->intra_matrix, intra_matrix);
3442 MATCH_PER_STREAM_OPT(inter_matrices, str, inter_matrix, oc, st);
3444 if (!(video_enc->inter_matrix = av_mallocz(sizeof(*video_enc->inter_matrix) * 64))) {
3445 av_log(NULL, AV_LOG_FATAL, "Could not allocate memory for inter matrix.\n");
3448 parse_matrix_coeffs(video_enc->inter_matrix, inter_matrix);
3451 MATCH_PER_STREAM_OPT(rc_overrides, str, p, oc, st);
3454 int e=sscanf(p, "%d,%d,%d", &start, &end, &q);
3456 av_log(NULL, AV_LOG_FATAL, "error parsing rc_override\n");
3459 video_enc->rc_override=
3460 av_realloc(video_enc->rc_override,
3461 sizeof(RcOverride)*(i+1));
3462 video_enc->rc_override[i].start_frame= start;
3463 video_enc->rc_override[i].end_frame = end;
3465 video_enc->rc_override[i].qscale= q;
3466 video_enc->rc_override[i].quality_factor= 1.0;
3469 video_enc->rc_override[i].qscale= 0;
3470 video_enc->rc_override[i].quality_factor= -q/100.0;
3475 video_enc->rc_override_count=i;
3476 if (!video_enc->rc_initial_buffer_occupancy)
3477 video_enc->rc_initial_buffer_occupancy = video_enc->rc_buffer_size*3/4;
3478 video_enc->intra_dc_precision= intra_dc_precision - 8;
3483 video_enc->flags |= CODEC_FLAG_PASS1;
3485 video_enc->flags |= CODEC_FLAG_PASS2;
3489 MATCH_PER_STREAM_OPT(forced_key_frames, str, forced_key_frames, oc, st);
3490 if (forced_key_frames)
3491 parse_forced_key_frames(forced_key_frames, ost, video_enc);
3493 MATCH_PER_STREAM_OPT(force_fps, i, ost->force_fps, oc, st);
3495 ost->top_field_first = -1;
3496 MATCH_PER_STREAM_OPT(top_field_first, i, ost->top_field_first, oc, st);
3498 MATCH_PER_STREAM_OPT(copy_initial_nonkeyframes, i, ost->copy_initial_nonkeyframes, oc ,st);
3501 MATCH_PER_STREAM_OPT(filters, str, filters, oc, st);
3503 ost->avfilter = av_strdup(filters);
3510 static OutputStream *new_audio_stream(OptionsContext *o, AVFormatContext *oc)
3514 AVCodecContext *audio_enc;
3516 ost = new_output_stream(o, oc, AVMEDIA_TYPE_AUDIO);
3519 audio_enc = st->codec;
3520 audio_enc->codec_type = AVMEDIA_TYPE_AUDIO;
3522 if (!ost->stream_copy) {
3523 char *sample_fmt = NULL;
3525 MATCH_PER_STREAM_OPT(audio_channels, i, audio_enc->channels, oc, st);
3527 MATCH_PER_STREAM_OPT(sample_fmts, str, sample_fmt, oc, st);
3529 (audio_enc->sample_fmt = av_get_sample_fmt(sample_fmt)) == AV_SAMPLE_FMT_NONE) {
3530 av_log(NULL, AV_LOG_FATAL, "Invalid sample format '%s'\n", sample_fmt);
3534 MATCH_PER_STREAM_OPT(audio_sample_rate, i, audio_enc->sample_rate, oc, st);
3540 static OutputStream *new_data_stream(OptionsContext *o, AVFormatContext *oc)
3544 ost = new_output_stream(o, oc, AVMEDIA_TYPE_DATA);
3545 if (!ost->stream_copy) {
3546 av_log(NULL, AV_LOG_FATAL, "Data stream encoding not supported yet (only streamcopy)\n");
3553 static OutputStream *new_attachment_stream(OptionsContext *o, AVFormatContext *oc)
3555 OutputStream *ost = new_output_stream(o, oc, AVMEDIA_TYPE_ATTACHMENT);
3556 ost->stream_copy = 1;
3560 static OutputStream *new_subtitle_stream(OptionsContext *o, AVFormatContext *oc)
3564 AVCodecContext *subtitle_enc;
3566 ost = new_output_stream(o, oc, AVMEDIA_TYPE_SUBTITLE);
3568 subtitle_enc = st->codec;
3570 subtitle_enc->codec_type = AVMEDIA_TYPE_SUBTITLE;
3575 /* arg format is "output-stream-index:streamid-value". */
3576 static int opt_streamid(OptionsContext *o, const char *opt, const char *arg)
3582 av_strlcpy(idx_str, arg, sizeof(idx_str));
3583 p = strchr(idx_str, ':');
3585 av_log(NULL, AV_LOG_FATAL,
3586 "Invalid value '%s' for option '%s', required syntax is 'index:value'\n",
3591 idx = parse_number_or_die(opt, idx_str, OPT_INT, 0, MAX_STREAMS-1);
3592 o->streamid_map = grow_array(o->streamid_map, sizeof(*o->streamid_map), &o->nb_streamid_map, idx+1);
3593 o->streamid_map[idx] = parse_number_or_die(opt, p, OPT_INT, 0, INT_MAX);
3597 static int copy_chapters(InputFile *ifile, OutputFile *ofile, int copy_metadata)
3599 AVFormatContext *is = ifile->ctx;
3600 AVFormatContext *os = ofile->ctx;
3603 for (i = 0; i < is->nb_chapters; i++) {
3604 AVChapter *in_ch = is->chapters[i], *out_ch;
3605 int64_t ts_off = av_rescale_q(ofile->start_time - ifile->ts_offset,
3606 AV_TIME_BASE_Q, in_ch->time_base);
3607 int64_t rt = (ofile->recording_time == INT64_MAX) ? INT64_MAX :
3608 av_rescale_q(ofile->recording_time, AV_TIME_BASE_Q, in_ch->time_base);
3611 if (in_ch->end < ts_off)
3613 if (rt != INT64_MAX && in_ch->start > rt + ts_off)
3616 out_ch = av_mallocz(sizeof(AVChapter));
3618 return AVERROR(ENOMEM);
3620 out_ch->id = in_ch->id;
3621 out_ch->time_base = in_ch->time_base;
3622 out_ch->start = FFMAX(0, in_ch->start - ts_off);
3623 out_ch->end = FFMIN(rt, in_ch->end - ts_off);
3626 av_dict_copy(&out_ch->metadata, in_ch->metadata, 0);
3629 os->chapters = av_realloc(os->chapters, sizeof(AVChapter)*os->nb_chapters);
3631 return AVERROR(ENOMEM);
3632 os->chapters[os->nb_chapters - 1] = out_ch;
3637 static int read_ffserver_streams(OptionsContext *o, AVFormatContext *s, const char *filename)
3640 AVFormatContext *ic = avformat_alloc_context();
3642 ic->interrupt_callback = int_cb;
3643 err = avformat_open_input(&ic, filename, NULL, NULL);
3646 /* copy stream format */
3647 for(i=0;i<ic->nb_streams;i++) {
3652 codec = avcodec_find_encoder(ic->streams[i]->codec->codec_id);
3653 ost = new_output_stream(o, s, codec->type);
3656 // FIXME: a more elegant solution is needed
3657 memcpy(st, ic->streams[i], sizeof(AVStream));
3658 st->info = av_malloc(sizeof(*st->info));
3659 memcpy(st->info, ic->streams[i]->info, sizeof(*st->info));
3660 avcodec_copy_context(st->codec, ic->streams[i]->codec);
3662 if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO && !ost->stream_copy)
3663 choose_sample_fmt(st, codec);
3664 else if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO && !ost->stream_copy)
3665 choose_pixel_fmt(st, codec);
3668 av_close_input_file(ic);
3672 static void opt_output_file(void *optctx, const char *filename)
3674 OptionsContext *o = optctx;
3675 AVFormatContext *oc;
3677 AVOutputFormat *file_oformat;
3681 if (!strcmp(filename, "-"))
3684 err = avformat_alloc_output_context2(&oc, NULL, o->format, filename);
3686 print_error(filename, err);
3690 file_oformat= oc->oformat;
3691 oc->interrupt_callback = int_cb;
3693 if (!strcmp(file_oformat->name, "ffm") &&
3694 av_strstart(filename, "http:", NULL)) {
3695 /* special case for files sent to ffserver: we get the stream
3696 parameters from ffserver */
3697 int err = read_ffserver_streams(o, oc, filename);
3699 print_error(filename, err);
3702 } else if (!o->nb_stream_maps) {
3703 /* pick the "best" stream of each type */
3704 #define NEW_STREAM(type, index)\
3706 ost = new_ ## type ## _stream(o, oc);\
3707 ost->source_index = index;\
3708 ost->sync_ist = &input_streams[index];\
3709 input_streams[index].discard = 0;\
3712 /* video: highest resolution */
3713 if (!o->video_disable && oc->oformat->video_codec != CODEC_ID_NONE) {
3714 int area = 0, idx = -1;
3715 for (i = 0; i < nb_input_streams; i++) {
3716 ist = &input_streams[i];
3717 if (ist->st->codec->codec_type == AVMEDIA_TYPE_VIDEO &&
3718 ist->st->codec->width * ist->st->codec->height > area) {
3719 area = ist->st->codec->width * ist->st->codec->height;
3723 NEW_STREAM(video, idx);
3726 /* audio: most channels */
3727 if (!o->audio_disable && oc->oformat->audio_codec != CODEC_ID_NONE) {
3728 int channels = 0, idx = -1;
3729 for (i = 0; i < nb_input_streams; i++) {
3730 ist = &input_streams[i];
3731 if (ist->st->codec->codec_type == AVMEDIA_TYPE_AUDIO &&
3732 ist->st->codec->channels > channels) {
3733 channels = ist->st->codec->channels;
3737 NEW_STREAM(audio, idx);
3740 /* subtitles: pick first */
3741 if (!o->subtitle_disable && oc->oformat->subtitle_codec != CODEC_ID_NONE) {
3742 for (i = 0; i < nb_input_streams; i++)
3743 if (input_streams[i].st->codec->codec_type == AVMEDIA_TYPE_SUBTITLE) {
3744 NEW_STREAM(subtitle, i);
3748 /* do something with data? */
3750 for (i = 0; i < o->nb_stream_maps; i++) {
3751 StreamMap *map = &o->stream_maps[i];
3756 ist = &input_streams[input_files[map->file_index].ist_index + map->stream_index];
3757 switch (ist->st->codec->codec_type) {
3758 case AVMEDIA_TYPE_VIDEO: ost = new_video_stream(o, oc); break;
3759 case AVMEDIA_TYPE_AUDIO: ost = new_audio_stream(o, oc); break;
3760 case AVMEDIA_TYPE_SUBTITLE: ost = new_subtitle_stream(o, oc); break;
3761 case AVMEDIA_TYPE_DATA: ost = new_data_stream(o, oc); break;
3762 case AVMEDIA_TYPE_ATTACHMENT: ost = new_attachment_stream(o, oc); break;
3764 av_log(NULL, AV_LOG_FATAL, "Cannot map stream #%d:%d - unsupported type.\n",
3765 map->file_index, map->stream_index);
3769 ost->source_index = input_files[map->file_index].ist_index + map->stream_index;
3770 ost->sync_ist = &input_streams[input_files[map->sync_file_index].ist_index +
3771 map->sync_stream_index];
3776 /* handle attached files */
3777 for (i = 0; i < o->nb_attachments; i++) {
3779 uint8_t *attachment;
3783 if ((err = avio_open2(&pb, o->attachments[i], AVIO_FLAG_READ, &int_cb, NULL)) < 0) {
3784 av_log(NULL, AV_LOG_FATAL, "Could not open attachment file %s.\n",
3788 if ((len = avio_size(pb)) <= 0) {
3789 av_log(NULL, AV_LOG_FATAL, "Could not get size of the attachment %s.\n",
3793 if (!(attachment = av_malloc(len))) {
3794 av_log(NULL, AV_LOG_FATAL, "Attachment %s too large to fit into memory.\n",
3798 avio_read(pb, attachment, len);
3800 ost = new_attachment_stream(o, oc);
3801 ost->stream_copy = 0;
3802 ost->source_index = -1;
3803 ost->attachment_filename = o->attachments[i];
3804 ost->st->codec->extradata = attachment;
3805 ost->st->codec->extradata_size = len;
3807 p = strrchr(o->attachments[i], '/');
3808 av_dict_set(&ost->st->metadata, "filename", (p && *p) ? p + 1 : o->attachments[i], AV_DICT_DONT_OVERWRITE);
3812 output_files = grow_array(output_files, sizeof(*output_files), &nb_output_files, nb_output_files + 1);
3813 output_files[nb_output_files - 1].ctx = oc;
3814 output_files[nb_output_files - 1].ost_index = nb_output_streams - oc->nb_streams;
3815 output_files[nb_output_files - 1].recording_time = o->recording_time;
3816 output_files[nb_output_files - 1].start_time = o->start_time;
3817 output_files[nb_output_files - 1].limit_filesize = o->limit_filesize;
3818 av_dict_copy(&output_files[nb_output_files - 1].opts, format_opts, 0);
3820 /* check filename in case of an image number is expected */
3821 if (oc->oformat->flags & AVFMT_NEEDNUMBER) {
3822 if (!av_filename_number_test(oc->filename)) {
3823 print_error(oc->filename, AVERROR(EINVAL));
3828 if (!(oc->oformat->flags & AVFMT_NOFILE)) {
3829 /* test if it already exists to avoid loosing precious files */
3830 assert_file_overwrite(filename);
3833 if ((err = avio_open2(&oc->pb, filename, AVIO_FLAG_WRITE,
3834 &oc->interrupt_callback,
3835 &output_files[nb_output_files - 1].opts)) < 0) {
3836 print_error(filename, err);
3841 if (o->mux_preload) {
3843 snprintf(buf, sizeof(buf), "%d", (int)(o->mux_preload*AV_TIME_BASE));
3844 av_dict_set(&output_files[nb_output_files - 1].opts, "preload", buf, 0);
3846 oc->max_delay = (int)(o->mux_max_delay * AV_TIME_BASE);
3849 if (o->chapters_input_file >= nb_input_files) {
3850 if (o->chapters_input_file == INT_MAX) {
3851 /* copy chapters from the first input file that has them*/
3852 o->chapters_input_file = -1;
3853 for (i = 0; i < nb_input_files; i++)
3854 if (input_files[i].ctx->nb_chapters) {
3855 o->chapters_input_file = i;
3859 av_log(NULL, AV_LOG_FATAL, "Invalid input file index %d in chapter mapping.\n",
3860 o->chapters_input_file);
3864 if (o->chapters_input_file >= 0)
3865 copy_chapters(&input_files[o->chapters_input_file], &output_files[nb_output_files - 1],
3866 !o->metadata_chapters_manual);
3869 for (i = 0; i < o->nb_meta_data_maps; i++) {
3870 AVFormatContext *files[2];
3871 AVDictionary **meta[2];
3874 #define METADATA_CHECK_INDEX(index, nb_elems, desc)\
3875 if ((index) < 0 || (index) >= (nb_elems)) {\
3876 av_log(NULL, AV_LOG_FATAL, "Invalid %s index %d while processing metadata maps\n",\
3881 int in_file_index = o->meta_data_maps[i][1].file;
3882 if (in_file_index < 0)
3884 METADATA_CHECK_INDEX(in_file_index, nb_input_files, "input file")
3887 files[1] = input_files[in_file_index].ctx;
3889 for (j = 0; j < 2; j++) {
3890 MetadataMap *map = &o->meta_data_maps[i][j];
3892 switch (map->type) {
3894 meta[j] = &files[j]->metadata;
3897 METADATA_CHECK_INDEX(map->index, files[j]->nb_streams, "stream")
3898 meta[j] = &files[j]->streams[map->index]->metadata;
3901 METADATA_CHECK_INDEX(map->index, files[j]->nb_chapters, "chapter")
3902 meta[j] = &files[j]->chapters[map->index]->metadata;
3905 METADATA_CHECK_INDEX(map->index, files[j]->nb_programs, "program")
3906 meta[j] = &files[j]->programs[map->index]->metadata;
3911 av_dict_copy(meta[0], *meta[1], AV_DICT_DONT_OVERWRITE);
3914 /* copy global metadata by default */
3915 if (!o->metadata_global_manual && nb_input_files)
3916 av_dict_copy(&oc->metadata, input_files[0].ctx->metadata,
3917 AV_DICT_DONT_OVERWRITE);
3918 if (!o->metadata_streams_manual)
3919 for (i = output_files[nb_output_files - 1].ost_index; i < nb_output_streams; i++) {
3921 if (output_streams[i].source_index < 0) /* this is true e.g. for attached files */
3923 ist = &input_streams[output_streams[i].source_index];
3924 av_dict_copy(&output_streams[i].st->metadata, ist->st->metadata, AV_DICT_DONT_OVERWRITE);
3927 /* process manually set metadata */
3928 for (i = 0; i < o->nb_metadata; i++) {
3933 val = strchr(o->metadata[i].u.str, '=');
3935 av_log(NULL, AV_LOG_FATAL, "No '=' character in metadata string %s.\n",
3936 o->metadata[i].u.str);
3941 parse_meta_type(o->metadata[i].specifier, &type, &index);
3947 if (index < 0 || index >= oc->nb_streams) {
3948 av_log(NULL, AV_LOG_FATAL, "Invalid stream index %d in metadata specifier.\n", index);
3951 m = &oc->streams[index]->metadata;
3954 if (index < 0 || index >= oc->nb_chapters) {
3955 av_log(NULL, AV_LOG_FATAL, "Invalid chapter index %d in metadata specifier.\n", index);
3958 m = &oc->chapters[index]->metadata;
3961 av_log(NULL, AV_LOG_FATAL, "Invalid metadata specifier %s.\n", o->metadata[i].specifier);
3965 av_dict_set(m, o->metadata[i].u.str, *val ? val : NULL, 0);
3971 /* same option as mencoder */
3972 static int opt_pass(const char *opt, const char *arg)
3974 do_pass = parse_number_or_die(opt, arg, OPT_INT, 1, 2);
3978 static int64_t getutime(void)
3981 struct rusage rusage;
3983 getrusage(RUSAGE_SELF, &rusage);
3984 return (rusage.ru_utime.tv_sec * 1000000LL) + rusage.ru_utime.tv_usec;
3985 #elif HAVE_GETPROCESSTIMES
3987 FILETIME c, e, k, u;
3988 proc = GetCurrentProcess();
3989 GetProcessTimes(proc, &c, &e, &k, &u);
3990 return ((int64_t) u.dwHighDateTime << 32 | u.dwLowDateTime) / 10;
3992 return av_gettime();
3996 static int64_t getmaxrss(void)
3998 #if HAVE_GETRUSAGE && HAVE_STRUCT_RUSAGE_RU_MAXRSS
3999 struct rusage rusage;
4000 getrusage(RUSAGE_SELF, &rusage);
4001 return (int64_t)rusage.ru_maxrss * 1024;
4002 #elif HAVE_GETPROCESSMEMORYINFO
4004 PROCESS_MEMORY_COUNTERS memcounters;
4005 proc = GetCurrentProcess();
4006 memcounters.cb = sizeof(memcounters);
4007 GetProcessMemoryInfo(proc, &memcounters, sizeof(memcounters));
4008 return memcounters.PeakPagefileUsage;
4014 static int opt_audio_qscale(OptionsContext *o, const char *opt, const char *arg)
4016 return parse_option(o, "q:a", arg, options);
4019 static void show_usage(void)
4021 printf("Hyper fast Audio and Video encoder\n");
4022 printf("usage: %s [options] [[infile options] -i infile]... {[outfile options] outfile}...\n", program_name);
4026 static int opt_help(const char *opt, const char *arg)
4028 int flags = AV_OPT_FLAG_DECODING_PARAM | AV_OPT_FLAG_ENCODING_PARAM;
4029 av_log_set_callback(log_callback_help);
4031 show_help_options(options, "Main options:\n",
4032 OPT_EXPERT | OPT_AUDIO | OPT_VIDEO | OPT_SUBTITLE | OPT_GRAB, 0);
4033 show_help_options(options, "\nAdvanced options:\n",
4034 OPT_EXPERT | OPT_AUDIO | OPT_VIDEO | OPT_SUBTITLE | OPT_GRAB,
4036 show_help_options(options, "\nVideo options:\n",
4037 OPT_EXPERT | OPT_AUDIO | OPT_VIDEO | OPT_GRAB,
4039 show_help_options(options, "\nAdvanced Video options:\n",
4040 OPT_EXPERT | OPT_AUDIO | OPT_VIDEO | OPT_GRAB,
4041 OPT_VIDEO | OPT_EXPERT);
4042 show_help_options(options, "\nAudio options:\n",
4043 OPT_EXPERT | OPT_AUDIO | OPT_VIDEO | OPT_GRAB,
4045 show_help_options(options, "\nAdvanced Audio options:\n",
4046 OPT_EXPERT | OPT_AUDIO | OPT_VIDEO | OPT_GRAB,
4047 OPT_AUDIO | OPT_EXPERT);
4048 show_help_options(options, "\nSubtitle options:\n",
4049 OPT_SUBTITLE | OPT_GRAB,
4051 show_help_options(options, "\nAudio/Video grab options:\n",
4055 show_help_children(avcodec_get_class(), flags);
4056 show_help_children(avformat_get_class(), flags);
4057 show_help_children(sws_get_class(), flags);
4062 static int opt_target(OptionsContext *o, const char *opt, const char *arg)
4064 enum { PAL, NTSC, FILM, UNKNOWN } norm = UNKNOWN;
4065 static const char *const frame_rates[] = {"25", "30000/1001", "24000/1001"};
4067 if(!strncmp(arg, "pal-", 4)) {
4070 } else if(!strncmp(arg, "ntsc-", 5)) {
4073 } else if(!strncmp(arg, "film-", 5)) {
4077 /* Try to determine PAL/NTSC by peeking in the input files */
4078 if(nb_input_files) {
4080 for (j = 0; j < nb_input_files; j++) {
4081 for (i = 0; i < input_files[j].nb_streams; i++) {
4082 AVCodecContext *c = input_files[j].ctx->streams[i]->codec;
4083 if(c->codec_type != AVMEDIA_TYPE_VIDEO)
4085 fr = c->time_base.den * 1000 / c->time_base.num;
4089 } else if((fr == 29970) || (fr == 23976)) {
4098 if (norm != UNKNOWN)
4099 av_log(NULL, AV_LOG_INFO, "Assuming %s for target.\n", norm == PAL ? "PAL" : "NTSC");
4102 if(norm == UNKNOWN) {
4103 av_log(NULL, AV_LOG_FATAL, "Could not determine norm (PAL/NTSC/NTSC-Film) for target.\n");
4104 av_log(NULL, AV_LOG_FATAL, "Please prefix target with \"pal-\", \"ntsc-\" or \"film-\",\n");
4105 av_log(NULL, AV_LOG_FATAL, "or set a framerate with \"-r xxx\".\n");
4109 if(!strcmp(arg, "vcd")) {
4110 opt_video_codec(o, "c:v", "mpeg1video");
4111 opt_audio_codec(o, "c:a", "mp2");
4112 parse_option(o, "f", "vcd", options);
4114 parse_option(o, "s", norm == PAL ? "352x288" : "352x240", options);
4115 parse_option(o, "r", frame_rates[norm], options);
4116 opt_default("g", norm == PAL ? "15" : "18");
4118 opt_default("b", "1150000");
4119 opt_default("maxrate", "1150000");
4120 opt_default("minrate", "1150000");
4121 opt_default("bufsize", "327680"); // 40*1024*8;
4123 opt_default("b:a", "224000");
4124 parse_option(o, "ar", "44100", options);
4125 parse_option(o, "ac", "2", options);
4127 opt_default("packetsize", "2324");
4128 opt_default("muxrate", "1411200"); // 2352 * 75 * 8;
4130 /* We have to offset the PTS, so that it is consistent with the SCR.
4131 SCR starts at 36000, but the first two packs contain only padding
4132 and the first pack from the other stream, respectively, may also have
4133 been written before.
4134 So the real data starts at SCR 36000+3*1200. */
4135 o->mux_preload = (36000+3*1200) / 90000.0; //0.44
4136 } else if(!strcmp(arg, "svcd")) {
4138 opt_video_codec(o, "c:v", "mpeg2video");
4139 opt_audio_codec(o, "c:a", "mp2");
4140 parse_option(o, "f", "svcd", options);
4142 parse_option(o, "s", norm == PAL ? "480x576" : "480x480", options);
4143 parse_option(o, "r", frame_rates[norm], options);
4144 opt_default("g", norm == PAL ? "15" : "18");
4146 opt_default("b", "2040000");
4147 opt_default("maxrate", "2516000");
4148 opt_default("minrate", "0"); //1145000;
4149 opt_default("bufsize", "1835008"); //224*1024*8;
4150 opt_default("flags", "+scan_offset");
4153 opt_default("b:a", "224000");
4154 parse_option(o, "ar", "44100", options);
4156 opt_default("packetsize", "2324");
4158 } else if(!strcmp(arg, "dvd")) {
4160 opt_video_codec(o, "c:v", "mpeg2video");
4161 opt_audio_codec(o, "c:a", "ac3");
4162 parse_option(o, "f", "dvd", options);
4164 parse_option(o, "s", norm == PAL ? "720x576" : "720x480", options);
4165 parse_option(o, "r", frame_rates[norm], options);
4166 opt_default("g", norm == PAL ? "15" : "18");
4168 opt_default("b", "6000000");
4169 opt_default("maxrate", "9000000");
4170 opt_default("minrate", "0"); //1500000;
4171 opt_default("bufsize", "1835008"); //224*1024*8;
4173 opt_default("packetsize", "2048"); // from www.mpucoder.com: DVD sectors contain 2048 bytes of data, this is also the size of one pack.
4174 opt_default("muxrate", "10080000"); // from mplex project: data_rate = 1260000. mux_rate = data_rate * 8
4176 opt_default("b:a", "448000");
4177 parse_option(o, "ar", "48000", options);
4179 } else if(!strncmp(arg, "dv", 2)) {
4181 parse_option(o, "f", "dv", options);
4183 parse_option(o, "s", norm == PAL ? "720x576" : "720x480", options);
4184 parse_option(o, "pix_fmt", !strncmp(arg, "dv50", 4) ? "yuv422p" :
4185 norm == PAL ? "yuv420p" : "yuv411p", options);
4186 parse_option(o, "r", frame_rates[norm], options);
4188 parse_option(o, "ar", "48000", options);
4189 parse_option(o, "ac", "2", options);
4192 av_log(NULL, AV_LOG_ERROR, "Unknown target: %s\n", arg);
4193 return AVERROR(EINVAL);
4198 static int opt_vstats_file(const char *opt, const char *arg)
4200 av_free (vstats_filename);
4201 vstats_filename=av_strdup (arg);
4205 static int opt_vstats(const char *opt, const char *arg)
4208 time_t today2 = time(NULL);
4209 struct tm *today = localtime(&today2);
4211 snprintf(filename, sizeof(filename), "vstats_%02d%02d%02d.log", today->tm_hour, today->tm_min,
4213 return opt_vstats_file(opt, filename);
4216 static int opt_video_frames(OptionsContext *o, const char *opt, const char *arg)
4218 return parse_option(o, "frames:v", arg, options);
4221 static int opt_audio_frames(OptionsContext *o, const char *opt, const char *arg)
4223 return parse_option(o, "frames:a", arg, options);
4226 static int opt_data_frames(OptionsContext *o, const char *opt, const char *arg)
4228 return parse_option(o, "frames:d", arg, options);
4231 static void log_callback_null(void* ptr, int level, const char* fmt, va_list vl)
4235 static int opt_passlogfile(const char *opt, const char *arg)
4237 pass_logfilename_prefix = arg;
4238 #if CONFIG_LIBX264_ENCODER
4239 return opt_default("passlogfile", arg);
4245 static int opt_video_tag(OptionsContext *o, const char *opt, const char *arg)
4247 return parse_option(o, "tag:v", arg, options);
4250 static int opt_audio_tag(OptionsContext *o, const char *opt, const char *arg)
4252 return parse_option(o, "tag:a", arg, options);
4255 static int opt_subtitle_tag(OptionsContext *o, const char *opt, const char *arg)
4257 return parse_option(o, "tag:s", arg, options);
4260 static int opt_video_filters(OptionsContext *o, const char *opt, const char *arg)
4262 return parse_option(o, "filter:v", arg, options);
4265 #define OFFSET(x) offsetof(OptionsContext, x)
4266 static const OptionDef options[] = {
4268 #include "cmdutils_common_opts.h"
4269 { "f", HAS_ARG | OPT_STRING | OPT_OFFSET, {.off = OFFSET(format)}, "force format", "fmt" },
4270 { "i", HAS_ARG | OPT_FUNC2, {(void*)opt_input_file}, "input file name", "filename" },
4271 { "y", OPT_BOOL, {(void*)&file_overwrite}, "overwrite output files" },
4272 { "n", OPT_BOOL, {(void*)&no_file_overwrite}, "do not overwrite output files" },
4273 { "c", HAS_ARG | OPT_STRING | OPT_SPEC, {.off = OFFSET(codec_names)}, "codec name", "codec" },
4274 { "codec", HAS_ARG | OPT_STRING | OPT_SPEC, {.off = OFFSET(codec_names)}, "codec name", "codec" },
4275 { "pre", HAS_ARG | OPT_STRING | OPT_SPEC, {.off = OFFSET(presets)}, "preset name", "preset" },
4276 { "map", HAS_ARG | OPT_EXPERT | OPT_FUNC2, {(void*)opt_map}, "set input stream mapping", "file.stream[:syncfile.syncstream]" },
4277 { "map_metadata", HAS_ARG | OPT_EXPERT | OPT_FUNC2, {(void*)opt_map_metadata}, "set metadata information of outfile from infile",
4278 "outfile[,metadata]:infile[,metadata]" },
4279 { "map_chapters", OPT_INT | HAS_ARG | OPT_EXPERT | OPT_OFFSET, {.off = OFFSET(chapters_input_file)}, "set chapters mapping", "input_file_index" },
4280 { "t", HAS_ARG | OPT_TIME | OPT_OFFSET, {.off = OFFSET(recording_time)}, "record or transcode \"duration\" seconds of audio/video", "duration" },
4281 { "fs", HAS_ARG | OPT_INT64 | OPT_OFFSET, {.off = OFFSET(limit_filesize)}, "set the limit file size in bytes", "limit_size" }, //
4282 { "ss", HAS_ARG | OPT_TIME | OPT_OFFSET, {.off = OFFSET(start_time)}, "set the start time offset", "time_off" },
4283 { "itsoffset", HAS_ARG | OPT_TIME | OPT_OFFSET, {.off = OFFSET(input_ts_offset)}, "set the input ts offset", "time_off" },
4284 { "itsscale", HAS_ARG | OPT_DOUBLE | OPT_SPEC, {.off = OFFSET(ts_scale)}, "set the input ts scale", "scale" },
4285 { "metadata", HAS_ARG | OPT_STRING | OPT_SPEC, {.off = OFFSET(metadata)}, "add metadata", "string=string" },
4286 { "dframes", HAS_ARG | OPT_FUNC2, {(void*)opt_data_frames}, "set the number of data frames to record", "number" },
4287 { "benchmark", OPT_BOOL | OPT_EXPERT, {(void*)&do_benchmark},
4288 "add timings for benchmarking" },
4289 { "timelimit", HAS_ARG, {(void*)opt_timelimit}, "set max runtime in seconds", "limit" },
4290 { "dump", OPT_BOOL | OPT_EXPERT, {(void*)&do_pkt_dump},
4291 "dump each input packet" },
4292 { "hex", OPT_BOOL | OPT_EXPERT, {(void*)&do_hex_dump},
4293 "when dumping packets, also dump the payload" },
4294 { "re", OPT_BOOL | OPT_EXPERT | OPT_OFFSET, {.off = OFFSET(rate_emu)}, "read input at native frame rate", "" },
4295 { "target", HAS_ARG | OPT_FUNC2, {(void*)opt_target}, "specify target file type (\"vcd\", \"svcd\", \"dvd\", \"dv\", \"dv50\", \"pal-vcd\", \"ntsc-svcd\", ...)", "type" },
4296 { "vsync", HAS_ARG | OPT_INT | OPT_EXPERT, {(void*)&video_sync_method}, "video sync method", "" },
4297 { "async", HAS_ARG | OPT_INT | OPT_EXPERT, {(void*)&audio_sync_method}, "audio sync method", "" },
4298 { "adrift_threshold", HAS_ARG | OPT_FLOAT | OPT_EXPERT, {(void*)&audio_drift_threshold}, "audio drift threshold", "threshold" },
4299 { "copyts", OPT_BOOL | OPT_EXPERT, {(void*)©_ts}, "copy timestamps" },
4300 { "copytb", OPT_BOOL | OPT_EXPERT, {(void*)©_tb}, "copy input stream time base when stream copying" },
4301 { "shortest", OPT_BOOL | OPT_EXPERT, {(void*)&opt_shortest}, "finish encoding within shortest input" }, //
4302 { "dts_delta_threshold", HAS_ARG | OPT_FLOAT | OPT_EXPERT, {(void*)&dts_delta_threshold}, "timestamp discontinuity delta threshold", "threshold" },
4303 { "xerror", OPT_BOOL, {(void*)&exit_on_error}, "exit on error", "error" },
4304 { "copyinkf", OPT_BOOL | OPT_EXPERT | OPT_SPEC, {.off = OFFSET(copy_initial_nonkeyframes)}, "copy initial non-keyframes" },
4305 { "frames", OPT_INT64 | HAS_ARG | OPT_SPEC, {.off = OFFSET(max_frames)}, "set the number of frames to record", "number" },
4306 { "tag", OPT_STRING | HAS_ARG | OPT_SPEC, {.off = OFFSET(codec_tags)}, "force codec tag/fourcc", "fourcc/tag" },
4307 { "q", HAS_ARG | OPT_EXPERT | OPT_DOUBLE | OPT_SPEC, {.off = OFFSET(qscale)}, "use fixed quality scale (VBR)", "q" },
4308 { "qscale", HAS_ARG | OPT_EXPERT | OPT_DOUBLE | OPT_SPEC, {.off = OFFSET(qscale)}, "use fixed quality scale (VBR)", "q" },
4310 { "filter", HAS_ARG | OPT_STRING | OPT_SPEC, {.off = OFFSET(filters)}, "set stream filterchain", "filter_list" },
4312 { "stats", OPT_BOOL, {&print_stats}, "print progress report during encoding", },
4313 { "attach", HAS_ARG | OPT_FUNC2, {(void*)opt_attach}, "add an attachment to the output file", "filename" },
4314 { "dump_attachment", HAS_ARG | OPT_STRING | OPT_SPEC, {.off = OFFSET(dump_attachment)}, "extract an attachment into a file", "filename" },
4317 { "vframes", HAS_ARG | OPT_VIDEO | OPT_FUNC2, {(void*)opt_video_frames}, "set the number of video frames to record", "number" },
4318 { "r", HAS_ARG | OPT_VIDEO | OPT_STRING | OPT_SPEC, {.off = OFFSET(frame_rates)}, "set frame rate (Hz value, fraction or abbreviation)", "rate" },
4319 { "s", HAS_ARG | OPT_VIDEO | OPT_STRING | OPT_SPEC, {.off = OFFSET(frame_sizes)}, "set frame size (WxH or abbreviation)", "size" },
4320 { "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" },
4321 { "pix_fmt", HAS_ARG | OPT_EXPERT | OPT_VIDEO | OPT_STRING | OPT_SPEC, {.off = OFFSET(frame_pix_fmts)}, "set pixel format", "format" },
4322 { "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" },
4323 { "vn", OPT_BOOL | OPT_VIDEO | OPT_OFFSET, {.off = OFFSET(video_disable)}, "disable video" },
4324 { "vdt", OPT_INT | HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)&video_discard}, "discard threshold", "n" },
4325 { "rc_override", HAS_ARG | OPT_EXPERT | OPT_VIDEO | OPT_STRING | OPT_SPEC, {.off = OFFSET(rc_overrides)}, "rate control override for specific intervals", "override" },
4326 { "vcodec", HAS_ARG | OPT_VIDEO | OPT_FUNC2, {(void*)opt_video_codec}, "force video codec ('copy' to copy stream)", "codec" },
4327 { "same_quant", OPT_BOOL | OPT_VIDEO, {(void*)&same_quant},
4328 "use same quantizer as source (implies VBR)" },
4329 { "pass", HAS_ARG | OPT_VIDEO, {(void*)opt_pass}, "select the pass number (1 or 2)", "n" },
4330 { "passlogfile", HAS_ARG | OPT_VIDEO, {(void*)&opt_passlogfile}, "select two pass log file name prefix", "prefix" },
4331 { "deinterlace", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, {(void*)&do_deinterlace},
4332 "deinterlace pictures" },
4333 { "vstats", OPT_EXPERT | OPT_VIDEO, {(void*)&opt_vstats}, "dump video coding statistics to file" },
4334 { "vstats_file", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_vstats_file}, "dump video coding statistics to file", "file" },
4336 { "vf", HAS_ARG | OPT_VIDEO | OPT_FUNC2, {(void*)opt_video_filters}, "video filters", "filter list" },
4338 { "intra_matrix", HAS_ARG | OPT_EXPERT | OPT_VIDEO | OPT_STRING | OPT_SPEC, {.off = OFFSET(intra_matrices)}, "specify intra matrix coeffs", "matrix" },
4339 { "inter_matrix", HAS_ARG | OPT_EXPERT | OPT_VIDEO | OPT_STRING | OPT_SPEC, {.off = OFFSET(inter_matrices)}, "specify inter matrix coeffs", "matrix" },
4340 { "top", HAS_ARG | OPT_EXPERT | OPT_VIDEO | OPT_INT| OPT_SPEC, {.off = OFFSET(top_field_first)}, "top=1/bottom=0/auto=-1 field first", "" },
4341 { "dc", OPT_INT | HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)&intra_dc_precision}, "intra_dc_precision", "precision" },
4342 { "vtag", HAS_ARG | OPT_EXPERT | OPT_VIDEO | OPT_FUNC2, {(void*)opt_video_tag}, "force video tag/fourcc", "fourcc/tag" },
4343 { "qphist", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, { (void *)&qp_hist }, "show QP histogram" },
4344 { "force_fps", OPT_BOOL | OPT_EXPERT | OPT_VIDEO | OPT_SPEC, {.off = OFFSET(force_fps)}, "force the selected framerate, disable the best supported framerate selection" },
4345 { "streamid", HAS_ARG | OPT_EXPERT | OPT_FUNC2, {(void*)opt_streamid}, "set the value of an outfile streamid", "streamIndex:value" },
4346 { "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" },
4349 { "aframes", HAS_ARG | OPT_AUDIO | OPT_FUNC2, {(void*)opt_audio_frames}, "set the number of audio frames to record", "number" },
4350 { "aq", HAS_ARG | OPT_AUDIO | OPT_FUNC2, {(void*)opt_audio_qscale}, "set audio quality (codec-specific)", "quality", },
4351 { "ar", HAS_ARG | OPT_AUDIO | OPT_INT | OPT_SPEC, {.off = OFFSET(audio_sample_rate)}, "set audio sampling rate (in Hz)", "rate" },
4352 { "ac", HAS_ARG | OPT_AUDIO | OPT_INT | OPT_SPEC, {.off = OFFSET(audio_channels)}, "set number of audio channels", "channels" },
4353 { "an", OPT_BOOL | OPT_AUDIO | OPT_OFFSET, {.off = OFFSET(audio_disable)}, "disable audio" },
4354 { "acodec", HAS_ARG | OPT_AUDIO | OPT_FUNC2, {(void*)opt_audio_codec}, "force audio codec ('copy' to copy stream)", "codec" },
4355 { "atag", HAS_ARG | OPT_EXPERT | OPT_AUDIO | OPT_FUNC2, {(void*)opt_audio_tag}, "force audio tag/fourcc", "fourcc/tag" },
4356 { "vol", OPT_INT | HAS_ARG | OPT_AUDIO, {(void*)&audio_volume}, "change audio volume (256=normal)" , "volume" }, //
4357 { "sample_fmt", HAS_ARG | OPT_EXPERT | OPT_AUDIO | OPT_SPEC | OPT_STRING, {.off = OFFSET(sample_fmts)}, "set sample format", "format" },
4359 /* subtitle options */
4360 { "sn", OPT_BOOL | OPT_SUBTITLE | OPT_OFFSET, {.off = OFFSET(subtitle_disable)}, "disable subtitle" },
4361 { "scodec", HAS_ARG | OPT_SUBTITLE | OPT_FUNC2, {(void*)opt_subtitle_codec}, "force subtitle codec ('copy' to copy stream)", "codec" },
4362 { "stag", HAS_ARG | OPT_EXPERT | OPT_SUBTITLE | OPT_FUNC2, {(void*)opt_subtitle_tag}, "force subtitle tag/fourcc", "fourcc/tag" },
4365 { "isync", OPT_BOOL | OPT_EXPERT | OPT_GRAB, {(void*)&input_sync}, "sync read on input", "" },
4368 { "muxdelay", OPT_FLOAT | HAS_ARG | OPT_EXPERT | OPT_OFFSET, {.off = OFFSET(mux_max_delay)}, "set the maximum demux-decode delay", "seconds" },
4369 { "muxpreload", OPT_FLOAT | HAS_ARG | OPT_EXPERT | OPT_OFFSET, {.off = OFFSET(mux_preload)}, "set the initial demux-decode delay", "seconds" },
4371 { "bsf", HAS_ARG | OPT_STRING | OPT_SPEC, {.off = OFFSET(bitstream_filters)}, "A comma-separated list of bitstream filters", "bitstream_filters" },
4373 /* data codec support */
4374 { "dcodec", HAS_ARG | OPT_DATA | OPT_FUNC2, {(void*)opt_data_codec}, "force data codec ('copy' to copy stream)", "codec" },
4376 { "default", HAS_ARG | OPT_AUDIO | OPT_VIDEO | OPT_EXPERT, {(void*)opt_default}, "generic catch all option", "" },
4380 int main(int argc, char **argv)
4382 OptionsContext o = { 0 };
4387 av_log_set_flags(AV_LOG_SKIP_REPEATED);
4388 parse_loglevel(argc, argv, options);
4390 if(argc>1 && !strcmp(argv[1], "-d")){
4392 av_log_set_callback(log_callback_null);
4397 avcodec_register_all();
4399 avdevice_register_all();
4402 avfilter_register_all();
4405 avformat_network_init();
4410 parse_options(&o, argc, argv, options, opt_output_file);
4412 if(nb_output_files <= 0 && nb_input_files == 0) {
4414 av_log(NULL, AV_LOG_WARNING, "Use -h to get full help or, even better, run 'man %s'\n", program_name);
4418 /* file converter / grab */
4419 if (nb_output_files <= 0) {
4420 fprintf(stderr, "At least one output file must be specified\n");
4424 if (nb_input_files == 0) {
4425 av_log(NULL, AV_LOG_FATAL, "At least one input file must be specified\n");
4430 if (transcode(output_files, nb_output_files, input_files, nb_input_files) < 0)
4432 ti = getutime() - ti;
4434 int maxrss = getmaxrss() / 1024;
4435 printf("bench: utime=%0.3fs maxrss=%ikB\n", ti / 1000000.0, maxrss);