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 "libavutil/imgutils.h"
48 #include "libavformat/os_support.h"
50 #include "libavformat/ffm.h" // not public API
53 # include "libavfilter/avcodec.h"
54 # include "libavfilter/avfilter.h"
55 # include "libavfilter/avfiltergraph.h"
56 # include "libavfilter/buffersink.h"
57 # include "libavfilter/buffersrc.h"
58 # include "libavfilter/vsrc_buffer.h"
61 #if HAVE_SYS_RESOURCE_H
62 #include <sys/types.h>
64 #include <sys/resource.h>
65 #elif HAVE_GETPROCESSTIMES
68 #if HAVE_GETPROCESSMEMORYINFO
74 #include <sys/select.h>
79 #include <sys/ioctl.h>
89 #include "libavutil/avassert.h"
91 const char program_name[] = "avconv";
92 const int program_birth_year = 2000;
94 /* select an input stream for an output stream */
95 typedef struct StreamMap {
96 int disabled; /** 1 is this mapping is disabled by a negative map */
100 int sync_stream_index;
104 * select an input file for an output file
106 typedef struct MetadataMap {
107 int file; ///< file index
108 char type; ///< type of metadata to copy -- (g)lobal, (s)tream, (c)hapter or (p)rogram
109 int index; ///< stream/chapter/program number
112 static const OptionDef options[];
114 #define MAX_STREAMS 1024 /* arbitrary sanity check value */
116 static int frame_bits_per_raw_sample = 0;
117 static int video_discard = 0;
118 static int same_quant = 0;
119 static int do_deinterlace = 0;
120 static int intra_dc_precision = 8;
121 static int qp_hist = 0;
123 static int file_overwrite = 0;
124 static int no_file_overwrite = 0;
125 static int do_benchmark = 0;
126 static int do_hex_dump = 0;
127 static int do_pkt_dump = 0;
128 static int do_pass = 0;
129 static const char *pass_logfilename_prefix;
130 static int video_sync_method = -1;
131 static int audio_sync_method = 0;
132 static float audio_drift_threshold = 0.1;
133 static int copy_ts = 0;
134 static int copy_tb = 1;
135 static int opt_shortest = 0;
136 static char *vstats_filename;
137 static FILE *vstats_file;
139 static int audio_volume = 256;
141 static int exit_on_error = 0;
142 static int using_stdin = 0;
143 static int run_as_daemon = 0;
144 static int q_pressed = 0;
145 static int64_t video_size = 0;
146 static int64_t audio_size = 0;
147 static int64_t extra_size = 0;
148 static int nb_frames_dup = 0;
149 static int nb_frames_drop = 0;
150 static int input_sync;
152 static float dts_delta_threshold = 10;
154 static int print_stats = 1;
156 static uint8_t *audio_buf;
157 static uint8_t *audio_out;
158 static unsigned int allocated_audio_out_size, allocated_audio_buf_size;
160 #define DEFAULT_PASS_LOGFILENAME_PREFIX "av2pass"
162 typedef struct FrameBuffer {
168 enum PixelFormat pix_fmt;
171 struct InputStream *ist;
172 struct FrameBuffer *next;
175 typedef struct InputStream {
178 int discard; /* true if stream data should be discarded */
179 int decoding_needed; /* true if the packets must be decoded in 'raw_fifo' */
181 AVFrame *decoded_frame;
182 AVFrame *filtered_frame;
184 int64_t start; /* time when read started */
185 int64_t next_pts; /* synthetic pts for cases where pkt.pts
187 int64_t pts; /* current pts */
189 int is_start; /* is 1 at the start and after a discontinuity */
190 int showed_multi_packet_warning;
193 /* a pool of free buffers for decoded data */
194 FrameBuffer *buffer_pool;
197 typedef struct InputFile {
198 AVFormatContext *ctx;
199 int eof_reached; /* true if eof reached */
200 int ist_index; /* index of first stream in ist_table */
201 int buffer_size; /* current total buffer size */
203 int nb_streams; /* number of stream that avconv is aware of; may be different
204 from ctx.nb_streams if new streams appear during av_read_frame() */
208 typedef struct OutputStream {
209 int file_index; /* file index */
210 int index; /* stream index in the output file */
211 int source_index; /* InputStream index */
212 AVStream *st; /* stream in the output file */
213 int encoding_needed; /* true if encoding needed for this stream */
215 /* input pts and corresponding output pts
217 // double sync_ipts; /* dts from the AVPacket of the demuxer in second units */
218 struct InputStream *sync_ist; /* input stream to sync against */
219 int64_t sync_opts; /* output frame counter, could be changed to some true timestamp */ // FIXME look at frame_number
220 AVBitStreamFilterContext *bitstream_filters;
226 AVFrame resample_frame; /* temporary frame for image resampling */
227 struct SwsContext *img_resample_ctx; /* for image resampling */
230 int resample_pix_fmt;
231 AVRational frame_rate;
235 float frame_aspect_ratio;
237 /* forced key frames */
238 int64_t *forced_kf_pts;
244 ReSampleContext *resample; /* for audio resampling */
245 int resample_sample_fmt;
246 int resample_channels;
247 int resample_sample_rate;
249 AVAudioConvert *reformat_ctx;
250 AVFifoBuffer *fifo; /* for compression: one audio fifo per codec */
254 AVFilterContext *output_video_filter;
255 AVFilterContext *input_video_filter;
256 AVFilterBufferRef *picref;
258 AVFilterGraph *graph;
263 int is_past_recording_time;
265 const char *attachment_filename;
266 int copy_initial_nonkeyframes;
271 /* init terminal so that we can grab keys */
272 static struct termios oldtty;
275 typedef struct OutputFile {
276 AVFormatContext *ctx;
278 int ost_index; /* index of the first stream in output_streams */
279 int64_t recording_time; /* desired length of the resulting file in microseconds */
280 int64_t start_time; /* start time in microseconds */
281 uint64_t limit_filesize;
284 static InputStream *input_streams = NULL;
285 static int nb_input_streams = 0;
286 static InputFile *input_files = NULL;
287 static int nb_input_files = 0;
289 static OutputStream *output_streams = NULL;
290 static int nb_output_streams = 0;
291 static OutputFile *output_files = NULL;
292 static int nb_output_files = 0;
294 typedef struct OptionsContext {
295 /* input/output options */
299 SpecifierOpt *codec_names;
301 SpecifierOpt *audio_channels;
302 int nb_audio_channels;
303 SpecifierOpt *audio_sample_rate;
304 int nb_audio_sample_rate;
305 SpecifierOpt *frame_rates;
307 SpecifierOpt *frame_sizes;
309 SpecifierOpt *frame_pix_fmts;
310 int nb_frame_pix_fmts;
313 int64_t input_ts_offset;
316 SpecifierOpt *ts_scale;
318 SpecifierOpt *dump_attachment;
319 int nb_dump_attachment;
322 StreamMap *stream_maps;
324 /* first item specifies output metadata, second is input */
325 MetadataMap (*meta_data_maps)[2];
326 int nb_meta_data_maps;
327 int metadata_global_manual;
328 int metadata_streams_manual;
329 int metadata_chapters_manual;
330 const char **attachments;
333 int chapters_input_file;
335 int64_t recording_time;
336 uint64_t limit_filesize;
342 int subtitle_disable;
345 /* indexed by output file stream index */
349 SpecifierOpt *metadata;
351 SpecifierOpt *max_frames;
353 SpecifierOpt *bitstream_filters;
354 int nb_bitstream_filters;
355 SpecifierOpt *codec_tags;
357 SpecifierOpt *sample_fmts;
359 SpecifierOpt *qscale;
361 SpecifierOpt *forced_key_frames;
362 int nb_forced_key_frames;
363 SpecifierOpt *force_fps;
365 SpecifierOpt *frame_aspect_ratios;
366 int nb_frame_aspect_ratios;
367 SpecifierOpt *rc_overrides;
369 SpecifierOpt *intra_matrices;
370 int nb_intra_matrices;
371 SpecifierOpt *inter_matrices;
372 int nb_inter_matrices;
373 SpecifierOpt *top_field_first;
374 int nb_top_field_first;
375 SpecifierOpt *metadata_map;
377 SpecifierOpt *presets;
379 SpecifierOpt *copy_initial_nonkeyframes;
380 int nb_copy_initial_nonkeyframes;
382 SpecifierOpt *filters;
387 #define MATCH_PER_STREAM_OPT(name, type, outvar, fmtctx, st)\
390 for (i = 0; i < o->nb_ ## name; i++) {\
391 char *spec = o->name[i].specifier;\
392 if ((ret = check_stream_specifier(fmtctx, st, spec)) > 0)\
393 outvar = o->name[i].u.type;\
399 static void reset_options(OptionsContext *o)
401 const OptionDef *po = options;
403 /* all OPT_SPEC and OPT_STRING can be freed in generic way */
405 void *dst = (uint8_t*)o + po->u.off;
407 if (po->flags & OPT_SPEC) {
408 SpecifierOpt **so = dst;
409 int i, *count = (int*)(so + 1);
410 for (i = 0; i < *count; i++) {
411 av_freep(&(*so)[i].specifier);
412 if (po->flags & OPT_STRING)
413 av_freep(&(*so)[i].u.str);
417 } else if (po->flags & OPT_OFFSET && po->flags & OPT_STRING)
422 av_freep(&o->stream_maps);
423 av_freep(&o->meta_data_maps);
424 av_freep(&o->streamid_map);
426 memset(o, 0, sizeof(*o));
428 o->mux_max_delay = 0.7;
429 o->recording_time = INT64_MAX;
430 o->limit_filesize = UINT64_MAX;
431 o->chapters_input_file = INT_MAX;
437 static int alloc_buffer(InputStream *ist, FrameBuffer **pbuf)
439 AVCodecContext *s = ist->st->codec;
440 FrameBuffer *buf = av_mallocz(sizeof(*buf));
442 const int pixel_size = av_pix_fmt_descriptors[s->pix_fmt].comp[0].step_minus1+1;
443 int h_chroma_shift, v_chroma_shift;
444 int edge = 32; // XXX should be avcodec_get_edge_width(), but that fails on svq1
445 int w = s->width, h = s->height;
448 return AVERROR(ENOMEM);
450 if (!(s->flags & CODEC_FLAG_EMU_EDGE)) {
455 avcodec_align_dimensions(s, &w, &h);
456 if ((ret = av_image_alloc(buf->base, buf->linesize, w, h,
457 s->pix_fmt, 32)) < 0) {
461 /* XXX this shouldn't be needed, but some tests break without this line
462 * those decoders are buggy and need to be fixed.
463 * the following tests fail:
464 * bethsoft-vid, cdgraphics, ansi, aasc, fraps-v1, qtrle-1bit
466 memset(buf->base[0], 128, ret);
468 avcodec_get_chroma_sub_sample(s->pix_fmt, &h_chroma_shift, &v_chroma_shift);
469 for (int i = 0; i < FF_ARRAY_ELEMS(buf->data); i++) {
470 const int h_shift = i==0 ? 0 : h_chroma_shift;
471 const int v_shift = i==0 ? 0 : v_chroma_shift;
472 if (s->flags & CODEC_FLAG_EMU_EDGE)
473 buf->data[i] = buf->base[i];
475 buf->data[i] = buf->base[i] +
476 FFALIGN((buf->linesize[i]*edge >> v_shift) +
477 (pixel_size*edge >> h_shift), 32);
481 buf->pix_fmt = s->pix_fmt;
488 static void free_buffer_pool(InputStream *ist)
490 FrameBuffer *buf = ist->buffer_pool;
492 ist->buffer_pool = buf->next;
493 av_freep(&buf->base[0]);
495 buf = ist->buffer_pool;
499 static void unref_buffer(InputStream *ist, FrameBuffer *buf)
501 av_assert0(buf->refcount);
503 if (!buf->refcount) {
504 buf->next = ist->buffer_pool;
505 ist->buffer_pool = buf;
509 static int codec_get_buffer(AVCodecContext *s, AVFrame *frame)
511 InputStream *ist = s->opaque;
515 if (!ist->buffer_pool && (ret = alloc_buffer(ist, &ist->buffer_pool)) < 0)
518 buf = ist->buffer_pool;
519 ist->buffer_pool = buf->next;
521 if (buf->w != s->width || buf->h != s->height || buf->pix_fmt != s->pix_fmt) {
522 av_freep(&buf->base[0]);
524 if ((ret = alloc_buffer(ist, &buf)) < 0)
530 frame->type = FF_BUFFER_TYPE_USER;
531 frame->extended_data = frame->data;
532 frame->pkt_pts = s->pkt ? s->pkt->pts : AV_NOPTS_VALUE;
534 for (i = 0; i < FF_ARRAY_ELEMS(buf->data); i++) {
535 frame->base[i] = buf->base[i]; // XXX h264.c uses base though it shouldn't
536 frame->data[i] = buf->data[i];
537 frame->linesize[i] = buf->linesize[i];
543 static void codec_release_buffer(AVCodecContext *s, AVFrame *frame)
545 InputStream *ist = s->opaque;
546 FrameBuffer *buf = frame->opaque;
549 for (i = 0; i < FF_ARRAY_ELEMS(frame->data); i++)
550 frame->data[i] = NULL;
552 unref_buffer(ist, buf);
555 static void filter_release_buffer(AVFilterBuffer *fb)
557 FrameBuffer *buf = fb->priv;
559 unref_buffer(buf->ist, buf);
564 static int configure_video_filters(InputStream *ist, OutputStream *ost)
566 AVFilterContext *last_filter, *filter;
567 /** filter graph containing all filters including input & output */
568 AVCodecContext *codec = ost->st->codec;
569 AVCodecContext *icodec = ist->st->codec;
570 enum PixelFormat pix_fmts[] = { codec->pix_fmt, PIX_FMT_NONE };
571 AVBufferSinkParams *buffersink_params = av_buffersink_params_alloc();
572 AVRational sample_aspect_ratio;
576 ost->graph = avfilter_graph_alloc();
578 if (ist->st->sample_aspect_ratio.num) {
579 sample_aspect_ratio = ist->st->sample_aspect_ratio;
581 sample_aspect_ratio = ist->st->codec->sample_aspect_ratio;
583 snprintf(args, 255, "%d:%d:%d:%d:%d:%d:%d", ist->st->codec->width,
584 ist->st->codec->height, ist->st->codec->pix_fmt, 1, AV_TIME_BASE,
585 sample_aspect_ratio.num, sample_aspect_ratio.den);
587 ret = avfilter_graph_create_filter(&ost->input_video_filter, avfilter_get_by_name("buffer"),
588 "src", args, NULL, ost->graph);
591 #if FF_API_OLD_VSINK_API
592 ret = avfilter_graph_create_filter(&ost->output_video_filter, avfilter_get_by_name("buffersink"),
593 "out", NULL, pix_fmts, ost->graph);
595 buffersink_params->pixel_fmts = pix_fmts;
596 ret = avfilter_graph_create_filter(&ost->output_video_filter, avfilter_get_by_name("buffersink"),
597 "out", NULL, buffersink_params, ost->graph);
599 av_freep(&buffersink_params);
602 last_filter = ost->input_video_filter;
604 if (codec->width != icodec->width || codec->height != icodec->height) {
605 snprintf(args, 255, "%d:%d:flags=0x%X",
608 (unsigned)ost->sws_flags);
609 if ((ret = avfilter_graph_create_filter(&filter, avfilter_get_by_name("scale"),
610 NULL, args, NULL, ost->graph)) < 0)
612 if ((ret = avfilter_link(last_filter, 0, filter, 0)) < 0)
614 last_filter = filter;
617 snprintf(args, sizeof(args), "flags=0x%X", (unsigned)ost->sws_flags);
618 ost->graph->scale_sws_opts = av_strdup(args);
621 AVFilterInOut *outputs = avfilter_inout_alloc();
622 AVFilterInOut *inputs = avfilter_inout_alloc();
624 outputs->name = av_strdup("in");
625 outputs->filter_ctx = last_filter;
626 outputs->pad_idx = 0;
627 outputs->next = NULL;
629 inputs->name = av_strdup("out");
630 inputs->filter_ctx = ost->output_video_filter;
634 if ((ret = avfilter_graph_parse(ost->graph, ost->avfilter, &inputs, &outputs, NULL)) < 0)
636 av_freep(&ost->avfilter);
638 if ((ret = avfilter_link(last_filter, 0, ost->output_video_filter, 0)) < 0)
642 if ((ret = avfilter_graph_config(ost->graph, NULL)) < 0)
645 codec->width = ost->output_video_filter->inputs[0]->w;
646 codec->height = ost->output_video_filter->inputs[0]->h;
647 codec->sample_aspect_ratio = ost->st->sample_aspect_ratio =
648 ost->frame_aspect_ratio ? // overridden by the -aspect cli option
649 av_d2q(ost->frame_aspect_ratio * codec->height/codec->width, 255) :
650 ost->output_video_filter->inputs[0]->sample_aspect_ratio;
654 #endif /* CONFIG_AVFILTER */
656 static void term_exit(void)
658 av_log(NULL, AV_LOG_QUIET, "%s", "");
661 tcsetattr (0, TCSANOW, &oldtty);
665 static volatile int received_sigterm = 0;
668 sigterm_handler(int sig)
670 received_sigterm = sig;
675 static void term_init(void)
685 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
686 |INLCR|IGNCR|ICRNL|IXON);
687 tty.c_oflag |= OPOST;
688 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
689 tty.c_cflag &= ~(CSIZE|PARENB);
694 tcsetattr (0, TCSANOW, &tty);
695 signal(SIGQUIT, sigterm_handler); /* Quit (POSIX). */
699 signal(SIGINT , sigterm_handler); /* Interrupt (ANSI). */
700 signal(SIGTERM, sigterm_handler); /* Termination (ANSI). */
702 signal(SIGXCPU, sigterm_handler);
706 /* read a key without blocking */
707 static int read_key(void)
722 n = select(1, &rfds, NULL, NULL, &tv);
737 static int decode_interrupt_cb(void *ctx)
739 q_pressed += read_key() == 'q';
740 return q_pressed > 1;
743 static const AVIOInterruptCB int_cb = { decode_interrupt_cb, NULL };
745 void exit_program(int ret)
750 for (i = 0; i < nb_output_files; i++) {
751 AVFormatContext *s = output_files[i].ctx;
752 if (!(s->oformat->flags & AVFMT_NOFILE) && s->pb)
754 avformat_free_context(s);
755 av_dict_free(&output_files[i].opts);
757 for (i = 0; i < nb_input_files; i++) {
758 avformat_close_input(&input_files[i].ctx);
760 for (i = 0; i < nb_input_streams; i++) {
761 av_freep(&input_streams[i].decoded_frame);
762 av_freep(&input_streams[i].filtered_frame);
763 av_dict_free(&input_streams[i].opts);
764 free_buffer_pool(&input_streams[i]);
769 av_free(vstats_filename);
771 av_freep(&input_streams);
772 av_freep(&input_files);
773 av_freep(&output_streams);
774 av_freep(&output_files);
779 allocated_audio_buf_size = allocated_audio_out_size = 0;
784 avformat_network_deinit();
786 if (received_sigterm) {
787 av_log(NULL, AV_LOG_INFO, "Received signal %d: terminating.\n",
788 (int) received_sigterm);
795 static void assert_avoptions(AVDictionary *m)
797 AVDictionaryEntry *t;
798 if ((t = av_dict_get(m, "", NULL, AV_DICT_IGNORE_SUFFIX))) {
799 av_log(NULL, AV_LOG_FATAL, "Option %s not found.\n", t->key);
804 static void assert_codec_experimental(AVCodecContext *c, int encoder)
806 const char *codec_string = encoder ? "encoder" : "decoder";
808 if (c->codec->capabilities & CODEC_CAP_EXPERIMENTAL &&
809 c->strict_std_compliance > FF_COMPLIANCE_EXPERIMENTAL) {
810 av_log(NULL, AV_LOG_FATAL, "%s '%s' is experimental and might produce bad "
811 "results.\nAdd '-strict experimental' if you want to use it.\n",
812 codec_string, c->codec->name);
813 codec = encoder ? avcodec_find_encoder(c->codec->id) : avcodec_find_decoder(c->codec->id);
814 if (!(codec->capabilities & CODEC_CAP_EXPERIMENTAL))
815 av_log(NULL, AV_LOG_FATAL, "Or use the non experimental %s '%s'.\n",
816 codec_string, codec->name);
821 static void choose_sample_fmt(AVStream *st, AVCodec *codec)
823 if (codec && codec->sample_fmts) {
824 const enum AVSampleFormat *p = codec->sample_fmts;
825 for (; *p != -1; p++) {
826 if (*p == st->codec->sample_fmt)
830 if((codec->capabilities & CODEC_CAP_LOSSLESS) && av_get_sample_fmt_name(st->codec->sample_fmt) > av_get_sample_fmt_name(codec->sample_fmts[0]))
831 av_log(NULL, AV_LOG_ERROR, "Convertion will not be lossless'\n");
832 if(av_get_sample_fmt_name(st->codec->sample_fmt))
833 av_log(NULL, AV_LOG_WARNING,
834 "Incompatible sample format '%s' for codec '%s', auto-selecting format '%s'\n",
835 av_get_sample_fmt_name(st->codec->sample_fmt),
837 av_get_sample_fmt_name(codec->sample_fmts[0]));
838 st->codec->sample_fmt = codec->sample_fmts[0];
843 static void choose_sample_rate(AVStream *st, AVCodec *codec)
845 if (codec && codec->supported_samplerates) {
846 const int *p = codec->supported_samplerates;
848 int best_dist = INT_MAX;
850 int dist = abs(st->codec->sample_rate - *p);
851 if (dist < best_dist) {
857 av_log(st->codec, AV_LOG_WARNING, "Requested sampling rate unsupported using closest supported (%d)\n", best);
859 st->codec->sample_rate = best;
863 static void choose_pixel_fmt(AVStream *st, AVCodec *codec)
865 if (codec && codec->pix_fmts) {
866 const enum PixelFormat *p = codec->pix_fmts;
867 if (st->codec->strict_std_compliance <= FF_COMPLIANCE_UNOFFICIAL) {
868 if (st->codec->codec_id == CODEC_ID_MJPEG) {
869 p = (const enum PixelFormat[]) { PIX_FMT_YUVJ420P, PIX_FMT_YUVJ422P, PIX_FMT_YUV420P, PIX_FMT_YUV422P, PIX_FMT_NONE };
870 } else if (st->codec->codec_id == CODEC_ID_LJPEG) {
871 p = (const enum PixelFormat[]) { PIX_FMT_YUVJ420P, PIX_FMT_YUVJ422P, PIX_FMT_YUVJ444P, PIX_FMT_YUV420P,
872 PIX_FMT_YUV422P, PIX_FMT_YUV444P, PIX_FMT_BGRA, PIX_FMT_NONE };
875 for (; *p != PIX_FMT_NONE; p++) {
876 if (*p == st->codec->pix_fmt)
879 if (*p == PIX_FMT_NONE) {
880 if (st->codec->pix_fmt != PIX_FMT_NONE)
881 av_log(NULL, AV_LOG_WARNING,
882 "Incompatible pixel format '%s' for codec '%s', auto-selecting format '%s'\n",
883 av_pix_fmt_descriptors[st->codec->pix_fmt].name,
885 av_pix_fmt_descriptors[codec->pix_fmts[0]].name);
886 st->codec->pix_fmt = codec->pix_fmts[0];
892 get_sync_ipts(const OutputStream *ost)
894 const InputStream *ist = ost->sync_ist;
895 OutputFile *of = &output_files[ost->file_index];
896 return (double)(ist->pts - of->start_time) / AV_TIME_BASE;
899 static void write_frame(AVFormatContext *s, AVPacket *pkt, AVCodecContext *avctx, AVBitStreamFilterContext *bsfc)
904 AVPacket new_pkt = *pkt;
905 int a = av_bitstream_filter_filter(bsfc, avctx, NULL,
906 &new_pkt.data, &new_pkt.size,
907 pkt->data, pkt->size,
908 pkt->flags & AV_PKT_FLAG_KEY);
911 new_pkt.destruct = av_destruct_packet;
913 av_log(NULL, AV_LOG_ERROR, "%s failed for stream %d, codec %s",
914 bsfc->filter->name, pkt->stream_index,
915 avctx->codec ? avctx->codec->name : "copy");
925 ret = av_interleaved_write_frame(s, pkt);
927 print_error("av_interleaved_write_frame()", ret);
932 static void generate_silence(uint8_t* buf, enum AVSampleFormat sample_fmt, size_t size)
934 int fill_char = 0x00;
935 if (sample_fmt == AV_SAMPLE_FMT_U8)
937 memset(buf, fill_char, size);
940 static void do_audio_out(AVFormatContext *s, OutputStream *ost,
941 InputStream *ist, AVFrame *decoded_frame)
944 int64_t audio_out_size, audio_buf_size;
946 int size_out, frame_bytes, ret, resample_changed;
947 AVCodecContext *enc = ost->st->codec;
948 AVCodecContext *dec = ist->st->codec;
949 int osize = av_get_bytes_per_sample(enc->sample_fmt);
950 int isize = av_get_bytes_per_sample(dec->sample_fmt);
951 const int coded_bps = av_get_bits_per_sample(enc->codec->id);
952 uint8_t *buf = decoded_frame->data[0];
953 int size = decoded_frame->nb_samples * dec->channels * isize;
954 int64_t allocated_for_size = size;
957 audio_buf_size = (allocated_for_size + isize * dec->channels - 1) / (isize * dec->channels);
958 audio_buf_size = (audio_buf_size * enc->sample_rate + dec->sample_rate) / dec->sample_rate;
959 audio_buf_size = audio_buf_size * 2 + 10000; // safety factors for the deprecated resampling API
960 audio_buf_size = FFMAX(audio_buf_size, enc->frame_size);
961 audio_buf_size *= osize * enc->channels;
963 audio_out_size = FFMAX(audio_buf_size, enc->frame_size * osize * enc->channels);
964 if (coded_bps > 8 * osize)
965 audio_out_size = audio_out_size * coded_bps / (8*osize);
966 audio_out_size += FF_MIN_BUFFER_SIZE;
968 if (audio_out_size > INT_MAX || audio_buf_size > INT_MAX) {
969 av_log(NULL, AV_LOG_FATAL, "Buffer sizes too large\n");
973 av_fast_malloc(&audio_buf, &allocated_audio_buf_size, audio_buf_size);
974 av_fast_malloc(&audio_out, &allocated_audio_out_size, audio_out_size);
975 if (!audio_buf || !audio_out) {
976 av_log(NULL, AV_LOG_FATAL, "Out of memory in do_audio_out\n");
980 if (enc->channels != dec->channels)
981 ost->audio_resample = 1;
983 resample_changed = ost->resample_sample_fmt != dec->sample_fmt ||
984 ost->resample_channels != dec->channels ||
985 ost->resample_sample_rate != dec->sample_rate;
987 if ((ost->audio_resample && !ost->resample) || resample_changed) {
988 if (resample_changed) {
989 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",
990 ist->file_index, ist->st->index,
991 ost->resample_sample_rate, av_get_sample_fmt_name(ost->resample_sample_fmt), ost->resample_channels,
992 dec->sample_rate, av_get_sample_fmt_name(dec->sample_fmt), dec->channels);
993 ost->resample_sample_fmt = dec->sample_fmt;
994 ost->resample_channels = dec->channels;
995 ost->resample_sample_rate = dec->sample_rate;
997 audio_resample_close(ost->resample);
999 /* if audio_sync_method is >1 the resampler is needed for audio drift compensation */
1000 if (audio_sync_method <= 1 &&
1001 ost->resample_sample_fmt == enc->sample_fmt &&
1002 ost->resample_channels == enc->channels &&
1003 ost->resample_sample_rate == enc->sample_rate) {
1004 ost->resample = NULL;
1005 ost->audio_resample = 0;
1007 if (dec->sample_fmt != AV_SAMPLE_FMT_S16)
1008 av_log(NULL, AV_LOG_WARNING, "Using s16 intermediate sample format for resampling\n");
1009 ost->resample = av_audio_resample_init(enc->channels, dec->channels,
1010 enc->sample_rate, dec->sample_rate,
1011 enc->sample_fmt, dec->sample_fmt,
1013 if (!ost->resample) {
1014 av_log(NULL, AV_LOG_FATAL, "Can not resample %d channels @ %d Hz to %d channels @ %d Hz\n",
1015 dec->channels, dec->sample_rate,
1016 enc->channels, enc->sample_rate);
1022 #define MAKE_SFMT_PAIR(a,b) ((a)+AV_SAMPLE_FMT_NB*(b))
1023 if (!ost->audio_resample && dec->sample_fmt != enc->sample_fmt &&
1024 MAKE_SFMT_PAIR(enc->sample_fmt,dec->sample_fmt) != ost->reformat_pair) {
1025 if (ost->reformat_ctx)
1026 av_audio_convert_free(ost->reformat_ctx);
1027 ost->reformat_ctx = av_audio_convert_alloc(enc->sample_fmt, 1,
1028 dec->sample_fmt, 1, NULL, 0);
1029 if (!ost->reformat_ctx) {
1030 av_log(NULL, AV_LOG_FATAL, "Cannot convert %s sample format to %s sample format\n",
1031 av_get_sample_fmt_name(dec->sample_fmt),
1032 av_get_sample_fmt_name(enc->sample_fmt));
1035 ost->reformat_pair = MAKE_SFMT_PAIR(enc->sample_fmt,dec->sample_fmt);
1038 if (audio_sync_method) {
1039 double delta = get_sync_ipts(ost) * enc->sample_rate - ost->sync_opts -
1040 av_fifo_size(ost->fifo) / (enc->channels * osize);
1041 int idelta = delta * dec->sample_rate / enc->sample_rate;
1042 int byte_delta = idelta * isize * dec->channels;
1044 // FIXME resample delay
1045 if (fabs(delta) > 50) {
1046 if (ist->is_start || fabs(delta) > audio_drift_threshold*enc->sample_rate) {
1047 if (byte_delta < 0) {
1048 byte_delta = FFMAX(byte_delta, -size);
1051 av_log(NULL, AV_LOG_VERBOSE, "discarding %d audio samples\n",
1052 -byte_delta / (isize * dec->channels));
1057 static uint8_t *input_tmp = NULL;
1058 input_tmp = av_realloc(input_tmp, byte_delta + size);
1060 if (byte_delta > allocated_for_size - size) {
1061 allocated_for_size = byte_delta + (int64_t)size;
1066 generate_silence(input_tmp, dec->sample_fmt, byte_delta);
1067 memcpy(input_tmp + byte_delta, buf, size);
1070 av_log(NULL, AV_LOG_VERBOSE, "adding %d audio samples of silence\n", idelta);
1072 } else if (audio_sync_method > 1) {
1073 int comp = av_clip(delta, -audio_sync_method, audio_sync_method);
1074 av_assert0(ost->audio_resample);
1075 av_log(NULL, AV_LOG_VERBOSE, "compensating audio timestamp drift:%f compensation:%d in:%d\n",
1076 delta, comp, enc->sample_rate);
1077 // 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));
1078 av_resample_compensate(*(struct AVResampleContext**)ost->resample, comp, enc->sample_rate);
1082 ost->sync_opts = lrintf(get_sync_ipts(ost) * enc->sample_rate) -
1083 av_fifo_size(ost->fifo) / (enc->channels * osize); // FIXME wrong
1085 if (ost->audio_resample) {
1087 size_out = audio_resample(ost->resample,
1088 (short *)buftmp, (short *)buf,
1089 size / (dec->channels * isize));
1090 size_out = size_out * enc->channels * osize;
1096 if (!ost->audio_resample && dec->sample_fmt != enc->sample_fmt) {
1097 const void *ibuf[6] = { buftmp };
1098 void *obuf[6] = { audio_buf };
1099 int istride[6] = { isize };
1100 int ostride[6] = { osize };
1101 int len = size_out / istride[0];
1102 if (av_audio_convert(ost->reformat_ctx, obuf, ostride, ibuf, istride, len) < 0) {
1103 printf("av_audio_convert() failed\n");
1109 size_out = len * osize;
1112 /* now encode as many frames as possible */
1113 if (enc->frame_size > 1) {
1114 /* output resampled raw samples */
1115 if (av_fifo_realloc2(ost->fifo, av_fifo_size(ost->fifo) + size_out) < 0) {
1116 av_log(NULL, AV_LOG_FATAL, "av_fifo_realloc2() failed\n");
1119 av_fifo_generic_write(ost->fifo, buftmp, size_out, NULL);
1121 frame_bytes = enc->frame_size * osize * enc->channels;
1123 while (av_fifo_size(ost->fifo) >= frame_bytes) {
1125 av_init_packet(&pkt);
1127 av_fifo_generic_read(ost->fifo, audio_buf, frame_bytes, NULL);
1129 // FIXME pass ost->sync_opts as AVFrame.pts in avcodec_encode_audio()
1131 ret = avcodec_encode_audio(enc, audio_out, audio_out_size,
1132 (short *)audio_buf);
1134 av_log(NULL, AV_LOG_FATAL, "Audio encoding failed\n");
1138 pkt.stream_index = ost->index;
1139 pkt.data = audio_out;
1141 if (enc->coded_frame && enc->coded_frame->pts != AV_NOPTS_VALUE)
1142 pkt.pts = av_rescale_q(enc->coded_frame->pts, enc->time_base, ost->st->time_base);
1143 pkt.flags |= AV_PKT_FLAG_KEY;
1144 write_frame(s, &pkt, enc, ost->bitstream_filters);
1146 ost->sync_opts += enc->frame_size;
1150 av_init_packet(&pkt);
1152 ost->sync_opts += size_out / (osize * enc->channels);
1154 /* output a pcm frame */
1155 /* determine the size of the coded buffer */
1158 size_out = size_out * coded_bps / 8;
1160 if (size_out > audio_out_size) {
1161 av_log(NULL, AV_LOG_FATAL, "Internal error, buffer size too small\n");
1165 // FIXME pass ost->sync_opts as AVFrame.pts in avcodec_encode_audio()
1166 ret = avcodec_encode_audio(enc, audio_out, size_out,
1169 av_log(NULL, AV_LOG_FATAL, "Audio encoding failed\n");
1173 pkt.stream_index = ost->index;
1174 pkt.data = audio_out;
1176 if (enc->coded_frame && enc->coded_frame->pts != AV_NOPTS_VALUE)
1177 pkt.pts = av_rescale_q(enc->coded_frame->pts, enc->time_base, ost->st->time_base);
1178 pkt.flags |= AV_PKT_FLAG_KEY;
1179 write_frame(s, &pkt, enc, ost->bitstream_filters);
1183 static void pre_process_video_frame(InputStream *ist, AVPicture *picture, void **bufp)
1185 AVCodecContext *dec;
1186 AVPicture *picture2;
1187 AVPicture picture_tmp;
1190 dec = ist->st->codec;
1192 /* deinterlace : must be done before any resize */
1193 if (do_deinterlace) {
1196 /* create temporary picture */
1197 size = avpicture_get_size(dec->pix_fmt, dec->width, dec->height);
1198 buf = av_malloc(size);
1202 picture2 = &picture_tmp;
1203 avpicture_fill(picture2, buf, dec->pix_fmt, dec->width, dec->height);
1205 if (avpicture_deinterlace(picture2, picture,
1206 dec->pix_fmt, dec->width, dec->height) < 0) {
1207 /* if error, do not deinterlace */
1208 av_log(NULL, AV_LOG_WARNING, "Deinterlacing failed\n");
1217 if (picture != picture2)
1218 *picture = *picture2;
1222 static void do_subtitle_out(AVFormatContext *s,
1228 static uint8_t *subtitle_out = NULL;
1229 int subtitle_out_max_size = 1024 * 1024;
1230 int subtitle_out_size, nb, i;
1231 AVCodecContext *enc;
1234 if (pts == AV_NOPTS_VALUE) {
1235 av_log(NULL, AV_LOG_ERROR, "Subtitle packets must have a pts\n");
1241 enc = ost->st->codec;
1243 if (!subtitle_out) {
1244 subtitle_out = av_malloc(subtitle_out_max_size);
1247 /* Note: DVB subtitle need one packet to draw them and one other
1248 packet to clear them */
1249 /* XXX: signal it in the codec context ? */
1250 if (enc->codec_id == CODEC_ID_DVB_SUBTITLE)
1255 for (i = 0; i < nb; i++) {
1256 sub->pts = av_rescale_q(pts, ist->st->time_base, AV_TIME_BASE_Q);
1257 // start_display_time is required to be 0
1258 sub->pts += av_rescale_q(sub->start_display_time, (AVRational){ 1, 1000 }, AV_TIME_BASE_Q);
1259 sub->end_display_time -= sub->start_display_time;
1260 sub->start_display_time = 0;
1261 subtitle_out_size = avcodec_encode_subtitle(enc, subtitle_out,
1262 subtitle_out_max_size, sub);
1263 if (subtitle_out_size < 0) {
1264 av_log(NULL, AV_LOG_FATAL, "Subtitle encoding failed\n");
1268 av_init_packet(&pkt);
1269 pkt.stream_index = ost->index;
1270 pkt.data = subtitle_out;
1271 pkt.size = subtitle_out_size;
1272 pkt.pts = av_rescale_q(sub->pts, AV_TIME_BASE_Q, ost->st->time_base);
1273 if (enc->codec_id == CODEC_ID_DVB_SUBTITLE) {
1274 /* XXX: the pts correction is handled here. Maybe handling
1275 it in the codec would be better */
1277 pkt.pts += 90 * sub->start_display_time;
1279 pkt.pts += 90 * sub->end_display_time;
1281 write_frame(s, &pkt, ost->st->codec, ost->bitstream_filters);
1285 static int bit_buffer_size = 1024 * 256;
1286 static uint8_t *bit_buffer = NULL;
1288 static void do_video_resample(OutputStream *ost,
1290 AVFrame *in_picture,
1291 AVFrame **out_picture)
1293 int resample_changed = 0;
1294 AVCodecContext *dec = ist->st->codec;
1295 AVCodecContext *enc = ost->st->codec;
1296 *out_picture = in_picture;
1298 resample_changed = ost->resample_width != dec->width ||
1299 ost->resample_height != dec->height ||
1300 ost->resample_pix_fmt != dec->pix_fmt;
1302 #if !CONFIG_AVFILTER
1303 if (resample_changed) {
1304 av_log(NULL, AV_LOG_INFO,
1305 "Input stream #%d:%d frame changed from size:%dx%d fmt:%s to size:%dx%d fmt:%s\n",
1306 ist->file_index, ist->st->index,
1307 ost->resample_width, ost->resample_height, av_get_pix_fmt_name(ost->resample_pix_fmt),
1308 dec->width , dec->height , av_get_pix_fmt_name(dec->pix_fmt));
1309 ost->resample_width = dec->width;
1310 ost->resample_height = dec->height;
1311 ost->resample_pix_fmt = dec->pix_fmt;
1314 ost->video_resample = dec->width != enc->width ||
1315 dec->height != enc->height ||
1316 dec->pix_fmt != enc->pix_fmt;
1318 if (ost->video_resample) {
1319 *out_picture = &ost->resample_frame;
1320 if (!ost->img_resample_ctx || resample_changed) {
1321 /* initialize the destination picture */
1322 if (!ost->resample_frame.data[0]) {
1323 avcodec_get_frame_defaults(&ost->resample_frame);
1324 if (avpicture_alloc((AVPicture *)&ost->resample_frame, enc->pix_fmt,
1325 enc->width, enc->height)) {
1326 fprintf(stderr, "Cannot allocate temp picture, check pix fmt\n");
1330 /* initialize a new scaler context */
1331 sws_freeContext(ost->img_resample_ctx);
1332 ost->img_resample_ctx = sws_getContext(dec->width, dec->height, dec->pix_fmt,
1333 enc->width, enc->height, enc->pix_fmt,
1334 ost->sws_flags, NULL, NULL, NULL);
1335 if (ost->img_resample_ctx == NULL) {
1336 av_log(NULL, AV_LOG_FATAL, "Cannot get resampling context\n");
1340 sws_scale(ost->img_resample_ctx, in_picture->data, in_picture->linesize,
1341 0, ost->resample_height, (*out_picture)->data, (*out_picture)->linesize);
1344 if (resample_changed) {
1345 avfilter_graph_free(&ost->graph);
1346 if (configure_video_filters(ist, ost)) {
1347 av_log(NULL, AV_LOG_FATAL, "Error reinitializing filters!\n");
1352 if (resample_changed) {
1353 ost->resample_width = dec->width;
1354 ost->resample_height = dec->height;
1355 ost->resample_pix_fmt = dec->pix_fmt;
1360 static void do_video_out(AVFormatContext *s,
1363 AVFrame *in_picture,
1364 int *frame_size, float quality)
1366 int nb_frames, i, ret, format_video_sync;
1367 AVFrame *final_picture;
1368 AVCodecContext *enc;
1371 enc = ost->st->codec;
1373 sync_ipts = get_sync_ipts(ost) / av_q2d(enc->time_base);
1375 /* by default, we output a single frame */
1380 format_video_sync = video_sync_method;
1381 if (format_video_sync < 0)
1382 format_video_sync = (s->oformat->flags & AVFMT_NOTIMESTAMPS) ? 0 :
1383 (s->oformat->flags & AVFMT_VARIABLE_FPS) ? 2 : 1;
1385 if (format_video_sync) {
1386 double vdelta = sync_ipts - ost->sync_opts;
1387 // FIXME set to 0.5 after we fix some dts/pts bugs like in avidec.c
1390 else if (format_video_sync == 2) {
1391 if (vdelta <= -0.6) {
1393 } else if (vdelta > 0.6)
1394 ost->sync_opts = lrintf(sync_ipts);
1395 } else if (vdelta > 1.1)
1396 nb_frames = lrintf(vdelta);
1397 //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);
1398 if (nb_frames == 0) {
1400 av_log(NULL, AV_LOG_VERBOSE, "*** drop!\n");
1401 } else if (nb_frames > 1) {
1402 nb_frames_dup += nb_frames - 1;
1403 av_log(NULL, AV_LOG_VERBOSE, "*** %d dup!\n", nb_frames - 1);
1406 ost->sync_opts = lrintf(sync_ipts);
1408 nb_frames = FFMIN(nb_frames, ost->max_frames - ost->frame_number);
1412 do_video_resample(ost, ist, in_picture, &final_picture);
1414 /* duplicates frame if needed */
1415 for (i = 0; i < nb_frames; i++) {
1417 av_init_packet(&pkt);
1418 pkt.stream_index = ost->index;
1420 if (s->oformat->flags & AVFMT_RAWPICTURE &&
1421 enc->codec->id == CODEC_ID_RAWVIDEO) {
1422 /* raw pictures are written as AVPicture structure to
1423 avoid any copies. We support temporarily the older
1425 enc->coded_frame->interlaced_frame = in_picture->interlaced_frame;
1426 enc->coded_frame->top_field_first = in_picture->top_field_first;
1427 pkt.data = (uint8_t *)final_picture;
1428 pkt.size = sizeof(AVPicture);
1429 pkt.pts = av_rescale_q(ost->sync_opts, enc->time_base, ost->st->time_base);
1430 pkt.flags |= AV_PKT_FLAG_KEY;
1432 write_frame(s, &pkt, ost->st->codec, ost->bitstream_filters);
1434 AVFrame big_picture;
1436 big_picture = *final_picture;
1437 /* better than nothing: use input picture interlaced
1439 big_picture.interlaced_frame = in_picture->interlaced_frame;
1440 if (ost->st->codec->flags & (CODEC_FLAG_INTERLACED_DCT|CODEC_FLAG_INTERLACED_ME)) {
1441 if (ost->top_field_first == -1)
1442 big_picture.top_field_first = in_picture->top_field_first;
1444 big_picture.top_field_first = !!ost->top_field_first;
1447 /* handles same_quant here. This is not correct because it may
1448 not be a global option */
1449 big_picture.quality = quality;
1450 if (!enc->me_threshold)
1451 big_picture.pict_type = 0;
1452 // big_picture.pts = AV_NOPTS_VALUE;
1453 big_picture.pts = ost->sync_opts;
1454 // big_picture.pts= av_rescale(ost->sync_opts, AV_TIME_BASE*(int64_t)enc->time_base.num, enc->time_base.den);
1455 // av_log(NULL, AV_LOG_DEBUG, "%"PRId64" -> encoder\n", ost->sync_opts);
1456 if (ost->forced_kf_index < ost->forced_kf_count &&
1457 big_picture.pts >= ost->forced_kf_pts[ost->forced_kf_index]) {
1458 big_picture.pict_type = AV_PICTURE_TYPE_I;
1459 ost->forced_kf_index++;
1461 ret = avcodec_encode_video(enc,
1462 bit_buffer, bit_buffer_size,
1465 av_log(NULL, AV_LOG_FATAL, "Video encoding failed\n");
1470 pkt.data = bit_buffer;
1472 if (enc->coded_frame->pts != AV_NOPTS_VALUE)
1473 pkt.pts = av_rescale_q(enc->coded_frame->pts, enc->time_base, ost->st->time_base);
1474 /*av_log(NULL, AV_LOG_DEBUG, "encoder -> %"PRId64"/%"PRId64"\n",
1475 pkt.pts != AV_NOPTS_VALUE ? av_rescale(pkt.pts, enc->time_base.den, AV_TIME_BASE*(int64_t)enc->time_base.num) : -1,
1476 pkt.dts != AV_NOPTS_VALUE ? av_rescale(pkt.dts, enc->time_base.den, AV_TIME_BASE*(int64_t)enc->time_base.num) : -1);*/
1478 if (enc->coded_frame->key_frame)
1479 pkt.flags |= AV_PKT_FLAG_KEY;
1480 write_frame(s, &pkt, ost->st->codec, ost->bitstream_filters);
1483 // fprintf(stderr,"\nFrame: %3d size: %5d type: %d",
1484 // enc->frame_number-1, ret, enc->pict_type);
1485 /* if two pass, output log */
1486 if (ost->logfile && enc->stats_out) {
1487 fprintf(ost->logfile, "%s", enc->stats_out);
1492 ost->frame_number++;
1496 static double psnr(double d)
1498 return -10.0 * log(d) / log(10.0);
1501 static void do_video_stats(AVFormatContext *os, OutputStream *ost,
1504 AVCodecContext *enc;
1506 double ti1, bitrate, avg_bitrate;
1508 /* this is executed just the first time do_video_stats is called */
1510 vstats_file = fopen(vstats_filename, "w");
1517 enc = ost->st->codec;
1518 if (enc->codec_type == AVMEDIA_TYPE_VIDEO) {
1519 frame_number = ost->frame_number;
1520 fprintf(vstats_file, "frame= %5d q= %2.1f ", frame_number, enc->coded_frame->quality / (float)FF_QP2LAMBDA);
1521 if (enc->flags&CODEC_FLAG_PSNR)
1522 fprintf(vstats_file, "PSNR= %6.2f ", psnr(enc->coded_frame->error[0] / (enc->width * enc->height * 255.0 * 255.0)));
1524 fprintf(vstats_file,"f_size= %6d ", frame_size);
1525 /* compute pts value */
1526 ti1 = ost->sync_opts * av_q2d(enc->time_base);
1530 bitrate = (frame_size * 8) / av_q2d(enc->time_base) / 1000.0;
1531 avg_bitrate = (double)(video_size * 8) / ti1 / 1000.0;
1532 fprintf(vstats_file, "s_size= %8.0fkB time= %0.3f br= %7.1fkbits/s avg_br= %7.1fkbits/s ",
1533 (double)video_size / 1024, ti1, bitrate, avg_bitrate);
1534 fprintf(vstats_file, "type= %c\n", av_get_picture_type_char(enc->coded_frame->pict_type));
1538 static void print_report(OutputFile *output_files,
1539 OutputStream *ost_table, int nb_ostreams,
1540 int is_last_report, int64_t timer_start)
1544 AVFormatContext *oc;
1546 AVCodecContext *enc;
1547 int frame_number, vid, i;
1549 int64_t pts = INT64_MAX;
1550 static int64_t last_time = -1;
1551 static int qp_histogram[52];
1552 int hours, mins, secs, us;
1554 if (!print_stats && !is_last_report)
1557 if (!is_last_report) {
1559 /* display the report every 0.5 seconds */
1560 cur_time = av_gettime();
1561 if (last_time == -1) {
1562 last_time = cur_time;
1565 if ((cur_time - last_time) < 500000)
1567 last_time = cur_time;
1571 oc = output_files[0].ctx;
1573 total_size = avio_size(oc->pb);
1574 if (total_size < 0) // FIXME improve avio_size() so it works with non seekable output too
1575 total_size = avio_tell(oc->pb);
1579 for (i = 0; i < nb_ostreams; i++) {
1581 ost = &ost_table[i];
1582 enc = ost->st->codec;
1583 if (!ost->stream_copy && enc->coded_frame)
1584 q = enc->coded_frame->quality / (float)FF_QP2LAMBDA;
1585 if (vid && enc->codec_type == AVMEDIA_TYPE_VIDEO) {
1586 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "q=%2.1f ", q);
1588 if (!vid && enc->codec_type == AVMEDIA_TYPE_VIDEO) {
1589 float t = (av_gettime() - timer_start) / 1000000.0;
1591 frame_number = ost->frame_number;
1592 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "frame=%5d fps=%3d q=%3.1f ",
1593 frame_number, (t > 1) ? (int)(frame_number / t + 0.5) : 0, q);
1595 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "L");
1599 if (qp >= 0 && qp < FF_ARRAY_ELEMS(qp_histogram))
1601 for (j = 0; j < 32; j++)
1602 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "%X", (int)lrintf(log(qp_histogram[j] + 1) / log(2)));
1604 if (enc->flags&CODEC_FLAG_PSNR) {
1606 double error, error_sum = 0;
1607 double scale, scale_sum = 0;
1608 char type[3] = { 'Y','U','V' };
1609 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "PSNR=");
1610 for (j = 0; j < 3; j++) {
1611 if (is_last_report) {
1612 error = enc->error[j];
1613 scale = enc->width * enc->height * 255.0 * 255.0 * frame_number;
1615 error = enc->coded_frame->error[j];
1616 scale = enc->width * enc->height * 255.0 * 255.0;
1622 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "%c:%2.2f ", type[j], psnr(error / scale));
1624 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "*:%2.2f ", psnr(error_sum / scale_sum));
1628 /* compute min output value */
1629 pts = FFMIN(pts, av_rescale_q(ost->st->pts.val,
1630 ost->st->time_base, AV_TIME_BASE_Q));
1633 secs = pts / AV_TIME_BASE;
1634 us = pts % AV_TIME_BASE;
1640 bitrate = pts ? total_size * 8 / (pts / 1000.0) : 0;
1642 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
1643 "size=%8.0fkB time=", total_size / 1024.0);
1644 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
1645 "%02d:%02d:%02d.%02d ", hours, mins, secs,
1646 (100 * us) / AV_TIME_BASE);
1647 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
1648 "bitrate=%6.1fkbits/s", bitrate);
1650 if (nb_frames_dup || nb_frames_drop)
1651 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), " dup=%d drop=%d",
1652 nb_frames_dup, nb_frames_drop);
1654 av_log(NULL, AV_LOG_INFO, "%s \r", buf);
1658 if (is_last_report) {
1659 int64_t raw= audio_size + video_size + extra_size;
1660 av_log(NULL, AV_LOG_INFO, "\n");
1661 av_log(NULL, AV_LOG_INFO, "video:%1.0fkB audio:%1.0fkB global headers:%1.0fkB muxing overhead %f%%\n",
1662 video_size / 1024.0,
1663 audio_size / 1024.0,
1664 extra_size / 1024.0,
1665 100.0 * (total_size - raw) / raw
1670 static void flush_encoders(OutputStream *ost_table, int nb_ostreams)
1674 for (i = 0; i < nb_ostreams; i++) {
1675 OutputStream *ost = &ost_table[i];
1676 AVCodecContext *enc = ost->st->codec;
1677 AVFormatContext *os = output_files[ost->file_index].ctx;
1679 if (!ost->encoding_needed)
1682 if (ost->st->codec->codec_type == AVMEDIA_TYPE_AUDIO && enc->frame_size <= 1)
1684 if (ost->st->codec->codec_type == AVMEDIA_TYPE_VIDEO && (os->oformat->flags & AVFMT_RAWPICTURE) && enc->codec->id == CODEC_ID_RAWVIDEO)
1690 av_init_packet(&pkt);
1691 pkt.stream_index = ost->index;
1693 switch (ost->st->codec->codec_type) {
1694 case AVMEDIA_TYPE_AUDIO:
1695 fifo_bytes = av_fifo_size(ost->fifo);
1697 /* encode any samples remaining in fifo */
1698 if (fifo_bytes > 0) {
1699 int osize = av_get_bytes_per_sample(enc->sample_fmt);
1700 int fs_tmp = enc->frame_size;
1702 av_fifo_generic_read(ost->fifo, audio_buf, fifo_bytes, NULL);
1703 if (enc->codec->capabilities & CODEC_CAP_SMALL_LAST_FRAME) {
1704 enc->frame_size = fifo_bytes / (osize * enc->channels);
1706 int frame_bytes = enc->frame_size*osize*enc->channels;
1707 if (allocated_audio_buf_size < frame_bytes)
1709 generate_silence(audio_buf+fifo_bytes, enc->sample_fmt, frame_bytes - fifo_bytes);
1712 ret = avcodec_encode_audio(enc, bit_buffer, bit_buffer_size, (short *)audio_buf);
1713 pkt.duration = av_rescale((int64_t)enc->frame_size*ost->st->time_base.den,
1714 ost->st->time_base.num, enc->sample_rate);
1715 enc->frame_size = fs_tmp;
1718 ret = avcodec_encode_audio(enc, bit_buffer, bit_buffer_size, NULL);
1721 av_log(NULL, AV_LOG_FATAL, "Audio encoding failed\n");
1725 pkt.flags |= AV_PKT_FLAG_KEY;
1727 case AVMEDIA_TYPE_VIDEO:
1728 ret = avcodec_encode_video(enc, bit_buffer, bit_buffer_size, NULL);
1730 av_log(NULL, AV_LOG_FATAL, "Video encoding failed\n");
1734 if (enc->coded_frame && enc->coded_frame->key_frame)
1735 pkt.flags |= AV_PKT_FLAG_KEY;
1736 if (ost->logfile && enc->stats_out) {
1737 fprintf(ost->logfile, "%s", enc->stats_out);
1746 pkt.data = bit_buffer;
1748 if (enc->coded_frame && enc->coded_frame->pts != AV_NOPTS_VALUE)
1749 pkt.pts = av_rescale_q(enc->coded_frame->pts, enc->time_base, ost->st->time_base);
1750 write_frame(os, &pkt, ost->st->codec, ost->bitstream_filters);
1756 * Check whether a packet from ist should be written into ost at this time
1758 static int check_output_constraints(InputStream *ist, OutputStream *ost)
1760 OutputFile *of = &output_files[ost->file_index];
1761 int ist_index = ist - input_streams;
1763 if (ost->source_index != ist_index)
1766 if (of->start_time && ist->pts < of->start_time)
1769 if (of->recording_time != INT64_MAX &&
1770 av_compare_ts(ist->pts, AV_TIME_BASE_Q, of->recording_time + of->start_time,
1771 (AVRational){ 1, 1000000 }) >= 0) {
1772 ost->is_past_recording_time = 1;
1779 static void do_streamcopy(InputStream *ist, OutputStream *ost, const AVPacket *pkt)
1781 OutputFile *of = &output_files[ost->file_index];
1782 int64_t ost_tb_start_time = av_rescale_q(of->start_time, AV_TIME_BASE_Q, ost->st->time_base);
1786 av_init_packet(&opkt);
1788 if ((!ost->frame_number && !(pkt->flags & AV_PKT_FLAG_KEY)) &&
1789 !ost->copy_initial_nonkeyframes)
1792 /* force the input stream PTS */
1793 if (ost->st->codec->codec_type == AVMEDIA_TYPE_AUDIO)
1794 audio_size += pkt->size;
1795 else if (ost->st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
1796 video_size += pkt->size;
1800 opkt.stream_index = ost->index;
1801 if (pkt->pts != AV_NOPTS_VALUE)
1802 opkt.pts = av_rescale_q(pkt->pts, ist->st->time_base, ost->st->time_base) - ost_tb_start_time;
1804 opkt.pts = AV_NOPTS_VALUE;
1806 if (pkt->dts == AV_NOPTS_VALUE)
1807 opkt.dts = av_rescale_q(ist->pts, AV_TIME_BASE_Q, ost->st->time_base);
1809 opkt.dts = av_rescale_q(pkt->dts, ist->st->time_base, ost->st->time_base);
1810 opkt.dts -= ost_tb_start_time;
1812 opkt.duration = av_rescale_q(pkt->duration, ist->st->time_base, ost->st->time_base);
1813 opkt.flags = pkt->flags;
1815 // FIXME remove the following 2 lines they shall be replaced by the bitstream filters
1816 if ( ost->st->codec->codec_id != CODEC_ID_H264
1817 && ost->st->codec->codec_id != CODEC_ID_MPEG1VIDEO
1818 && ost->st->codec->codec_id != CODEC_ID_MPEG2VIDEO
1820 if (av_parser_change(ist->st->parser, ost->st->codec, &opkt.data, &opkt.size, pkt->data, pkt->size, pkt->flags & AV_PKT_FLAG_KEY))
1821 opkt.destruct = av_destruct_packet;
1823 opkt.data = pkt->data;
1824 opkt.size = pkt->size;
1826 if (of->ctx->oformat->flags & AVFMT_RAWPICTURE) {
1827 /* store AVPicture in AVPacket, as expected by the output format */
1828 avpicture_fill(&pict, opkt.data, ost->st->codec->pix_fmt, ost->st->codec->width, ost->st->codec->height);
1829 opkt.data = (uint8_t *)&pict;
1830 opkt.size = sizeof(AVPicture);
1831 opkt.flags |= AV_PKT_FLAG_KEY;
1834 write_frame(of->ctx, &opkt, ost->st->codec, ost->bitstream_filters);
1835 ost->st->codec->frame_number++;
1836 ost->frame_number++;
1837 av_free_packet(&opkt);
1840 static void rate_emu_sleep(InputStream *ist)
1842 if (input_files[ist->file_index].rate_emu) {
1843 int64_t pts = av_rescale(ist->pts, 1000000, AV_TIME_BASE);
1844 int64_t now = av_gettime() - ist->start;
1850 static int transcode_audio(InputStream *ist, AVPacket *pkt, int *got_output)
1852 AVFrame *decoded_frame;
1853 AVCodecContext *avctx = ist->st->codec;
1854 int bps = av_get_bytes_per_sample(ist->st->codec->sample_fmt);
1857 if (!ist->decoded_frame && !(ist->decoded_frame = avcodec_alloc_frame()))
1858 return AVERROR(ENOMEM);
1860 avcodec_get_frame_defaults(ist->decoded_frame);
1861 decoded_frame = ist->decoded_frame;
1863 ret = avcodec_decode_audio4(avctx, decoded_frame, got_output, pkt);
1869 /* no audio frame */
1873 /* if the decoder provides a pts, use it instead of the last packet pts.
1874 the decoder could be delaying output by a packet or more. */
1875 if (decoded_frame->pts != AV_NOPTS_VALUE)
1876 ist->next_pts = decoded_frame->pts;
1878 /* increment next_pts to use for the case where the input stream does not
1879 have timestamps or there are multiple frames in the packet */
1880 ist->next_pts += ((int64_t)AV_TIME_BASE * decoded_frame->nb_samples) /
1883 // preprocess audio (volume)
1884 if (audio_volume != 256) {
1885 int decoded_data_size = decoded_frame->nb_samples * avctx->channels * bps;
1886 void *samples = decoded_frame->data[0];
1887 switch (avctx->sample_fmt) {
1888 case AV_SAMPLE_FMT_U8:
1890 uint8_t *volp = samples;
1891 for (i = 0; i < (decoded_data_size / sizeof(*volp)); i++) {
1892 int v = (((*volp - 128) * audio_volume + 128) >> 8) + 128;
1893 *volp++ = av_clip_uint8(v);
1897 case AV_SAMPLE_FMT_S16:
1899 int16_t *volp = samples;
1900 for (i = 0; i < (decoded_data_size / sizeof(*volp)); i++) {
1901 int v = ((*volp) * audio_volume + 128) >> 8;
1902 *volp++ = av_clip_int16(v);
1906 case AV_SAMPLE_FMT_S32:
1908 int32_t *volp = samples;
1909 for (i = 0; i < (decoded_data_size / sizeof(*volp)); i++) {
1910 int64_t v = (((int64_t)*volp * audio_volume + 128) >> 8);
1911 *volp++ = av_clipl_int32(v);
1915 case AV_SAMPLE_FMT_FLT:
1917 float *volp = samples;
1918 float scale = audio_volume / 256.f;
1919 for (i = 0; i < (decoded_data_size / sizeof(*volp)); i++) {
1924 case AV_SAMPLE_FMT_DBL:
1926 double *volp = samples;
1927 double scale = audio_volume / 256.;
1928 for (i = 0; i < (decoded_data_size / sizeof(*volp)); i++) {
1934 av_log(NULL, AV_LOG_FATAL,
1935 "Audio volume adjustment on sample format %s is not supported.\n",
1936 av_get_sample_fmt_name(ist->st->codec->sample_fmt));
1941 rate_emu_sleep(ist);
1943 for (i = 0; i < nb_output_streams; i++) {
1944 OutputStream *ost = &output_streams[i];
1946 if (!check_output_constraints(ist, ost) || !ost->encoding_needed)
1948 do_audio_out(output_files[ost->file_index].ctx, ost, ist, decoded_frame);
1954 static int transcode_video(InputStream *ist, AVPacket *pkt, int *got_output, int64_t *pkt_pts)
1956 AVFrame *decoded_frame, *filtered_frame = NULL;
1957 void *buffer_to_free = NULL;
1961 int frame_available = 1;
1964 if (!ist->decoded_frame && !(ist->decoded_frame = avcodec_alloc_frame()))
1965 return AVERROR(ENOMEM);
1967 avcodec_get_frame_defaults(ist->decoded_frame);
1968 decoded_frame = ist->decoded_frame;
1969 pkt->pts = *pkt_pts;
1970 pkt->dts = ist->pts;
1971 *pkt_pts = AV_NOPTS_VALUE;
1973 ret = avcodec_decode_video2(ist->st->codec,
1974 decoded_frame, got_output, pkt);
1978 quality = same_quant ? decoded_frame->quality : 0;
1980 /* no picture yet */
1983 ist->next_pts = ist->pts = decoded_frame->best_effort_timestamp;
1985 ist->next_pts += av_rescale_q(pkt->duration, ist->st->time_base, AV_TIME_BASE_Q);
1986 else if (ist->st->codec->time_base.num != 0) {
1987 int ticks = ist->st->parser ? ist->st->parser->repeat_pict + 1 :
1988 ist->st->codec->ticks_per_frame;
1989 ist->next_pts += ((int64_t)AV_TIME_BASE *
1990 ist->st->codec->time_base.num * ticks) /
1991 ist->st->codec->time_base.den;
1994 pre_process_video_frame(ist, (AVPicture *)decoded_frame, &buffer_to_free);
1996 rate_emu_sleep(ist);
1998 for (i = 0; i < nb_output_streams; i++) {
1999 OutputStream *ost = &output_streams[i];
2002 if (!check_output_constraints(ist, ost) || !ost->encoding_needed)
2006 if (!decoded_frame->sample_aspect_ratio.num)
2007 decoded_frame->sample_aspect_ratio = ist->st->sample_aspect_ratio;
2008 decoded_frame->pts = ist->pts;
2009 if (ist->st->codec->codec->capabilities & CODEC_CAP_DR1) {
2010 FrameBuffer *buf = decoded_frame->opaque;
2011 AVFilterBufferRef *fb = avfilter_get_video_buffer_ref_from_arrays(
2012 decoded_frame->data, decoded_frame->linesize,
2013 AV_PERM_READ | AV_PERM_PRESERVE,
2014 ist->st->codec->width, ist->st->codec->height,
2015 ist->st->codec->pix_fmt);
2017 avfilter_copy_frame_props(fb, decoded_frame);
2019 fb->buf->priv = buf;
2020 fb->buf->free = filter_release_buffer;
2023 av_buffersrc_buffer(ost->input_video_filter, fb);
2025 av_vsrc_buffer_add_frame(ost->input_video_filter, decoded_frame, AV_VSRC_BUF_FLAG_OVERWRITE);
2027 if (!ist->filtered_frame && !(ist->filtered_frame = avcodec_alloc_frame())) {
2028 av_free(buffer_to_free);
2029 return AVERROR(ENOMEM);
2031 avcodec_get_frame_defaults(ist->filtered_frame);
2032 filtered_frame = ist->filtered_frame;
2034 frame_available = avfilter_poll_frame(ost->output_video_filter->inputs[0]);
2035 while (frame_available) {
2036 if (ost->output_video_filter) {
2037 AVRational ist_pts_tb = ost->output_video_filter->inputs[0]->time_base;
2038 if (av_buffersink_get_buffer_ref(ost->output_video_filter, &ost->picref, 0) < 0)
2041 avfilter_fill_frame_from_video_buffer_ref(filtered_frame, ost->picref);
2042 ist->pts = av_rescale_q(ost->picref->pts, ist_pts_tb, AV_TIME_BASE_Q);
2045 if (ost->picref->video && !ost->frame_aspect_ratio)
2046 ost->st->codec->sample_aspect_ratio = ost->picref->video->sample_aspect_ratio;
2048 filtered_frame = decoded_frame;
2051 do_video_out(output_files[ost->file_index].ctx, ost, ist, filtered_frame, &frame_size,
2052 same_quant ? quality : ost->st->codec->global_quality);
2053 if (vstats_filename && frame_size)
2054 do_video_stats(output_files[ost->file_index].ctx, ost, frame_size);
2057 frame_available = ost->output_video_filter && avfilter_poll_frame(ost->output_video_filter->inputs[0]);
2059 avfilter_unref_buffer(ost->picref);
2064 av_free(buffer_to_free);
2068 static int transcode_subtitles(InputStream *ist, AVPacket *pkt, int *got_output)
2070 AVSubtitle subtitle;
2071 int i, ret = avcodec_decode_subtitle2(ist->st->codec,
2072 &subtitle, got_output, pkt);
2078 rate_emu_sleep(ist);
2080 for (i = 0; i < nb_output_streams; i++) {
2081 OutputStream *ost = &output_streams[i];
2083 if (!check_output_constraints(ist, ost) || !ost->encoding_needed)
2086 do_subtitle_out(output_files[ost->file_index].ctx, ost, ist, &subtitle, pkt->pts);
2089 avsubtitle_free(&subtitle);
2093 /* pkt = NULL means EOF (needed to flush decoder buffers) */
2094 static int output_packet(InputStream *ist,
2095 OutputStream *ost_table, int nb_ostreams,
2096 const AVPacket *pkt)
2100 int64_t pkt_pts = AV_NOPTS_VALUE;
2103 if (ist->next_pts == AV_NOPTS_VALUE)
2104 ist->next_pts = ist->pts;
2108 av_init_packet(&avpkt);
2116 if (pkt->dts != AV_NOPTS_VALUE)
2117 ist->next_pts = ist->pts = av_rescale_q(pkt->dts, ist->st->time_base, AV_TIME_BASE_Q);
2118 if (pkt->pts != AV_NOPTS_VALUE)
2119 pkt_pts = av_rescale_q(pkt->pts, ist->st->time_base, AV_TIME_BASE_Q);
2121 // while we have more to decode or while the decoder did output something on EOF
2122 while (ist->decoding_needed && (avpkt.size > 0 || (!pkt && got_output))) {
2126 ist->pts = ist->next_pts;
2128 if (avpkt.size && avpkt.size != pkt->size) {
2129 av_log(NULL, ist->showed_multi_packet_warning ? AV_LOG_VERBOSE : AV_LOG_WARNING,
2130 "Multiple frames in a packet from stream %d\n", pkt->stream_index);
2131 ist->showed_multi_packet_warning = 1;
2134 switch (ist->st->codec->codec_type) {
2135 case AVMEDIA_TYPE_AUDIO:
2136 ret = transcode_audio (ist, &avpkt, &got_output);
2138 case AVMEDIA_TYPE_VIDEO:
2139 ret = transcode_video (ist, &avpkt, &got_output, &pkt_pts);
2141 case AVMEDIA_TYPE_SUBTITLE:
2142 ret = transcode_subtitles(ist, &avpkt, &got_output);
2150 // touch data and size only if not EOF
2160 /* handle stream copy */
2161 if (!ist->decoding_needed) {
2162 rate_emu_sleep(ist);
2163 ist->pts = ist->next_pts;
2164 switch (ist->st->codec->codec_type) {
2165 case AVMEDIA_TYPE_AUDIO:
2166 ist->next_pts += ((int64_t)AV_TIME_BASE * ist->st->codec->frame_size) /
2167 ist->st->codec->sample_rate;
2169 case AVMEDIA_TYPE_VIDEO:
2170 if (ist->st->codec->time_base.num != 0) {
2171 int ticks = ist->st->parser ? ist->st->parser->repeat_pict + 1 : ist->st->codec->ticks_per_frame;
2172 ist->next_pts += ((int64_t)AV_TIME_BASE *
2173 ist->st->codec->time_base.num * ticks) /
2174 ist->st->codec->time_base.den;
2179 for (i = 0; pkt && i < nb_ostreams; i++) {
2180 OutputStream *ost = &ost_table[i];
2182 if (!check_output_constraints(ist, ost) || ost->encoding_needed)
2185 do_streamcopy(ist, ost, pkt);
2191 static void print_sdp(OutputFile *output_files, int n)
2195 AVFormatContext **avc = av_malloc(sizeof(*avc) * n);
2199 for (i = 0; i < n; i++)
2200 avc[i] = output_files[i].ctx;
2202 av_sdp_create(avc, n, sdp, sizeof(sdp));
2203 printf("SDP:\n%s\n", sdp);
2208 static int init_input_stream(int ist_index, OutputStream *output_streams, int nb_output_streams,
2209 char *error, int error_len)
2212 InputStream *ist = &input_streams[ist_index];
2213 if (ist->decoding_needed) {
2214 AVCodec *codec = ist->dec;
2216 snprintf(error, error_len, "Decoder (codec id %d) not found for input stream #%d:%d",
2217 ist->st->codec->codec_id, ist->file_index, ist->st->index);
2218 return AVERROR(EINVAL);
2221 if (codec->type == AVMEDIA_TYPE_VIDEO && codec->capabilities & CODEC_CAP_DR1) {
2222 ist->st->codec->get_buffer = codec_get_buffer;
2223 ist->st->codec->release_buffer = codec_release_buffer;
2224 ist->st->codec->opaque = ist;
2227 if (avcodec_open2(ist->st->codec, codec, &ist->opts) < 0) {
2228 snprintf(error, error_len, "Error while opening decoder for input stream #%d:%d",
2229 ist->file_index, ist->st->index);
2230 return AVERROR(EINVAL);
2232 assert_codec_experimental(ist->st->codec, 0);
2233 assert_avoptions(ist->opts);
2236 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;
2237 ist->next_pts = AV_NOPTS_VALUE;
2243 static int transcode_init(OutputFile *output_files,
2244 int nb_output_files,
2245 InputFile *input_files,
2248 int ret = 0, i, j, k;
2249 AVFormatContext *oc;
2250 AVCodecContext *codec, *icodec;
2256 /* init framerate emulation */
2257 for (i = 0; i < nb_input_files; i++) {
2258 InputFile *ifile = &input_files[i];
2259 if (ifile->rate_emu)
2260 for (j = 0; j < ifile->nb_streams; j++)
2261 input_streams[j + ifile->ist_index].start = av_gettime();
2264 /* output stream init */
2265 for (i = 0; i < nb_output_files; i++) {
2266 oc = output_files[i].ctx;
2267 if (!oc->nb_streams && !(oc->oformat->flags & AVFMT_NOSTREAMS)) {
2268 av_dump_format(oc, i, oc->filename, 1);
2269 av_log(NULL, AV_LOG_ERROR, "Output file #%d does not contain any stream\n", i);
2270 return AVERROR(EINVAL);
2274 /* for each output stream, we compute the right encoding parameters */
2275 for (i = 0; i < nb_output_streams; i++) {
2276 ost = &output_streams[i];
2277 oc = output_files[ost->file_index].ctx;
2278 ist = &input_streams[ost->source_index];
2280 if (ost->attachment_filename)
2283 codec = ost->st->codec;
2284 icodec = ist->st->codec;
2286 ost->st->disposition = ist->st->disposition;
2287 codec->bits_per_raw_sample = icodec->bits_per_raw_sample;
2288 codec->chroma_sample_location = icodec->chroma_sample_location;
2290 if (ost->stream_copy) {
2291 uint64_t extra_size = (uint64_t)icodec->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE;
2293 if (extra_size > INT_MAX) {
2294 return AVERROR(EINVAL);
2297 /* if stream_copy is selected, no need to decode or encode */
2298 codec->codec_id = icodec->codec_id;
2299 codec->codec_type = icodec->codec_type;
2301 if (!codec->codec_tag) {
2302 if (!oc->oformat->codec_tag ||
2303 av_codec_get_id (oc->oformat->codec_tag, icodec->codec_tag) == codec->codec_id ||
2304 av_codec_get_tag(oc->oformat->codec_tag, icodec->codec_id) <= 0)
2305 codec->codec_tag = icodec->codec_tag;
2308 codec->bit_rate = icodec->bit_rate;
2309 codec->rc_max_rate = icodec->rc_max_rate;
2310 codec->rc_buffer_size = icodec->rc_buffer_size;
2311 codec->field_order = icodec->field_order;
2312 codec->extradata = av_mallocz(extra_size);
2313 if (!codec->extradata) {
2314 return AVERROR(ENOMEM);
2316 memcpy(codec->extradata, icodec->extradata, icodec->extradata_size);
2318 codec->extradata_size = icodec->extradata_size;
2320 codec->time_base = icodec->time_base;
2321 codec->time_base.num *= icodec->ticks_per_frame;
2322 av_reduce(&codec->time_base.num, &codec->time_base.den,
2323 codec->time_base.num, codec->time_base.den, INT_MAX);
2325 codec->time_base = ist->st->time_base;
2327 switch (codec->codec_type) {
2328 case AVMEDIA_TYPE_AUDIO:
2329 if (audio_volume != 256) {
2330 av_log(NULL, AV_LOG_FATAL, "-acodec copy and -vol are incompatible (frames are not decoded)\n");
2333 codec->channel_layout = icodec->channel_layout;
2334 codec->sample_rate = icodec->sample_rate;
2335 codec->channels = icodec->channels;
2336 codec->frame_size = icodec->frame_size;
2337 codec->audio_service_type = icodec->audio_service_type;
2338 codec->block_align = icodec->block_align;
2340 case AVMEDIA_TYPE_VIDEO:
2341 codec->pix_fmt = icodec->pix_fmt;
2342 codec->width = icodec->width;
2343 codec->height = icodec->height;
2344 codec->has_b_frames = icodec->has_b_frames;
2345 if (!codec->sample_aspect_ratio.num) {
2346 codec->sample_aspect_ratio =
2347 ost->st->sample_aspect_ratio =
2348 ist->st->sample_aspect_ratio.num ? ist->st->sample_aspect_ratio :
2349 ist->st->codec->sample_aspect_ratio.num ?
2350 ist->st->codec->sample_aspect_ratio : (AVRational){0, 1};
2353 case AVMEDIA_TYPE_SUBTITLE:
2354 codec->width = icodec->width;
2355 codec->height = icodec->height;
2357 case AVMEDIA_TYPE_DATA:
2358 case AVMEDIA_TYPE_ATTACHMENT:
2365 ost->enc = avcodec_find_encoder(ost->st->codec->codec_id);
2367 ist->decoding_needed = 1;
2368 ost->encoding_needed = 1;
2370 switch (codec->codec_type) {
2371 case AVMEDIA_TYPE_AUDIO:
2372 ost->fifo = av_fifo_alloc(1024);
2374 return AVERROR(ENOMEM);
2376 ost->reformat_pair = MAKE_SFMT_PAIR(AV_SAMPLE_FMT_NONE,AV_SAMPLE_FMT_NONE);
2378 if (!codec->sample_rate)
2379 codec->sample_rate = icodec->sample_rate;
2380 choose_sample_rate(ost->st, ost->enc);
2381 codec->time_base = (AVRational){ 1, codec->sample_rate };
2383 if (codec->sample_fmt == AV_SAMPLE_FMT_NONE)
2384 codec->sample_fmt = icodec->sample_fmt;
2385 choose_sample_fmt(ost->st, ost->enc);
2387 if (!codec->channels) {
2388 codec->channels = icodec->channels;
2389 codec->channel_layout = icodec->channel_layout;
2391 if (av_get_channel_layout_nb_channels(codec->channel_layout) != codec->channels)
2392 codec->channel_layout = 0;
2394 ost->audio_resample = codec-> sample_rate != icodec->sample_rate || audio_sync_method > 1;
2395 icodec->request_channels = codec-> channels;
2396 ost->resample_sample_fmt = icodec->sample_fmt;
2397 ost->resample_sample_rate = icodec->sample_rate;
2398 ost->resample_channels = icodec->channels;
2400 case AVMEDIA_TYPE_VIDEO:
2401 if (codec->pix_fmt == PIX_FMT_NONE)
2402 codec->pix_fmt = icodec->pix_fmt;
2403 choose_pixel_fmt(ost->st, ost->enc);
2405 if (ost->st->codec->pix_fmt == PIX_FMT_NONE) {
2406 av_log(NULL, AV_LOG_FATAL, "Video pixel format is unknown, stream cannot be encoded\n");
2410 if (!codec->width || !codec->height) {
2411 codec->width = icodec->width;
2412 codec->height = icodec->height;
2415 ost->video_resample = codec->width != icodec->width ||
2416 codec->height != icodec->height ||
2417 codec->pix_fmt != icodec->pix_fmt;
2418 if (ost->video_resample) {
2419 codec->bits_per_raw_sample= frame_bits_per_raw_sample;
2422 ost->resample_height = icodec->height;
2423 ost->resample_width = icodec->width;
2424 ost->resample_pix_fmt = icodec->pix_fmt;
2426 if (!ost->frame_rate.num)
2427 ost->frame_rate = ist->st->r_frame_rate.num ? ist->st->r_frame_rate : (AVRational) { 25, 1 };
2428 if (ost->enc && ost->enc->supported_framerates && !ost->force_fps) {
2429 int idx = av_find_nearest_q_idx(ost->frame_rate, ost->enc->supported_framerates);
2430 ost->frame_rate = ost->enc->supported_framerates[idx];
2432 codec->time_base = (AVRational){ost->frame_rate.den, ost->frame_rate.num};
2433 if( av_q2d(codec->time_base) < 0.001 && video_sync_method
2434 && (video_sync_method==1 || (video_sync_method<0 && !(oc->oformat->flags & AVFMT_VARIABLE_FPS)))){
2435 av_log(oc, AV_LOG_WARNING, "Frame rate very high for a muxer not effciciently supporting it.\n"
2436 "Please consider specifiying a lower framerate, a different muxer or -vsync 2\n");
2440 if (configure_video_filters(ist, ost)) {
2441 av_log(NULL, AV_LOG_FATAL, "Error opening filters!\n");
2446 case AVMEDIA_TYPE_SUBTITLE:
2453 if (codec->codec_id != CODEC_ID_H264 &&
2454 (codec->flags & (CODEC_FLAG_PASS1 | CODEC_FLAG_PASS2))) {
2455 char logfilename[1024];
2458 snprintf(logfilename, sizeof(logfilename), "%s-%d.log",
2459 pass_logfilename_prefix ? pass_logfilename_prefix : DEFAULT_PASS_LOGFILENAME_PREFIX,
2461 if (codec->flags & CODEC_FLAG_PASS1) {
2462 f = fopen(logfilename, "wb");
2464 av_log(NULL, AV_LOG_FATAL, "Cannot write log file '%s' for pass-1 encoding: %s\n",
2465 logfilename, strerror(errno));
2471 size_t logbuffer_size;
2472 if (cmdutils_read_file(logfilename, &logbuffer, &logbuffer_size) < 0) {
2473 av_log(NULL, AV_LOG_FATAL, "Error reading log file '%s' for pass-2 encoding\n",
2477 codec->stats_in = logbuffer;
2481 if (codec->codec_type == AVMEDIA_TYPE_VIDEO) {
2482 /* maximum video buffer size is 6-bytes per pixel, plus DPX header size */
2483 int size = codec->width * codec->height;
2484 bit_buffer_size = FFMAX(bit_buffer_size, 6 * size + 1664);
2489 bit_buffer = av_malloc(bit_buffer_size);
2491 av_log(NULL, AV_LOG_ERROR, "Cannot allocate %d bytes output buffer\n",
2493 return AVERROR(ENOMEM);
2496 /* open each encoder */
2497 for (i = 0; i < nb_output_streams; i++) {
2498 ost = &output_streams[i];
2499 if (ost->encoding_needed) {
2500 AVCodec *codec = ost->enc;
2501 AVCodecContext *dec = input_streams[ost->source_index].st->codec;
2503 snprintf(error, sizeof(error), "Encoder (codec id %d) not found for output stream #%d:%d",
2504 ost->st->codec->codec_id, ost->file_index, ost->index);
2505 ret = AVERROR(EINVAL);
2508 if (dec->subtitle_header) {
2509 ost->st->codec->subtitle_header = av_malloc(dec->subtitle_header_size);
2510 if (!ost->st->codec->subtitle_header) {
2511 ret = AVERROR(ENOMEM);
2514 memcpy(ost->st->codec->subtitle_header, dec->subtitle_header, dec->subtitle_header_size);
2515 ost->st->codec->subtitle_header_size = dec->subtitle_header_size;
2517 if (avcodec_open2(ost->st->codec, codec, &ost->opts) < 0) {
2518 snprintf(error, sizeof(error), "Error while opening encoder for output stream #%d:%d - maybe incorrect parameters such as bit_rate, rate, width or height",
2519 ost->file_index, ost->index);
2520 ret = AVERROR(EINVAL);
2523 assert_codec_experimental(ost->st->codec, 1);
2524 assert_avoptions(ost->opts);
2525 if (ost->st->codec->bit_rate && ost->st->codec->bit_rate < 1000)
2526 av_log(NULL, AV_LOG_WARNING, "The bitrate parameter is set too low."
2527 "It takes bits/s as argument, not kbits/s\n");
2528 extra_size += ost->st->codec->extradata_size;
2530 if (ost->st->codec->me_threshold)
2531 input_streams[ost->source_index].st->codec->debug |= FF_DEBUG_MV;
2535 /* init input streams */
2536 for (i = 0; i < nb_input_streams; i++)
2537 if ((ret = init_input_stream(i, output_streams, nb_output_streams, error, sizeof(error))) < 0)
2540 /* discard unused programs */
2541 for (i = 0; i < nb_input_files; i++) {
2542 InputFile *ifile = &input_files[i];
2543 for (j = 0; j < ifile->ctx->nb_programs; j++) {
2544 AVProgram *p = ifile->ctx->programs[j];
2545 int discard = AVDISCARD_ALL;
2547 for (k = 0; k < p->nb_stream_indexes; k++)
2548 if (!input_streams[ifile->ist_index + p->stream_index[k]].discard) {
2549 discard = AVDISCARD_DEFAULT;
2552 p->discard = discard;
2556 /* open files and write file headers */
2557 for (i = 0; i < nb_output_files; i++) {
2558 oc = output_files[i].ctx;
2559 oc->interrupt_callback = int_cb;
2560 if (avformat_write_header(oc, &output_files[i].opts) < 0) {
2561 snprintf(error, sizeof(error), "Could not write header for output file #%d (incorrect codec parameters ?)", i);
2562 ret = AVERROR(EINVAL);
2565 // assert_avoptions(output_files[i].opts);
2566 if (strcmp(oc->oformat->name, "rtp")) {
2572 /* dump the file output parameters - cannot be done before in case
2574 for (i = 0; i < nb_output_files; i++) {
2575 av_dump_format(output_files[i].ctx, i, output_files[i].ctx->filename, 1);
2578 /* dump the stream mapping */
2579 av_log(NULL, AV_LOG_INFO, "Stream mapping:\n");
2580 for (i = 0; i < nb_output_streams; i++) {
2581 ost = &output_streams[i];
2583 if (ost->attachment_filename) {
2584 /* an attached file */
2585 av_log(NULL, AV_LOG_INFO, " File %s -> Stream #%d:%d\n",
2586 ost->attachment_filename, ost->file_index, ost->index);
2589 av_log(NULL, AV_LOG_INFO, " Stream #%d:%d -> #%d:%d",
2590 input_streams[ost->source_index].file_index,
2591 input_streams[ost->source_index].st->index,
2594 if (ost->sync_ist != &input_streams[ost->source_index])
2595 av_log(NULL, AV_LOG_INFO, " [sync #%d:%d]",
2596 ost->sync_ist->file_index,
2597 ost->sync_ist->st->index);
2598 if (ost->stream_copy)
2599 av_log(NULL, AV_LOG_INFO, " (copy)");
2601 av_log(NULL, AV_LOG_INFO, " (%s -> %s)", input_streams[ost->source_index].dec ?
2602 input_streams[ost->source_index].dec->name : "?",
2603 ost->enc ? ost->enc->name : "?");
2604 av_log(NULL, AV_LOG_INFO, "\n");
2608 av_log(NULL, AV_LOG_ERROR, "%s\n", error);
2613 print_sdp(output_files, nb_output_files);
2620 * The following code is the main loop of the file converter
2622 static int transcode(OutputFile *output_files,
2623 int nb_output_files,
2624 InputFile *input_files,
2628 AVFormatContext *is, *os;
2632 int no_packet_count = 0;
2633 int64_t timer_start;
2636 if (!(no_packet = av_mallocz(nb_input_files)))
2639 ret = transcode_init(output_files, nb_output_files, input_files, nb_input_files);
2644 av_log(NULL, AV_LOG_INFO, "Press [q] to stop, [?] for help\n");
2645 avio_set_interrupt_cb(decode_interrupt_cb);
2649 timer_start = av_gettime();
2651 for (; received_sigterm == 0;) {
2652 int file_index, ist_index;
2657 ipts_min = INT64_MAX;
2659 /* if 'q' pressed, exits */
2663 /* read_key() returns 0 on EOF */
2667 if (key == '+') av_log_set_level(av_log_get_level()+10);
2668 if (key == '-') av_log_set_level(av_log_get_level()-10);
2669 if (key == 's') qp_hist ^= 1;
2672 do_hex_dump = do_pkt_dump = 0;
2673 } else if(do_pkt_dump){
2677 av_log_set_level(AV_LOG_DEBUG);
2679 if (key == 'd' || key == 'D'){
2682 debug = input_streams[0].st->codec->debug<<1;
2683 if(!debug) debug = 1;
2684 while(debug & (FF_DEBUG_DCT_COEFF|FF_DEBUG_VIS_QP|FF_DEBUG_VIS_MB_TYPE)) //unsupported, would just crash
2687 scanf("%d", &debug);
2688 for(i=0;i<nb_input_streams;i++) {
2689 input_streams[i].st->codec->debug = debug;
2691 for(i=0;i<nb_output_streams;i++) {
2692 ost = &output_streams[i];
2693 ost->st->codec->debug = debug;
2695 if(debug) av_log_set_level(AV_LOG_DEBUG);
2696 fprintf(stderr,"debug=%d\n", debug);
2699 fprintf(stderr, "key function\n"
2700 "? show this help\n"
2701 "+ increase verbosity\n"
2702 "- decrease verbosity\n"
2703 "D cycle through available debug modes\n"
2704 "h dump packets/hex press to cycle through the 3 states\n"
2706 "s Show QP histogram\n"
2711 /* select the stream that we must read now by looking at the
2712 smallest output pts */
2714 for (i = 0; i < nb_output_streams; i++) {
2718 ost = &output_streams[i];
2719 of = &output_files[ost->file_index];
2720 os = output_files[ost->file_index].ctx;
2721 ist = &input_streams[ost->source_index];
2722 if (ost->is_past_recording_time || no_packet[ist->file_index] ||
2723 (os->pb && avio_tell(os->pb) >= of->limit_filesize))
2725 opts = ost->st->pts.val * av_q2d(ost->st->time_base);
2727 if (!input_files[ist->file_index].eof_reached) {
2728 if (ipts < ipts_min) {
2731 file_index = ist->file_index;
2733 if (opts < opts_min) {
2735 if (!input_sync) file_index = ist->file_index;
2738 if (ost->frame_number >= ost->max_frames) {
2740 for (j = 0; j < of->ctx->nb_streams; j++)
2741 output_streams[of->ost_index + j].is_past_recording_time = 1;
2745 /* if none, if is finished */
2746 if (file_index < 0) {
2747 if (no_packet_count) {
2748 no_packet_count = 0;
2749 memset(no_packet, 0, nb_input_files);
2756 /* read a frame from it and output it in the fifo */
2757 is = input_files[file_index].ctx;
2758 ret = av_read_frame(is, &pkt);
2759 if (ret == AVERROR(EAGAIN)) {
2760 no_packet[file_index] = 1;
2765 input_files[file_index].eof_reached = 1;
2772 no_packet_count = 0;
2773 memset(no_packet, 0, nb_input_files);
2776 av_pkt_dump_log2(NULL, AV_LOG_DEBUG, &pkt, do_hex_dump,
2777 is->streams[pkt.stream_index]);
2779 /* the following test is needed in case new streams appear
2780 dynamically in stream : we ignore them */
2781 if (pkt.stream_index >= input_files[file_index].nb_streams)
2782 goto discard_packet;
2783 ist_index = input_files[file_index].ist_index + pkt.stream_index;
2784 ist = &input_streams[ist_index];
2786 goto discard_packet;
2788 if (pkt.dts != AV_NOPTS_VALUE)
2789 pkt.dts += av_rescale_q(input_files[ist->file_index].ts_offset, AV_TIME_BASE_Q, ist->st->time_base);
2790 if (pkt.pts != AV_NOPTS_VALUE)
2791 pkt.pts += av_rescale_q(input_files[ist->file_index].ts_offset, AV_TIME_BASE_Q, ist->st->time_base);
2793 if (pkt.pts != AV_NOPTS_VALUE)
2794 pkt.pts *= ist->ts_scale;
2795 if (pkt.dts != AV_NOPTS_VALUE)
2796 pkt.dts *= ist->ts_scale;
2798 //fprintf(stderr, "next:%"PRId64" dts:%"PRId64" off:%"PRId64" %d\n",
2800 // pkt.dts, input_files[ist->file_index].ts_offset,
2801 // ist->st->codec->codec_type);
2802 if (pkt.dts != AV_NOPTS_VALUE && ist->next_pts != AV_NOPTS_VALUE
2803 && (is->iformat->flags & AVFMT_TS_DISCONT)) {
2804 int64_t pkt_dts = av_rescale_q(pkt.dts, ist->st->time_base, AV_TIME_BASE_Q);
2805 int64_t delta = pkt_dts - ist->next_pts;
2806 if ((FFABS(delta) > 1LL * dts_delta_threshold * AV_TIME_BASE || pkt_dts + 1 < ist->pts) && !copy_ts) {
2807 input_files[ist->file_index].ts_offset -= delta;
2808 av_log(NULL, AV_LOG_DEBUG,
2809 "timestamp discontinuity %"PRId64", new offset= %"PRId64"\n",
2810 delta, input_files[ist->file_index].ts_offset);
2811 pkt.dts-= av_rescale_q(delta, AV_TIME_BASE_Q, ist->st->time_base);
2812 if (pkt.pts != AV_NOPTS_VALUE)
2813 pkt.pts-= av_rescale_q(delta, AV_TIME_BASE_Q, ist->st->time_base);
2817 // fprintf(stderr,"read #%d.%d size=%d\n", ist->file_index, ist->st->index, pkt.size);
2818 if (output_packet(ist, output_streams, nb_output_streams, &pkt) < 0) {
2820 av_log(NULL, AV_LOG_ERROR, "Error while decoding stream #%d:%d\n",
2821 ist->file_index, ist->st->index);
2824 av_free_packet(&pkt);
2829 av_free_packet(&pkt);
2831 /* dump report by using the output first video and audio streams */
2832 print_report(output_files, output_streams, nb_output_streams, 0, timer_start);
2835 /* at the end of stream, we must flush the decoder buffers */
2836 for (i = 0; i < nb_input_streams; i++) {
2837 ist = &input_streams[i];
2838 if (ist->decoding_needed) {
2839 output_packet(ist, output_streams, nb_output_streams, NULL);
2842 flush_encoders(output_streams, nb_output_streams);
2846 /* write the trailer if needed and close file */
2847 for (i = 0; i < nb_output_files; i++) {
2848 os = output_files[i].ctx;
2849 av_write_trailer(os);
2852 /* dump report by using the first video and audio streams */
2853 print_report(output_files, output_streams, nb_output_streams, 1, timer_start);
2855 /* close each encoder */
2856 for (i = 0; i < nb_output_streams; i++) {
2857 ost = &output_streams[i];
2858 if (ost->encoding_needed) {
2859 av_freep(&ost->st->codec->stats_in);
2860 avcodec_close(ost->st->codec);
2863 avfilter_graph_free(&ost->graph);
2867 /* close each decoder */
2868 for (i = 0; i < nb_input_streams; i++) {
2869 ist = &input_streams[i];
2870 if (ist->decoding_needed) {
2871 avcodec_close(ist->st->codec);
2879 av_freep(&bit_buffer);
2880 av_freep(&no_packet);
2882 if (output_streams) {
2883 for (i = 0; i < nb_output_streams; i++) {
2884 ost = &output_streams[i];
2886 if (ost->stream_copy)
2887 av_freep(&ost->st->codec->extradata);
2889 fclose(ost->logfile);
2890 ost->logfile = NULL;
2892 av_fifo_free(ost->fifo); /* works even if fifo is not
2893 initialized but set to zero */
2894 av_freep(&ost->st->codec->subtitle_header);
2895 av_free(ost->resample_frame.data[0]);
2896 av_free(ost->forced_kf_pts);
2897 if (ost->video_resample)
2898 sws_freeContext(ost->img_resample_ctx);
2900 audio_resample_close(ost->resample);
2901 if (ost->reformat_ctx)
2902 av_audio_convert_free(ost->reformat_ctx);
2903 av_dict_free(&ost->opts);
2910 static double parse_frame_aspect_ratio(const char *arg)
2917 p = strchr(arg, ':');
2919 x = strtol(arg, &end, 10);
2921 y = strtol(end + 1, &end, 10);
2923 ar = (double)x / (double)y;
2925 ar = strtod(arg, NULL);
2928 av_log(NULL, AV_LOG_FATAL, "Incorrect aspect ratio specification.\n");
2934 static int opt_audio_codec(OptionsContext *o, const char *opt, const char *arg)
2936 return parse_option(o, "codec:a", arg, options);
2939 static int opt_video_codec(OptionsContext *o, const char *opt, const char *arg)
2941 return parse_option(o, "codec:v", arg, options);
2944 static int opt_subtitle_codec(OptionsContext *o, const char *opt, const char *arg)
2946 return parse_option(o, "codec:s", arg, options);
2949 static int opt_data_codec(OptionsContext *o, const char *opt, const char *arg)
2951 return parse_option(o, "codec:d", arg, options);
2954 static int opt_map(OptionsContext *o, const char *opt, const char *arg)
2956 StreamMap *m = NULL;
2957 int i, negative = 0, file_idx;
2958 int sync_file_idx = -1, sync_stream_idx;
2966 map = av_strdup(arg);
2968 /* parse sync stream first, just pick first matching stream */
2969 if (sync = strchr(map, ',')) {
2971 sync_file_idx = strtol(sync + 1, &sync, 0);
2972 if (sync_file_idx >= nb_input_files || sync_file_idx < 0) {
2973 av_log(NULL, AV_LOG_FATAL, "Invalid sync file index: %d.\n", sync_file_idx);
2978 for (i = 0; i < input_files[sync_file_idx].nb_streams; i++)
2979 if (check_stream_specifier(input_files[sync_file_idx].ctx,
2980 input_files[sync_file_idx].ctx->streams[i], sync) == 1) {
2981 sync_stream_idx = i;
2984 if (i == input_files[sync_file_idx].nb_streams) {
2985 av_log(NULL, AV_LOG_FATAL, "Sync stream specification in map %s does not "
2986 "match any streams.\n", arg);
2992 file_idx = strtol(map, &p, 0);
2993 if (file_idx >= nb_input_files || file_idx < 0) {
2994 av_log(NULL, AV_LOG_FATAL, "Invalid input file index: %d.\n", file_idx);
2998 /* disable some already defined maps */
2999 for (i = 0; i < o->nb_stream_maps; i++) {
3000 m = &o->stream_maps[i];
3001 if (file_idx == m->file_index &&
3002 check_stream_specifier(input_files[m->file_index].ctx,
3003 input_files[m->file_index].ctx->streams[m->stream_index],
3004 *p == ':' ? p + 1 : p) > 0)
3008 for (i = 0; i < input_files[file_idx].nb_streams; i++) {
3009 if (check_stream_specifier(input_files[file_idx].ctx, input_files[file_idx].ctx->streams[i],
3010 *p == ':' ? p + 1 : p) <= 0)
3012 o->stream_maps = grow_array(o->stream_maps, sizeof(*o->stream_maps),
3013 &o->nb_stream_maps, o->nb_stream_maps + 1);
3014 m = &o->stream_maps[o->nb_stream_maps - 1];
3016 m->file_index = file_idx;
3017 m->stream_index = i;
3019 if (sync_file_idx >= 0) {
3020 m->sync_file_index = sync_file_idx;
3021 m->sync_stream_index = sync_stream_idx;
3023 m->sync_file_index = file_idx;
3024 m->sync_stream_index = i;
3029 av_log(NULL, AV_LOG_FATAL, "Stream map '%s' matches no streams.\n", arg);
3037 static int opt_attach(OptionsContext *o, const char *opt, const char *arg)
3039 o->attachments = grow_array(o->attachments, sizeof(*o->attachments),
3040 &o->nb_attachments, o->nb_attachments + 1);
3041 o->attachments[o->nb_attachments - 1] = arg;
3046 * Parse a metadata specifier in arg.
3047 * @param type metadata type is written here -- g(lobal)/s(tream)/c(hapter)/p(rogram)
3048 * @param index for type c/p, chapter/program index is written here
3049 * @param stream_spec for type s, the stream specifier is written here
3051 static void parse_meta_type(char *arg, char *type, int *index, const char **stream_spec)
3059 if (*(++arg) && *arg != ':') {
3060 av_log(NULL, AV_LOG_FATAL, "Invalid metadata specifier %s.\n", arg);
3063 *stream_spec = *arg == ':' ? arg + 1 : "";
3067 if (*(++arg) == ':')
3068 *index = strtol(++arg, NULL, 0);
3071 av_log(NULL, AV_LOG_FATAL, "Invalid metadata type %c.\n", *arg);
3078 static int copy_metadata(char *outspec, char *inspec, AVFormatContext *oc, AVFormatContext *ic, OptionsContext *o)
3080 AVDictionary **meta_in = NULL;
3081 AVDictionary **meta_out;
3083 char type_in, type_out;
3084 const char *istream_spec = NULL, *ostream_spec = NULL;
3085 int idx_in = 0, idx_out = 0;
3087 parse_meta_type(inspec, &type_in, &idx_in, &istream_spec);
3088 parse_meta_type(outspec, &type_out, &idx_out, &ostream_spec);
3090 if (type_in == 'g' || type_out == 'g')
3091 o->metadata_global_manual = 1;
3092 if (type_in == 's' || type_out == 's')
3093 o->metadata_streams_manual = 1;
3094 if (type_in == 'c' || type_out == 'c')
3095 o->metadata_chapters_manual = 1;
3097 #define METADATA_CHECK_INDEX(index, nb_elems, desc)\
3098 if ((index) < 0 || (index) >= (nb_elems)) {\
3099 av_log(NULL, AV_LOG_FATAL, "Invalid %s index %d while processing metadata maps.\n",\
3104 #define SET_DICT(type, meta, context, index)\
3107 meta = &context->metadata;\
3110 METADATA_CHECK_INDEX(index, context->nb_chapters, "chapter")\
3111 meta = &context->chapters[index]->metadata;\
3114 METADATA_CHECK_INDEX(index, context->nb_programs, "program")\
3115 meta = &context->programs[index]->metadata;\
3119 SET_DICT(type_in, meta_in, ic, idx_in);
3120 SET_DICT(type_out, meta_out, oc, idx_out);
3122 /* for input streams choose first matching stream */
3123 if (type_in == 's') {
3124 for (i = 0; i < ic->nb_streams; i++) {
3125 if ((ret = check_stream_specifier(ic, ic->streams[i], istream_spec)) > 0) {
3126 meta_in = &ic->streams[i]->metadata;
3132 av_log(NULL, AV_LOG_FATAL, "Stream specifier %s does not match any streams.\n", istream_spec);
3137 if (type_out == 's') {
3138 for (i = 0; i < oc->nb_streams; i++) {
3139 if ((ret = check_stream_specifier(oc, oc->streams[i], ostream_spec)) > 0) {
3140 meta_out = &oc->streams[i]->metadata;
3141 av_dict_copy(meta_out, *meta_in, AV_DICT_DONT_OVERWRITE);
3146 av_dict_copy(meta_out, *meta_in, AV_DICT_DONT_OVERWRITE);
3151 static AVCodec *find_codec_or_die(const char *name, enum AVMediaType type, int encoder)
3153 const char *codec_string = encoder ? "encoder" : "decoder";
3157 avcodec_find_encoder_by_name(name) :
3158 avcodec_find_decoder_by_name(name);
3160 av_log(NULL, AV_LOG_FATAL, "Unknown %s '%s'\n", codec_string, name);
3163 if (codec->type != type) {
3164 av_log(NULL, AV_LOG_FATAL, "Invalid %s type '%s'\n", codec_string, name);
3170 static AVCodec *choose_decoder(OptionsContext *o, AVFormatContext *s, AVStream *st)
3172 char *codec_name = NULL;
3174 MATCH_PER_STREAM_OPT(codec_names, str, codec_name, s, st);
3176 AVCodec *codec = find_codec_or_die(codec_name, st->codec->codec_type, 0);
3177 st->codec->codec_id = codec->id;
3180 return avcodec_find_decoder(st->codec->codec_id);
3184 * Add all the streams from the given input file to the global
3185 * list of input streams.
3187 static void add_input_streams(OptionsContext *o, AVFormatContext *ic)
3189 int i, rfps, rfps_base;
3191 for (i = 0; i < ic->nb_streams; i++) {
3192 AVStream *st = ic->streams[i];
3193 AVCodecContext *dec = st->codec;
3196 input_streams = grow_array(input_streams, sizeof(*input_streams), &nb_input_streams, nb_input_streams + 1);
3197 ist = &input_streams[nb_input_streams - 1];
3199 ist->file_index = nb_input_files;
3201 ist->opts = filter_codec_opts(codec_opts, choose_decoder(o, ic, st), ic, st);
3203 ist->ts_scale = 1.0;
3204 MATCH_PER_STREAM_OPT(ts_scale, dbl, ist->ts_scale, ic, st);
3206 ist->dec = choose_decoder(o, ic, st);
3208 switch (dec->codec_type) {
3209 case AVMEDIA_TYPE_AUDIO:
3211 ist->dec = avcodec_find_decoder(dec->codec_id);
3212 if(o->audio_disable)
3213 st->discard = AVDISCARD_ALL;
3215 case AVMEDIA_TYPE_VIDEO:
3217 ist->dec = avcodec_find_decoder(dec->codec_id);
3218 rfps = ic->streams[i]->r_frame_rate.num;
3219 rfps_base = ic->streams[i]->r_frame_rate.den;
3221 dec->flags |= CODEC_FLAG_EMU_EDGE;
3224 if (dec->time_base.den != rfps * dec->ticks_per_frame || dec->time_base.num != rfps_base) {
3226 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",
3227 i, (float)dec->time_base.den / dec->time_base.num, dec->time_base.den, dec->time_base.num,
3228 (float)rfps / rfps_base, rfps, rfps_base);
3231 if (o->video_disable)
3232 st->discard = AVDISCARD_ALL;
3233 else if (video_discard)
3234 st->discard = video_discard;
3236 case AVMEDIA_TYPE_DATA:
3238 case AVMEDIA_TYPE_SUBTITLE:
3240 ist->dec = avcodec_find_decoder(dec->codec_id);
3241 if(o->subtitle_disable)
3242 st->discard = AVDISCARD_ALL;
3244 case AVMEDIA_TYPE_ATTACHMENT:
3245 case AVMEDIA_TYPE_UNKNOWN:
3253 static void assert_file_overwrite(const char *filename)
3255 if ((!file_overwrite || no_file_overwrite) &&
3256 (strchr(filename, ':') == NULL || filename[1] == ':' ||
3257 av_strstart(filename, "file:", NULL))) {
3258 if (avio_check(filename, 0) == 0) {
3259 if (!using_stdin && (!no_file_overwrite || file_overwrite)) {
3260 fprintf(stderr,"File '%s' already exists. Overwrite ? [y/N] ", filename);
3262 if (!read_yesno()) {
3263 fprintf(stderr, "Not overwriting - exiting\n");
3268 fprintf(stderr,"File '%s' already exists. Exiting.\n", filename);
3275 static void dump_attachment(AVStream *st, const char *filename)
3278 AVIOContext *out = NULL;
3279 AVDictionaryEntry *e;
3281 if (!st->codec->extradata_size) {
3282 av_log(NULL, AV_LOG_WARNING, "No extradata to dump in stream #%d:%d.\n",
3283 nb_input_files - 1, st->index);
3286 if (!*filename && (e = av_dict_get(st->metadata, "filename", NULL, 0)))
3287 filename = e->value;
3289 av_log(NULL, AV_LOG_FATAL, "No filename specified and no 'filename' tag"
3290 "in stream #%d:%d.\n", nb_input_files - 1, st->index);
3294 assert_file_overwrite(filename);
3296 if ((ret = avio_open2(&out, filename, AVIO_FLAG_WRITE, &int_cb, NULL)) < 0) {
3297 av_log(NULL, AV_LOG_FATAL, "Could not open file %s for writing.\n",
3302 avio_write(out, st->codec->extradata, st->codec->extradata_size);
3307 static int opt_input_file(OptionsContext *o, const char *opt, const char *filename)
3309 AVFormatContext *ic;
3310 AVInputFormat *file_iformat = NULL;
3314 AVDictionary **opts;
3315 int orig_nb_streams; // number of streams before avformat_find_stream_info
3318 if (!(file_iformat = av_find_input_format(o->format))) {
3319 av_log(NULL, AV_LOG_FATAL, "Unknown input format: '%s'\n", o->format);
3324 if (!strcmp(filename, "-"))
3327 using_stdin |= !strncmp(filename, "pipe:", 5) ||
3328 !strcmp(filename, "/dev/stdin");
3330 /* get default parameters from command line */
3331 ic = avformat_alloc_context();
3333 print_error(filename, AVERROR(ENOMEM));
3336 if (o->nb_audio_sample_rate) {
3337 snprintf(buf, sizeof(buf), "%d", o->audio_sample_rate[o->nb_audio_sample_rate - 1].u.i);
3338 av_dict_set(&format_opts, "sample_rate", buf, 0);
3340 if (o->nb_audio_channels) {
3341 snprintf(buf, sizeof(buf), "%d", o->audio_channels[o->nb_audio_channels - 1].u.i);
3342 av_dict_set(&format_opts, "channels", buf, 0);
3344 if (o->nb_frame_rates) {
3345 av_dict_set(&format_opts, "framerate", o->frame_rates[o->nb_frame_rates - 1].u.str, 0);
3347 if (o->nb_frame_sizes) {
3348 av_dict_set(&format_opts, "video_size", o->frame_sizes[o->nb_frame_sizes - 1].u.str, 0);
3350 if (o->nb_frame_pix_fmts)
3351 av_dict_set(&format_opts, "pixel_format", o->frame_pix_fmts[o->nb_frame_pix_fmts - 1].u.str, 0);
3353 ic->flags |= AVFMT_FLAG_NONBLOCK;
3354 ic->interrupt_callback = int_cb;
3356 /* open the input file with generic avformat function */
3357 err = avformat_open_input(&ic, filename, file_iformat, &format_opts);
3359 print_error(filename, err);
3362 assert_avoptions(format_opts);
3364 /* apply forced codec ids */
3365 for (i = 0; i < ic->nb_streams; i++)
3366 choose_decoder(o, ic, ic->streams[i]);
3368 /* Set AVCodecContext options for avformat_find_stream_info */
3369 opts = setup_find_stream_info_opts(ic, codec_opts);
3370 orig_nb_streams = ic->nb_streams;
3372 /* If not enough info to get the stream parameters, we decode the
3373 first frames to get it. (used in mpeg case for example) */
3374 ret = avformat_find_stream_info(ic, opts);
3376 av_log(NULL, AV_LOG_FATAL, "%s: could not find codec parameters\n", filename);
3377 avformat_close_input(&ic);
3381 timestamp = o->start_time;
3382 /* add the stream start time */
3383 if (ic->start_time != AV_NOPTS_VALUE)
3384 timestamp += ic->start_time;
3386 /* if seeking requested, we execute it */
3387 if (o->start_time != 0) {
3388 ret = av_seek_frame(ic, -1, timestamp, AVSEEK_FLAG_BACKWARD);
3390 av_log(NULL, AV_LOG_WARNING, "%s: could not seek to position %0.3f\n",
3391 filename, (double)timestamp / AV_TIME_BASE);
3395 /* update the current parameters so that they match the one of the input stream */
3396 add_input_streams(o, ic);
3398 /* dump the file content */
3399 av_dump_format(ic, nb_input_files, filename, 0);
3401 input_files = grow_array(input_files, sizeof(*input_files), &nb_input_files, nb_input_files + 1);
3402 input_files[nb_input_files - 1].ctx = ic;
3403 input_files[nb_input_files - 1].ist_index = nb_input_streams - ic->nb_streams;
3404 input_files[nb_input_files - 1].ts_offset = o->input_ts_offset - (copy_ts ? 0 : timestamp);
3405 input_files[nb_input_files - 1].nb_streams = ic->nb_streams;
3406 input_files[nb_input_files - 1].rate_emu = o->rate_emu;
3408 for (i = 0; i < o->nb_dump_attachment; i++) {
3411 for (j = 0; j < ic->nb_streams; j++) {
3412 AVStream *st = ic->streams[j];
3414 if (check_stream_specifier(ic, st, o->dump_attachment[i].specifier) == 1)
3415 dump_attachment(st, o->dump_attachment[i].u.str);
3419 for (i = 0; i < orig_nb_streams; i++)
3420 av_dict_free(&opts[i]);
3427 static void parse_forced_key_frames(char *kf, OutputStream *ost,
3428 AVCodecContext *avctx)
3434 for (p = kf; *p; p++)
3437 ost->forced_kf_count = n;
3438 ost->forced_kf_pts = av_malloc(sizeof(*ost->forced_kf_pts) * n);
3439 if (!ost->forced_kf_pts) {
3440 av_log(NULL, AV_LOG_FATAL, "Could not allocate forced key frames array.\n");
3443 for (i = 0; i < n; i++) {
3444 p = i ? strchr(p, ',') + 1 : kf;
3445 t = parse_time_or_die("force_key_frames", p, 1);
3446 ost->forced_kf_pts[i] = av_rescale_q(t, AV_TIME_BASE_Q, avctx->time_base);
3450 static uint8_t *get_line(AVIOContext *s)
3456 if (avio_open_dyn_buf(&line) < 0) {
3457 av_log(NULL, AV_LOG_FATAL, "Could not alloc buffer for reading preset.\n");
3461 while ((c = avio_r8(s)) && c != '\n')
3464 avio_close_dyn_buf(line, &buf);
3469 static int get_preset_file_2(const char *preset_name, const char *codec_name, AVIOContext **s)
3472 char filename[1000];
3473 const char *base[3] = { getenv("AVCONV_DATADIR"),
3478 for (i = 0; i < FF_ARRAY_ELEMS(base) && ret; i++) {
3482 snprintf(filename, sizeof(filename), "%s%s/%s-%s.avpreset", base[i],
3483 i != 1 ? "" : "/.avconv", codec_name, preset_name);
3484 ret = avio_open2(s, filename, AVIO_FLAG_READ, &int_cb, NULL);
3487 snprintf(filename, sizeof(filename), "%s%s/%s.avpreset", base[i],
3488 i != 1 ? "" : "/.avconv", preset_name);
3489 ret = avio_open2(s, filename, AVIO_FLAG_READ, &int_cb, NULL);
3495 static void choose_encoder(OptionsContext *o, AVFormatContext *s, OutputStream *ost)
3497 char *codec_name = NULL;
3499 MATCH_PER_STREAM_OPT(codec_names, str, codec_name, s, ost->st);
3501 ost->st->codec->codec_id = av_guess_codec(s->oformat, NULL, s->filename,
3502 NULL, ost->st->codec->codec_type);
3503 ost->enc = avcodec_find_encoder(ost->st->codec->codec_id);
3504 } else if (!strcmp(codec_name, "copy"))
3505 ost->stream_copy = 1;
3507 ost->enc = find_codec_or_die(codec_name, ost->st->codec->codec_type, 1);
3508 ost->st->codec->codec_id = ost->enc->id;
3512 static OutputStream *new_output_stream(OptionsContext *o, AVFormatContext *oc, enum AVMediaType type)
3515 AVStream *st = avformat_new_stream(oc, NULL);
3516 int idx = oc->nb_streams - 1, ret = 0;
3517 char *bsf = NULL, *next, *codec_tag = NULL;
3518 AVBitStreamFilterContext *bsfc, *bsfc_prev = NULL;
3520 char *buf = NULL, *arg = NULL, *preset = NULL;
3521 AVIOContext *s = NULL;
3524 av_log(NULL, AV_LOG_FATAL, "Could not alloc stream.\n");
3528 if (oc->nb_streams - 1 < o->nb_streamid_map)
3529 st->id = o->streamid_map[oc->nb_streams - 1];
3531 output_streams = grow_array(output_streams, sizeof(*output_streams), &nb_output_streams,
3532 nb_output_streams + 1);
3533 ost = &output_streams[nb_output_streams - 1];
3534 ost->file_index = nb_output_files;
3537 st->codec->codec_type = type;
3538 choose_encoder(o, oc, ost);
3540 ost->opts = filter_codec_opts(codec_opts, ost->enc, oc, st);
3543 avcodec_get_context_defaults3(st->codec, ost->enc);
3544 st->codec->codec_type = type; // XXX hack, avcodec_get_context_defaults2() sets type to unknown for stream copy
3546 MATCH_PER_STREAM_OPT(presets, str, preset, oc, st);
3547 if (preset && (!(ret = get_preset_file_2(preset, ost->enc->name, &s)))) {
3550 if (!buf[0] || buf[0] == '#') {
3554 if (!(arg = strchr(buf, '='))) {
3555 av_log(NULL, AV_LOG_FATAL, "Invalid line found in the preset file.\n");
3559 av_dict_set(&ost->opts, buf, arg, AV_DICT_DONT_OVERWRITE);
3561 } while (!s->eof_reached);
3565 av_log(NULL, AV_LOG_FATAL,
3566 "Preset %s specified for stream %d:%d, but could not be opened.\n",
3567 preset, ost->file_index, ost->index);
3571 ost->max_frames = INT64_MAX;
3572 MATCH_PER_STREAM_OPT(max_frames, i64, ost->max_frames, oc, st);
3574 MATCH_PER_STREAM_OPT(bitstream_filters, str, bsf, oc, st);
3576 if (next = strchr(bsf, ','))
3578 if (!(bsfc = av_bitstream_filter_init(bsf))) {
3579 av_log(NULL, AV_LOG_FATAL, "Unknown bitstream filter %s\n", bsf);
3583 bsfc_prev->next = bsfc;
3585 ost->bitstream_filters = bsfc;
3591 MATCH_PER_STREAM_OPT(codec_tags, str, codec_tag, oc, st);
3593 uint32_t tag = strtol(codec_tag, &next, 0);
3595 tag = AV_RL32(codec_tag);
3596 st->codec->codec_tag = tag;
3599 MATCH_PER_STREAM_OPT(qscale, dbl, qscale, oc, st);
3600 if (qscale >= 0 || same_quant) {
3601 st->codec->flags |= CODEC_FLAG_QSCALE;
3602 st->codec->global_quality = FF_QP2LAMBDA * qscale;
3605 if (oc->oformat->flags & AVFMT_GLOBALHEADER)
3606 st->codec->flags |= CODEC_FLAG_GLOBAL_HEADER;
3608 av_opt_get_int(sws_opts, "sws_flags", 0, &ost->sws_flags);
3612 static void parse_matrix_coeffs(uint16_t *dest, const char *str)
3615 const char *p = str;
3622 av_log(NULL, AV_LOG_FATAL, "Syntax error in matrix \"%s\" at coeff %d\n", str, i);
3629 static OutputStream *new_video_stream(OptionsContext *o, AVFormatContext *oc)
3633 AVCodecContext *video_enc;
3635 ost = new_output_stream(o, oc, AVMEDIA_TYPE_VIDEO);
3637 video_enc = st->codec;
3639 if (!ost->stream_copy) {
3640 const char *p = NULL;
3641 char *forced_key_frames = NULL, *frame_rate = NULL, *frame_size = NULL;
3642 char *frame_aspect_ratio = NULL, *frame_pix_fmt = NULL;
3643 char *intra_matrix = NULL, *inter_matrix = NULL, *filters = NULL;
3646 MATCH_PER_STREAM_OPT(frame_rates, str, frame_rate, oc, st);
3647 if (frame_rate && av_parse_video_rate(&ost->frame_rate, frame_rate) < 0) {
3648 av_log(NULL, AV_LOG_FATAL, "Invalid framerate value: %s\n", frame_rate);
3652 MATCH_PER_STREAM_OPT(frame_sizes, str, frame_size, oc, st);
3653 if (frame_size && av_parse_video_size(&video_enc->width, &video_enc->height, frame_size) < 0) {
3654 av_log(NULL, AV_LOG_FATAL, "Invalid frame size: %s.\n", frame_size);
3658 MATCH_PER_STREAM_OPT(frame_aspect_ratios, str, frame_aspect_ratio, oc, st);
3659 if (frame_aspect_ratio)
3660 ost->frame_aspect_ratio = parse_frame_aspect_ratio(frame_aspect_ratio);
3662 MATCH_PER_STREAM_OPT(frame_pix_fmts, str, frame_pix_fmt, oc, st);
3663 if (frame_pix_fmt && (video_enc->pix_fmt = av_get_pix_fmt(frame_pix_fmt)) == PIX_FMT_NONE) {
3664 av_log(NULL, AV_LOG_FATAL, "Unknown pixel format requested: %s.\n", frame_pix_fmt);
3667 st->sample_aspect_ratio = video_enc->sample_aspect_ratio;
3669 MATCH_PER_STREAM_OPT(intra_matrices, str, intra_matrix, oc, st);
3671 if (!(video_enc->intra_matrix = av_mallocz(sizeof(*video_enc->intra_matrix) * 64))) {
3672 av_log(NULL, AV_LOG_FATAL, "Could not allocate memory for intra matrix.\n");
3675 parse_matrix_coeffs(video_enc->intra_matrix, intra_matrix);
3677 MATCH_PER_STREAM_OPT(inter_matrices, str, inter_matrix, oc, st);
3679 if (!(video_enc->inter_matrix = av_mallocz(sizeof(*video_enc->inter_matrix) * 64))) {
3680 av_log(NULL, AV_LOG_FATAL, "Could not allocate memory for inter matrix.\n");
3683 parse_matrix_coeffs(video_enc->inter_matrix, inter_matrix);
3686 MATCH_PER_STREAM_OPT(rc_overrides, str, p, oc, st);
3687 for (i = 0; p; i++) {
3689 int e = sscanf(p, "%d,%d,%d", &start, &end, &q);
3691 av_log(NULL, AV_LOG_FATAL, "error parsing rc_override\n");
3694 video_enc->rc_override =
3695 av_realloc(video_enc->rc_override,
3696 sizeof(RcOverride) * (i + 1));
3697 video_enc->rc_override[i].start_frame = start;
3698 video_enc->rc_override[i].end_frame = end;
3700 video_enc->rc_override[i].qscale = q;
3701 video_enc->rc_override[i].quality_factor = 1.0;
3704 video_enc->rc_override[i].qscale = 0;
3705 video_enc->rc_override[i].quality_factor = -q/100.0;
3710 video_enc->rc_override_count = i;
3711 if (!video_enc->rc_initial_buffer_occupancy)
3712 video_enc->rc_initial_buffer_occupancy = video_enc->rc_buffer_size * 3 / 4;
3713 video_enc->intra_dc_precision = intra_dc_precision - 8;
3718 video_enc->flags |= CODEC_FLAG_PASS1;
3720 video_enc->flags |= CODEC_FLAG_PASS2;
3724 MATCH_PER_STREAM_OPT(forced_key_frames, str, forced_key_frames, oc, st);
3725 if (forced_key_frames)
3726 parse_forced_key_frames(forced_key_frames, ost, video_enc);
3728 MATCH_PER_STREAM_OPT(force_fps, i, ost->force_fps, oc, st);
3730 ost->top_field_first = -1;
3731 MATCH_PER_STREAM_OPT(top_field_first, i, ost->top_field_first, oc, st);
3733 MATCH_PER_STREAM_OPT(copy_initial_nonkeyframes, i, ost->copy_initial_nonkeyframes, oc ,st);
3736 MATCH_PER_STREAM_OPT(filters, str, filters, oc, st);
3738 ost->avfilter = av_strdup(filters);
3745 static OutputStream *new_audio_stream(OptionsContext *o, AVFormatContext *oc)
3749 AVCodecContext *audio_enc;
3751 ost = new_output_stream(o, oc, AVMEDIA_TYPE_AUDIO);
3754 audio_enc = st->codec;
3755 audio_enc->codec_type = AVMEDIA_TYPE_AUDIO;
3757 if (!ost->stream_copy) {
3758 char *sample_fmt = NULL;
3760 MATCH_PER_STREAM_OPT(audio_channels, i, audio_enc->channels, oc, st);
3762 MATCH_PER_STREAM_OPT(sample_fmts, str, sample_fmt, oc, st);
3764 (audio_enc->sample_fmt = av_get_sample_fmt(sample_fmt)) == AV_SAMPLE_FMT_NONE) {
3765 av_log(NULL, AV_LOG_FATAL, "Invalid sample format '%s'\n", sample_fmt);
3769 MATCH_PER_STREAM_OPT(audio_sample_rate, i, audio_enc->sample_rate, oc, st);
3775 static OutputStream *new_data_stream(OptionsContext *o, AVFormatContext *oc)
3779 ost = new_output_stream(o, oc, AVMEDIA_TYPE_DATA);
3780 if (!ost->stream_copy) {
3781 av_log(NULL, AV_LOG_FATAL, "Data stream encoding not supported yet (only streamcopy)\n");
3788 static OutputStream *new_attachment_stream(OptionsContext *o, AVFormatContext *oc)
3790 OutputStream *ost = new_output_stream(o, oc, AVMEDIA_TYPE_ATTACHMENT);
3791 ost->stream_copy = 1;
3795 static OutputStream *new_subtitle_stream(OptionsContext *o, AVFormatContext *oc)
3799 AVCodecContext *subtitle_enc;
3801 ost = new_output_stream(o, oc, AVMEDIA_TYPE_SUBTITLE);
3803 subtitle_enc = st->codec;
3805 subtitle_enc->codec_type = AVMEDIA_TYPE_SUBTITLE;
3810 /* arg format is "output-stream-index:streamid-value". */
3811 static int opt_streamid(OptionsContext *o, const char *opt, const char *arg)
3817 av_strlcpy(idx_str, arg, sizeof(idx_str));
3818 p = strchr(idx_str, ':');
3820 av_log(NULL, AV_LOG_FATAL,
3821 "Invalid value '%s' for option '%s', required syntax is 'index:value'\n",
3826 idx = parse_number_or_die(opt, idx_str, OPT_INT, 0, MAX_STREAMS-1);
3827 o->streamid_map = grow_array(o->streamid_map, sizeof(*o->streamid_map), &o->nb_streamid_map, idx+1);
3828 o->streamid_map[idx] = parse_number_or_die(opt, p, OPT_INT, 0, INT_MAX);
3832 static int copy_chapters(InputFile *ifile, OutputFile *ofile, int copy_metadata)
3834 AVFormatContext *is = ifile->ctx;
3835 AVFormatContext *os = ofile->ctx;
3838 for (i = 0; i < is->nb_chapters; i++) {
3839 AVChapter *in_ch = is->chapters[i], *out_ch;
3840 int64_t ts_off = av_rescale_q(ofile->start_time - ifile->ts_offset,
3841 AV_TIME_BASE_Q, in_ch->time_base);
3842 int64_t rt = (ofile->recording_time == INT64_MAX) ? INT64_MAX :
3843 av_rescale_q(ofile->recording_time, AV_TIME_BASE_Q, in_ch->time_base);
3846 if (in_ch->end < ts_off)
3848 if (rt != INT64_MAX && in_ch->start > rt + ts_off)
3851 out_ch = av_mallocz(sizeof(AVChapter));
3853 return AVERROR(ENOMEM);
3855 out_ch->id = in_ch->id;
3856 out_ch->time_base = in_ch->time_base;
3857 out_ch->start = FFMAX(0, in_ch->start - ts_off);
3858 out_ch->end = FFMIN(rt, in_ch->end - ts_off);
3861 av_dict_copy(&out_ch->metadata, in_ch->metadata, 0);
3864 os->chapters = av_realloc(os->chapters, sizeof(AVChapter) * os->nb_chapters);
3866 return AVERROR(ENOMEM);
3867 os->chapters[os->nb_chapters - 1] = out_ch;
3872 static void opt_output_file(void *optctx, const char *filename)
3874 OptionsContext *o = optctx;
3875 AVFormatContext *oc;
3877 AVOutputFormat *file_oformat;
3881 if (!strcmp(filename, "-"))
3884 err = avformat_alloc_output_context2(&oc, NULL, o->format, filename);
3886 print_error(filename, err);
3890 file_oformat= oc->oformat;
3891 oc->interrupt_callback = int_cb;
3893 if (!o->nb_stream_maps) {
3894 /* pick the "best" stream of each type */
3895 #define NEW_STREAM(type, index)\
3897 ost = new_ ## type ## _stream(o, oc);\
3898 ost->source_index = index;\
3899 ost->sync_ist = &input_streams[index];\
3900 input_streams[index].discard = 0;\
3903 /* video: highest resolution */
3904 if (!o->video_disable && oc->oformat->video_codec != CODEC_ID_NONE) {
3905 int area = 0, idx = -1;
3906 for (i = 0; i < nb_input_streams; i++) {
3907 ist = &input_streams[i];
3908 if (ist->st->codec->codec_type == AVMEDIA_TYPE_VIDEO &&
3909 ist->st->codec->width * ist->st->codec->height > area) {
3910 area = ist->st->codec->width * ist->st->codec->height;
3914 NEW_STREAM(video, idx);
3917 /* audio: most channels */
3918 if (!o->audio_disable && oc->oformat->audio_codec != CODEC_ID_NONE) {
3919 int channels = 0, idx = -1;
3920 for (i = 0; i < nb_input_streams; i++) {
3921 ist = &input_streams[i];
3922 if (ist->st->codec->codec_type == AVMEDIA_TYPE_AUDIO &&
3923 ist->st->codec->channels > channels) {
3924 channels = ist->st->codec->channels;
3928 NEW_STREAM(audio, idx);
3931 /* subtitles: pick first */
3932 if (!o->subtitle_disable && oc->oformat->subtitle_codec != CODEC_ID_NONE) {
3933 for (i = 0; i < nb_input_streams; i++)
3934 if (input_streams[i].st->codec->codec_type == AVMEDIA_TYPE_SUBTITLE) {
3935 NEW_STREAM(subtitle, i);
3939 /* do something with data? */
3941 for (i = 0; i < o->nb_stream_maps; i++) {
3942 StreamMap *map = &o->stream_maps[i];
3947 ist = &input_streams[input_files[map->file_index].ist_index + map->stream_index];
3948 switch (ist->st->codec->codec_type) {
3949 case AVMEDIA_TYPE_VIDEO: ost = new_video_stream(o, oc); break;
3950 case AVMEDIA_TYPE_AUDIO: ost = new_audio_stream(o, oc); break;
3951 case AVMEDIA_TYPE_SUBTITLE: ost = new_subtitle_stream(o, oc); break;
3952 case AVMEDIA_TYPE_DATA: ost = new_data_stream(o, oc); break;
3953 case AVMEDIA_TYPE_ATTACHMENT: ost = new_attachment_stream(o, oc); break;
3955 av_log(NULL, AV_LOG_FATAL, "Cannot map stream #%d:%d - unsupported type.\n",
3956 map->file_index, map->stream_index);
3960 ost->source_index = input_files[map->file_index].ist_index + map->stream_index;
3961 ost->sync_ist = &input_streams[input_files[map->sync_file_index].ist_index +
3962 map->sync_stream_index];
3967 /* handle attached files */
3968 for (i = 0; i < o->nb_attachments; i++) {
3970 uint8_t *attachment;
3974 if ((err = avio_open2(&pb, o->attachments[i], AVIO_FLAG_READ, &int_cb, NULL)) < 0) {
3975 av_log(NULL, AV_LOG_FATAL, "Could not open attachment file %s.\n",
3979 if ((len = avio_size(pb)) <= 0) {
3980 av_log(NULL, AV_LOG_FATAL, "Could not get size of the attachment %s.\n",
3984 if (!(attachment = av_malloc(len))) {
3985 av_log(NULL, AV_LOG_FATAL, "Attachment %s too large to fit into memory.\n",
3989 avio_read(pb, attachment, len);
3991 ost = new_attachment_stream(o, oc);
3992 ost->stream_copy = 0;
3993 ost->source_index = -1;
3994 ost->attachment_filename = o->attachments[i];
3995 ost->st->codec->extradata = attachment;
3996 ost->st->codec->extradata_size = len;
3998 p = strrchr(o->attachments[i], '/');
3999 av_dict_set(&ost->st->metadata, "filename", (p && *p) ? p + 1 : o->attachments[i], AV_DICT_DONT_OVERWRITE);
4003 output_files = grow_array(output_files, sizeof(*output_files), &nb_output_files, nb_output_files + 1);
4004 output_files[nb_output_files - 1].ctx = oc;
4005 output_files[nb_output_files - 1].ost_index = nb_output_streams - oc->nb_streams;
4006 output_files[nb_output_files - 1].recording_time = o->recording_time;
4007 output_files[nb_output_files - 1].start_time = o->start_time;
4008 output_files[nb_output_files - 1].limit_filesize = o->limit_filesize;
4009 av_dict_copy(&output_files[nb_output_files - 1].opts, format_opts, 0);
4011 /* check filename in case of an image number is expected */
4012 if (oc->oformat->flags & AVFMT_NEEDNUMBER) {
4013 if (!av_filename_number_test(oc->filename)) {
4014 print_error(oc->filename, AVERROR(EINVAL));
4019 if (!(oc->oformat->flags & AVFMT_NOFILE)) {
4020 /* test if it already exists to avoid losing precious files */
4021 assert_file_overwrite(filename);
4024 if ((err = avio_open2(&oc->pb, filename, AVIO_FLAG_WRITE,
4025 &oc->interrupt_callback,
4026 &output_files[nb_output_files - 1].opts)) < 0) {
4027 print_error(filename, err);
4032 if (o->mux_preload) {
4034 snprintf(buf, sizeof(buf), "%d", (int)(o->mux_preload*AV_TIME_BASE));
4035 av_dict_set(&output_files[nb_output_files - 1].opts, "preload", buf, 0);
4037 oc->max_delay = (int)(o->mux_max_delay * AV_TIME_BASE);
4040 for (i = 0; i < o->nb_metadata_map; i++) {
4042 int in_file_index = strtol(o->metadata_map[i].u.str, &p, 0);
4044 if (in_file_index < 0)
4046 if (in_file_index >= nb_input_files) {
4047 av_log(NULL, AV_LOG_FATAL, "Invalid input file index %d while processing metadata maps\n", in_file_index);
4050 copy_metadata(o->metadata_map[i].specifier, *p ? p + 1 : p, oc, input_files[in_file_index].ctx, o);
4054 if (o->chapters_input_file >= nb_input_files) {
4055 if (o->chapters_input_file == INT_MAX) {
4056 /* copy chapters from the first input file that has them*/
4057 o->chapters_input_file = -1;
4058 for (i = 0; i < nb_input_files; i++)
4059 if (input_files[i].ctx->nb_chapters) {
4060 o->chapters_input_file = i;
4064 av_log(NULL, AV_LOG_FATAL, "Invalid input file index %d in chapter mapping.\n",
4065 o->chapters_input_file);
4069 if (o->chapters_input_file >= 0)
4070 copy_chapters(&input_files[o->chapters_input_file], &output_files[nb_output_files - 1],
4071 !o->metadata_chapters_manual);
4073 /* copy global metadata by default */
4074 if (!o->metadata_global_manual && nb_input_files)
4075 av_dict_copy(&oc->metadata, input_files[0].ctx->metadata,
4076 AV_DICT_DONT_OVERWRITE);
4077 if (!o->metadata_streams_manual)
4078 for (i = output_files[nb_output_files - 1].ost_index; i < nb_output_streams; i++) {
4080 if (output_streams[i].source_index < 0) /* this is true e.g. for attached files */
4082 ist = &input_streams[output_streams[i].source_index];
4083 av_dict_copy(&output_streams[i].st->metadata, ist->st->metadata, AV_DICT_DONT_OVERWRITE);
4086 /* process manually set metadata */
4087 for (i = 0; i < o->nb_metadata; i++) {
4090 const char *stream_spec;
4091 int index = 0, j, ret;
4093 val = strchr(o->metadata[i].u.str, '=');
4095 av_log(NULL, AV_LOG_FATAL, "No '=' character in metadata string %s.\n",
4096 o->metadata[i].u.str);
4101 parse_meta_type(o->metadata[i].specifier, &type, &index, &stream_spec);
4103 for (j = 0; j < oc->nb_streams; j++) {
4104 if ((ret = check_stream_specifier(oc, oc->streams[j], stream_spec)) > 0) {
4105 av_dict_set(&oc->streams[j]->metadata, o->metadata[i].u.str, *val ? val : NULL, 0);
4109 printf("ret %d, stream_spec %s\n", ret, stream_spec);
4117 if (index < 0 || index >= oc->nb_chapters) {
4118 av_log(NULL, AV_LOG_FATAL, "Invalid chapter index %d in metadata specifier.\n", index);
4121 m = &oc->chapters[index]->metadata;
4124 av_log(NULL, AV_LOG_FATAL, "Invalid metadata specifier %s.\n", o->metadata[i].specifier);
4127 av_dict_set(m, o->metadata[i].u.str, *val ? val : NULL, 0);
4134 /* same option as mencoder */
4135 static int opt_pass(const char *opt, const char *arg)
4137 do_pass = parse_number_or_die(opt, arg, OPT_INT, 1, 2);
4141 static int64_t getutime(void)
4144 struct rusage rusage;
4146 getrusage(RUSAGE_SELF, &rusage);
4147 return (rusage.ru_utime.tv_sec * 1000000LL) + rusage.ru_utime.tv_usec;
4148 #elif HAVE_GETPROCESSTIMES
4150 FILETIME c, e, k, u;
4151 proc = GetCurrentProcess();
4152 GetProcessTimes(proc, &c, &e, &k, &u);
4153 return ((int64_t) u.dwHighDateTime << 32 | u.dwLowDateTime) / 10;
4155 return av_gettime();
4159 static int64_t getmaxrss(void)
4161 #if HAVE_GETRUSAGE && HAVE_STRUCT_RUSAGE_RU_MAXRSS
4162 struct rusage rusage;
4163 getrusage(RUSAGE_SELF, &rusage);
4164 return (int64_t)rusage.ru_maxrss * 1024;
4165 #elif HAVE_GETPROCESSMEMORYINFO
4167 PROCESS_MEMORY_COUNTERS memcounters;
4168 proc = GetCurrentProcess();
4169 memcounters.cb = sizeof(memcounters);
4170 GetProcessMemoryInfo(proc, &memcounters, sizeof(memcounters));
4171 return memcounters.PeakPagefileUsage;
4177 static int opt_audio_qscale(OptionsContext *o, const char *opt, const char *arg)
4179 return parse_option(o, "q:a", arg, options);
4182 static void show_usage(void)
4184 printf("Hyper fast Audio and Video encoder\n");
4185 printf("usage: %s [options] [[infile options] -i infile]... {[outfile options] outfile}...\n", program_name);
4189 static int opt_help(const char *opt, const char *arg)
4191 int flags = AV_OPT_FLAG_DECODING_PARAM | AV_OPT_FLAG_ENCODING_PARAM;
4192 av_log_set_callback(log_callback_help);
4194 show_help_options(options, "Main options:\n",
4195 OPT_EXPERT | OPT_AUDIO | OPT_VIDEO | OPT_SUBTITLE | OPT_GRAB, 0);
4196 show_help_options(options, "\nAdvanced options:\n",
4197 OPT_EXPERT | OPT_AUDIO | OPT_VIDEO | OPT_SUBTITLE | OPT_GRAB,
4199 show_help_options(options, "\nVideo options:\n",
4200 OPT_EXPERT | OPT_AUDIO | OPT_VIDEO | OPT_GRAB,
4202 show_help_options(options, "\nAdvanced Video options:\n",
4203 OPT_EXPERT | OPT_AUDIO | OPT_VIDEO | OPT_GRAB,
4204 OPT_VIDEO | OPT_EXPERT);
4205 show_help_options(options, "\nAudio options:\n",
4206 OPT_EXPERT | OPT_AUDIO | OPT_VIDEO | OPT_GRAB,
4208 show_help_options(options, "\nAdvanced Audio options:\n",
4209 OPT_EXPERT | OPT_AUDIO | OPT_VIDEO | OPT_GRAB,
4210 OPT_AUDIO | OPT_EXPERT);
4211 show_help_options(options, "\nSubtitle options:\n",
4212 OPT_SUBTITLE | OPT_GRAB,
4214 show_help_options(options, "\nAudio/Video grab options:\n",
4218 show_help_children(avcodec_get_class(), flags);
4219 show_help_children(avformat_get_class(), flags);
4220 show_help_children(sws_get_class(), flags);
4225 static int opt_target(OptionsContext *o, const char *opt, const char *arg)
4227 enum { PAL, NTSC, FILM, UNKNOWN } norm = UNKNOWN;
4228 static const char *const frame_rates[] = { "25", "30000/1001", "24000/1001" };
4230 if (!strncmp(arg, "pal-", 4)) {
4233 } else if (!strncmp(arg, "ntsc-", 5)) {
4236 } else if (!strncmp(arg, "film-", 5)) {
4240 /* Try to determine PAL/NTSC by peeking in the input files */
4241 if (nb_input_files) {
4243 for (j = 0; j < nb_input_files; j++) {
4244 for (i = 0; i < input_files[j].nb_streams; i++) {
4245 AVCodecContext *c = input_files[j].ctx->streams[i]->codec;
4246 if (c->codec_type != AVMEDIA_TYPE_VIDEO)
4248 fr = c->time_base.den * 1000 / c->time_base.num;
4252 } else if ((fr == 29970) || (fr == 23976)) {
4257 if (norm != UNKNOWN)
4261 if (norm != UNKNOWN)
4262 av_log(NULL, AV_LOG_INFO, "Assuming %s for target.\n", norm == PAL ? "PAL" : "NTSC");
4265 if (norm == UNKNOWN) {
4266 av_log(NULL, AV_LOG_FATAL, "Could not determine norm (PAL/NTSC/NTSC-Film) for target.\n");
4267 av_log(NULL, AV_LOG_FATAL, "Please prefix target with \"pal-\", \"ntsc-\" or \"film-\",\n");
4268 av_log(NULL, AV_LOG_FATAL, "or set a framerate with \"-r xxx\".\n");
4272 if (!strcmp(arg, "vcd")) {
4273 opt_video_codec(o, "c:v", "mpeg1video");
4274 opt_audio_codec(o, "c:a", "mp2");
4275 parse_option(o, "f", "vcd", options);
4277 parse_option(o, "s", norm == PAL ? "352x288" : "352x240", options);
4278 parse_option(o, "r", frame_rates[norm], options);
4279 opt_default("g", norm == PAL ? "15" : "18");
4281 opt_default("b", "1150000");
4282 opt_default("maxrate", "1150000");
4283 opt_default("minrate", "1150000");
4284 opt_default("bufsize", "327680"); // 40*1024*8;
4286 opt_default("b:a", "224000");
4287 parse_option(o, "ar", "44100", options);
4288 parse_option(o, "ac", "2", options);
4290 opt_default("packetsize", "2324");
4291 opt_default("muxrate", "1411200"); // 2352 * 75 * 8;
4293 /* We have to offset the PTS, so that it is consistent with the SCR.
4294 SCR starts at 36000, but the first two packs contain only padding
4295 and the first pack from the other stream, respectively, may also have
4296 been written before.
4297 So the real data starts at SCR 36000+3*1200. */
4298 o->mux_preload = (36000 + 3 * 1200) / 90000.0; // 0.44
4299 } else if (!strcmp(arg, "svcd")) {
4301 opt_video_codec(o, "c:v", "mpeg2video");
4302 opt_audio_codec(o, "c:a", "mp2");
4303 parse_option(o, "f", "svcd", options);
4305 parse_option(o, "s", norm == PAL ? "480x576" : "480x480", options);
4306 parse_option(o, "r", frame_rates[norm], options);
4307 opt_default("g", norm == PAL ? "15" : "18");
4309 opt_default("b", "2040000");
4310 opt_default("maxrate", "2516000");
4311 opt_default("minrate", "0"); // 1145000;
4312 opt_default("bufsize", "1835008"); // 224*1024*8;
4313 opt_default("flags", "+scan_offset");
4316 opt_default("b:a", "224000");
4317 parse_option(o, "ar", "44100", options);
4319 opt_default("packetsize", "2324");
4321 } else if (!strcmp(arg, "dvd")) {
4323 opt_video_codec(o, "c:v", "mpeg2video");
4324 opt_audio_codec(o, "c:a", "ac3");
4325 parse_option(o, "f", "dvd", options);
4327 parse_option(o, "s", norm == PAL ? "720x576" : "720x480", options);
4328 parse_option(o, "r", frame_rates[norm], options);
4329 opt_default("g", norm == PAL ? "15" : "18");
4331 opt_default("b", "6000000");
4332 opt_default("maxrate", "9000000");
4333 opt_default("minrate", "0"); // 1500000;
4334 opt_default("bufsize", "1835008"); // 224*1024*8;
4336 opt_default("packetsize", "2048"); // from www.mpucoder.com: DVD sectors contain 2048 bytes of data, this is also the size of one pack.
4337 opt_default("muxrate", "10080000"); // from mplex project: data_rate = 1260000. mux_rate = data_rate * 8
4339 opt_default("b:a", "448000");
4340 parse_option(o, "ar", "48000", options);
4342 } else if (!strncmp(arg, "dv", 2)) {
4344 parse_option(o, "f", "dv", options);
4346 parse_option(o, "s", norm == PAL ? "720x576" : "720x480", options);
4347 parse_option(o, "pix_fmt", !strncmp(arg, "dv50", 4) ? "yuv422p" :
4348 norm == PAL ? "yuv420p" : "yuv411p", options);
4349 parse_option(o, "r", frame_rates[norm], options);
4351 parse_option(o, "ar", "48000", options);
4352 parse_option(o, "ac", "2", options);
4355 av_log(NULL, AV_LOG_ERROR, "Unknown target: %s\n", arg);
4356 return AVERROR(EINVAL);
4361 static int opt_vstats_file(const char *opt, const char *arg)
4363 av_free (vstats_filename);
4364 vstats_filename = av_strdup (arg);
4368 static int opt_vstats(const char *opt, const char *arg)
4371 time_t today2 = time(NULL);
4372 struct tm *today = localtime(&today2);
4374 snprintf(filename, sizeof(filename), "vstats_%02d%02d%02d.log", today->tm_hour, today->tm_min,
4376 return opt_vstats_file(opt, filename);
4379 static int opt_video_frames(OptionsContext *o, const char *opt, const char *arg)
4381 return parse_option(o, "frames:v", arg, options);
4384 static int opt_audio_frames(OptionsContext *o, const char *opt, const char *arg)
4386 return parse_option(o, "frames:a", arg, options);
4389 static int opt_data_frames(OptionsContext *o, const char *opt, const char *arg)
4391 return parse_option(o, "frames:d", arg, options);
4394 static void log_callback_null(void* ptr, int level, const char* fmt, va_list vl)
4398 static int opt_passlogfile(const char *opt, const char *arg)
4400 pass_logfilename_prefix = arg;
4401 #if CONFIG_LIBX264_ENCODER
4402 return opt_default("passlogfile", arg);
4408 static int opt_video_tag(OptionsContext *o, const char *opt, const char *arg)
4410 return parse_option(o, "tag:v", arg, options);
4413 static int opt_audio_tag(OptionsContext *o, const char *opt, const char *arg)
4415 return parse_option(o, "tag:a", arg, options);
4418 static int opt_subtitle_tag(OptionsContext *o, const char *opt, const char *arg)
4420 return parse_option(o, "tag:s", arg, options);
4423 static int opt_video_filters(OptionsContext *o, const char *opt, const char *arg)
4425 return parse_option(o, "filter:v", arg, options);
4428 #define OFFSET(x) offsetof(OptionsContext, x)
4429 static const OptionDef options[] = {
4431 #include "cmdutils_common_opts.h"
4432 { "f", HAS_ARG | OPT_STRING | OPT_OFFSET, {.off = OFFSET(format)}, "force format", "fmt" },
4433 { "i", HAS_ARG | OPT_FUNC2, {(void*)opt_input_file}, "input file name", "filename" },
4434 { "y", OPT_BOOL, {(void*)&file_overwrite}, "overwrite output files" },
4435 { "n", OPT_BOOL, {(void*)&no_file_overwrite}, "do not overwrite output files" },
4436 { "c", HAS_ARG | OPT_STRING | OPT_SPEC, {.off = OFFSET(codec_names)}, "codec name", "codec" },
4437 { "codec", HAS_ARG | OPT_STRING | OPT_SPEC, {.off = OFFSET(codec_names)}, "codec name", "codec" },
4438 { "pre", HAS_ARG | OPT_STRING | OPT_SPEC, {.off = OFFSET(presets)}, "preset name", "preset" },
4439 { "map", HAS_ARG | OPT_EXPERT | OPT_FUNC2, {(void*)opt_map}, "set input stream mapping", "[-]input_file_id[:stream_specifier][,sync_file_id[:stream_specifier]]" },
4440 { "map_metadata", HAS_ARG | OPT_STRING | OPT_SPEC, {.off = OFFSET(metadata_map)}, "set metadata information of outfile from infile",
4441 "outfile[,metadata]:infile[,metadata]" },
4442 { "map_chapters", OPT_INT | HAS_ARG | OPT_EXPERT | OPT_OFFSET, {.off = OFFSET(chapters_input_file)}, "set chapters mapping", "input_file_index" },
4443 { "t", HAS_ARG | OPT_TIME | OPT_OFFSET, {.off = OFFSET(recording_time)}, "record or transcode \"duration\" seconds of audio/video", "duration" },
4444 { "fs", HAS_ARG | OPT_INT64 | OPT_OFFSET, {.off = OFFSET(limit_filesize)}, "set the limit file size in bytes", "limit_size" }, //
4445 { "ss", HAS_ARG | OPT_TIME | OPT_OFFSET, {.off = OFFSET(start_time)}, "set the start time offset", "time_off" },
4446 { "itsoffset", HAS_ARG | OPT_TIME | OPT_OFFSET, {.off = OFFSET(input_ts_offset)}, "set the input ts offset", "time_off" },
4447 { "itsscale", HAS_ARG | OPT_DOUBLE | OPT_SPEC, {.off = OFFSET(ts_scale)}, "set the input ts scale", "scale" },
4448 { "metadata", HAS_ARG | OPT_STRING | OPT_SPEC, {.off = OFFSET(metadata)}, "add metadata", "string=string" },
4449 { "dframes", HAS_ARG | OPT_FUNC2, {(void*)opt_data_frames}, "set the number of data frames to record", "number" },
4450 { "benchmark", OPT_BOOL | OPT_EXPERT, {(void*)&do_benchmark},
4451 "add timings for benchmarking" },
4452 { "timelimit", HAS_ARG, {(void*)opt_timelimit}, "set max runtime in seconds", "limit" },
4453 { "dump", OPT_BOOL | OPT_EXPERT, {(void*)&do_pkt_dump},
4454 "dump each input packet" },
4455 { "hex", OPT_BOOL | OPT_EXPERT, {(void*)&do_hex_dump},
4456 "when dumping packets, also dump the payload" },
4457 { "re", OPT_BOOL | OPT_EXPERT | OPT_OFFSET, {.off = OFFSET(rate_emu)}, "read input at native frame rate", "" },
4458 { "target", HAS_ARG | OPT_FUNC2, {(void*)opt_target}, "specify target file type (\"vcd\", \"svcd\", \"dvd\", \"dv\", \"dv50\", \"pal-vcd\", \"ntsc-svcd\", ...)", "type" },
4459 { "vsync", HAS_ARG | OPT_INT | OPT_EXPERT, {(void*)&video_sync_method}, "video sync method", "" },
4460 { "async", HAS_ARG | OPT_INT | OPT_EXPERT, {(void*)&audio_sync_method}, "audio sync method", "" },
4461 { "adrift_threshold", HAS_ARG | OPT_FLOAT | OPT_EXPERT, {(void*)&audio_drift_threshold}, "audio drift threshold", "threshold" },
4462 { "copyts", OPT_BOOL | OPT_EXPERT, {(void*)©_ts}, "copy timestamps" },
4463 { "copytb", OPT_BOOL | OPT_EXPERT, {(void*)©_tb}, "copy input stream time base when stream copying" },
4464 { "shortest", OPT_BOOL | OPT_EXPERT, {(void*)&opt_shortest}, "finish encoding within shortest input" }, //
4465 { "dts_delta_threshold", HAS_ARG | OPT_FLOAT | OPT_EXPERT, {(void*)&dts_delta_threshold}, "timestamp discontinuity delta threshold", "threshold" },
4466 { "xerror", OPT_BOOL, {(void*)&exit_on_error}, "exit on error", "error" },
4467 { "copyinkf", OPT_BOOL | OPT_EXPERT | OPT_SPEC, {.off = OFFSET(copy_initial_nonkeyframes)}, "copy initial non-keyframes" },
4468 { "frames", OPT_INT64 | HAS_ARG | OPT_SPEC, {.off = OFFSET(max_frames)}, "set the number of frames to record", "number" },
4469 { "tag", OPT_STRING | HAS_ARG | OPT_SPEC, {.off = OFFSET(codec_tags)}, "force codec tag/fourcc", "fourcc/tag" },
4470 { "q", HAS_ARG | OPT_EXPERT | OPT_DOUBLE | OPT_SPEC, {.off = OFFSET(qscale)}, "use fixed quality scale (VBR)", "q" },
4471 { "qscale", HAS_ARG | OPT_EXPERT | OPT_DOUBLE | OPT_SPEC, {.off = OFFSET(qscale)}, "use fixed quality scale (VBR)", "q" },
4473 { "filter", HAS_ARG | OPT_STRING | OPT_SPEC, {.off = OFFSET(filters)}, "set stream filterchain", "filter_list" },
4475 { "stats", OPT_BOOL, {&print_stats}, "print progress report during encoding", },
4476 { "attach", HAS_ARG | OPT_FUNC2, {(void*)opt_attach}, "add an attachment to the output file", "filename" },
4477 { "dump_attachment", HAS_ARG | OPT_STRING | OPT_SPEC, {.off = OFFSET(dump_attachment)}, "extract an attachment into a file", "filename" },
4480 { "vframes", HAS_ARG | OPT_VIDEO | OPT_FUNC2, {(void*)opt_video_frames}, "set the number of video frames to record", "number" },
4481 { "r", HAS_ARG | OPT_VIDEO | OPT_STRING | OPT_SPEC, {.off = OFFSET(frame_rates)}, "set frame rate (Hz value, fraction or abbreviation)", "rate" },
4482 { "s", HAS_ARG | OPT_VIDEO | OPT_STRING | OPT_SPEC, {.off = OFFSET(frame_sizes)}, "set frame size (WxH or abbreviation)", "size" },
4483 { "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" },
4484 { "pix_fmt", HAS_ARG | OPT_EXPERT | OPT_VIDEO | OPT_STRING | OPT_SPEC, {.off = OFFSET(frame_pix_fmts)}, "set pixel format", "format" },
4485 { "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" },
4486 { "vn", OPT_BOOL | OPT_VIDEO | OPT_OFFSET, {.off = OFFSET(video_disable)}, "disable video" },
4487 { "vdt", OPT_INT | HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)&video_discard}, "discard threshold", "n" },
4488 { "rc_override", HAS_ARG | OPT_EXPERT | OPT_VIDEO | OPT_STRING | OPT_SPEC, {.off = OFFSET(rc_overrides)}, "rate control override for specific intervals", "override" },
4489 { "vcodec", HAS_ARG | OPT_VIDEO | OPT_FUNC2, {(void*)opt_video_codec}, "force video codec ('copy' to copy stream)", "codec" },
4490 { "same_quant", OPT_BOOL | OPT_VIDEO, {(void*)&same_quant},
4491 "use same quantizer as source (implies VBR)" },
4492 { "pass", HAS_ARG | OPT_VIDEO, {(void*)opt_pass}, "select the pass number (1 or 2)", "n" },
4493 { "passlogfile", HAS_ARG | OPT_VIDEO, {(void*)&opt_passlogfile}, "select two pass log file name prefix", "prefix" },
4494 { "deinterlace", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, {(void*)&do_deinterlace},
4495 "deinterlace pictures" },
4496 { "vstats", OPT_EXPERT | OPT_VIDEO, {(void*)&opt_vstats}, "dump video coding statistics to file" },
4497 { "vstats_file", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_vstats_file}, "dump video coding statistics to file", "file" },
4499 { "vf", HAS_ARG | OPT_VIDEO | OPT_FUNC2, {(void*)opt_video_filters}, "video filters", "filter list" },
4501 { "intra_matrix", HAS_ARG | OPT_EXPERT | OPT_VIDEO | OPT_STRING | OPT_SPEC, {.off = OFFSET(intra_matrices)}, "specify intra matrix coeffs", "matrix" },
4502 { "inter_matrix", HAS_ARG | OPT_EXPERT | OPT_VIDEO | OPT_STRING | OPT_SPEC, {.off = OFFSET(inter_matrices)}, "specify inter matrix coeffs", "matrix" },
4503 { "top", HAS_ARG | OPT_EXPERT | OPT_VIDEO | OPT_INT| OPT_SPEC, {.off = OFFSET(top_field_first)}, "top=1/bottom=0/auto=-1 field first", "" },
4504 { "dc", OPT_INT | HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)&intra_dc_precision}, "intra_dc_precision", "precision" },
4505 { "vtag", HAS_ARG | OPT_EXPERT | OPT_VIDEO | OPT_FUNC2, {(void*)opt_video_tag}, "force video tag/fourcc", "fourcc/tag" },
4506 { "qphist", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, { (void *)&qp_hist }, "show QP histogram" },
4507 { "force_fps", OPT_BOOL | OPT_EXPERT | OPT_VIDEO | OPT_SPEC, {.off = OFFSET(force_fps)}, "force the selected framerate, disable the best supported framerate selection" },
4508 { "streamid", HAS_ARG | OPT_EXPERT | OPT_FUNC2, {(void*)opt_streamid}, "set the value of an outfile streamid", "streamIndex:value" },
4509 { "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" },
4512 { "aframes", HAS_ARG | OPT_AUDIO | OPT_FUNC2, {(void*)opt_audio_frames}, "set the number of audio frames to record", "number" },
4513 { "aq", HAS_ARG | OPT_AUDIO | OPT_FUNC2, {(void*)opt_audio_qscale}, "set audio quality (codec-specific)", "quality", },
4514 { "ar", HAS_ARG | OPT_AUDIO | OPT_INT | OPT_SPEC, {.off = OFFSET(audio_sample_rate)}, "set audio sampling rate (in Hz)", "rate" },
4515 { "ac", HAS_ARG | OPT_AUDIO | OPT_INT | OPT_SPEC, {.off = OFFSET(audio_channels)}, "set number of audio channels", "channels" },
4516 { "an", OPT_BOOL | OPT_AUDIO | OPT_OFFSET, {.off = OFFSET(audio_disable)}, "disable audio" },
4517 { "acodec", HAS_ARG | OPT_AUDIO | OPT_FUNC2, {(void*)opt_audio_codec}, "force audio codec ('copy' to copy stream)", "codec" },
4518 { "atag", HAS_ARG | OPT_EXPERT | OPT_AUDIO | OPT_FUNC2, {(void*)opt_audio_tag}, "force audio tag/fourcc", "fourcc/tag" },
4519 { "vol", OPT_INT | HAS_ARG | OPT_AUDIO, {(void*)&audio_volume}, "change audio volume (256=normal)" , "volume" }, //
4520 { "sample_fmt", HAS_ARG | OPT_EXPERT | OPT_AUDIO | OPT_SPEC | OPT_STRING, {.off = OFFSET(sample_fmts)}, "set sample format", "format" },
4522 /* subtitle options */
4523 { "sn", OPT_BOOL | OPT_SUBTITLE | OPT_OFFSET, {.off = OFFSET(subtitle_disable)}, "disable subtitle" },
4524 { "scodec", HAS_ARG | OPT_SUBTITLE | OPT_FUNC2, {(void*)opt_subtitle_codec}, "force subtitle codec ('copy' to copy stream)", "codec" },
4525 { "stag", HAS_ARG | OPT_EXPERT | OPT_SUBTITLE | OPT_FUNC2, {(void*)opt_subtitle_tag}, "force subtitle tag/fourcc", "fourcc/tag" },
4528 { "isync", OPT_BOOL | OPT_EXPERT | OPT_GRAB, {(void*)&input_sync}, "sync read on input", "" },
4531 { "muxdelay", OPT_FLOAT | HAS_ARG | OPT_EXPERT | OPT_OFFSET, {.off = OFFSET(mux_max_delay)}, "set the maximum demux-decode delay", "seconds" },
4532 { "muxpreload", OPT_FLOAT | HAS_ARG | OPT_EXPERT | OPT_OFFSET, {.off = OFFSET(mux_preload)}, "set the initial demux-decode delay", "seconds" },
4534 { "bsf", HAS_ARG | OPT_STRING | OPT_SPEC, {.off = OFFSET(bitstream_filters)}, "A comma-separated list of bitstream filters", "bitstream_filters" },
4536 /* data codec support */
4537 { "dcodec", HAS_ARG | OPT_DATA | OPT_FUNC2, {(void*)opt_data_codec}, "force data codec ('copy' to copy stream)", "codec" },
4539 { "default", HAS_ARG | OPT_AUDIO | OPT_VIDEO | OPT_EXPERT, {(void*)opt_default}, "generic catch all option", "" },
4543 int main(int argc, char **argv)
4545 OptionsContext o = { 0 };
4550 av_log_set_flags(AV_LOG_SKIP_REPEATED);
4551 parse_loglevel(argc, argv, options);
4553 if(argc>1 && !strcmp(argv[1], "-d")){
4555 av_log_set_callback(log_callback_null);
4560 avcodec_register_all();
4562 avdevice_register_all();
4565 avfilter_register_all();
4568 avformat_network_init();
4570 show_banner(argc, argv, options);
4573 parse_options(&o, argc, argv, options, opt_output_file);
4575 if (nb_output_files <= 0 && nb_input_files == 0) {
4577 av_log(NULL, AV_LOG_WARNING, "Use -h to get full help or, even better, run 'man %s'\n", program_name);
4581 /* file converter / grab */
4582 if (nb_output_files <= 0) {
4583 fprintf(stderr, "At least one output file must be specified\n");
4587 if (nb_input_files == 0) {
4588 av_log(NULL, AV_LOG_FATAL, "At least one input file must be specified\n");
4593 if (transcode(output_files, nb_output_files, input_files, nb_input_files) < 0)
4595 ti = getutime() - ti;
4597 int maxrss = getmaxrss() / 1024;
4598 printf("bench: utime=%0.3fs maxrss=%ikB\n", ti / 1000000.0, maxrss);