2 * Copyright (c) 2000-2003 Fabrice Bellard
4 * This file is part of FFmpeg.
6 * FFmpeg is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License as published by the Free Software Foundation; either
9 * version 2.1 of the License, or (at your option) any later version.
11 * FFmpeg is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
16 * You should have received a copy of the GNU Lesser General Public
17 * License along with FFmpeg; if not, write to the Free Software
18 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
23 * multimedia converter based on the FFmpeg libraries
35 #include "libavformat/avformat.h"
36 #include "libavdevice/avdevice.h"
37 #include "libswscale/swscale.h"
38 #include "libavutil/opt.h"
39 #include "libavcodec/audioconvert.h"
40 #include "libavutil/audioconvert.h"
41 #include "libavutil/parseutils.h"
42 #include "libavutil/samplefmt.h"
43 #include "libavutil/colorspace.h"
44 #include "libavutil/fifo.h"
45 #include "libavutil/intreadwrite.h"
46 #include "libavutil/dict.h"
47 #include "libavutil/mathematics.h"
48 #include "libavutil/pixdesc.h"
49 #include "libavutil/avstring.h"
50 #include "libavutil/libm.h"
51 #include "libavutil/imgutils.h"
52 #include "libavutil/timestamp.h"
53 #include "libavformat/os_support.h"
54 #include "libswresample/swresample.h"
56 #include "libavformat/ffm.h" // not public API
58 # include "libavfilter/avcodec.h"
59 # include "libavfilter/avfilter.h"
60 # include "libavfilter/avfiltergraph.h"
61 # include "libavfilter/buffersink.h"
62 # include "libavfilter/buffersrc.h"
63 # include "libavfilter/vsrc_buffer.h"
65 #if HAVE_SYS_RESOURCE_H
66 #include <sys/types.h>
68 #include <sys/resource.h>
69 #elif HAVE_GETPROCESSTIMES
72 #if HAVE_GETPROCESSMEMORYINFO
78 #include <sys/select.h>
83 #include <sys/ioctl.h>
93 #include "libavutil/avassert.h"
96 #define VSYNC_PASSTHROUGH 0
99 #define VSYNC_DROP 0xff
101 const char program_name[] = "ffmpeg";
102 const int program_birth_year = 2000;
104 /* select an input stream for an output stream */
105 typedef struct StreamMap {
106 int disabled; /** 1 is this mapping is disabled by a negative map */
110 int sync_stream_index;
114 int file_idx, stream_idx, channel_idx; // input
115 int ofile_idx, ostream_idx; // output
118 static const OptionDef options[];
120 #define MAX_STREAMS 1024 /* arbitrary sanity check value */
122 static int frame_bits_per_raw_sample = 0;
123 static int video_discard = 0;
124 static int same_quant = 0;
125 static int do_deinterlace = 0;
126 static int intra_dc_precision = 8;
127 static int qp_hist = 0;
128 static int intra_only = 0;
129 static const char *video_codec_name = NULL;
130 static const char *audio_codec_name = NULL;
131 static const char *subtitle_codec_name = NULL;
133 static int file_overwrite = 0;
134 static int no_file_overwrite = 0;
135 static int do_benchmark = 0;
136 static int do_benchmark_all = 0;
137 static int do_hex_dump = 0;
138 static int do_pkt_dump = 0;
139 static int do_psnr = 0;
140 static int do_pass = 0;
141 static const char *pass_logfilename_prefix;
142 static int video_sync_method = VSYNC_AUTO;
143 static int audio_sync_method = 0;
144 static float audio_drift_threshold = 0.1;
145 static int copy_ts = 0;
146 static int copy_tb = -1;
147 static int opt_shortest = 0;
148 static char *vstats_filename;
149 static FILE *vstats_file;
151 static int audio_volume = 256;
153 static int exit_on_error = 0;
154 static int using_stdin = 0;
155 static int run_as_daemon = 0;
156 static volatile int received_nb_signals = 0;
157 static int64_t video_size = 0;
158 static int64_t audio_size = 0;
159 static int64_t extra_size = 0;
160 static int nb_frames_dup = 0;
161 static int nb_frames_drop = 0;
162 static int input_sync;
164 static float dts_delta_threshold = 10;
165 static float dts_error_threshold = 3600*30;
167 static int print_stats = 1;
168 static int debug_ts = 0;
169 static int current_time;
171 static uint8_t *audio_buf;
172 static unsigned int allocated_audio_buf_size;
173 static uint8_t *async_buf;
174 static unsigned int allocated_async_buf_size;
176 #define DEFAULT_PASS_LOGFILENAME_PREFIX "ffmpeg2pass"
178 typedef struct FrameBuffer {
184 enum PixelFormat pix_fmt;
187 struct InputStream *ist;
188 struct FrameBuffer *next;
191 typedef struct InputStream {
194 int discard; /* true if stream data should be discarded */
195 int decoding_needed; /* true if the packets must be decoded in 'raw_fifo' */
197 AVFrame *decoded_frame;
198 AVFrame *filtered_frame;
200 int64_t start; /* time when read started */
201 /* predicted dts of the next packet read for this stream or (when there are
202 * several frames in a packet) of the next frame in current packet */
204 /* dts of the last packet read for this stream */
207 int64_t next_pts; ///< synthetic pts for the next decode frame
208 int64_t pts; ///< current pts of the decoded frame
210 int is_start; /* is 1 at the start and after a discontinuity */
211 int showed_multi_packet_warning;
214 /* a pool of free buffers for decoded data */
215 FrameBuffer *buffer_pool;
219 typedef struct InputFile {
220 AVFormatContext *ctx;
221 int eof_reached; /* true if eof reached */
222 int ist_index; /* index of first stream in input_streams */
223 int buffer_size; /* current total buffer size */
225 int nb_streams; /* number of stream that ffmpeg is aware of; may be different
226 from ctx.nb_streams if new streams appear during av_read_frame() */
230 typedef struct OutputStream {
231 int file_index; /* file index */
232 int index; /* stream index in the output file */
233 int source_index; /* InputStream index */
234 AVStream *st; /* stream in the output file */
235 int encoding_needed; /* true if encoding needed for this stream */
237 /* input pts and corresponding output pts
239 struct InputStream *sync_ist; /* input stream to sync against */
240 int64_t sync_opts; /* output frame counter, could be changed to some true timestamp */ // FIXME look at frame_number
241 AVBitStreamFilterContext *bitstream_filters;
244 AVFrame *output_frame;
250 int resample_pix_fmt;
251 AVRational frame_rate;
255 float frame_aspect_ratio;
257 /* forced key frames */
258 int64_t *forced_kf_pts;
264 int audio_channels_map[SWR_CH_MAX]; ///< list of the channels id to pick from the source stream
265 int audio_channels_mapped; ///< number of channels in audio_channels_map
266 int resample_sample_fmt;
267 int resample_channels;
268 int resample_sample_rate;
269 float rematrix_volume;
270 AVFifoBuffer *fifo; /* for compression: one audio fifo per codec */
275 AVFilterContext *output_video_filter;
276 AVFilterContext *input_video_filter;
278 AVFilterGraph *graph;
281 int64_t swr_dither_method;
282 double swr_dither_scale;
284 int is_past_recording_time;
286 const char *attachment_filename;
287 int copy_initial_nonkeyframes;
293 /* init terminal so that we can grab keys */
294 static struct termios oldtty;
295 static int restore_tty;
298 typedef struct OutputFile {
299 AVFormatContext *ctx;
301 int ost_index; /* index of the first stream in output_streams */
302 int64_t recording_time; /* desired length of the resulting file in microseconds */
303 int64_t start_time; /* start time in microseconds */
304 uint64_t limit_filesize; /* filesize limit expressed in bytes */
307 static InputStream *input_streams = NULL;
308 static int nb_input_streams = 0;
309 static InputFile *input_files = NULL;
310 static int nb_input_files = 0;
312 static OutputStream *output_streams = NULL;
313 static int nb_output_streams = 0;
314 static OutputFile *output_files = NULL;
315 static int nb_output_files = 0;
317 typedef struct OptionsContext {
318 /* input/output options */
322 SpecifierOpt *codec_names;
324 SpecifierOpt *audio_channels;
325 int nb_audio_channels;
326 SpecifierOpt *audio_sample_rate;
327 int nb_audio_sample_rate;
328 SpecifierOpt *rematrix_volume;
329 int nb_rematrix_volume;
330 SpecifierOpt *frame_rates;
332 SpecifierOpt *frame_sizes;
334 SpecifierOpt *frame_pix_fmts;
335 int nb_frame_pix_fmts;
338 int64_t input_ts_offset;
341 SpecifierOpt *ts_scale;
343 SpecifierOpt *dump_attachment;
344 int nb_dump_attachment;
347 StreamMap *stream_maps;
349 AudioChannelMap *audio_channel_maps; ///< one info entry per -map_channel
350 int nb_audio_channel_maps; ///< number of (valid) -map_channel settings
351 int metadata_global_manual;
352 int metadata_streams_manual;
353 int metadata_chapters_manual;
354 const char **attachments;
357 int chapters_input_file;
359 int64_t recording_time;
360 uint64_t limit_filesize;
366 int subtitle_disable;
369 /* indexed by output file stream index */
373 SpecifierOpt *metadata;
375 SpecifierOpt *max_frames;
377 SpecifierOpt *bitstream_filters;
378 int nb_bitstream_filters;
379 SpecifierOpt *codec_tags;
381 SpecifierOpt *sample_fmts;
383 SpecifierOpt *qscale;
385 SpecifierOpt *forced_key_frames;
386 int nb_forced_key_frames;
387 SpecifierOpt *force_fps;
389 SpecifierOpt *frame_aspect_ratios;
390 int nb_frame_aspect_ratios;
391 SpecifierOpt *rc_overrides;
393 SpecifierOpt *intra_matrices;
394 int nb_intra_matrices;
395 SpecifierOpt *inter_matrices;
396 int nb_inter_matrices;
397 SpecifierOpt *top_field_first;
398 int nb_top_field_first;
399 SpecifierOpt *metadata_map;
401 SpecifierOpt *presets;
403 SpecifierOpt *copy_initial_nonkeyframes;
404 int nb_copy_initial_nonkeyframes;
405 SpecifierOpt *filters;
409 #define MATCH_PER_STREAM_OPT(name, type, outvar, fmtctx, st)\
412 for (i = 0; i < o->nb_ ## name; i++) {\
413 char *spec = o->name[i].specifier;\
414 if ((ret = check_stream_specifier(fmtctx, st, spec)) > 0)\
415 outvar = o->name[i].u.type;\
421 static int64_t getutime(void)
424 struct rusage rusage;
426 getrusage(RUSAGE_SELF, &rusage);
427 return (rusage.ru_utime.tv_sec * 1000000LL) + rusage.ru_utime.tv_usec;
428 #elif HAVE_GETPROCESSTIMES
431 proc = GetCurrentProcess();
432 GetProcessTimes(proc, &c, &e, &k, &u);
433 return ((int64_t) u.dwHighDateTime << 32 | u.dwLowDateTime) / 10;
439 static void update_benchmark(const char *fmt, ...)
441 if (do_benchmark_all) {
442 int64_t t = getutime();
448 vsnprintf(buf, sizeof(buf), fmt, va);
450 printf("bench: %8"PRIu64" %s \n", t - current_time, buf);
456 static void reset_options(OptionsContext *o, int is_input)
458 const OptionDef *po = options;
459 OptionsContext bak= *o;
461 /* all OPT_SPEC and OPT_STRING can be freed in generic way */
463 void *dst = (uint8_t*)o + po->u.off;
465 if (po->flags & OPT_SPEC) {
466 SpecifierOpt **so = dst;
467 int i, *count = (int*)(so + 1);
468 for (i = 0; i < *count; i++) {
469 av_freep(&(*so)[i].specifier);
470 if (po->flags & OPT_STRING)
471 av_freep(&(*so)[i].u.str);
475 } else if (po->flags & OPT_OFFSET && po->flags & OPT_STRING)
480 av_freep(&o->stream_maps);
481 av_freep(&o->audio_channel_maps);
482 av_freep(&o->streamid_map);
484 memset(o, 0, sizeof(*o));
486 if(is_input) o->recording_time = bak.recording_time;
487 else o->recording_time = INT64_MAX;
488 o->mux_max_delay = 0.7;
489 o->limit_filesize = UINT64_MAX;
490 o->chapters_input_file = INT_MAX;
496 static int alloc_buffer(InputStream *ist, AVCodecContext *s, FrameBuffer **pbuf)
498 FrameBuffer *buf = av_mallocz(sizeof(*buf));
500 const int pixel_size = av_pix_fmt_descriptors[s->pix_fmt].comp[0].step_minus1+1;
501 int h_chroma_shift, v_chroma_shift;
502 int edge = 32; // XXX should be avcodec_get_edge_width(), but that fails on svq1
503 int w = s->width, h = s->height;
506 return AVERROR(ENOMEM);
508 if (!(s->flags & CODEC_FLAG_EMU_EDGE)) {
513 avcodec_align_dimensions(s, &w, &h);
514 if ((ret = av_image_alloc(buf->base, buf->linesize, w, h,
515 s->pix_fmt, 32)) < 0) {
519 /* XXX this shouldn't be needed, but some tests break without this line
520 * those decoders are buggy and need to be fixed.
521 * the following tests fail:
522 * cdgraphics, ansi, aasc, fraps-v1, qtrle-1bit
524 memset(buf->base[0], 128, ret);
526 avcodec_get_chroma_sub_sample(s->pix_fmt, &h_chroma_shift, &v_chroma_shift);
527 for (i = 0; i < FF_ARRAY_ELEMS(buf->data); i++) {
528 const int h_shift = i==0 ? 0 : h_chroma_shift;
529 const int v_shift = i==0 ? 0 : v_chroma_shift;
530 if ((s->flags & CODEC_FLAG_EMU_EDGE) || !buf->linesize[1])
531 buf->data[i] = buf->base[i];
533 buf->data[i] = buf->base[i] +
534 FFALIGN((buf->linesize[i]*edge >> v_shift) +
535 (pixel_size*edge >> h_shift), 32);
539 buf->pix_fmt = s->pix_fmt;
546 static void free_buffer_pool(InputStream *ist)
548 FrameBuffer *buf = ist->buffer_pool;
550 ist->buffer_pool = buf->next;
551 av_freep(&buf->base[0]);
553 buf = ist->buffer_pool;
557 static void unref_buffer(InputStream *ist, FrameBuffer *buf)
559 av_assert0(buf->refcount);
561 if (!buf->refcount) {
562 buf->next = ist->buffer_pool;
563 ist->buffer_pool = buf;
567 static int codec_get_buffer(AVCodecContext *s, AVFrame *frame)
569 InputStream *ist = s->opaque;
573 if(av_image_check_size(s->width, s->height, 0, s) || s->pix_fmt<0)
576 if (!ist->buffer_pool && (ret = alloc_buffer(ist, s, &ist->buffer_pool)) < 0)
579 buf = ist->buffer_pool;
580 ist->buffer_pool = buf->next;
582 if (buf->w != s->width || buf->h != s->height || buf->pix_fmt != s->pix_fmt) {
583 av_freep(&buf->base[0]);
585 if ((ret = alloc_buffer(ist, s, &buf)) < 0)
591 frame->type = FF_BUFFER_TYPE_USER;
592 frame->extended_data = frame->data;
593 frame->pkt_pts = s->pkt ? s->pkt->pts : AV_NOPTS_VALUE;
594 frame->width = buf->w;
595 frame->height = buf->h;
596 frame->format = buf->pix_fmt;
597 frame->sample_aspect_ratio = s->sample_aspect_ratio;
599 for (i = 0; i < FF_ARRAY_ELEMS(buf->data); i++) {
600 frame->base[i] = buf->base[i]; // XXX h264.c uses base though it shouldn't
601 frame->data[i] = buf->data[i];
602 frame->linesize[i] = buf->linesize[i];
608 static void codec_release_buffer(AVCodecContext *s, AVFrame *frame)
610 InputStream *ist = s->opaque;
611 FrameBuffer *buf = frame->opaque;
614 if(frame->type!=FF_BUFFER_TYPE_USER)
615 return avcodec_default_release_buffer(s, frame);
617 for (i = 0; i < FF_ARRAY_ELEMS(frame->data); i++)
618 frame->data[i] = NULL;
620 unref_buffer(ist, buf);
623 static void filter_release_buffer(AVFilterBuffer *fb)
625 FrameBuffer *buf = fb->priv;
627 unref_buffer(buf->ist, buf);
630 static int configure_video_filters(InputStream *ist, OutputStream *ost)
632 AVFilterContext *last_filter, *filter;
633 /** filter graph containing all filters including input & output */
634 AVCodecContext *codec = ost->st->codec;
635 AVCodecContext *icodec = ist->st->codec;
636 enum PixelFormat pix_fmts[] = { codec->pix_fmt, PIX_FMT_NONE };
637 AVBufferSinkParams *buffersink_params = av_buffersink_params_alloc();
638 AVRational sample_aspect_ratio;
642 ost->graph = avfilter_graph_alloc();
644 return AVERROR(ENOMEM);
646 if (ist->st->sample_aspect_ratio.num) {
647 sample_aspect_ratio = ist->st->sample_aspect_ratio;
649 sample_aspect_ratio = ist->st->codec->sample_aspect_ratio;
651 snprintf(args, 255, "%d:%d:%d:%d:%d:%d:%d:flags=%d", ist->st->codec->width,
652 ist->st->codec->height, ist->st->codec->pix_fmt, 1, AV_TIME_BASE,
653 sample_aspect_ratio.num, sample_aspect_ratio.den, SWS_BILINEAR + ((icodec->flags&CODEC_FLAG_BITEXACT) ? SWS_BITEXACT:0));
655 ret = avfilter_graph_create_filter(&ost->input_video_filter, avfilter_get_by_name("buffer"),
656 "src", args, NULL, ost->graph);
660 #if FF_API_OLD_VSINK_API
661 ret = avfilter_graph_create_filter(&ost->output_video_filter, avfilter_get_by_name("buffersink"),
662 "out", NULL, pix_fmts, ost->graph);
664 buffersink_params->pixel_fmts = pix_fmts;
665 ret = avfilter_graph_create_filter(&ost->output_video_filter, avfilter_get_by_name("buffersink"),
666 "out", NULL, buffersink_params, ost->graph);
668 av_freep(&buffersink_params);
672 last_filter = ost->input_video_filter;
674 if (codec->width != icodec->width || codec->height != icodec->height) {
675 snprintf(args, 255, "%d:%d:flags=0x%X",
678 (unsigned)ost->sws_flags);
679 if ((ret = avfilter_graph_create_filter(&filter, avfilter_get_by_name("scale"),
680 NULL, args, NULL, ost->graph)) < 0)
682 if ((ret = avfilter_link(last_filter, 0, filter, 0)) < 0)
684 last_filter = filter;
687 snprintf(args, sizeof(args), "flags=0x%X", (unsigned)ost->sws_flags);
688 ost->graph->scale_sws_opts = av_strdup(args);
691 AVFilterInOut *outputs = avfilter_inout_alloc();
692 AVFilterInOut *inputs = avfilter_inout_alloc();
694 outputs->name = av_strdup("in");
695 outputs->filter_ctx = last_filter;
696 outputs->pad_idx = 0;
697 outputs->next = NULL;
699 inputs->name = av_strdup("out");
700 inputs->filter_ctx = ost->output_video_filter;
704 if ((ret = avfilter_graph_parse(ost->graph, ost->avfilter, &inputs, &outputs, NULL)) < 0)
706 av_freep(&ost->avfilter);
708 if ((ret = avfilter_link(last_filter, 0, ost->output_video_filter, 0)) < 0)
712 if ((ret = avfilter_graph_config(ost->graph, NULL)) < 0)
715 codec->width = ost->output_video_filter->inputs[0]->w;
716 codec->height = ost->output_video_filter->inputs[0]->h;
717 codec->sample_aspect_ratio = ost->st->sample_aspect_ratio =
718 ost->frame_aspect_ratio ? // overridden by the -aspect cli option
719 av_d2q(ost->frame_aspect_ratio * codec->height/codec->width, 255) :
720 ost->output_video_filter->inputs[0]->sample_aspect_ratio;
725 static void term_exit(void)
727 av_log(NULL, AV_LOG_QUIET, "%s", "");
730 tcsetattr (0, TCSANOW, &oldtty);
734 static volatile int received_sigterm = 0;
736 static void sigterm_handler(int sig)
738 received_sigterm = sig;
739 received_nb_signals++;
741 if(received_nb_signals > 3)
745 static void term_init(void)
751 if (tcgetattr (0, &tty) == 0) {
756 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
757 |INLCR|IGNCR|ICRNL|IXON);
758 tty.c_oflag |= OPOST;
759 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
760 tty.c_cflag &= ~(CSIZE|PARENB);
765 tcsetattr (0, TCSANOW, &tty);
767 signal(SIGQUIT, sigterm_handler); /* Quit (POSIX). */
770 avformat_network_deinit();
772 signal(SIGINT , sigterm_handler); /* Interrupt (ANSI). */
773 signal(SIGTERM, sigterm_handler); /* Termination (ANSI). */
775 signal(SIGXCPU, sigterm_handler);
779 /* read a key without blocking */
780 static int read_key(void)
792 n = select(1, &rfds, NULL, NULL, &tv);
801 # if HAVE_PEEKNAMEDPIPE
803 static HANDLE input_handle;
806 input_handle = GetStdHandle(STD_INPUT_HANDLE);
807 is_pipe = !GetConsoleMode(input_handle, &dw);
810 if (stdin->_cnt > 0) {
815 /* When running under a GUI, you will end here. */
816 if (!PeekNamedPipe(input_handle, NULL, 0, NULL, &nchars, NULL))
833 static int decode_interrupt_cb(void *ctx)
835 return received_nb_signals > 1;
838 static const AVIOInterruptCB int_cb = { decode_interrupt_cb, NULL };
840 void av_noreturn exit_program(int ret)
845 for (i = 0; i < nb_output_files; i++) {
846 AVFormatContext *s = output_files[i].ctx;
847 if (!(s->oformat->flags & AVFMT_NOFILE) && s->pb)
849 avformat_free_context(s);
850 av_dict_free(&output_files[i].opts);
852 for (i = 0; i < nb_output_streams; i++) {
853 AVBitStreamFilterContext *bsfc = output_streams[i].bitstream_filters;
855 AVBitStreamFilterContext *next = bsfc->next;
856 av_bitstream_filter_close(bsfc);
859 output_streams[i].bitstream_filters = NULL;
861 if (output_streams[i].output_frame) {
862 AVFrame *frame = output_streams[i].output_frame;
863 if (frame->extended_data != frame->data)
864 av_freep(&frame->extended_data);
868 for (i = 0; i < nb_input_files; i++) {
869 avformat_close_input(&input_files[i].ctx);
871 for (i = 0; i < nb_input_streams; i++) {
872 av_freep(&input_streams[i].decoded_frame);
873 av_freep(&input_streams[i].filtered_frame);
874 av_dict_free(&input_streams[i].opts);
875 free_buffer_pool(&input_streams[i]);
880 av_free(vstats_filename);
882 av_freep(&input_streams);
883 av_freep(&input_files);
884 av_freep(&output_streams);
885 av_freep(&output_files);
888 av_freep(&audio_buf);
889 allocated_audio_buf_size = 0;
890 av_freep(&async_buf);
891 allocated_async_buf_size = 0;
894 avformat_network_deinit();
896 if (received_sigterm) {
897 av_log(NULL, AV_LOG_INFO, "Received signal %d: terminating.\n",
898 (int) received_sigterm);
902 exit(ret); /* not all OS-es handle main() return value */
905 static void assert_avoptions(AVDictionary *m)
907 AVDictionaryEntry *t;
908 if ((t = av_dict_get(m, "", NULL, AV_DICT_IGNORE_SUFFIX))) {
909 av_log(NULL, AV_LOG_FATAL, "Option %s not found.\n", t->key);
914 static void assert_codec_experimental(AVCodecContext *c, int encoder)
916 const char *codec_string = encoder ? "encoder" : "decoder";
918 if (c->codec->capabilities & CODEC_CAP_EXPERIMENTAL &&
919 c->strict_std_compliance > FF_COMPLIANCE_EXPERIMENTAL) {
920 av_log(NULL, AV_LOG_FATAL, "%s '%s' is experimental and might produce bad "
921 "results.\nAdd '-strict experimental' if you want to use it.\n",
922 codec_string, c->codec->name);
923 codec = encoder ? avcodec_find_encoder(c->codec->id) : avcodec_find_decoder(c->codec->id);
924 if (!(codec->capabilities & CODEC_CAP_EXPERIMENTAL))
925 av_log(NULL, AV_LOG_FATAL, "Or use the non experimental %s '%s'.\n",
926 codec_string, codec->name);
931 static void choose_sample_fmt(AVStream *st, AVCodec *codec)
933 if (codec && codec->sample_fmts) {
934 const enum AVSampleFormat *p = codec->sample_fmts;
935 for (; *p != -1; p++) {
936 if (*p == st->codec->sample_fmt)
940 if((codec->capabilities & CODEC_CAP_LOSSLESS) && av_get_sample_fmt_name(st->codec->sample_fmt) > av_get_sample_fmt_name(codec->sample_fmts[0]))
941 av_log(NULL, AV_LOG_ERROR, "Conversion will not be lossless.\n");
942 if(av_get_sample_fmt_name(st->codec->sample_fmt))
943 av_log(NULL, AV_LOG_WARNING,
944 "Incompatible sample format '%s' for codec '%s', auto-selecting format '%s'\n",
945 av_get_sample_fmt_name(st->codec->sample_fmt),
947 av_get_sample_fmt_name(codec->sample_fmts[0]));
948 st->codec->sample_fmt = codec->sample_fmts[0];
953 static void choose_sample_rate(AVStream *st, AVCodec *codec)
955 if (codec && codec->supported_samplerates) {
956 const int *p = codec->supported_samplerates;
958 int best_dist = INT_MAX;
960 int dist = abs(st->codec->sample_rate - *p);
961 if (dist < best_dist) {
968 const int *sample_rates = codec->supported_samplerates;
969 av_log(st->codec, AV_LOG_WARNING,
970 "Requested sampling rate (%dHz) unsupported, using %dHz instead\n"
971 "Available sampling rates for %s:",
972 st->codec->sample_rate, best, codec->name);
973 for (i = 0; sample_rates[i]; i++) {
974 if (!sample_rates[i + 1]) av_log(st->codec, AV_LOG_WARNING, " and");
975 else if (i) av_log(st->codec, AV_LOG_WARNING, ",");
976 av_log(st->codec, AV_LOG_WARNING, " %d", sample_rates[i]);
978 av_log(st->codec, AV_LOG_WARNING, ".\n");
980 st->codec->sample_rate = best;
984 static void choose_pixel_fmt(AVStream *st, AVCodec *codec)
986 if (codec && codec->pix_fmts) {
987 const enum PixelFormat *p = codec->pix_fmts;
988 int has_alpha= av_pix_fmt_descriptors[st->codec->pix_fmt].nb_components % 2 == 0;
989 enum PixelFormat best= PIX_FMT_NONE;
990 if (st->codec->strict_std_compliance <= FF_COMPLIANCE_UNOFFICIAL) {
991 if (st->codec->codec_id == CODEC_ID_MJPEG) {
992 p = (const enum PixelFormat[]) { PIX_FMT_YUVJ420P, PIX_FMT_YUVJ422P, PIX_FMT_YUV420P, PIX_FMT_YUV422P, PIX_FMT_NONE };
993 } else if (st->codec->codec_id == CODEC_ID_LJPEG) {
994 p = (const enum PixelFormat[]) { PIX_FMT_YUVJ420P, PIX_FMT_YUVJ422P, PIX_FMT_YUVJ444P, PIX_FMT_YUV420P,
995 PIX_FMT_YUV422P, PIX_FMT_YUV444P, PIX_FMT_BGRA, PIX_FMT_NONE };
998 for (; *p != PIX_FMT_NONE; p++) {
999 best= avcodec_find_best_pix_fmt2(best, *p, st->codec->pix_fmt, has_alpha, NULL);
1000 if (*p == st->codec->pix_fmt)
1003 if (*p == PIX_FMT_NONE) {
1004 if (st->codec->pix_fmt != PIX_FMT_NONE)
1005 av_log(NULL, AV_LOG_WARNING,
1006 "Incompatible pixel format '%s' for codec '%s', auto-selecting format '%s'\n",
1007 av_pix_fmt_descriptors[st->codec->pix_fmt].name,
1009 av_pix_fmt_descriptors[best].name);
1010 st->codec->pix_fmt = best;
1016 get_sync_ipts(const OutputStream *ost, int64_t pts)
1018 OutputFile *of = &output_files[ost->file_index];
1019 return (double)(pts - of->start_time) / AV_TIME_BASE;
1022 static void write_frame(AVFormatContext *s, AVPacket *pkt, OutputStream *ost)
1024 AVBitStreamFilterContext *bsfc = ost->bitstream_filters;
1025 AVCodecContext *avctx = ost->st->codec;
1028 if ((avctx->codec_type == AVMEDIA_TYPE_VIDEO && video_sync_method == VSYNC_DROP) ||
1029 (avctx->codec_type == AVMEDIA_TYPE_AUDIO && audio_sync_method < 0))
1030 pkt->pts = pkt->dts = AV_NOPTS_VALUE;
1033 * Audio encoders may split the packets -- #frames in != #packets out.
1034 * But there is no reordering, so we can limit the number of output packets
1035 * by simply dropping them here.
1036 * Counting encoded video frames needs to be done separately because of
1037 * reordering, see do_video_out()
1039 if (!(avctx->codec_type == AVMEDIA_TYPE_VIDEO && avctx->codec)) {
1040 if (ost->frame_number >= ost->max_frames) {
1041 av_free_packet(pkt);
1044 ost->frame_number++;
1048 AVPacket new_pkt = *pkt;
1049 int a = av_bitstream_filter_filter(bsfc, avctx, NULL,
1050 &new_pkt.data, &new_pkt.size,
1051 pkt->data, pkt->size,
1052 pkt->flags & AV_PKT_FLAG_KEY);
1054 av_free_packet(pkt);
1055 new_pkt.destruct = av_destruct_packet;
1057 av_log(NULL, AV_LOG_ERROR, "Failed to open bitstream filter %s for stream %d with codec %s",
1058 bsfc->filter->name, pkt->stream_index,
1059 avctx->codec ? avctx->codec->name : "copy");
1069 pkt->stream_index = ost->index;
1070 ret = av_interleaved_write_frame(s, pkt);
1072 print_error("av_interleaved_write_frame()", ret);
1077 static void generate_silence(uint8_t* buf, enum AVSampleFormat sample_fmt, size_t size)
1079 int fill_char = 0x00;
1080 if (sample_fmt == AV_SAMPLE_FMT_U8)
1082 memset(buf, fill_char, size);
1085 static int encode_audio_frame(AVFormatContext *s, OutputStream *ost,
1086 const uint8_t *buf, int buf_size)
1088 AVCodecContext *enc = ost->st->codec;
1089 AVFrame *frame = NULL;
1091 int ret, got_packet;
1093 av_init_packet(&pkt);
1097 if (buf && buf_size) {
1098 if (!ost->output_frame) {
1099 ost->output_frame = avcodec_alloc_frame();
1100 if (!ost->output_frame) {
1101 av_log(NULL, AV_LOG_FATAL, "out-of-memory in encode_audio_frame()\n");
1105 frame = ost->output_frame;
1106 if (frame->extended_data != frame->data)
1107 av_freep(&frame->extended_data);
1108 avcodec_get_frame_defaults(frame);
1110 frame->nb_samples = buf_size /
1111 (enc->channels * av_get_bytes_per_sample(enc->sample_fmt));
1112 if ((ret = avcodec_fill_audio_frame(frame, enc->channels, enc->sample_fmt,
1113 buf, buf_size, 1)) < 0) {
1114 av_log(NULL, AV_LOG_FATAL, "Audio encoding failed (avcodec_fill_audio_frame)\n");
1118 frame->pts = ost->sync_opts;
1119 ost->sync_opts += frame->nb_samples;
1123 update_benchmark(NULL);
1124 if (avcodec_encode_audio2(enc, &pkt, frame, &got_packet) < 0) {
1125 av_log(NULL, AV_LOG_FATAL, "Audio encoding failed (avcodec_encode_audio2)\n");
1128 update_benchmark("encode_audio %d.%d", ost->file_index, ost->index);
1133 if (pkt.pts != AV_NOPTS_VALUE)
1134 pkt.pts = av_rescale_q(pkt.pts, enc->time_base, ost->st->time_base);
1135 if (pkt.dts != AV_NOPTS_VALUE) {
1136 int64_t max = ost->st->cur_dts + !(s->oformat->flags & AVFMT_TS_NONSTRICT);
1137 pkt.dts = av_rescale_q(pkt.dts, enc->time_base, ost->st->time_base);
1138 if (ost->st->cur_dts && ost->st->cur_dts != AV_NOPTS_VALUE && max > pkt.dts) {
1139 av_log(s, max - pkt.dts > 2 ? AV_LOG_WARNING : AV_LOG_DEBUG, "Audio timestamp %"PRId64" < %"PRId64" invalid, cliping\n", pkt.dts, max);
1140 pkt.pts = pkt.dts = max;
1143 if (pkt.duration > 0)
1144 pkt.duration = av_rescale_q(pkt.duration, enc->time_base, ost->st->time_base);
1146 write_frame(s, &pkt, ost);
1148 audio_size += pkt.size;
1150 av_free_packet(&pkt);
1154 av_log(NULL, AV_LOG_INFO, "encoder -> type:audio "
1155 "pkt_pts:%s pkt_pts_time:%s pkt_dts:%s pkt_dts_time:%s\n",
1156 av_ts2str(pkt.pts), av_ts2timestr(pkt.pts, &ost->st->time_base),
1157 av_ts2str(pkt.dts), av_ts2timestr(pkt.dts, &ost->st->time_base));
1163 static int alloc_audio_output_buf(AVCodecContext *dec, AVCodecContext *enc,
1166 int64_t audio_buf_samples;
1169 /* calculate required number of samples to allocate */
1170 audio_buf_samples = ((int64_t)nb_samples * enc->sample_rate + dec->sample_rate) /
1172 audio_buf_samples = 4 * audio_buf_samples + 10000; // safety factors for resampling
1173 audio_buf_samples = FFMAX(audio_buf_samples, enc->frame_size);
1174 if (audio_buf_samples > INT_MAX)
1175 return AVERROR(EINVAL);
1177 audio_buf_size = av_samples_get_buffer_size(NULL, enc->channels,
1179 enc->sample_fmt, 0);
1180 if (audio_buf_size < 0)
1181 return audio_buf_size;
1183 av_fast_malloc(&audio_buf, &allocated_audio_buf_size, audio_buf_size);
1185 return AVERROR(ENOMEM);
1190 static void do_audio_out(AVFormatContext *s, OutputStream *ost,
1191 InputStream *ist, AVFrame *decoded_frame)
1196 int frame_bytes, resample_changed;
1197 AVCodecContext *enc = ost->st->codec;
1198 AVCodecContext *dec = ist->st->codec;
1199 int osize = av_get_bytes_per_sample(enc->sample_fmt);
1200 int isize = av_get_bytes_per_sample(dec->sample_fmt);
1201 uint8_t *buf[AV_NUM_DATA_POINTERS];
1202 int size = decoded_frame->nb_samples * dec->channels * isize;
1203 int planes = av_sample_fmt_is_planar(dec->sample_fmt) ? dec->channels : 1;
1206 av_assert0(planes <= AV_NUM_DATA_POINTERS);
1208 for(i=0; i<planes; i++)
1209 buf[i]= decoded_frame->data[i];
1211 if (alloc_audio_output_buf(dec, enc, decoded_frame->nb_samples) < 0) {
1212 av_log(NULL, AV_LOG_FATAL, "Error allocating audio buffer\n");
1216 if (enc->channels != dec->channels
1217 || enc->sample_fmt != dec->sample_fmt
1218 || enc->sample_rate!= dec->sample_rate
1220 ost->audio_resample = 1;
1222 resample_changed = ost->resample_sample_fmt != dec->sample_fmt ||
1223 ost->resample_channels != dec->channels ||
1224 ost->resample_sample_rate != dec->sample_rate;
1226 if ((ost->audio_resample && !ost->swr) || resample_changed || ost->audio_channels_mapped) {
1227 if (resample_changed) {
1228 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",
1229 ist->file_index, ist->st->index,
1230 ost->resample_sample_rate, av_get_sample_fmt_name(ost->resample_sample_fmt), ost->resample_channels,
1231 dec->sample_rate, av_get_sample_fmt_name(dec->sample_fmt), dec->channels);
1232 ost->resample_sample_fmt = dec->sample_fmt;
1233 ost->resample_channels = dec->channels;
1234 ost->resample_sample_rate = dec->sample_rate;
1235 swr_free(&ost->swr);
1237 /* if audio_sync_method is >1 the resampler is needed for audio drift compensation */
1238 if (audio_sync_method <= 1 && !ost->audio_channels_mapped &&
1239 ost->resample_sample_fmt == enc->sample_fmt &&
1240 ost->resample_channels == enc->channels &&
1241 ost->resample_sample_rate == enc->sample_rate) {
1243 ost->audio_resample = 0;
1245 ost->swr = swr_alloc_set_opts(ost->swr,
1246 enc->channel_layout, enc->sample_fmt, enc->sample_rate,
1247 dec->channel_layout, dec->sample_fmt, dec->sample_rate,
1249 av_opt_set_int(ost->swr, "dither_method", ost->swr_dither_method,0);
1250 av_opt_set_int(ost->swr, "dither_scale", ost->swr_dither_scale,0);
1251 if (ost->audio_channels_mapped)
1252 swr_set_channel_mapping(ost->swr, ost->audio_channels_map);
1253 av_opt_set_double(ost->swr, "rmvol", ost->rematrix_volume, 0);
1254 if (ost->audio_channels_mapped) {
1255 av_opt_set_int(ost->swr, "icl", av_get_default_channel_layout(ost->audio_channels_mapped), 0);
1256 av_opt_set_int(ost->swr, "uch", ost->audio_channels_mapped, 0);
1258 if (av_opt_set_int(ost->swr, "ich", dec->channels, 0) < 0) {
1259 av_log(NULL, AV_LOG_FATAL, "Unsupported number of input channels\n");
1262 if (av_opt_set_int(ost->swr, "och", enc->channels, 0) < 0) {
1263 av_log(NULL, AV_LOG_FATAL, "Unsupported number of output channels\n");
1266 if(audio_sync_method>1) av_opt_set_int(ost->swr, "flags", SWR_FLAG_RESAMPLE, 0);
1267 if(ost->swr && swr_init(ost->swr) < 0){
1268 av_log(NULL, AV_LOG_FATAL, "swr_init() failed\n");
1269 swr_free(&ost->swr);
1273 av_log(NULL, AV_LOG_FATAL, "Can not resample %d channels @ %d Hz to %d channels @ %d Hz\n",
1274 dec->channels, dec->sample_rate,
1275 enc->channels, enc->sample_rate);
1281 av_assert0(ost->audio_resample || dec->sample_fmt==enc->sample_fmt);
1283 if (audio_sync_method > 0) {
1284 double delta = get_sync_ipts(ost, ist->pts) * enc->sample_rate - ost->sync_opts -
1285 av_fifo_size(ost->fifo) / (enc->channels * osize);
1286 int idelta = delta * dec->sample_rate / enc->sample_rate;
1287 int byte_delta = idelta * isize * dec->channels;
1289 // FIXME resample delay
1290 if (fabs(delta) > 50) {
1291 if (ist->is_start || fabs(delta) > audio_drift_threshold*enc->sample_rate) {
1292 if (byte_delta < 0) {
1293 byte_delta = FFMAX(byte_delta, -size);
1295 for (i=0; i<planes; i++)
1296 buf[i] -= byte_delta/planes;
1297 av_log(NULL, AV_LOG_VERBOSE, "discarding %d audio samples\n",
1298 -byte_delta / (isize * dec->channels));
1303 av_fast_malloc(&async_buf, &allocated_async_buf_size,
1306 av_log(NULL, AV_LOG_FATAL, "Out of memory in do_audio_out\n");
1310 if (alloc_audio_output_buf(dec, enc, decoded_frame->nb_samples + idelta) < 0) {
1311 av_log(NULL, AV_LOG_FATAL, "Error allocating audio buffer\n");
1316 for (i=0; i<planes; i++) {
1317 uint8_t *t = async_buf + i*((byte_delta + size)/planes);
1318 generate_silence(t, dec->sample_fmt, byte_delta/planes);
1319 memcpy(t + byte_delta/planes, buf[i], size/planes);
1323 av_log(NULL, AV_LOG_VERBOSE, "adding %d audio samples of silence\n", idelta);
1325 } else if (audio_sync_method > 1) {
1326 int comp = av_clip(delta, -audio_sync_method, audio_sync_method);
1327 av_assert0(ost->audio_resample);
1328 av_log(NULL, AV_LOG_VERBOSE, "compensating audio timestamp drift:%f compensation:%d in:%d\n",
1329 delta, comp, enc->sample_rate);
1330 // 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));
1331 swr_set_compensation(ost->swr, comp, enc->sample_rate);
1334 } else if (audio_sync_method == 0)
1335 ost->sync_opts = lrintf(get_sync_ipts(ost, ist->pts) * enc->sample_rate) -
1336 av_fifo_size(ost->fifo) / (enc->channels * osize); // FIXME wrong
1338 if (ost->audio_resample || ost->audio_channels_mapped) {
1340 size_out = swr_convert(ost->swr, ( uint8_t*[]){buftmp}, allocated_audio_buf_size / (enc->channels * osize),
1341 buf, size / (dec->channels * isize));
1343 av_log(NULL, AV_LOG_FATAL, "swr_convert failed\n");
1346 size_out = size_out * enc->channels * osize;
1352 av_assert0(ost->audio_resample || dec->sample_fmt==enc->sample_fmt);
1354 /* now encode as many frames as possible */
1355 if (!(enc->codec->capabilities & CODEC_CAP_VARIABLE_FRAME_SIZE)) {
1356 /* output resampled raw samples */
1357 if (av_fifo_realloc2(ost->fifo, av_fifo_size(ost->fifo) + size_out) < 0) {
1358 av_log(NULL, AV_LOG_FATAL, "av_fifo_realloc2() failed\n");
1361 av_fifo_generic_write(ost->fifo, buftmp, size_out, NULL);
1363 frame_bytes = enc->frame_size * osize * enc->channels;
1365 while (av_fifo_size(ost->fifo) >= frame_bytes) {
1366 av_fifo_generic_read(ost->fifo, audio_buf, frame_bytes, NULL);
1367 encode_audio_frame(s, ost, audio_buf, frame_bytes);
1370 encode_audio_frame(s, ost, buftmp, size_out);
1374 static void pre_process_video_frame(InputStream *ist, AVPicture *picture, void **bufp)
1376 AVCodecContext *dec;
1377 AVPicture *picture2;
1378 AVPicture picture_tmp;
1381 dec = ist->st->codec;
1383 /* deinterlace : must be done before any resize */
1384 if (do_deinterlace) {
1387 /* create temporary picture */
1388 size = avpicture_get_size(dec->pix_fmt, dec->width, dec->height);
1389 buf = av_malloc(size);
1393 picture2 = &picture_tmp;
1394 avpicture_fill(picture2, buf, dec->pix_fmt, dec->width, dec->height);
1396 if (avpicture_deinterlace(picture2, picture,
1397 dec->pix_fmt, dec->width, dec->height) < 0) {
1398 /* if error, do not deinterlace */
1399 av_log(NULL, AV_LOG_WARNING, "Deinterlacing failed\n");
1408 if (picture != picture2)
1409 *picture = *picture2;
1413 static void do_subtitle_out(AVFormatContext *s,
1419 static uint8_t *subtitle_out = NULL;
1420 int subtitle_out_max_size = 1024 * 1024;
1421 int subtitle_out_size, nb, i;
1422 AVCodecContext *enc;
1425 if (pts == AV_NOPTS_VALUE) {
1426 av_log(NULL, AV_LOG_ERROR, "Subtitle packets must have a pts\n");
1432 enc = ost->st->codec;
1434 if (!subtitle_out) {
1435 subtitle_out = av_malloc(subtitle_out_max_size);
1438 /* Note: DVB subtitle need one packet to draw them and one other
1439 packet to clear them */
1440 /* XXX: signal it in the codec context ? */
1441 if (enc->codec_id == CODEC_ID_DVB_SUBTITLE)
1446 for (i = 0; i < nb; i++) {
1447 ost->sync_opts = av_rescale_q(pts, ist->st->time_base, enc->time_base);
1449 sub->pts = av_rescale_q(pts, ist->st->time_base, AV_TIME_BASE_Q);
1450 // start_display_time is required to be 0
1451 sub->pts += av_rescale_q(sub->start_display_time, (AVRational){ 1, 1000 }, AV_TIME_BASE_Q);
1452 sub->end_display_time -= sub->start_display_time;
1453 sub->start_display_time = 0;
1454 subtitle_out_size = avcodec_encode_subtitle(enc, subtitle_out,
1455 subtitle_out_max_size, sub);
1456 if (subtitle_out_size < 0) {
1457 av_log(NULL, AV_LOG_FATAL, "Subtitle encoding failed\n");
1461 av_init_packet(&pkt);
1462 pkt.data = subtitle_out;
1463 pkt.size = subtitle_out_size;
1464 pkt.pts = av_rescale_q(sub->pts, AV_TIME_BASE_Q, ost->st->time_base);
1465 if (enc->codec_id == CODEC_ID_DVB_SUBTITLE) {
1466 /* XXX: the pts correction is handled here. Maybe handling
1467 it in the codec would be better */
1469 pkt.pts += 90 * sub->start_display_time;
1471 pkt.pts += 90 * sub->end_display_time;
1473 write_frame(s, &pkt, ost);
1477 static double psnr(double d)
1479 return -10.0 * log(d) / log(10.0);
1482 static void do_video_stats(AVFormatContext *os, OutputStream *ost,
1485 AVCodecContext *enc;
1487 double ti1, bitrate, avg_bitrate;
1489 /* this is executed just the first time do_video_stats is called */
1491 vstats_file = fopen(vstats_filename, "w");
1498 enc = ost->st->codec;
1499 if (enc->codec_type == AVMEDIA_TYPE_VIDEO) {
1500 frame_number = ost->frame_number;
1501 fprintf(vstats_file, "frame= %5d q= %2.1f ", frame_number, enc->coded_frame->quality / (float)FF_QP2LAMBDA);
1502 if (enc->flags&CODEC_FLAG_PSNR)
1503 fprintf(vstats_file, "PSNR= %6.2f ", psnr(enc->coded_frame->error[0] / (enc->width * enc->height * 255.0 * 255.0)));
1505 fprintf(vstats_file,"f_size= %6d ", frame_size);
1506 /* compute pts value */
1507 ti1 = ost->sync_opts * av_q2d(enc->time_base);
1511 bitrate = (frame_size * 8) / av_q2d(enc->time_base) / 1000.0;
1512 avg_bitrate = (double)(video_size * 8) / ti1 / 1000.0;
1513 fprintf(vstats_file, "s_size= %8.0fkB time= %0.3f br= %7.1fkbits/s avg_br= %7.1fkbits/s ",
1514 (double)video_size / 1024, ti1, bitrate, avg_bitrate);
1515 fprintf(vstats_file, "type= %c\n", av_get_picture_type_char(enc->coded_frame->pict_type));
1520 static void do_video_out(AVFormatContext *s, OutputStream *ost,
1521 InputStream *ist, AVFrame *in_picture)
1523 int nb_frames, i, ret, format_video_sync;
1524 AVCodecContext *enc;
1525 double sync_ipts, delta;
1526 double duration = 0;
1528 float quality = same_quant ? in_picture->quality
1529 : ost->st->codec->global_quality;
1531 enc = ost->st->codec;
1533 if (ist->st->start_time != AV_NOPTS_VALUE && ist->st->first_dts != AV_NOPTS_VALUE) {
1534 duration = FFMAX(av_q2d(ist->st->time_base), av_q2d(ist->st->codec->time_base));
1535 if(ist->st->r_frame_rate.num)
1536 duration= FFMAX(duration, 1/av_q2d(ist->st->r_frame_rate));
1537 if(ist->st->avg_frame_rate.num && 0)
1538 duration= FFMAX(duration, 1/av_q2d(ist->st->avg_frame_rate));
1540 duration /= av_q2d(enc->time_base);
1543 sync_ipts = get_sync_ipts(ost, in_picture->pts) / av_q2d(enc->time_base);
1544 delta = sync_ipts - ost->sync_opts + duration;
1546 /* by default, we output a single frame */
1549 format_video_sync = video_sync_method;
1550 if (format_video_sync == VSYNC_AUTO)
1551 format_video_sync = (s->oformat->flags & AVFMT_VARIABLE_FPS) ? ((s->oformat->flags & AVFMT_NOTIMESTAMPS) ? VSYNC_PASSTHROUGH : VSYNC_VFR) : 1;
1553 switch (format_video_sync) {
1555 // FIXME set to 0.5 after we fix some dts/pts bugs like in avidec.c
1558 else if (delta > 1.1)
1559 nb_frames = lrintf(delta);
1564 else if (delta > 0.6)
1565 ost->sync_opts = lrintf(sync_ipts);
1568 case VSYNC_PASSTHROUGH:
1569 ost->sync_opts = lrintf(sync_ipts);
1575 nb_frames = FFMIN(nb_frames, ost->max_frames - ost->frame_number);
1576 if (nb_frames == 0) {
1578 av_log(NULL, AV_LOG_VERBOSE, "*** drop!\n");
1580 } else if (nb_frames > 1) {
1581 nb_frames_dup += nb_frames - 1;
1582 av_log(NULL, AV_LOG_VERBOSE, "*** %d dup!\n", nb_frames - 1);
1585 /* duplicates frame if needed */
1586 for (i = 0; i < nb_frames; i++) {
1588 av_init_packet(&pkt);
1592 if (s->oformat->flags & AVFMT_RAWPICTURE &&
1593 enc->codec->id == CODEC_ID_RAWVIDEO) {
1594 /* raw pictures are written as AVPicture structure to
1595 avoid any copies. We support temporarily the older
1597 enc->coded_frame->interlaced_frame = in_picture->interlaced_frame;
1598 enc->coded_frame->top_field_first = in_picture->top_field_first;
1599 pkt.data = (uint8_t *)in_picture;
1600 pkt.size = sizeof(AVPicture);
1601 pkt.pts = av_rescale_q(ost->sync_opts, enc->time_base, ost->st->time_base);
1602 pkt.flags |= AV_PKT_FLAG_KEY;
1604 write_frame(s, &pkt, ost);
1607 AVFrame big_picture;
1609 big_picture = *in_picture;
1610 /* better than nothing: use input picture interlaced
1612 big_picture.interlaced_frame = in_picture->interlaced_frame;
1613 if (ost->st->codec->flags & (CODEC_FLAG_INTERLACED_DCT|CODEC_FLAG_INTERLACED_ME)) {
1614 if (ost->top_field_first == -1)
1615 big_picture.top_field_first = in_picture->top_field_first;
1617 big_picture.top_field_first = !!ost->top_field_first;
1620 /* handles same_quant here. This is not correct because it may
1621 not be a global option */
1622 big_picture.quality = quality;
1623 if (!enc->me_threshold)
1624 big_picture.pict_type = 0;
1625 big_picture.pts = ost->sync_opts;
1626 if (ost->forced_kf_index < ost->forced_kf_count &&
1627 big_picture.pts >= ost->forced_kf_pts[ost->forced_kf_index]) {
1628 big_picture.pict_type = AV_PICTURE_TYPE_I;
1629 ost->forced_kf_index++;
1631 update_benchmark(NULL);
1632 ret = avcodec_encode_video2(enc, &pkt, &big_picture, &got_packet);
1633 update_benchmark("encode_video %d.%d", ost->file_index, ost->index);
1635 av_log(NULL, AV_LOG_FATAL, "Video encoding failed\n");
1640 if (pkt.pts == AV_NOPTS_VALUE && !(enc->codec->capabilities & CODEC_CAP_DELAY))
1641 pkt.pts = ost->sync_opts;
1643 if (pkt.pts != AV_NOPTS_VALUE)
1644 pkt.pts = av_rescale_q(pkt.pts, enc->time_base, ost->st->time_base);
1645 if (pkt.dts != AV_NOPTS_VALUE)
1646 pkt.dts = av_rescale_q(pkt.dts, enc->time_base, ost->st->time_base);
1649 av_log(NULL, AV_LOG_INFO, "encoder -> type:video "
1650 "pkt_pts:%s pkt_pts_time:%s pkt_dts:%s pkt_dts_time:%s\n",
1651 av_ts2str(pkt.pts), av_ts2timestr(pkt.pts, &ost->st->time_base),
1652 av_ts2str(pkt.dts), av_ts2timestr(pkt.dts, &ost->st->time_base));
1655 write_frame(s, &pkt, ost);
1656 frame_size = pkt.size;
1657 video_size += pkt.size;
1658 av_free_packet(&pkt);
1660 /* if two pass, output log */
1661 if (ost->logfile && enc->stats_out) {
1662 fprintf(ost->logfile, "%s", enc->stats_out);
1668 * For video, number of frames in == number of packets out.
1669 * But there may be reordering, so we can't throw away frames on encoder
1670 * flush, we need to limit them here, before they go into encoder.
1672 ost->frame_number++;
1674 if (vstats_filename && frame_size)
1675 do_video_stats(output_files[ost->file_index].ctx, ost, frame_size);
1678 static void print_report(OutputFile *output_files,
1679 OutputStream *ost_table, int nb_ostreams,
1680 int is_last_report, int64_t timer_start, int64_t cur_time)
1684 AVFormatContext *oc;
1686 AVCodecContext *enc;
1687 int frame_number, vid, i;
1689 int64_t pts = INT64_MAX;
1690 static int64_t last_time = -1;
1691 static int qp_histogram[52];
1692 int hours, mins, secs, us;
1694 if (!print_stats && !is_last_report)
1697 if (!is_last_report) {
1698 if (last_time == -1) {
1699 last_time = cur_time;
1702 if ((cur_time - last_time) < 500000)
1704 last_time = cur_time;
1708 oc = output_files[0].ctx;
1710 total_size = avio_size(oc->pb);
1711 if (total_size < 0) { // FIXME improve avio_size() so it works with non seekable output too
1712 total_size = avio_tell(oc->pb);
1719 for (i = 0; i < nb_ostreams; i++) {
1721 ost = &ost_table[i];
1722 enc = ost->st->codec;
1723 if (!ost->stream_copy && enc->coded_frame)
1724 q = enc->coded_frame->quality / (float)FF_QP2LAMBDA;
1725 if (vid && enc->codec_type == AVMEDIA_TYPE_VIDEO) {
1726 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "q=%2.1f ", q);
1728 if (!vid && enc->codec_type == AVMEDIA_TYPE_VIDEO) {
1729 float fps, t = (cur_time-timer_start) / 1000000.0;
1731 frame_number = ost->frame_number;
1732 fps = t > 1 ? frame_number / t : 0;
1733 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "frame=%5d fps=%3.*f q=%3.1f ",
1734 frame_number, fps < 9.95, fps, q);
1736 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "L");
1740 if (qp >= 0 && qp < FF_ARRAY_ELEMS(qp_histogram))
1742 for (j = 0; j < 32; j++)
1743 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "%X", (int)lrintf(log(qp_histogram[j] + 1) / log(2)));
1745 if (enc->flags&CODEC_FLAG_PSNR) {
1747 double error, error_sum = 0;
1748 double scale, scale_sum = 0;
1749 char type[3] = { 'Y','U','V' };
1750 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "PSNR=");
1751 for (j = 0; j < 3; j++) {
1752 if (is_last_report) {
1753 error = enc->error[j];
1754 scale = enc->width * enc->height * 255.0 * 255.0 * frame_number;
1756 error = enc->coded_frame->error[j];
1757 scale = enc->width * enc->height * 255.0 * 255.0;
1763 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "%c:%2.2f ", type[j], psnr(error / scale));
1765 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "*:%2.2f ", psnr(error_sum / scale_sum));
1769 /* compute min output value */
1770 pts = FFMIN(pts, av_rescale_q(ost->st->pts.val,
1771 ost->st->time_base, AV_TIME_BASE_Q));
1774 secs = pts / AV_TIME_BASE;
1775 us = pts % AV_TIME_BASE;
1781 bitrate = pts ? total_size * 8 / (pts / 1000.0) : 0;
1783 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
1784 "size=%8.0fkB time=", total_size / 1024.0);
1785 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
1786 "%02d:%02d:%02d.%02d ", hours, mins, secs,
1787 (100 * us) / AV_TIME_BASE);
1788 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
1789 "bitrate=%6.1fkbits/s", bitrate);
1791 if (nb_frames_dup || nb_frames_drop)
1792 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), " dup=%d drop=%d",
1793 nb_frames_dup, nb_frames_drop);
1795 av_log(NULL, AV_LOG_INFO, "%s \r", buf);
1799 if (is_last_report) {
1800 int64_t raw= audio_size + video_size + extra_size;
1801 av_log(NULL, AV_LOG_INFO, "\n");
1802 av_log(NULL, AV_LOG_INFO, "video:%1.0fkB audio:%1.0fkB global headers:%1.0fkB muxing overhead %f%%\n",
1803 video_size / 1024.0,
1804 audio_size / 1024.0,
1805 extra_size / 1024.0,
1806 100.0 * (total_size - raw) / raw
1808 if(video_size + audio_size + extra_size == 0){
1809 av_log(NULL, AV_LOG_WARNING, "Output file is empty, nothing was encoded (check -ss / -t / -frames parameters if used)\n");
1814 static void flush_encoders(OutputStream *ost_table, int nb_ostreams)
1818 for (i = 0; i < nb_ostreams; i++) {
1819 OutputStream *ost = &ost_table[i];
1820 AVCodecContext *enc = ost->st->codec;
1821 AVFormatContext *os = output_files[ost->file_index].ctx;
1822 int stop_encoding = 0;
1824 if (!ost->encoding_needed)
1827 if (ost->st->codec->codec_type == AVMEDIA_TYPE_AUDIO && enc->frame_size <= 1)
1829 if (ost->st->codec->codec_type == AVMEDIA_TYPE_VIDEO && (os->oformat->flags & AVFMT_RAWPICTURE) && enc->codec->id == CODEC_ID_RAWVIDEO)
1834 int fifo_bytes, got_packet;
1835 av_init_packet(&pkt);
1839 switch (ost->st->codec->codec_type) {
1840 case AVMEDIA_TYPE_AUDIO:
1841 fifo_bytes = av_fifo_size(ost->fifo);
1842 if (fifo_bytes > 0) {
1843 /* encode any samples remaining in fifo */
1844 int frame_bytes = fifo_bytes;
1846 av_fifo_generic_read(ost->fifo, audio_buf, fifo_bytes, NULL);
1848 /* pad last frame with silence if needed */
1849 if (!(enc->codec->capabilities & CODEC_CAP_SMALL_LAST_FRAME)) {
1850 frame_bytes = enc->frame_size * enc->channels *
1851 av_get_bytes_per_sample(enc->sample_fmt);
1852 if (allocated_audio_buf_size < frame_bytes)
1854 generate_silence(audio_buf+fifo_bytes, enc->sample_fmt, frame_bytes - fifo_bytes);
1856 encode_audio_frame(os, ost, audio_buf, frame_bytes);
1858 /* flush encoder with NULL frames until it is done
1859 returning packets */
1860 if (encode_audio_frame(os, ost, NULL, 0) == 0) {
1866 case AVMEDIA_TYPE_VIDEO:
1867 update_benchmark(NULL);
1868 ret = avcodec_encode_video2(enc, &pkt, NULL, &got_packet);
1869 update_benchmark("encode_video %d.%d", ost->file_index, ost->index);
1871 av_log(NULL, AV_LOG_FATAL, "Video encoding failed\n");
1874 video_size += pkt.size;
1875 if (ost->logfile && enc->stats_out) {
1876 fprintf(ost->logfile, "%s", enc->stats_out);
1882 if (pkt.pts != AV_NOPTS_VALUE)
1883 pkt.pts = av_rescale_q(pkt.pts, enc->time_base, ost->st->time_base);
1884 if (pkt.dts != AV_NOPTS_VALUE)
1885 pkt.dts = av_rescale_q(pkt.dts, enc->time_base, ost->st->time_base);
1886 write_frame(os, &pkt, ost);
1898 * Check whether a packet from ist should be written into ost at this time
1900 static int check_output_constraints(InputStream *ist, OutputStream *ost)
1902 OutputFile *of = &output_files[ost->file_index];
1903 int ist_index = ist - input_streams;
1905 if (ost->source_index != ist_index)
1908 if (of->start_time && ist->pts < of->start_time)
1911 if (of->recording_time != INT64_MAX &&
1912 av_compare_ts(ist->pts, AV_TIME_BASE_Q, of->recording_time + of->start_time,
1913 (AVRational){ 1, 1000000 }) >= 0) {
1914 ost->is_past_recording_time = 1;
1921 static void do_streamcopy(InputStream *ist, OutputStream *ost, const AVPacket *pkt)
1923 OutputFile *of = &output_files[ost->file_index];
1924 int64_t ost_tb_start_time = av_rescale_q(of->start_time, AV_TIME_BASE_Q, ost->st->time_base);
1928 av_init_packet(&opkt);
1930 if ((!ost->frame_number && !(pkt->flags & AV_PKT_FLAG_KEY)) &&
1931 !ost->copy_initial_nonkeyframes)
1934 /* force the input stream PTS */
1935 if (ost->st->codec->codec_type == AVMEDIA_TYPE_AUDIO)
1936 audio_size += pkt->size;
1937 else if (ost->st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
1938 video_size += pkt->size;
1942 if (pkt->pts != AV_NOPTS_VALUE)
1943 opkt.pts = av_rescale_q(pkt->pts, ist->st->time_base, ost->st->time_base) - ost_tb_start_time;
1945 opkt.pts = AV_NOPTS_VALUE;
1947 if (pkt->dts == AV_NOPTS_VALUE)
1948 opkt.dts = av_rescale_q(ist->dts, AV_TIME_BASE_Q, ost->st->time_base);
1950 opkt.dts = av_rescale_q(pkt->dts, ist->st->time_base, ost->st->time_base);
1951 opkt.dts -= ost_tb_start_time;
1953 opkt.duration = av_rescale_q(pkt->duration, ist->st->time_base, ost->st->time_base);
1954 opkt.flags = pkt->flags;
1956 // FIXME remove the following 2 lines they shall be replaced by the bitstream filters
1957 if ( ost->st->codec->codec_id != CODEC_ID_H264
1958 && ost->st->codec->codec_id != CODEC_ID_MPEG1VIDEO
1959 && ost->st->codec->codec_id != CODEC_ID_MPEG2VIDEO
1960 && ost->st->codec->codec_id != CODEC_ID_VC1
1962 if (av_parser_change(ist->st->parser, ost->st->codec, &opkt.data, &opkt.size, pkt->data, pkt->size, pkt->flags & AV_PKT_FLAG_KEY))
1963 opkt.destruct = av_destruct_packet;
1965 opkt.data = pkt->data;
1966 opkt.size = pkt->size;
1968 if (of->ctx->oformat->flags & AVFMT_RAWPICTURE) {
1969 /* store AVPicture in AVPacket, as expected by the output format */
1970 avpicture_fill(&pict, opkt.data, ost->st->codec->pix_fmt, ost->st->codec->width, ost->st->codec->height);
1971 opkt.data = (uint8_t *)&pict;
1972 opkt.size = sizeof(AVPicture);
1973 opkt.flags |= AV_PKT_FLAG_KEY;
1976 write_frame(of->ctx, &opkt, ost);
1977 ost->st->codec->frame_number++;
1978 av_free_packet(&opkt);
1981 static void rate_emu_sleep(InputStream *ist)
1983 if (input_files[ist->file_index].rate_emu) {
1984 int64_t pts = av_rescale(ist->dts, 1000000, AV_TIME_BASE);
1985 int64_t now = av_gettime() - ist->start;
1991 static int transcode_audio(InputStream *ist, AVPacket *pkt, int *got_output)
1993 AVFrame *decoded_frame;
1994 AVCodecContext *avctx = ist->st->codec;
1995 int bps = av_get_bytes_per_sample(ist->st->codec->sample_fmt);
1998 if (!ist->decoded_frame && !(ist->decoded_frame = avcodec_alloc_frame()))
1999 return AVERROR(ENOMEM);
2001 avcodec_get_frame_defaults(ist->decoded_frame);
2002 decoded_frame = ist->decoded_frame;
2004 update_benchmark(NULL);
2005 ret = avcodec_decode_audio4(avctx, decoded_frame, got_output, pkt);
2006 update_benchmark("decode_audio %d.%d", ist->file_index, ist->st->index);
2010 if (avctx->sample_rate <= 0) {
2011 av_log(avctx, AV_LOG_ERROR, "Sample rate %d invalid\n", avctx->sample_rate);
2012 return AVERROR_INVALIDDATA;
2016 /* no audio frame */
2020 /* if the decoder provides a pts, use it instead of the last packet pts.
2021 the decoder could be delaying output by a packet or more. */
2022 if (decoded_frame->pts != AV_NOPTS_VALUE)
2023 ist->dts = ist->next_dts = ist->pts = ist->next_pts = decoded_frame->pts;
2025 /* increment next_dts to use for the case where the input stream does not
2026 have timestamps or there are multiple frames in the packet */
2027 ist->next_pts += ((int64_t)AV_TIME_BASE * decoded_frame->nb_samples) /
2029 ist->next_dts += ((int64_t)AV_TIME_BASE * decoded_frame->nb_samples) /
2033 // preprocess audio (volume)
2034 if (audio_volume != 256) {
2035 int decoded_data_size = decoded_frame->nb_samples * avctx->channels * bps;
2036 void *samples = decoded_frame->data[0];
2037 switch (avctx->sample_fmt) {
2038 case AV_SAMPLE_FMT_U8:
2040 uint8_t *volp = samples;
2041 for (i = 0; i < (decoded_data_size / sizeof(*volp)); i++) {
2042 int v = (((*volp - 128) * audio_volume + 128) >> 8) + 128;
2043 *volp++ = av_clip_uint8(v);
2047 case AV_SAMPLE_FMT_S16:
2049 int16_t *volp = samples;
2050 for (i = 0; i < (decoded_data_size / sizeof(*volp)); i++) {
2051 int v = ((*volp) * audio_volume + 128) >> 8;
2052 *volp++ = av_clip_int16(v);
2056 case AV_SAMPLE_FMT_S32:
2058 int32_t *volp = samples;
2059 for (i = 0; i < (decoded_data_size / sizeof(*volp)); i++) {
2060 int64_t v = (((int64_t)*volp * audio_volume + 128) >> 8);
2061 *volp++ = av_clipl_int32(v);
2065 case AV_SAMPLE_FMT_FLT:
2067 float *volp = samples;
2068 float scale = audio_volume / 256.f;
2069 for (i = 0; i < (decoded_data_size / sizeof(*volp)); i++) {
2074 case AV_SAMPLE_FMT_DBL:
2076 double *volp = samples;
2077 double scale = audio_volume / 256.;
2078 for (i = 0; i < (decoded_data_size / sizeof(*volp)); i++) {
2084 av_log(NULL, AV_LOG_FATAL,
2085 "Audio volume adjustment on sample format %s is not supported.\n",
2086 av_get_sample_fmt_name(ist->st->codec->sample_fmt));
2091 rate_emu_sleep(ist);
2093 for (i = 0; i < nb_output_streams; i++) {
2094 OutputStream *ost = &output_streams[i];
2096 if (!check_output_constraints(ist, ost) || !ost->encoding_needed)
2098 do_audio_out(output_files[ost->file_index].ctx, ost, ist, decoded_frame);
2104 static int transcode_video(InputStream *ist, AVPacket *pkt, int *got_output, int64_t *pkt_pts)
2106 AVFrame *decoded_frame;
2107 void *buffer_to_free = NULL;
2109 int64_t *best_effort_timestamp;
2110 AVRational *frame_sample_aspect;
2112 if (!ist->decoded_frame && !(ist->decoded_frame = avcodec_alloc_frame()))
2113 return AVERROR(ENOMEM);
2115 avcodec_get_frame_defaults(ist->decoded_frame);
2116 decoded_frame = ist->decoded_frame;
2117 pkt->pts = *pkt_pts;
2118 pkt->dts = ist->dts;
2119 *pkt_pts = AV_NOPTS_VALUE;
2121 update_benchmark(NULL);
2122 ret = avcodec_decode_video2(ist->st->codec,
2123 decoded_frame, got_output, pkt);
2124 update_benchmark("decode_video %d.%d", ist->file_index, ist->st->index);
2129 /* no picture yet */
2133 best_effort_timestamp= av_opt_ptr(avcodec_get_frame_class(), decoded_frame, "best_effort_timestamp");
2134 if(*best_effort_timestamp != AV_NOPTS_VALUE)
2135 ist->next_pts = ist->pts = decoded_frame->pts = *best_effort_timestamp;
2139 pre_process_video_frame(ist, (AVPicture *)decoded_frame, &buffer_to_free);
2141 frame_sample_aspect= av_opt_ptr(avcodec_get_frame_class(), decoded_frame, "sample_aspect_ratio");
2142 for(i=0;i<nb_output_streams;i++) {
2143 OutputStream *ost = ost = &output_streams[i];
2144 if(check_output_constraints(ist, ost) && ost->encoding_needed){
2145 int changed = ist->st->codec->width != ost->input_video_filter->outputs[0]->w
2146 || ist->st->codec->height != ost->input_video_filter->outputs[0]->h
2147 || ist->st->codec->pix_fmt != ost->input_video_filter->outputs[0]->format;
2148 if (!frame_sample_aspect->num)
2149 *frame_sample_aspect = ist->st->sample_aspect_ratio;
2150 decoded_frame->pts = ist->pts;
2151 if (ist->dr1 && decoded_frame->type==FF_BUFFER_TYPE_USER && !changed) {
2152 FrameBuffer *buf = decoded_frame->opaque;
2153 AVFilterBufferRef *fb = avfilter_get_video_buffer_ref_from_arrays(
2154 decoded_frame->data, decoded_frame->linesize,
2155 AV_PERM_READ | AV_PERM_PRESERVE,
2156 ist->st->codec->width, ist->st->codec->height,
2157 ist->st->codec->pix_fmt);
2159 avfilter_copy_frame_props(fb, decoded_frame);
2160 fb->buf->priv = buf;
2161 fb->buf->free = filter_release_buffer;
2164 av_buffersrc_buffer(ost->input_video_filter, fb);
2166 if((av_vsrc_buffer_add_frame(ost->input_video_filter, decoded_frame, AV_VSRC_BUF_FLAG_OVERWRITE)) < 0){
2167 av_log(NULL, AV_LOG_FATAL, "Failed to inject frame into filter network\n");
2173 rate_emu_sleep(ist);
2175 if (ist->st->sample_aspect_ratio.num)
2176 decoded_frame->sample_aspect_ratio = ist->st->sample_aspect_ratio;
2178 for (i = 0; i < nb_output_streams; i++) {
2179 OutputStream *ost = &output_streams[i];
2181 if (!check_output_constraints(ist, ost) || !ost->encoding_needed)
2184 while (av_buffersink_poll_frame(ost->output_video_filter)) {
2185 AVRational ist_pts_tb = ost->output_video_filter->inputs[0]->time_base;
2186 AVFrame *filtered_frame;
2187 AVFilterBufferRef *picref;
2189 if (av_buffersink_get_buffer_ref(ost->output_video_filter, &picref, 0) < 0){
2190 av_log(NULL, AV_LOG_WARNING, "AV Filter told us it has a frame available but failed to output one\n");
2193 if (!ist->filtered_frame && !(ist->filtered_frame = avcodec_alloc_frame())) {
2194 ret = AVERROR(ENOMEM);
2197 filtered_frame = ist->filtered_frame;
2198 *filtered_frame= *decoded_frame; //for me_threshold
2199 avfilter_fill_frame_from_video_buffer_ref(filtered_frame, picref);
2200 filtered_frame->pts = av_rescale_q(picref->pts, ist_pts_tb, AV_TIME_BASE_Q);
2201 if (!ost->frame_aspect_ratio)
2202 ost->st->codec->sample_aspect_ratio = picref->video->sample_aspect_ratio;
2203 do_video_out(output_files[ost->file_index].ctx, ost, ist, filtered_frame);
2205 avfilter_unref_buffer(picref);
2210 av_free(buffer_to_free);
2214 static int transcode_subtitles(InputStream *ist, AVPacket *pkt, int *got_output)
2216 AVSubtitle subtitle;
2217 int i, ret = avcodec_decode_subtitle2(ist->st->codec,
2218 &subtitle, got_output, pkt);
2224 rate_emu_sleep(ist);
2226 for (i = 0; i < nb_output_streams; i++) {
2227 OutputStream *ost = &output_streams[i];
2229 if (!check_output_constraints(ist, ost) || !ost->encoding_needed)
2232 do_subtitle_out(output_files[ost->file_index].ctx, ost, ist, &subtitle, pkt->pts);
2235 avsubtitle_free(&subtitle);
2239 /* pkt = NULL means EOF (needed to flush decoder buffers) */
2240 static int output_packet(InputStream *ist,
2241 OutputStream *ost_table, int nb_ostreams,
2242 const AVPacket *pkt)
2246 int64_t pkt_pts = AV_NOPTS_VALUE;
2250 if (ist->next_dts == AV_NOPTS_VALUE)
2251 ist->next_dts = ist->dts;
2252 if (ist->next_pts == AV_NOPTS_VALUE)
2253 ist->next_pts = ist->pts;
2257 av_init_packet(&avpkt);
2265 if (pkt->dts != AV_NOPTS_VALUE) {
2266 ist->next_dts = ist->dts = av_rescale_q(pkt->dts, ist->st->time_base, AV_TIME_BASE_Q);
2267 if (ist->st->codec->codec_type != AVMEDIA_TYPE_VIDEO || !ist->decoding_needed)
2268 ist->next_pts = ist->pts = av_rescale_q(pkt->dts, ist->st->time_base, AV_TIME_BASE_Q);
2270 if(pkt->pts != AV_NOPTS_VALUE)
2271 pkt_pts = av_rescale_q(pkt->pts, ist->st->time_base, AV_TIME_BASE_Q);
2273 // while we have more to decode or while the decoder did output something on EOF
2274 while (ist->decoding_needed && (avpkt.size > 0 || (!pkt && got_output))) {
2278 ist->pts = ist->next_pts;
2279 ist->dts = ist->next_dts;
2281 if (avpkt.size && avpkt.size != pkt->size) {
2282 av_log(NULL, ist->showed_multi_packet_warning ? AV_LOG_VERBOSE : AV_LOG_WARNING,
2283 "Multiple frames in a packet from stream %d\n", pkt->stream_index);
2284 ist->showed_multi_packet_warning = 1;
2287 switch (ist->st->codec->codec_type) {
2288 case AVMEDIA_TYPE_AUDIO:
2289 ret = transcode_audio (ist, &avpkt, &got_output);
2291 case AVMEDIA_TYPE_VIDEO:
2292 ret = transcode_video (ist, &avpkt, &got_output, &pkt_pts);
2293 if (avpkt.duration) {
2294 duration = av_rescale_q(avpkt.duration, ist->st->time_base, AV_TIME_BASE_Q);
2295 } else if(ist->st->codec->time_base.num != 0 && ist->st->codec->time_base.den != 0) {
2296 int ticks= ist->st->parser ? ist->st->parser->repeat_pict+1 : ist->st->codec->ticks_per_frame;
2297 duration = ((int64_t)AV_TIME_BASE *
2298 ist->st->codec->time_base.num * ticks) /
2299 ist->st->codec->time_base.den;
2303 if(ist->dts != AV_NOPTS_VALUE && duration) {
2304 ist->next_dts += duration;
2306 ist->next_dts = AV_NOPTS_VALUE;
2309 ist->next_pts += duration; //FIXME the duration is not correct in some cases
2311 case AVMEDIA_TYPE_SUBTITLE:
2312 ret = transcode_subtitles(ist, &avpkt, &got_output);
2322 avpkt.pts= AV_NOPTS_VALUE;
2324 // touch data and size only if not EOF
2326 if(ist->st->codec->codec_type != AVMEDIA_TYPE_AUDIO)
2336 /* handle stream copy */
2337 if (!ist->decoding_needed) {
2338 rate_emu_sleep(ist);
2339 ist->dts = ist->next_dts;
2340 switch (ist->st->codec->codec_type) {
2341 case AVMEDIA_TYPE_AUDIO:
2342 ist->next_dts += ((int64_t)AV_TIME_BASE * ist->st->codec->frame_size) /
2343 ist->st->codec->sample_rate;
2345 case AVMEDIA_TYPE_VIDEO:
2346 if (pkt->duration) {
2347 ist->next_dts += av_rescale_q(pkt->duration, ist->st->time_base, AV_TIME_BASE_Q);
2348 } else if(ist->st->codec->time_base.num != 0) {
2349 int ticks= ist->st->parser ? ist->st->parser->repeat_pict + 1 : ist->st->codec->ticks_per_frame;
2350 ist->next_dts += ((int64_t)AV_TIME_BASE *
2351 ist->st->codec->time_base.num * ticks) /
2352 ist->st->codec->time_base.den;
2356 ist->pts = ist->dts;
2357 ist->next_pts = ist->next_dts;
2359 for (i = 0; pkt && i < nb_ostreams; i++) {
2360 OutputStream *ost = &ost_table[i];
2362 if (!check_output_constraints(ist, ost) || ost->encoding_needed)
2365 do_streamcopy(ist, ost, pkt);
2371 static void print_sdp(OutputFile *output_files, int n)
2375 AVFormatContext **avc = av_malloc(sizeof(*avc) * n);
2379 for (i = 0; i < n; i++)
2380 avc[i] = output_files[i].ctx;
2382 av_sdp_create(avc, n, sdp, sizeof(sdp));
2383 printf("SDP:\n%s\n", sdp);
2388 static void get_default_channel_layouts(OutputStream *ost, InputStream *ist)
2390 char layout_name[256];
2391 AVCodecContext *enc = ost->st->codec;
2392 AVCodecContext *dec = ist->st->codec;
2394 if (!dec->channel_layout) {
2395 if (enc->channel_layout && dec->channels == enc->channels) {
2396 dec->channel_layout = enc->channel_layout;
2398 dec->channel_layout = av_get_default_channel_layout(dec->channels);
2400 if (!dec->channel_layout) {
2401 av_log(NULL, AV_LOG_FATAL, "Unable to find default channel "
2402 "layout for Input Stream #%d.%d\n", ist->file_index,
2407 av_get_channel_layout_string(layout_name, sizeof(layout_name),
2408 dec->channels, dec->channel_layout);
2409 av_log(NULL, AV_LOG_WARNING, "Guessed Channel Layout for Input Stream "
2410 "#%d.%d : %s\n", ist->file_index, ist->st->index, layout_name);
2412 if (!enc->channel_layout) {
2413 if (dec->channels == enc->channels) {
2414 enc->channel_layout = dec->channel_layout;
2417 enc->channel_layout = av_get_default_channel_layout(enc->channels);
2419 if (!enc->channel_layout) {
2420 av_log(NULL, AV_LOG_FATAL, "Unable to find default channel layout "
2421 "for Output Stream #%d.%d\n", ost->file_index,
2425 av_get_channel_layout_string(layout_name, sizeof(layout_name),
2426 enc->channels, enc->channel_layout);
2427 av_log(NULL, AV_LOG_WARNING, "Guessed Channel Layout for Output Stream "
2428 "#%d.%d : %s\n", ost->file_index, ost->st->index, layout_name);
2433 static int init_input_stream(int ist_index, OutputStream *output_streams, int nb_output_streams,
2434 char *error, int error_len)
2436 InputStream *ist = &input_streams[ist_index];
2439 if (ist->decoding_needed) {
2440 AVCodec *codec = ist->dec;
2442 snprintf(error, error_len, "Decoder (codec %s) not found for input stream #%d:%d",
2443 avcodec_get_name(ist->st->codec->codec_id), ist->file_index, ist->st->index);
2444 return AVERROR(EINVAL);
2447 ist->dr1 = codec->capabilities & CODEC_CAP_DR1;
2448 if (codec->type == AVMEDIA_TYPE_VIDEO && ist->dr1) {
2449 ist->st->codec->get_buffer = codec_get_buffer;
2450 ist->st->codec->release_buffer = codec_release_buffer;
2451 ist->st->codec->opaque = ist;
2454 if (!av_dict_get(ist->opts, "threads", NULL, 0))
2455 av_dict_set(&ist->opts, "threads", "auto", 0);
2456 if (avcodec_open2(ist->st->codec, codec, &ist->opts) < 0) {
2457 snprintf(error, error_len, "Error while opening decoder for input stream #%d:%d",
2458 ist->file_index, ist->st->index);
2459 return AVERROR(EINVAL);
2461 assert_codec_experimental(ist->st->codec, 0);
2462 assert_avoptions(ist->opts);
2464 if (ist->st->codec->codec_type == AVMEDIA_TYPE_AUDIO) {
2465 for (i = 0; i < nb_output_streams; i++) {
2466 OutputStream *ost = &output_streams[i];
2467 if (ost->source_index == ist_index) {
2468 if (!ist->st->codec->channel_layout || !ost->st->codec->channel_layout)
2469 get_default_channel_layouts(ost, ist);
2476 ist->dts = ist->st->avg_frame_rate.num ? - ist->st->codec->has_b_frames * AV_TIME_BASE / av_q2d(ist->st->avg_frame_rate) : 0;
2477 ist->next_pts = AV_NOPTS_VALUE;
2478 ist->next_dts = AV_NOPTS_VALUE;
2484 static int transcode_init(OutputFile *output_files, int nb_output_files,
2485 InputFile *input_files, int nb_input_files)
2487 int ret = 0, i, j, k;
2488 AVFormatContext *oc;
2489 AVCodecContext *codec, *icodec;
2495 /* init framerate emulation */
2496 for (i = 0; i < nb_input_files; i++) {
2497 InputFile *ifile = &input_files[i];
2498 if (ifile->rate_emu)
2499 for (j = 0; j < ifile->nb_streams; j++)
2500 input_streams[j + ifile->ist_index].start = av_gettime();
2503 /* output stream init */
2504 for (i = 0; i < nb_output_files; i++) {
2505 oc = output_files[i].ctx;
2506 if (!oc->nb_streams && !(oc->oformat->flags & AVFMT_NOSTREAMS)) {
2507 av_dump_format(oc, i, oc->filename, 1);
2508 av_log(NULL, AV_LOG_ERROR, "Output file #%d does not contain any stream\n", i);
2509 return AVERROR(EINVAL);
2513 /* for each output stream, we compute the right encoding parameters */
2514 for (i = 0; i < nb_output_streams; i++) {
2515 ost = &output_streams[i];
2516 oc = output_files[ost->file_index].ctx;
2517 ist = &input_streams[ost->source_index];
2519 if (ost->attachment_filename)
2522 codec = ost->st->codec;
2523 icodec = ist->st->codec;
2525 ost->st->disposition = ist->st->disposition;
2526 codec->bits_per_raw_sample = icodec->bits_per_raw_sample;
2527 codec->chroma_sample_location = icodec->chroma_sample_location;
2529 if (ost->stream_copy) {
2530 uint64_t extra_size = (uint64_t)icodec->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE;
2532 if (extra_size > INT_MAX) {
2533 return AVERROR(EINVAL);
2536 /* if stream_copy is selected, no need to decode or encode */
2537 codec->codec_id = icodec->codec_id;
2538 codec->codec_type = icodec->codec_type;
2540 if (!codec->codec_tag) {
2541 if (!oc->oformat->codec_tag ||
2542 av_codec_get_id (oc->oformat->codec_tag, icodec->codec_tag) == codec->codec_id ||
2543 av_codec_get_tag(oc->oformat->codec_tag, icodec->codec_id) <= 0)
2544 codec->codec_tag = icodec->codec_tag;
2547 codec->bit_rate = icodec->bit_rate;
2548 codec->rc_max_rate = icodec->rc_max_rate;
2549 codec->rc_buffer_size = icodec->rc_buffer_size;
2550 codec->field_order = icodec->field_order;
2551 codec->extradata = av_mallocz(extra_size);
2552 if (!codec->extradata) {
2553 return AVERROR(ENOMEM);
2555 memcpy(codec->extradata, icodec->extradata, icodec->extradata_size);
2556 codec->extradata_size= icodec->extradata_size;
2558 codec->time_base = ist->st->time_base;
2560 * Avi is a special case here because it supports variable fps but
2561 * having the fps and timebase differe significantly adds quite some
2564 if(!strcmp(oc->oformat->name, "avi")) {
2565 if ( copy_tb<0 && av_q2d(icodec->time_base)*icodec->ticks_per_frame > 2*av_q2d(ist->st->time_base)
2566 && av_q2d(ist->st->time_base) < 1.0/500
2568 codec->time_base = icodec->time_base;
2569 codec->time_base.num *= icodec->ticks_per_frame;
2570 codec->time_base.den *= 2;
2571 codec->ticks_per_frame = 2;
2573 } else if(!(oc->oformat->flags & AVFMT_VARIABLE_FPS)
2574 && strcmp(oc->oformat->name, "mov") && strcmp(oc->oformat->name, "mp4") && strcmp(oc->oformat->name, "3gp")
2575 && strcmp(oc->oformat->name, "3g2") && strcmp(oc->oformat->name, "psp") && strcmp(oc->oformat->name, "ipod")
2577 if( copy_tb<0 && av_q2d(icodec->time_base)*icodec->ticks_per_frame > av_q2d(ist->st->time_base)
2578 && av_q2d(ist->st->time_base) < 1.0/500
2580 codec->time_base = icodec->time_base;
2581 codec->time_base.num *= icodec->ticks_per_frame;
2584 av_reduce(&codec->time_base.num, &codec->time_base.den,
2585 codec->time_base.num, codec->time_base.den, INT_MAX);
2587 switch (codec->codec_type) {
2588 case AVMEDIA_TYPE_AUDIO:
2589 if (audio_volume != 256) {
2590 av_log(NULL, AV_LOG_FATAL, "-acodec copy and -vol are incompatible (frames are not decoded)\n");
2593 codec->channel_layout = icodec->channel_layout;
2594 codec->sample_rate = icodec->sample_rate;
2595 codec->channels = icodec->channels;
2596 codec->frame_size = icodec->frame_size;
2597 codec->audio_service_type = icodec->audio_service_type;
2598 codec->block_align = icodec->block_align;
2600 case AVMEDIA_TYPE_VIDEO:
2601 codec->pix_fmt = icodec->pix_fmt;
2602 codec->width = icodec->width;
2603 codec->height = icodec->height;
2604 codec->has_b_frames = icodec->has_b_frames;
2605 if (!codec->sample_aspect_ratio.num) {
2606 codec->sample_aspect_ratio =
2607 ost->st->sample_aspect_ratio =
2608 ist->st->sample_aspect_ratio.num ? ist->st->sample_aspect_ratio :
2609 ist->st->codec->sample_aspect_ratio.num ?
2610 ist->st->codec->sample_aspect_ratio : (AVRational){0, 1};
2612 ost->st->avg_frame_rate = ist->st->avg_frame_rate;
2614 case AVMEDIA_TYPE_SUBTITLE:
2615 codec->width = icodec->width;
2616 codec->height = icodec->height;
2618 case AVMEDIA_TYPE_DATA:
2619 case AVMEDIA_TYPE_ATTACHMENT:
2626 ost->enc = avcodec_find_encoder(codec->codec_id);
2628 ist->decoding_needed = 1;
2629 ost->encoding_needed = 1;
2631 switch (codec->codec_type) {
2632 case AVMEDIA_TYPE_AUDIO:
2633 ost->fifo = av_fifo_alloc(1024);
2635 return AVERROR(ENOMEM);
2637 if (!codec->sample_rate)
2638 codec->sample_rate = icodec->sample_rate;
2639 choose_sample_rate(ost->st, ost->enc);
2640 codec->time_base = (AVRational){ 1, codec->sample_rate };
2642 if (codec->sample_fmt == AV_SAMPLE_FMT_NONE)
2643 codec->sample_fmt = icodec->sample_fmt;
2644 choose_sample_fmt(ost->st, ost->enc);
2646 if (ost->audio_channels_mapped) {
2647 /* the requested output channel is set to the number of
2648 * -map_channel only if no -ac are specified */
2649 if (!codec->channels) {
2650 codec->channels = ost->audio_channels_mapped;
2651 codec->channel_layout = av_get_default_channel_layout(codec->channels);
2652 if (!codec->channel_layout) {
2653 av_log(NULL, AV_LOG_FATAL, "Unable to find an appropriate channel layout for requested number of channel\n");
2657 /* fill unused channel mapping with -1 (which means a muted
2658 * channel in case the number of output channels is bigger
2659 * than the number of mapped channel) */
2660 for (j = ost->audio_channels_mapped; j < FF_ARRAY_ELEMS(ost->audio_channels_map); j++)
2661 ost->audio_channels_map[j] = -1;
2662 } else if (!codec->channels) {
2663 codec->channels = icodec->channels;
2664 codec->channel_layout = icodec->channel_layout;
2666 if (av_get_channel_layout_nb_channels(codec->channel_layout) != codec->channels)
2667 codec->channel_layout = 0;
2669 ost->audio_resample = codec->sample_rate != icodec->sample_rate || audio_sync_method > 1;
2670 ost->audio_resample |= codec->sample_fmt != icodec->sample_fmt
2671 || codec->channel_layout != icodec->channel_layout;
2672 icodec->request_channels = codec->channels;
2673 ost->resample_sample_fmt = icodec->sample_fmt;
2674 ost->resample_sample_rate = icodec->sample_rate;
2675 ost->resample_channels = icodec->channels;
2677 case AVMEDIA_TYPE_VIDEO:
2678 if (codec->pix_fmt == PIX_FMT_NONE)
2679 codec->pix_fmt = icodec->pix_fmt;
2680 choose_pixel_fmt(ost->st, ost->enc);
2682 if (ost->st->codec->pix_fmt == PIX_FMT_NONE) {
2683 av_log(NULL, AV_LOG_FATAL, "Video pixel format is unknown, stream cannot be encoded\n");
2687 if (!codec->width || !codec->height) {
2688 codec->width = icodec->width;
2689 codec->height = icodec->height;
2692 ost->video_resample = codec->width != icodec->width ||
2693 codec->height != icodec->height ||
2694 codec->pix_fmt != icodec->pix_fmt;
2695 if (ost->video_resample) {
2696 codec->bits_per_raw_sample = frame_bits_per_raw_sample;
2699 ost->resample_height = icodec->height;
2700 ost->resample_width = icodec->width;
2701 ost->resample_pix_fmt = icodec->pix_fmt;
2703 if (!ost->frame_rate.num)
2704 ost->frame_rate = ist->st->r_frame_rate.num ? ist->st->r_frame_rate : (AVRational) { 25, 1 };
2705 if (ost->enc && ost->enc->supported_framerates && !ost->force_fps) {
2706 int idx = av_find_nearest_q_idx(ost->frame_rate, ost->enc->supported_framerates);
2707 ost->frame_rate = ost->enc->supported_framerates[idx];
2709 codec->time_base = (AVRational){ost->frame_rate.den, ost->frame_rate.num};
2710 if ( av_q2d(codec->time_base) < 0.001 && video_sync_method != VSYNC_PASSTHROUGH
2711 && (video_sync_method == VSYNC_CFR || (video_sync_method == VSYNC_AUTO && !(oc->oformat->flags & AVFMT_VARIABLE_FPS)))){
2712 av_log(oc, AV_LOG_WARNING, "Frame rate very high for a muxer not efficiently supporting it.\n"
2713 "Please consider specifying a lower framerate, a different muxer or -vsync 2\n");
2715 for (j = 0; j < ost->forced_kf_count; j++)
2716 ost->forced_kf_pts[j] = av_rescale_q(ost->forced_kf_pts[j],
2720 if (configure_video_filters(ist, ost)) {
2721 av_log(NULL, AV_LOG_FATAL, "Error opening filters!\n");
2725 case AVMEDIA_TYPE_SUBTITLE:
2726 codec->time_base = (AVRational){1, 1000};
2733 if (codec->flags & (CODEC_FLAG_PASS1 | CODEC_FLAG_PASS2)) {
2734 char logfilename[1024];
2737 snprintf(logfilename, sizeof(logfilename), "%s-%d.log",
2738 pass_logfilename_prefix ? pass_logfilename_prefix : DEFAULT_PASS_LOGFILENAME_PREFIX,
2740 if (!strcmp(ost->enc->name, "libx264")) {
2741 av_dict_set(&ost->opts, "stats", logfilename, AV_DICT_DONT_OVERWRITE);
2743 if (codec->flags & CODEC_FLAG_PASS2) {
2745 size_t logbuffer_size;
2746 if (cmdutils_read_file(logfilename, &logbuffer, &logbuffer_size) < 0) {
2747 av_log(NULL, AV_LOG_FATAL, "Error reading log file '%s' for pass-2 encoding\n",
2751 codec->stats_in = logbuffer;
2753 if (codec->flags & CODEC_FLAG_PASS1) {
2754 f = fopen(logfilename, "wb");
2756 av_log(NULL, AV_LOG_FATAL, "Cannot write log file '%s' for pass-1 encoding: %s\n",
2757 logfilename, strerror(errno));
2767 /* open each encoder */
2768 for (i = 0; i < nb_output_streams; i++) {
2769 ost = &output_streams[i];
2770 if (ost->encoding_needed) {
2771 AVCodec *codec = ost->enc;
2772 AVCodecContext *dec = input_streams[ost->source_index].st->codec;
2774 snprintf(error, sizeof(error), "Encoder (codec %s) not found for output stream #%d:%d",
2775 avcodec_get_name(ost->st->codec->codec_id), ost->file_index, ost->index);
2776 ret = AVERROR(EINVAL);
2779 if (dec->subtitle_header) {
2780 ost->st->codec->subtitle_header = av_malloc(dec->subtitle_header_size);
2781 if (!ost->st->codec->subtitle_header) {
2782 ret = AVERROR(ENOMEM);
2785 memcpy(ost->st->codec->subtitle_header, dec->subtitle_header, dec->subtitle_header_size);
2786 ost->st->codec->subtitle_header_size = dec->subtitle_header_size;
2788 if (!av_dict_get(ost->opts, "threads", NULL, 0))
2789 av_dict_set(&ost->opts, "threads", "auto", 0);
2790 if (avcodec_open2(ost->st->codec, codec, &ost->opts) < 0) {
2791 snprintf(error, sizeof(error), "Error while opening encoder for output stream #%d:%d - maybe incorrect parameters such as bit_rate, rate, width or height",
2792 ost->file_index, ost->index);
2793 ret = AVERROR(EINVAL);
2796 assert_codec_experimental(ost->st->codec, 1);
2797 assert_avoptions(ost->opts);
2798 if (ost->st->codec->bit_rate && ost->st->codec->bit_rate < 1000)
2799 av_log(NULL, AV_LOG_WARNING, "The bitrate parameter is set too low."
2800 " It takes bits/s as argument, not kbits/s\n");
2801 extra_size += ost->st->codec->extradata_size;
2803 if (ost->st->codec->me_threshold)
2804 input_streams[ost->source_index].st->codec->debug |= FF_DEBUG_MV;
2808 /* init input streams */
2809 for (i = 0; i < nb_input_streams; i++)
2810 if ((ret = init_input_stream(i, output_streams, nb_output_streams, error, sizeof(error))) < 0)
2813 /* discard unused programs */
2814 for (i = 0; i < nb_input_files; i++) {
2815 InputFile *ifile = &input_files[i];
2816 for (j = 0; j < ifile->ctx->nb_programs; j++) {
2817 AVProgram *p = ifile->ctx->programs[j];
2818 int discard = AVDISCARD_ALL;
2820 for (k = 0; k < p->nb_stream_indexes; k++)
2821 if (!input_streams[ifile->ist_index + p->stream_index[k]].discard) {
2822 discard = AVDISCARD_DEFAULT;
2825 p->discard = discard;
2829 /* open files and write file headers */
2830 for (i = 0; i < nb_output_files; i++) {
2831 oc = output_files[i].ctx;
2832 oc->interrupt_callback = int_cb;
2833 if (avformat_write_header(oc, &output_files[i].opts) < 0) {
2834 snprintf(error, sizeof(error), "Could not write header for output file #%d (incorrect codec parameters ?)", i);
2835 ret = AVERROR(EINVAL);
2838 // assert_avoptions(output_files[i].opts);
2839 if (strcmp(oc->oformat->name, "rtp")) {
2845 /* dump the file output parameters - cannot be done before in case
2847 for (i = 0; i < nb_output_files; i++) {
2848 av_dump_format(output_files[i].ctx, i, output_files[i].ctx->filename, 1);
2851 /* dump the stream mapping */
2852 av_log(NULL, AV_LOG_INFO, "Stream mapping:\n");
2853 for (i = 0; i < nb_output_streams; i++) {
2854 ost = &output_streams[i];
2856 if (ost->attachment_filename) {
2857 /* an attached file */
2858 av_log(NULL, AV_LOG_INFO, " File %s -> Stream #%d:%d\n",
2859 ost->attachment_filename, ost->file_index, ost->index);
2862 av_log(NULL, AV_LOG_INFO, " Stream #%d:%d -> #%d:%d",
2863 input_streams[ost->source_index].file_index,
2864 input_streams[ost->source_index].st->index,
2867 if (ost->audio_channels_mapped) {
2868 av_log(NULL, AV_LOG_INFO, " [ch:");
2869 for (j = 0; j < ost->audio_channels_mapped; j++)
2870 if (ost->audio_channels_map[j] == -1)
2871 av_log(NULL, AV_LOG_INFO, " M");
2873 av_log(NULL, AV_LOG_INFO, " %d", ost->audio_channels_map[j]);
2874 av_log(NULL, AV_LOG_INFO, "]");
2876 if (ost->sync_ist != &input_streams[ost->source_index])
2877 av_log(NULL, AV_LOG_INFO, " [sync #%d:%d]",
2878 ost->sync_ist->file_index,
2879 ost->sync_ist->st->index);
2880 if (ost->stream_copy)
2881 av_log(NULL, AV_LOG_INFO, " (copy)");
2883 av_log(NULL, AV_LOG_INFO, " (%s -> %s)", input_streams[ost->source_index].dec ?
2884 input_streams[ost->source_index].dec->name : "?",
2885 ost->enc ? ost->enc->name : "?");
2886 av_log(NULL, AV_LOG_INFO, "\n");
2890 av_log(NULL, AV_LOG_ERROR, "%s\n", error);
2895 print_sdp(output_files, nb_output_files);
2902 * The following code is the main loop of the file converter
2904 static int transcode(OutputFile *output_files, int nb_output_files,
2905 InputFile *input_files, int nb_input_files)
2908 AVFormatContext *is, *os;
2912 int no_packet_count = 0;
2913 int64_t timer_start;
2916 if (!(no_packet = av_mallocz(nb_input_files)))
2919 ret = transcode_init(output_files, nb_output_files, input_files, nb_input_files);
2924 av_log(NULL, AV_LOG_INFO, "Press [q] to stop, [?] for help\n");
2927 timer_start = av_gettime();
2929 for (; received_sigterm == 0;) {
2930 int file_index, ist_index;
2934 int64_t cur_time= av_gettime();
2936 ipts_min = INT64_MAX;
2938 /* if 'q' pressed, exits */
2940 static int64_t last_time;
2941 if (received_nb_signals)
2943 /* read_key() returns 0 on EOF */
2944 if(cur_time - last_time >= 100000 && !run_as_daemon){
2946 last_time = cur_time;
2951 if (key == '+') av_log_set_level(av_log_get_level()+10);
2952 if (key == '-') av_log_set_level(av_log_get_level()-10);
2953 if (key == 's') qp_hist ^= 1;
2956 do_hex_dump = do_pkt_dump = 0;
2957 } else if(do_pkt_dump){
2961 av_log_set_level(AV_LOG_DEBUG);
2963 if (key == 'c' || key == 'C'){
2964 char buf[4096], target[64], command[256], arg[256] = {0};
2967 fprintf(stderr, "\nEnter command: <target> <time> <command>[ <argument>]\n");
2969 while ((k = read_key()) != '\n' && k != '\r' && i < sizeof(buf)-1)
2974 (n = sscanf(buf, "%63[^ ] %lf %255[^ ] %255[^\n]", target, &time, command, arg)) >= 3) {
2975 av_log(NULL, AV_LOG_DEBUG, "Processing command target:%s time:%f command:%s arg:%s",
2976 target, time, command, arg);
2977 for (i = 0; i < nb_output_streams; i++) {
2978 ost = &output_streams[i];
2981 ret = avfilter_graph_send_command(ost->graph, target, command, arg, buf, sizeof(buf),
2982 key == 'c' ? AVFILTER_CMD_FLAG_ONE : 0);
2983 fprintf(stderr, "Command reply for stream %d: ret:%d res:%s\n", i, ret, buf);
2985 ret = avfilter_graph_queue_command(ost->graph, target, command, arg, 0, time);
2990 av_log(NULL, AV_LOG_ERROR,
2991 "Parse error, at least 3 arguments were expected, "
2992 "only %d given in string '%s'\n", n, buf);
2995 if (key == 'd' || key == 'D'){
2998 debug = input_streams[0].st->codec->debug<<1;
2999 if(!debug) debug = 1;
3000 while(debug & (FF_DEBUG_DCT_COEFF|FF_DEBUG_VIS_QP|FF_DEBUG_VIS_MB_TYPE)) //unsupported, would just crash
3003 if(scanf("%d", &debug)!=1)
3004 fprintf(stderr,"error parsing debug value\n");
3005 for(i=0;i<nb_input_streams;i++) {
3006 input_streams[i].st->codec->debug = debug;
3008 for(i=0;i<nb_output_streams;i++) {
3009 ost = &output_streams[i];
3010 ost->st->codec->debug = debug;
3012 if(debug) av_log_set_level(AV_LOG_DEBUG);
3013 fprintf(stderr,"debug=%d\n", debug);
3016 fprintf(stderr, "key function\n"
3017 "? show this help\n"
3018 "+ increase verbosity\n"
3019 "- decrease verbosity\n"
3020 "c Send command to filtergraph\n"
3021 "D cycle through available debug modes\n"
3022 "h dump packets/hex press to cycle through the 3 states\n"
3024 "s Show QP histogram\n"
3029 /* select the stream that we must read now by looking at the
3030 smallest output pts */
3032 for (i = 0; i < nb_output_streams; i++) {
3036 ost = &output_streams[i];
3037 of = &output_files[ost->file_index];
3038 os = output_files[ost->file_index].ctx;
3039 ist = &input_streams[ost->source_index];
3040 if (ost->is_past_recording_time || no_packet[ist->file_index] ||
3041 (os->pb && avio_tell(os->pb) >= of->limit_filesize))
3043 opts = ost->st->pts.val * av_q2d(ost->st->time_base);
3045 if (!input_files[ist->file_index].eof_reached) {
3046 if (ipts < ipts_min) {
3049 file_index = ist->file_index;
3051 if (opts < opts_min) {
3053 if (!input_sync) file_index = ist->file_index;
3056 if (ost->frame_number >= ost->max_frames) {
3058 for (j = 0; j < of->ctx->nb_streams; j++)
3059 output_streams[of->ost_index + j].is_past_recording_time = 1;
3063 /* if none, if is finished */
3064 if (file_index < 0) {
3065 if (no_packet_count) {
3066 no_packet_count = 0;
3067 memset(no_packet, 0, nb_input_files);
3074 /* read a frame from it and output it in the fifo */
3075 is = input_files[file_index].ctx;
3076 ret = av_read_frame(is, &pkt);
3077 if (ret == AVERROR(EAGAIN)) {
3078 no_packet[file_index] = 1;
3083 input_files[file_index].eof_reached = 1;
3090 no_packet_count = 0;
3091 memset(no_packet, 0, nb_input_files);
3094 av_pkt_dump_log2(NULL, AV_LOG_DEBUG, &pkt, do_hex_dump,
3095 is->streams[pkt.stream_index]);
3097 /* the following test is needed in case new streams appear
3098 dynamically in stream : we ignore them */
3099 if (pkt.stream_index >= input_files[file_index].nb_streams)
3100 goto discard_packet;
3101 ist_index = input_files[file_index].ist_index + pkt.stream_index;
3102 ist = &input_streams[ist_index];
3104 goto discard_packet;
3106 if (pkt.dts != AV_NOPTS_VALUE)
3107 pkt.dts += av_rescale_q(input_files[ist->file_index].ts_offset, AV_TIME_BASE_Q, ist->st->time_base);
3108 if (pkt.pts != AV_NOPTS_VALUE)
3109 pkt.pts += av_rescale_q(input_files[ist->file_index].ts_offset, AV_TIME_BASE_Q, ist->st->time_base);
3111 if (pkt.pts != AV_NOPTS_VALUE)
3112 pkt.pts *= ist->ts_scale;
3113 if (pkt.dts != AV_NOPTS_VALUE)
3114 pkt.dts *= ist->ts_scale;
3117 av_log(NULL, AV_LOG_INFO, "demuxer -> ist_index:%d type:%s "
3118 "next_pts:%s next_pts_time:%s pkt_pts:%s pkt_pts_time:%s pkt_dts:%s pkt_dts_time:%s off:%"PRId64"\n",
3119 ist_index, av_get_media_type_string(ist->st->codec->codec_type),
3120 av_ts2str(ist->next_pts), av_ts2timestr(ist->next_pts, &ist->st->time_base),
3121 av_ts2str(pkt.pts), av_ts2timestr(pkt.pts, &ist->st->time_base),
3122 av_ts2str(pkt.dts), av_ts2timestr(pkt.dts, &ist->st->time_base),
3123 input_files[ist->file_index].ts_offset);
3126 if (pkt.dts != AV_NOPTS_VALUE && ist->next_dts != AV_NOPTS_VALUE && !copy_ts) {
3127 int64_t pkt_dts = av_rescale_q(pkt.dts, ist->st->time_base, AV_TIME_BASE_Q);
3128 int64_t delta = pkt_dts - ist->next_dts;
3129 if (is->iformat->flags & AVFMT_TS_DISCONT) {
3130 if(delta < -1LL*dts_delta_threshold*AV_TIME_BASE ||
3131 (delta > 1LL*dts_delta_threshold*AV_TIME_BASE &&
3132 ist->st->codec->codec_type != AVMEDIA_TYPE_SUBTITLE) ||
3133 pkt_dts+1<ist->pts){
3134 input_files[ist->file_index].ts_offset -= delta;
3135 av_log(NULL, AV_LOG_DEBUG,
3136 "timestamp discontinuity %"PRId64", new offset= %"PRId64"\n",
3137 delta, input_files[ist->file_index].ts_offset);
3138 pkt.dts-= av_rescale_q(delta, AV_TIME_BASE_Q, ist->st->time_base);
3139 if (pkt.pts != AV_NOPTS_VALUE)
3140 pkt.pts-= av_rescale_q(delta, AV_TIME_BASE_Q, ist->st->time_base);
3143 if ( delta < -1LL*dts_error_threshold*AV_TIME_BASE ||
3144 (delta > 1LL*dts_error_threshold*AV_TIME_BASE && ist->st->codec->codec_type != AVMEDIA_TYPE_SUBTITLE) ||
3145 pkt_dts+1<ist->pts){
3146 av_log(NULL, AV_LOG_WARNING, "DTS %"PRId64", next:%"PRId64" st:%d invalid dropping\n", pkt.dts, ist->next_dts, pkt.stream_index);
3147 pkt.dts = AV_NOPTS_VALUE;
3149 if (pkt.pts != AV_NOPTS_VALUE){
3150 int64_t pkt_pts = av_rescale_q(pkt.pts, ist->st->time_base, AV_TIME_BASE_Q);
3151 delta = pkt_pts - ist->next_dts;
3152 if ( delta < -1LL*dts_error_threshold*AV_TIME_BASE ||
3153 (delta > 1LL*dts_error_threshold*AV_TIME_BASE && ist->st->codec->codec_type != AVMEDIA_TYPE_SUBTITLE) ||
3154 pkt_pts+1<ist->pts) {
3155 av_log(NULL, AV_LOG_WARNING, "PTS %"PRId64", next:%"PRId64" invalid dropping st:%d\n", pkt.pts, ist->next_dts, pkt.stream_index);
3156 pkt.pts = AV_NOPTS_VALUE;
3162 // fprintf(stderr,"read #%d.%d size=%d\n", ist->file_index, ist->st->index, pkt.size);
3163 if (output_packet(ist, output_streams, nb_output_streams, &pkt) < 0) {
3165 av_log(NULL, AV_LOG_ERROR, "Error while decoding stream #%d:%d\n",
3166 ist->file_index, ist->st->index);
3169 av_free_packet(&pkt);
3174 av_free_packet(&pkt);
3176 /* dump report by using the output first video and audio streams */
3177 print_report(output_files, output_streams, nb_output_streams, 0, timer_start, cur_time);
3180 /* at the end of stream, we must flush the decoder buffers */
3181 for (i = 0; i < nb_input_streams; i++) {
3182 ist = &input_streams[i];
3183 if (ist->decoding_needed) {
3184 output_packet(ist, output_streams, nb_output_streams, NULL);
3187 flush_encoders(output_streams, nb_output_streams);
3191 /* write the trailer if needed and close file */
3192 for (i = 0; i < nb_output_files; i++) {
3193 os = output_files[i].ctx;
3194 av_write_trailer(os);
3197 /* dump report by using the first video and audio streams */
3198 print_report(output_files, output_streams, nb_output_streams, 1, timer_start, av_gettime());
3200 /* close each encoder */
3201 for (i = 0; i < nb_output_streams; i++) {
3202 ost = &output_streams[i];
3203 if (ost->encoding_needed) {
3204 av_freep(&ost->st->codec->stats_in);
3205 avcodec_close(ost->st->codec);
3207 avfilter_graph_free(&ost->graph);
3210 /* close each decoder */
3211 for (i = 0; i < nb_input_streams; i++) {
3212 ist = &input_streams[i];
3213 if (ist->decoding_needed) {
3214 avcodec_close(ist->st->codec);
3222 av_freep(&no_packet);
3224 if (output_streams) {
3225 for (i = 0; i < nb_output_streams; i++) {
3226 ost = &output_streams[i];
3228 if (ost->stream_copy)
3229 av_freep(&ost->st->codec->extradata);
3231 fclose(ost->logfile);
3232 ost->logfile = NULL;
3234 av_fifo_free(ost->fifo); /* works even if fifo is not
3235 initialized but set to zero */
3236 av_freep(&ost->st->codec->subtitle_header);
3237 av_free(ost->forced_kf_pts);
3238 swr_free(&ost->swr);
3239 av_dict_free(&ost->opts);
3246 static int opt_frame_crop(const char *opt, const char *arg)
3248 av_log(NULL, AV_LOG_FATAL, "Option '%s' has been removed, use the crop filter instead\n", opt);
3249 return AVERROR(EINVAL);
3252 static int opt_pad(const char *opt, const char *arg)
3254 av_log(NULL, AV_LOG_FATAL, "Option '%s' has been removed, use the pad filter instead\n", opt);
3258 static int opt_video_channel(const char *opt, const char *arg)
3260 av_log(NULL, AV_LOG_WARNING, "This option is deprecated, use -channel.\n");
3261 return opt_default("channel", arg);
3264 static int opt_video_standard(const char *opt, const char *arg)
3266 av_log(NULL, AV_LOG_WARNING, "This option is deprecated, use -standard.\n");
3267 return opt_default("standard", arg);
3270 static int opt_audio_codec(OptionsContext *o, const char *opt, const char *arg)
3272 audio_codec_name = arg;
3273 return parse_option(o, "codec:a", arg, options);
3276 static int opt_video_codec(OptionsContext *o, const char *opt, const char *arg)
3278 video_codec_name = arg;
3279 return parse_option(o, "codec:v", arg, options);
3282 static int opt_subtitle_codec(OptionsContext *o, const char *opt, const char *arg)
3284 subtitle_codec_name = arg;
3285 return parse_option(o, "codec:s", arg, options);
3288 static int opt_data_codec(OptionsContext *o, const char *opt, const char *arg)
3290 return parse_option(o, "codec:d", arg, options);
3293 static int opt_map(OptionsContext *o, const char *opt, const char *arg)
3295 StreamMap *m = NULL;
3296 int i, negative = 0, file_idx;
3297 int sync_file_idx = -1, sync_stream_idx = 0;
3305 map = av_strdup(arg);
3307 /* parse sync stream first, just pick first matching stream */
3308 if (sync = strchr(map, ',')) {
3310 sync_file_idx = strtol(sync + 1, &sync, 0);
3311 if (sync_file_idx >= nb_input_files || sync_file_idx < 0) {
3312 av_log(NULL, AV_LOG_FATAL, "Invalid sync file index: %d.\n", sync_file_idx);
3317 for (i = 0; i < input_files[sync_file_idx].nb_streams; i++)
3318 if (check_stream_specifier(input_files[sync_file_idx].ctx,
3319 input_files[sync_file_idx].ctx->streams[i], sync) == 1) {
3320 sync_stream_idx = i;
3323 if (i == input_files[sync_file_idx].nb_streams) {
3324 av_log(NULL, AV_LOG_FATAL, "Sync stream specification in map %s does not "
3325 "match any streams.\n", arg);
3331 file_idx = strtol(map, &p, 0);
3332 if (file_idx >= nb_input_files || file_idx < 0) {
3333 av_log(NULL, AV_LOG_FATAL, "Invalid input file index: %d.\n", file_idx);
3337 /* disable some already defined maps */
3338 for (i = 0; i < o->nb_stream_maps; i++) {
3339 m = &o->stream_maps[i];
3340 if (file_idx == m->file_index &&
3341 check_stream_specifier(input_files[m->file_index].ctx,
3342 input_files[m->file_index].ctx->streams[m->stream_index],
3343 *p == ':' ? p + 1 : p) > 0)
3347 for (i = 0; i < input_files[file_idx].nb_streams; i++) {
3348 if (check_stream_specifier(input_files[file_idx].ctx, input_files[file_idx].ctx->streams[i],
3349 *p == ':' ? p + 1 : p) <= 0)
3351 o->stream_maps = grow_array(o->stream_maps, sizeof(*o->stream_maps),
3352 &o->nb_stream_maps, o->nb_stream_maps + 1);
3353 m = &o->stream_maps[o->nb_stream_maps - 1];
3355 m->file_index = file_idx;
3356 m->stream_index = i;
3358 if (sync_file_idx >= 0) {
3359 m->sync_file_index = sync_file_idx;
3360 m->sync_stream_index = sync_stream_idx;
3362 m->sync_file_index = file_idx;
3363 m->sync_stream_index = i;
3368 av_log(NULL, AV_LOG_FATAL, "Stream map '%s' matches no streams.\n", arg);
3376 static int opt_attach(OptionsContext *o, const char *opt, const char *arg)
3378 o->attachments = grow_array(o->attachments, sizeof(*o->attachments),
3379 &o->nb_attachments, o->nb_attachments + 1);
3380 o->attachments[o->nb_attachments - 1] = arg;
3384 static int opt_map_channel(OptionsContext *o, const char *opt, const char *arg)
3390 o->audio_channel_maps =
3391 grow_array(o->audio_channel_maps, sizeof(*o->audio_channel_maps),
3392 &o->nb_audio_channel_maps, o->nb_audio_channel_maps + 1);
3393 m = &o->audio_channel_maps[o->nb_audio_channel_maps - 1];
3395 /* muted channel syntax */
3396 n = sscanf(arg, "%d:%d.%d", &m->channel_idx, &m->ofile_idx, &m->ostream_idx);
3397 if ((n == 1 || n == 3) && m->channel_idx == -1) {
3398 m->file_idx = m->stream_idx = -1;
3400 m->ofile_idx = m->ostream_idx = -1;
3405 n = sscanf(arg, "%d.%d.%d:%d.%d",
3406 &m->file_idx, &m->stream_idx, &m->channel_idx,
3407 &m->ofile_idx, &m->ostream_idx);
3409 if (n != 3 && n != 5) {
3410 av_log(NULL, AV_LOG_FATAL, "Syntax error, mapchan usage: "
3411 "[file.stream.channel|-1][:syncfile:syncstream]\n");
3415 if (n != 5) // only file.stream.channel specified
3416 m->ofile_idx = m->ostream_idx = -1;
3419 if (m->file_idx < 0 || m->file_idx >= nb_input_files) {
3420 av_log(NULL, AV_LOG_FATAL, "mapchan: invalid input file index: %d\n",
3424 if (m->stream_idx < 0 ||
3425 m->stream_idx >= input_files[m->file_idx].nb_streams) {
3426 av_log(NULL, AV_LOG_FATAL, "mapchan: invalid input file stream index #%d.%d\n",
3427 m->file_idx, m->stream_idx);
3430 st = input_files[m->file_idx].ctx->streams[m->stream_idx];
3431 if (st->codec->codec_type != AVMEDIA_TYPE_AUDIO) {
3432 av_log(NULL, AV_LOG_FATAL, "mapchan: stream #%d.%d is not an audio stream.\n",
3433 m->file_idx, m->stream_idx);
3436 if (m->channel_idx < 0 || m->channel_idx >= st->codec->channels) {
3437 av_log(NULL, AV_LOG_FATAL, "mapchan: invalid audio channel #%d.%d.%d\n",
3438 m->file_idx, m->stream_idx, m->channel_idx);
3445 * Parse a metadata specifier in arg.
3446 * @param type metadata type is written here -- g(lobal)/s(tream)/c(hapter)/p(rogram)
3447 * @param index for type c/p, chapter/program index is written here
3448 * @param stream_spec for type s, the stream specifier is written here
3450 static void parse_meta_type(char *arg, char *type, int *index, const char **stream_spec)
3458 if (*(++arg) && *arg != ':') {
3459 av_log(NULL, AV_LOG_FATAL, "Invalid metadata specifier %s.\n", arg);
3462 *stream_spec = *arg == ':' ? arg + 1 : "";
3466 if (*(++arg) == ':')
3467 *index = strtol(++arg, NULL, 0);
3470 av_log(NULL, AV_LOG_FATAL, "Invalid metadata type %c.\n", *arg);
3477 static int copy_metadata(char *outspec, char *inspec, AVFormatContext *oc, AVFormatContext *ic, OptionsContext *o)
3479 AVDictionary **meta_in = NULL;
3480 AVDictionary **meta_out = NULL;
3482 char type_in, type_out;
3483 const char *istream_spec = NULL, *ostream_spec = NULL;
3484 int idx_in = 0, idx_out = 0;
3486 parse_meta_type(inspec, &type_in, &idx_in, &istream_spec);
3487 parse_meta_type(outspec, &type_out, &idx_out, &ostream_spec);
3490 if (type_out == 'g' || !*outspec)
3491 o->metadata_global_manual = 1;
3492 if (type_out == 's' || !*outspec)
3493 o->metadata_streams_manual = 1;
3494 if (type_out == 'c' || !*outspec)
3495 o->metadata_chapters_manual = 1;
3499 if (type_in == 'g' || type_out == 'g')
3500 o->metadata_global_manual = 1;
3501 if (type_in == 's' || type_out == 's')
3502 o->metadata_streams_manual = 1;
3503 if (type_in == 'c' || type_out == 'c')
3504 o->metadata_chapters_manual = 1;
3506 #define METADATA_CHECK_INDEX(index, nb_elems, desc)\
3507 if ((index) < 0 || (index) >= (nb_elems)) {\
3508 av_log(NULL, AV_LOG_FATAL, "Invalid %s index %d while processing metadata maps.\n",\
3513 #define SET_DICT(type, meta, context, index)\
3516 meta = &context->metadata;\
3519 METADATA_CHECK_INDEX(index, context->nb_chapters, "chapter")\
3520 meta = &context->chapters[index]->metadata;\
3523 METADATA_CHECK_INDEX(index, context->nb_programs, "program")\
3524 meta = &context->programs[index]->metadata;\
3528 SET_DICT(type_in, meta_in, ic, idx_in);
3529 SET_DICT(type_out, meta_out, oc, idx_out);
3531 /* for input streams choose first matching stream */
3532 if (type_in == 's') {
3533 for (i = 0; i < ic->nb_streams; i++) {
3534 if ((ret = check_stream_specifier(ic, ic->streams[i], istream_spec)) > 0) {
3535 meta_in = &ic->streams[i]->metadata;
3541 av_log(NULL, AV_LOG_FATAL, "Stream specifier %s does not match any streams.\n", istream_spec);
3546 if (type_out == 's') {
3547 for (i = 0; i < oc->nb_streams; i++) {
3548 if ((ret = check_stream_specifier(oc, oc->streams[i], ostream_spec)) > 0) {
3549 meta_out = &oc->streams[i]->metadata;
3550 av_dict_copy(meta_out, *meta_in, AV_DICT_DONT_OVERWRITE);
3555 av_dict_copy(meta_out, *meta_in, AV_DICT_DONT_OVERWRITE);
3560 static int opt_recording_timestamp(OptionsContext *o, const char *opt, const char *arg)
3563 int64_t recording_timestamp = parse_time_or_die(opt, arg, 0) / 1E6;
3564 struct tm time = *gmtime((time_t*)&recording_timestamp);
3565 strftime(buf, sizeof(buf), "creation_time=%FT%T%z", &time);
3566 parse_option(o, "metadata", buf, options);
3568 av_log(NULL, AV_LOG_WARNING, "%s is deprecated, set the 'creation_time' metadata "
3569 "tag instead.\n", opt);
3573 static AVCodec *find_codec_or_die(const char *name, enum AVMediaType type, int encoder)
3575 const char *codec_string = encoder ? "encoder" : "decoder";
3579 avcodec_find_encoder_by_name(name) :
3580 avcodec_find_decoder_by_name(name);
3582 av_log(NULL, AV_LOG_FATAL, "Unknown %s '%s'\n", codec_string, name);
3585 if (codec->type != type) {
3586 av_log(NULL, AV_LOG_FATAL, "Invalid %s type '%s'\n", codec_string, name);
3592 static AVCodec *choose_decoder(OptionsContext *o, AVFormatContext *s, AVStream *st)
3594 char *codec_name = NULL;
3596 MATCH_PER_STREAM_OPT(codec_names, str, codec_name, s, st);
3598 AVCodec *codec = find_codec_or_die(codec_name, st->codec->codec_type, 0);
3599 st->codec->codec_id = codec->id;
3602 return avcodec_find_decoder(st->codec->codec_id);
3606 * Add all the streams from the given input file to the global
3607 * list of input streams.
3609 static void add_input_streams(OptionsContext *o, AVFormatContext *ic)
3612 char *next, *codec_tag = NULL;
3614 for (i = 0; i < ic->nb_streams; i++) {
3615 AVStream *st = ic->streams[i];
3616 AVCodecContext *dec = st->codec;
3619 input_streams = grow_array(input_streams, sizeof(*input_streams), &nb_input_streams, nb_input_streams + 1);
3620 ist = &input_streams[nb_input_streams - 1];
3622 ist->file_index = nb_input_files;
3624 st->discard = AVDISCARD_ALL;
3625 ist->opts = filter_codec_opts(codec_opts, choose_decoder(o, ic, st), ic, st);
3627 ist->ts_scale = 1.0;
3628 MATCH_PER_STREAM_OPT(ts_scale, dbl, ist->ts_scale, ic, st);
3630 MATCH_PER_STREAM_OPT(codec_tags, str, codec_tag, ic, st);
3632 uint32_t tag = strtol(codec_tag, &next, 0);
3634 tag = AV_RL32(codec_tag);
3635 st->codec->codec_tag = tag;
3638 ist->dec = choose_decoder(o, ic, st);
3640 switch (dec->codec_type) {
3641 case AVMEDIA_TYPE_VIDEO:
3643 ist->dec = avcodec_find_decoder(dec->codec_id);
3645 dec->flags |= CODEC_FLAG_EMU_EDGE;
3649 case AVMEDIA_TYPE_AUDIO:
3650 case AVMEDIA_TYPE_DATA:
3651 case AVMEDIA_TYPE_SUBTITLE:
3653 ist->dec = avcodec_find_decoder(dec->codec_id);
3655 case AVMEDIA_TYPE_ATTACHMENT:
3656 case AVMEDIA_TYPE_UNKNOWN:
3664 static void assert_file_overwrite(const char *filename)
3666 if ((!file_overwrite || no_file_overwrite) &&
3667 (strchr(filename, ':') == NULL || filename[1] == ':' ||
3668 av_strstart(filename, "file:", NULL))) {
3669 if (avio_check(filename, 0) == 0) {
3670 if (!using_stdin && (!no_file_overwrite || file_overwrite)) {
3671 fprintf(stderr,"File '%s' already exists. Overwrite ? [y/N] ", filename);
3674 signal(SIGINT, SIG_DFL);
3675 if (!read_yesno()) {
3676 av_log(NULL, AV_LOG_FATAL, "Not overwriting - exiting\n");
3682 av_log(NULL, AV_LOG_FATAL, "File '%s' already exists. Exiting.\n", filename);
3689 static void dump_attachment(AVStream *st, const char *filename)
3692 AVIOContext *out = NULL;
3693 AVDictionaryEntry *e;
3695 if (!st->codec->extradata_size) {
3696 av_log(NULL, AV_LOG_WARNING, "No extradata to dump in stream #%d:%d.\n",
3697 nb_input_files - 1, st->index);
3700 if (!*filename && (e = av_dict_get(st->metadata, "filename", NULL, 0)))
3701 filename = e->value;
3703 av_log(NULL, AV_LOG_FATAL, "No filename specified and no 'filename' tag"
3704 "in stream #%d:%d.\n", nb_input_files - 1, st->index);
3708 assert_file_overwrite(filename);
3710 if ((ret = avio_open2(&out, filename, AVIO_FLAG_WRITE, &int_cb, NULL)) < 0) {
3711 av_log(NULL, AV_LOG_FATAL, "Could not open file %s for writing.\n",
3716 avio_write(out, st->codec->extradata, st->codec->extradata_size);
3721 static int opt_input_file(OptionsContext *o, const char *opt, const char *filename)
3723 AVFormatContext *ic;
3724 AVInputFormat *file_iformat = NULL;
3728 AVDictionary **opts;
3729 int orig_nb_streams; // number of streams before avformat_find_stream_info
3732 if (!(file_iformat = av_find_input_format(o->format))) {
3733 av_log(NULL, AV_LOG_FATAL, "Unknown input format: '%s'\n", o->format);
3738 if (!strcmp(filename, "-"))
3741 using_stdin |= !strncmp(filename, "pipe:", 5) ||
3742 !strcmp(filename, "/dev/stdin");
3744 /* get default parameters from command line */
3745 ic = avformat_alloc_context();
3747 print_error(filename, AVERROR(ENOMEM));
3750 if (o->nb_audio_sample_rate) {
3751 snprintf(buf, sizeof(buf), "%d", o->audio_sample_rate[o->nb_audio_sample_rate - 1].u.i);
3752 av_dict_set(&format_opts, "sample_rate", buf, 0);
3754 if (o->nb_audio_channels) {
3755 snprintf(buf, sizeof(buf), "%d", o->audio_channels[o->nb_audio_channels - 1].u.i);
3756 av_dict_set(&format_opts, "channels", buf, 0);
3758 if (o->nb_frame_rates) {
3759 av_dict_set(&format_opts, "framerate", o->frame_rates[o->nb_frame_rates - 1].u.str, 0);
3761 if (o->nb_frame_sizes) {
3762 av_dict_set(&format_opts, "video_size", o->frame_sizes[o->nb_frame_sizes - 1].u.str, 0);
3764 if (o->nb_frame_pix_fmts)
3765 av_dict_set(&format_opts, "pixel_format", o->frame_pix_fmts[o->nb_frame_pix_fmts - 1].u.str, 0);
3767 ic->video_codec_id = video_codec_name ?
3768 find_codec_or_die(video_codec_name , AVMEDIA_TYPE_VIDEO , 0)->id : CODEC_ID_NONE;
3769 ic->audio_codec_id = audio_codec_name ?
3770 find_codec_or_die(audio_codec_name , AVMEDIA_TYPE_AUDIO , 0)->id : CODEC_ID_NONE;
3771 ic->subtitle_codec_id= subtitle_codec_name ?
3772 find_codec_or_die(subtitle_codec_name, AVMEDIA_TYPE_SUBTITLE, 0)->id : CODEC_ID_NONE;
3773 ic->flags |= AVFMT_FLAG_NONBLOCK;
3774 ic->interrupt_callback = int_cb;
3776 /* open the input file with generic avformat function */
3777 err = avformat_open_input(&ic, filename, file_iformat, &format_opts);
3779 print_error(filename, err);
3782 assert_avoptions(format_opts);
3784 /* apply forced codec ids */
3785 for (i = 0; i < ic->nb_streams; i++)
3786 choose_decoder(o, ic, ic->streams[i]);
3788 /* Set AVCodecContext options for avformat_find_stream_info */
3789 opts = setup_find_stream_info_opts(ic, codec_opts);
3790 orig_nb_streams = ic->nb_streams;
3792 /* If not enough info to get the stream parameters, we decode the
3793 first frames to get it. (used in mpeg case for example) */
3794 ret = avformat_find_stream_info(ic, opts);
3796 av_log(NULL, AV_LOG_FATAL, "%s: could not find codec parameters\n", filename);
3797 avformat_close_input(&ic);
3801 timestamp = o->start_time;
3802 /* add the stream start time */
3803 if (ic->start_time != AV_NOPTS_VALUE)
3804 timestamp += ic->start_time;
3806 /* if seeking requested, we execute it */
3807 if (o->start_time != 0) {
3808 ret = av_seek_frame(ic, -1, timestamp, AVSEEK_FLAG_BACKWARD);
3810 av_log(NULL, AV_LOG_WARNING, "%s: could not seek to position %0.3f\n",
3811 filename, (double)timestamp / AV_TIME_BASE);
3815 /* update the current parameters so that they match the one of the input stream */
3816 add_input_streams(o, ic);
3818 /* dump the file content */
3819 av_dump_format(ic, nb_input_files, filename, 0);
3821 input_files = grow_array(input_files, sizeof(*input_files), &nb_input_files, nb_input_files + 1);
3822 input_files[nb_input_files - 1].ctx = ic;
3823 input_files[nb_input_files - 1].ist_index = nb_input_streams - ic->nb_streams;
3824 input_files[nb_input_files - 1].ts_offset = o->input_ts_offset - (copy_ts ? 0 : timestamp);
3825 input_files[nb_input_files - 1].nb_streams = ic->nb_streams;
3826 input_files[nb_input_files - 1].rate_emu = o->rate_emu;
3828 for (i = 0; i < o->nb_dump_attachment; i++) {
3831 for (j = 0; j < ic->nb_streams; j++) {
3832 AVStream *st = ic->streams[j];
3834 if (check_stream_specifier(ic, st, o->dump_attachment[i].specifier) == 1)
3835 dump_attachment(st, o->dump_attachment[i].u.str);
3839 for (i = 0; i < orig_nb_streams; i++)
3840 av_dict_free(&opts[i]);
3843 reset_options(o, 1);
3847 static void parse_forced_key_frames(char *kf, OutputStream *ost)
3852 for (p = kf; *p; p++)
3855 ost->forced_kf_count = n;
3856 ost->forced_kf_pts = av_malloc(sizeof(*ost->forced_kf_pts) * n);
3857 if (!ost->forced_kf_pts) {
3858 av_log(NULL, AV_LOG_FATAL, "Could not allocate forced key frames array.\n");
3861 for (i = 0; i < n; i++) {
3862 p = i ? strchr(p, ',') + 1 : kf;
3863 ost->forced_kf_pts[i] = parse_time_or_die("force_key_frames", p, 1);
3867 static uint8_t *get_line(AVIOContext *s)
3873 if (avio_open_dyn_buf(&line) < 0) {
3874 av_log(NULL, AV_LOG_FATAL, "Could not alloc buffer for reading preset.\n");
3878 while ((c = avio_r8(s)) && c != '\n')
3881 avio_close_dyn_buf(line, &buf);
3886 static int get_preset_file_2(const char *preset_name, const char *codec_name, AVIOContext **s)
3889 char filename[1000];
3890 const char *base[3] = { getenv("AVCONV_DATADIR"),
3895 for (i = 0; i < FF_ARRAY_ELEMS(base) && ret; i++) {
3899 snprintf(filename, sizeof(filename), "%s%s/%s-%s.avpreset", base[i],
3900 i != 1 ? "" : "/.avconv", codec_name, preset_name);
3901 ret = avio_open2(s, filename, AVIO_FLAG_READ, &int_cb, NULL);
3904 snprintf(filename, sizeof(filename), "%s%s/%s.avpreset", base[i],
3905 i != 1 ? "" : "/.avconv", preset_name);
3906 ret = avio_open2(s, filename, AVIO_FLAG_READ, &int_cb, NULL);
3912 static void choose_encoder(OptionsContext *o, AVFormatContext *s, OutputStream *ost)
3914 char *codec_name = NULL;
3916 MATCH_PER_STREAM_OPT(codec_names, str, codec_name, s, ost->st);
3918 ost->st->codec->codec_id = av_guess_codec(s->oformat, NULL, s->filename,
3919 NULL, ost->st->codec->codec_type);
3920 ost->enc = avcodec_find_encoder(ost->st->codec->codec_id);
3921 } else if (!strcmp(codec_name, "copy"))
3922 ost->stream_copy = 1;
3924 ost->enc = find_codec_or_die(codec_name, ost->st->codec->codec_type, 1);
3925 ost->st->codec->codec_id = ost->enc->id;
3929 static OutputStream *new_output_stream(OptionsContext *o, AVFormatContext *oc, enum AVMediaType type, int source_index)
3932 AVStream *st = avformat_new_stream(oc, NULL);
3933 int idx = oc->nb_streams - 1, ret = 0;
3934 char *bsf = NULL, *next, *codec_tag = NULL;
3935 AVBitStreamFilterContext *bsfc, *bsfc_prev = NULL;
3937 char *buf = NULL, *arg = NULL, *preset = NULL;
3938 AVIOContext *s = NULL;
3941 av_log(NULL, AV_LOG_FATAL, "Could not alloc stream.\n");
3945 if (oc->nb_streams - 1 < o->nb_streamid_map)
3946 st->id = o->streamid_map[oc->nb_streams - 1];
3948 output_streams = grow_array(output_streams, sizeof(*output_streams), &nb_output_streams,
3949 nb_output_streams + 1);
3950 ost = &output_streams[nb_output_streams - 1];
3951 ost->file_index = nb_output_files;
3954 st->codec->codec_type = type;
3955 choose_encoder(o, oc, ost);
3957 ost->opts = filter_codec_opts(codec_opts, ost->enc, oc, st);
3960 avcodec_get_context_defaults3(st->codec, ost->enc);
3961 st->codec->codec_type = type; // XXX hack, avcodec_get_context_defaults2() sets type to unknown for stream copy
3963 MATCH_PER_STREAM_OPT(presets, str, preset, oc, st);
3964 if (preset && (!(ret = get_preset_file_2(preset, ost->enc->name, &s)))) {
3967 if (!buf[0] || buf[0] == '#') {
3971 if (!(arg = strchr(buf, '='))) {
3972 av_log(NULL, AV_LOG_FATAL, "Invalid line found in the preset file.\n");
3976 av_dict_set(&ost->opts, buf, arg, AV_DICT_DONT_OVERWRITE);
3978 } while (!s->eof_reached);
3982 av_log(NULL, AV_LOG_FATAL,
3983 "Preset %s specified for stream %d:%d, but could not be opened.\n",
3984 preset, ost->file_index, ost->index);
3988 ost->max_frames = INT64_MAX;
3989 MATCH_PER_STREAM_OPT(max_frames, i64, ost->max_frames, oc, st);
3991 MATCH_PER_STREAM_OPT(bitstream_filters, str, bsf, oc, st);
3993 if (next = strchr(bsf, ','))
3995 if (!(bsfc = av_bitstream_filter_init(bsf))) {
3996 av_log(NULL, AV_LOG_FATAL, "Unknown bitstream filter %s\n", bsf);
4000 bsfc_prev->next = bsfc;
4002 ost->bitstream_filters = bsfc;
4008 MATCH_PER_STREAM_OPT(codec_tags, str, codec_tag, oc, st);
4010 uint32_t tag = strtol(codec_tag, &next, 0);
4012 tag = AV_RL32(codec_tag);
4013 st->codec->codec_tag = tag;
4016 MATCH_PER_STREAM_OPT(qscale, dbl, qscale, oc, st);
4017 if (qscale >= 0 || same_quant) {
4018 st->codec->flags |= CODEC_FLAG_QSCALE;
4019 st->codec->global_quality = FF_QP2LAMBDA * qscale;
4022 if (oc->oformat->flags & AVFMT_GLOBALHEADER)
4023 st->codec->flags |= CODEC_FLAG_GLOBAL_HEADER;
4025 av_opt_get_int(sws_opts, "sws_flags", 0, &ost->sws_flags);
4026 av_opt_get_int (swr_opts, "dither_method", 0, &ost->swr_dither_method);
4027 av_opt_get_double(swr_opts, "dither_scale" , 0, &ost->swr_dither_scale);
4029 ost->source_index = source_index;
4030 if (source_index >= 0) {
4031 ost->sync_ist = &input_streams[source_index];
4032 input_streams[source_index].discard = 0;
4033 input_streams[source_index].st->discard = AVDISCARD_NONE;
4039 static void parse_matrix_coeffs(uint16_t *dest, const char *str)
4042 const char *p = str;
4049 av_log(NULL, AV_LOG_FATAL, "Syntax error in matrix \"%s\" at coeff %d\n", str, i);
4056 static OutputStream *new_video_stream(OptionsContext *o, AVFormatContext *oc, int source_index)
4060 AVCodecContext *video_enc;
4062 ost = new_output_stream(o, oc, AVMEDIA_TYPE_VIDEO, source_index);
4064 video_enc = st->codec;
4066 if (!ost->stream_copy) {
4067 const char *p = NULL;
4068 char *forced_key_frames = NULL, *frame_rate = NULL, *frame_size = NULL;
4069 char *frame_aspect_ratio = NULL, *frame_pix_fmt = NULL;
4070 char *intra_matrix = NULL, *inter_matrix = NULL, *filters = NULL;
4073 MATCH_PER_STREAM_OPT(frame_rates, str, frame_rate, oc, st);
4074 if (frame_rate && av_parse_video_rate(&ost->frame_rate, frame_rate) < 0) {
4075 av_log(NULL, AV_LOG_FATAL, "Invalid framerate value: %s\n", frame_rate);
4079 MATCH_PER_STREAM_OPT(frame_sizes, str, frame_size, oc, st);
4080 if (frame_size && av_parse_video_size(&video_enc->width, &video_enc->height, frame_size) < 0) {
4081 av_log(NULL, AV_LOG_FATAL, "Invalid frame size: %s.\n", frame_size);
4085 MATCH_PER_STREAM_OPT(frame_aspect_ratios, str, frame_aspect_ratio, oc, st);
4086 if (frame_aspect_ratio) {
4088 if (av_parse_ratio(&q, frame_aspect_ratio, 255, 0, NULL) < 0 ||
4089 q.num <= 0 || q.den <= 0) {
4090 av_log(NULL, AV_LOG_FATAL, "Invalid aspect ratio: %s\n", frame_aspect_ratio);
4093 ost->frame_aspect_ratio = av_q2d(q);
4096 video_enc->bits_per_raw_sample = frame_bits_per_raw_sample;
4097 MATCH_PER_STREAM_OPT(frame_pix_fmts, str, frame_pix_fmt, oc, st);
4098 if (frame_pix_fmt && (video_enc->pix_fmt = av_get_pix_fmt(frame_pix_fmt)) == PIX_FMT_NONE) {
4099 av_log(NULL, AV_LOG_FATAL, "Unknown pixel format requested: %s.\n", frame_pix_fmt);
4102 st->sample_aspect_ratio = video_enc->sample_aspect_ratio;
4105 video_enc->gop_size = 0;
4106 MATCH_PER_STREAM_OPT(intra_matrices, str, intra_matrix, oc, st);
4108 if (!(video_enc->intra_matrix = av_mallocz(sizeof(*video_enc->intra_matrix) * 64))) {
4109 av_log(NULL, AV_LOG_FATAL, "Could not allocate memory for intra matrix.\n");
4112 parse_matrix_coeffs(video_enc->intra_matrix, intra_matrix);
4114 MATCH_PER_STREAM_OPT(inter_matrices, str, inter_matrix, oc, st);
4116 if (!(video_enc->inter_matrix = av_mallocz(sizeof(*video_enc->inter_matrix) * 64))) {
4117 av_log(NULL, AV_LOG_FATAL, "Could not allocate memory for inter matrix.\n");
4120 parse_matrix_coeffs(video_enc->inter_matrix, inter_matrix);
4123 MATCH_PER_STREAM_OPT(rc_overrides, str, p, oc, st);
4124 for (i = 0; p; i++) {
4126 int e = sscanf(p, "%d,%d,%d", &start, &end, &q);
4128 av_log(NULL, AV_LOG_FATAL, "error parsing rc_override\n");
4131 /* FIXME realloc failure */
4132 video_enc->rc_override =
4133 av_realloc(video_enc->rc_override,
4134 sizeof(RcOverride) * (i + 1));
4135 video_enc->rc_override[i].start_frame = start;
4136 video_enc->rc_override[i].end_frame = end;
4138 video_enc->rc_override[i].qscale = q;
4139 video_enc->rc_override[i].quality_factor = 1.0;
4142 video_enc->rc_override[i].qscale = 0;
4143 video_enc->rc_override[i].quality_factor = -q/100.0;
4148 video_enc->rc_override_count = i;
4149 if (!video_enc->rc_initial_buffer_occupancy)
4150 video_enc->rc_initial_buffer_occupancy = video_enc->rc_buffer_size * 3 / 4;
4151 video_enc->intra_dc_precision = intra_dc_precision - 8;
4154 video_enc->flags|= CODEC_FLAG_PSNR;
4159 video_enc->flags |= CODEC_FLAG_PASS1;
4162 video_enc->flags |= CODEC_FLAG_PASS2;
4166 MATCH_PER_STREAM_OPT(forced_key_frames, str, forced_key_frames, oc, st);
4167 if (forced_key_frames)
4168 parse_forced_key_frames(forced_key_frames, ost);
4170 MATCH_PER_STREAM_OPT(force_fps, i, ost->force_fps, oc, st);
4172 ost->top_field_first = -1;
4173 MATCH_PER_STREAM_OPT(top_field_first, i, ost->top_field_first, oc, st);
4175 MATCH_PER_STREAM_OPT(filters, str, filters, oc, st);
4177 ost->avfilter = av_strdup(filters);
4179 MATCH_PER_STREAM_OPT(copy_initial_nonkeyframes, i, ost->copy_initial_nonkeyframes, oc ,st);
4185 static OutputStream *new_audio_stream(OptionsContext *o, AVFormatContext *oc, int source_index)
4190 AVCodecContext *audio_enc;
4192 ost = new_output_stream(o, oc, AVMEDIA_TYPE_AUDIO, source_index);
4195 audio_enc = st->codec;
4196 audio_enc->codec_type = AVMEDIA_TYPE_AUDIO;
4198 if (!ost->stream_copy) {
4199 char *sample_fmt = NULL;
4201 MATCH_PER_STREAM_OPT(audio_channels, i, audio_enc->channels, oc, st);
4203 MATCH_PER_STREAM_OPT(sample_fmts, str, sample_fmt, oc, st);
4205 (audio_enc->sample_fmt = av_get_sample_fmt(sample_fmt)) == AV_SAMPLE_FMT_NONE) {
4206 av_log(NULL, AV_LOG_FATAL, "Invalid sample format '%s'\n", sample_fmt);
4210 MATCH_PER_STREAM_OPT(audio_sample_rate, i, audio_enc->sample_rate, oc, st);
4212 ost->rematrix_volume=1.0;
4213 MATCH_PER_STREAM_OPT(rematrix_volume, f, ost->rematrix_volume, oc, st);
4216 /* check for channel mapping for this audio stream */
4217 for (n = 0; n < o->nb_audio_channel_maps; n++) {
4218 AudioChannelMap *map = &o->audio_channel_maps[n];
4219 InputStream *ist = &input_streams[ost->source_index];
4220 if ((map->channel_idx == -1 || (ist->file_index == map->file_idx && ist->st->index == map->stream_idx)) &&
4221 (map->ofile_idx == -1 || ost->file_index == map->ofile_idx) &&
4222 (map->ostream_idx == -1 || ost->st->index == map->ostream_idx)) {
4223 if (ost->audio_channels_mapped < FF_ARRAY_ELEMS(ost->audio_channels_map))
4224 ost->audio_channels_map[ost->audio_channels_mapped++] = map->channel_idx;
4226 av_log(NULL, AV_LOG_FATAL, "Max channel mapping for output %d.%d reached\n",
4227 ost->file_index, ost->st->index);
4234 static OutputStream *new_data_stream(OptionsContext *o, AVFormatContext *oc, int source_index)
4238 ost = new_output_stream(o, oc, AVMEDIA_TYPE_DATA, source_index);
4239 if (!ost->stream_copy) {
4240 av_log(NULL, AV_LOG_FATAL, "Data stream encoding not supported yet (only streamcopy)\n");
4247 static OutputStream *new_attachment_stream(OptionsContext *o, AVFormatContext *oc, int source_index)
4249 OutputStream *ost = new_output_stream(o, oc, AVMEDIA_TYPE_ATTACHMENT, source_index);
4250 ost->stream_copy = 1;
4254 static OutputStream *new_subtitle_stream(OptionsContext *o, AVFormatContext *oc, int source_index)
4258 AVCodecContext *subtitle_enc;
4260 ost = new_output_stream(o, oc, AVMEDIA_TYPE_SUBTITLE, source_index);
4262 subtitle_enc = st->codec;
4264 subtitle_enc->codec_type = AVMEDIA_TYPE_SUBTITLE;
4269 /* arg format is "output-stream-index:streamid-value". */
4270 static int opt_streamid(OptionsContext *o, const char *opt, const char *arg)
4276 av_strlcpy(idx_str, arg, sizeof(idx_str));
4277 p = strchr(idx_str, ':');
4279 av_log(NULL, AV_LOG_FATAL,
4280 "Invalid value '%s' for option '%s', required syntax is 'index:value'\n",
4285 idx = parse_number_or_die(opt, idx_str, OPT_INT, 0, MAX_STREAMS-1);
4286 o->streamid_map = grow_array(o->streamid_map, sizeof(*o->streamid_map), &o->nb_streamid_map, idx+1);
4287 o->streamid_map[idx] = parse_number_or_die(opt, p, OPT_INT, 0, INT_MAX);
4291 static int copy_chapters(InputFile *ifile, OutputFile *ofile, int copy_metadata)
4293 AVFormatContext *is = ifile->ctx;
4294 AVFormatContext *os = ofile->ctx;
4297 for (i = 0; i < is->nb_chapters; i++) {
4298 AVChapter *in_ch = is->chapters[i], *out_ch;
4299 int64_t ts_off = av_rescale_q(ofile->start_time - ifile->ts_offset,
4300 AV_TIME_BASE_Q, in_ch->time_base);
4301 int64_t rt = (ofile->recording_time == INT64_MAX) ? INT64_MAX :
4302 av_rescale_q(ofile->recording_time, AV_TIME_BASE_Q, in_ch->time_base);
4305 if (in_ch->end < ts_off)
4307 if (rt != INT64_MAX && in_ch->start > rt + ts_off)
4310 out_ch = av_mallocz(sizeof(AVChapter));
4312 return AVERROR(ENOMEM);
4314 out_ch->id = in_ch->id;
4315 out_ch->time_base = in_ch->time_base;
4316 out_ch->start = FFMAX(0, in_ch->start - ts_off);
4317 out_ch->end = FFMIN(rt, in_ch->end - ts_off);
4320 av_dict_copy(&out_ch->metadata, in_ch->metadata, 0);
4323 os->chapters = av_realloc_f(os->chapters, os->nb_chapters, sizeof(AVChapter));
4325 return AVERROR(ENOMEM);
4326 os->chapters[os->nb_chapters - 1] = out_ch;
4331 static int read_ffserver_streams(OptionsContext *o, AVFormatContext *s, const char *filename)
4334 AVFormatContext *ic = avformat_alloc_context();
4336 ic->interrupt_callback = int_cb;
4337 err = avformat_open_input(&ic, filename, NULL, NULL);
4340 /* copy stream format */
4341 for(i=0;i<ic->nb_streams;i++) {
4345 AVCodecContext *avctx;
4347 codec = avcodec_find_encoder(ic->streams[i]->codec->codec_id);
4348 ost = new_output_stream(o, s, codec->type, -1);
4353 // FIXME: a more elegant solution is needed
4354 memcpy(st, ic->streams[i], sizeof(AVStream));
4356 st->info = av_malloc(sizeof(*st->info));
4357 memcpy(st->info, ic->streams[i]->info, sizeof(*st->info));
4359 avcodec_copy_context(st->codec, ic->streams[i]->codec);
4361 if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO && !ost->stream_copy)
4362 choose_sample_fmt(st, codec);
4363 else if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO && !ost->stream_copy)
4364 choose_pixel_fmt(st, codec);
4367 avformat_close_input(&ic);
4371 static void opt_output_file(void *optctx, const char *filename)
4373 OptionsContext *o = optctx;
4374 AVFormatContext *oc;
4376 AVOutputFormat *file_oformat;
4380 if (!strcmp(filename, "-"))
4383 err = avformat_alloc_output_context2(&oc, NULL, o->format, filename);
4385 print_error(filename, err);
4388 file_oformat= oc->oformat;
4389 oc->interrupt_callback = int_cb;
4391 if (!strcmp(file_oformat->name, "ffm") &&
4392 av_strstart(filename, "http:", NULL)) {
4394 /* special case for files sent to ffserver: we get the stream
4395 parameters from ffserver */
4396 int err = read_ffserver_streams(o, oc, filename);
4398 print_error(filename, err);
4401 for(j = nb_output_streams - oc->nb_streams; j < nb_output_streams; j++) {
4402 ost = &output_streams[j];
4403 for (i = 0; i < nb_input_streams; i++) {
4404 ist = &input_streams[i];
4405 if(ist->st->codec->codec_type == ost->st->codec->codec_type){
4407 ost->source_index= i;
4409 ist->st->discard = AVDISCARD_NONE;
4414 av_log(NULL, AV_LOG_FATAL, "Missing %s stream which is required by this ffm\n", av_get_media_type_string(ost->st->codec->codec_type));
4418 } else if (!o->nb_stream_maps) {
4419 /* pick the "best" stream of each type */
4421 /* video: highest resolution */
4422 if (!o->video_disable && oc->oformat->video_codec != CODEC_ID_NONE) {
4423 int area = 0, idx = -1;
4424 for (i = 0; i < nb_input_streams; i++) {
4425 ist = &input_streams[i];
4426 if (ist->st->codec->codec_type == AVMEDIA_TYPE_VIDEO &&
4427 ist->st->codec->width * ist->st->codec->height > area) {
4428 area = ist->st->codec->width * ist->st->codec->height;
4433 new_video_stream(o, oc, idx);
4436 /* audio: most channels */
4437 if (!o->audio_disable && oc->oformat->audio_codec != CODEC_ID_NONE) {
4438 int channels = 0, idx = -1;
4439 for (i = 0; i < nb_input_streams; i++) {
4440 ist = &input_streams[i];
4441 if (ist->st->codec->codec_type == AVMEDIA_TYPE_AUDIO &&
4442 ist->st->codec->channels > channels) {
4443 channels = ist->st->codec->channels;
4448 new_audio_stream(o, oc, idx);
4451 /* subtitles: pick first */
4452 if (!o->subtitle_disable && (oc->oformat->subtitle_codec != CODEC_ID_NONE || subtitle_codec_name)) {
4453 for (i = 0; i < nb_input_streams; i++)
4454 if (input_streams[i].st->codec->codec_type == AVMEDIA_TYPE_SUBTITLE) {
4455 new_subtitle_stream(o, oc, i);
4459 /* do something with data? */
4461 for (i = 0; i < o->nb_stream_maps; i++) {
4462 StreamMap *map = &o->stream_maps[i];
4463 int src_idx = input_files[map->file_index].ist_index + map->stream_index;
4468 ist = &input_streams[input_files[map->file_index].ist_index + map->stream_index];
4469 if(o->subtitle_disable && ist->st->codec->codec_type == AVMEDIA_TYPE_SUBTITLE)
4471 if(o-> audio_disable && ist->st->codec->codec_type == AVMEDIA_TYPE_AUDIO)
4473 if(o-> video_disable && ist->st->codec->codec_type == AVMEDIA_TYPE_VIDEO)
4475 if(o-> data_disable && ist->st->codec->codec_type == AVMEDIA_TYPE_DATA)
4478 switch (ist->st->codec->codec_type) {
4479 case AVMEDIA_TYPE_VIDEO: ost = new_video_stream(o, oc, src_idx); break;
4480 case AVMEDIA_TYPE_AUDIO: ost = new_audio_stream(o, oc, src_idx); break;
4481 case AVMEDIA_TYPE_SUBTITLE: ost = new_subtitle_stream(o, oc, src_idx); break;
4482 case AVMEDIA_TYPE_DATA: ost = new_data_stream(o, oc, src_idx); break;
4483 case AVMEDIA_TYPE_ATTACHMENT: ost = new_attachment_stream(o, oc, src_idx); break;
4485 av_log(NULL, AV_LOG_FATAL, "Cannot map stream #%d:%d - unsupported type.\n",
4486 map->file_index, map->stream_index);
4493 for (i = nb_output_streams - oc->nb_streams; i < nb_output_streams; i++) { //for all streams of this output file
4494 AVDictionaryEntry *e;
4495 ost = &output_streams[i];
4497 if ( ost->stream_copy
4498 && (e = av_dict_get(codec_opts, "flags", NULL, AV_DICT_IGNORE_SUFFIX))
4499 && (!e->key[5] || check_stream_specifier(oc, ost->st, e->key+6)))
4500 if (av_opt_set(ost->st->codec, "flags", e->value, 0) < 0)
4504 /* handle attached files */
4505 for (i = 0; i < o->nb_attachments; i++) {
4507 uint8_t *attachment;
4511 if ((err = avio_open2(&pb, o->attachments[i], AVIO_FLAG_READ, &int_cb, NULL)) < 0) {
4512 av_log(NULL, AV_LOG_FATAL, "Could not open attachment file %s.\n",
4516 if ((len = avio_size(pb)) <= 0) {
4517 av_log(NULL, AV_LOG_FATAL, "Could not get size of the attachment %s.\n",
4521 if (!(attachment = av_malloc(len))) {
4522 av_log(NULL, AV_LOG_FATAL, "Attachment %s too large to fit into memory.\n",
4526 avio_read(pb, attachment, len);
4528 ost = new_attachment_stream(o, oc, -1);
4529 ost->stream_copy = 0;
4530 ost->attachment_filename = o->attachments[i];
4531 ost->st->codec->extradata = attachment;
4532 ost->st->codec->extradata_size = len;
4534 p = strrchr(o->attachments[i], '/');
4535 av_dict_set(&ost->st->metadata, "filename", (p && *p) ? p + 1 : o->attachments[i], AV_DICT_DONT_OVERWRITE);
4539 output_files = grow_array(output_files, sizeof(*output_files), &nb_output_files, nb_output_files + 1);
4540 output_files[nb_output_files - 1].ctx = oc;
4541 output_files[nb_output_files - 1].ost_index = nb_output_streams - oc->nb_streams;
4542 output_files[nb_output_files - 1].recording_time = o->recording_time;
4543 if (o->recording_time != INT64_MAX)
4544 oc->duration = o->recording_time;
4545 output_files[nb_output_files - 1].start_time = o->start_time;
4546 output_files[nb_output_files - 1].limit_filesize = o->limit_filesize;
4547 av_dict_copy(&output_files[nb_output_files - 1].opts, format_opts, 0);
4549 /* check filename in case of an image number is expected */
4550 if (oc->oformat->flags & AVFMT_NEEDNUMBER) {
4551 if (!av_filename_number_test(oc->filename)) {
4552 print_error(oc->filename, AVERROR(EINVAL));
4557 if (!(oc->oformat->flags & AVFMT_NOFILE)) {
4558 /* test if it already exists to avoid losing precious files */
4559 assert_file_overwrite(filename);
4562 if ((err = avio_open2(&oc->pb, filename, AVIO_FLAG_WRITE,
4563 &oc->interrupt_callback,
4564 &output_files[nb_output_files - 1].opts)) < 0) {
4565 print_error(filename, err);
4570 if (o->mux_preload) {
4572 snprintf(buf, sizeof(buf), "%d", (int)(o->mux_preload*AV_TIME_BASE));
4573 av_dict_set(&output_files[nb_output_files - 1].opts, "preload", buf, 0);
4575 oc->max_delay = (int)(o->mux_max_delay * AV_TIME_BASE);
4578 for (i = 0; i < o->nb_metadata_map; i++) {
4580 int in_file_index = strtol(o->metadata_map[i].u.str, &p, 0);
4582 if (in_file_index >= nb_input_files) {
4583 av_log(NULL, AV_LOG_FATAL, "Invalid input file index %d while processing metadata maps\n", in_file_index);
4586 copy_metadata(o->metadata_map[i].specifier, *p ? p + 1 : p, oc, in_file_index >= 0 ? input_files[in_file_index].ctx : NULL, o);
4590 if (o->chapters_input_file >= nb_input_files) {
4591 if (o->chapters_input_file == INT_MAX) {
4592 /* copy chapters from the first input file that has them*/
4593 o->chapters_input_file = -1;
4594 for (i = 0; i < nb_input_files; i++)
4595 if (input_files[i].ctx->nb_chapters) {
4596 o->chapters_input_file = i;
4600 av_log(NULL, AV_LOG_FATAL, "Invalid input file index %d in chapter mapping.\n",
4601 o->chapters_input_file);
4605 if (o->chapters_input_file >= 0)
4606 copy_chapters(&input_files[o->chapters_input_file], &output_files[nb_output_files - 1],
4607 !o->metadata_chapters_manual);
4609 /* copy global metadata by default */
4610 if (!o->metadata_global_manual && nb_input_files){
4611 av_dict_copy(&oc->metadata, input_files[0].ctx->metadata,
4612 AV_DICT_DONT_OVERWRITE);
4613 if(o->recording_time != INT64_MAX)
4614 av_dict_set(&oc->metadata, "duration", NULL, 0);
4616 if (!o->metadata_streams_manual)
4617 for (i = output_files[nb_output_files - 1].ost_index; i < nb_output_streams; i++) {
4619 if (output_streams[i].source_index < 0) /* this is true e.g. for attached files */
4621 ist = &input_streams[output_streams[i].source_index];
4622 av_dict_copy(&output_streams[i].st->metadata, ist->st->metadata, AV_DICT_DONT_OVERWRITE);
4625 /* process manually set metadata */
4626 for (i = 0; i < o->nb_metadata; i++) {
4629 const char *stream_spec;
4630 int index = 0, j, ret = 0;
4632 val = strchr(o->metadata[i].u.str, '=');
4634 av_log(NULL, AV_LOG_FATAL, "No '=' character in metadata string %s.\n",
4635 o->metadata[i].u.str);
4640 parse_meta_type(o->metadata[i].specifier, &type, &index, &stream_spec);
4642 for (j = 0; j < oc->nb_streams; j++) {
4643 if ((ret = check_stream_specifier(oc, oc->streams[j], stream_spec)) > 0) {
4644 av_dict_set(&oc->streams[j]->metadata, o->metadata[i].u.str, *val ? val : NULL, 0);
4648 printf("ret %d, stream_spec %s\n", ret, stream_spec);
4656 if (index < 0 || index >= oc->nb_chapters) {
4657 av_log(NULL, AV_LOG_FATAL, "Invalid chapter index %d in metadata specifier.\n", index);
4660 m = &oc->chapters[index]->metadata;
4663 av_log(NULL, AV_LOG_FATAL, "Invalid metadata specifier %s.\n", o->metadata[i].specifier);
4666 av_dict_set(m, o->metadata[i].u.str, *val ? val : NULL, 0);
4670 reset_options(o, 0);
4673 /* same option as mencoder */
4674 static int opt_pass(const char *opt, const char *arg)
4676 do_pass = parse_number_or_die(opt, arg, OPT_INT, 1, 3);
4680 static int64_t getmaxrss(void)
4682 #if HAVE_GETRUSAGE && HAVE_STRUCT_RUSAGE_RU_MAXRSS
4683 struct rusage rusage;
4684 getrusage(RUSAGE_SELF, &rusage);
4685 return (int64_t)rusage.ru_maxrss * 1024;
4686 #elif HAVE_GETPROCESSMEMORYINFO
4688 PROCESS_MEMORY_COUNTERS memcounters;
4689 proc = GetCurrentProcess();
4690 memcounters.cb = sizeof(memcounters);
4691 GetProcessMemoryInfo(proc, &memcounters, sizeof(memcounters));
4692 return memcounters.PeakPagefileUsage;
4698 static int opt_audio_qscale(OptionsContext *o, const char *opt, const char *arg)
4700 return parse_option(o, "q:a", arg, options);
4703 static void show_usage(void)
4705 av_log(NULL, AV_LOG_INFO, "Hyper fast Audio and Video encoder\n");
4706 av_log(NULL, AV_LOG_INFO, "usage: %s [options] [[infile options] -i infile]... {[outfile options] outfile}...\n", program_name);
4707 av_log(NULL, AV_LOG_INFO, "\n");
4710 static int opt_help(const char *opt, const char *arg)
4712 int flags = AV_OPT_FLAG_DECODING_PARAM | AV_OPT_FLAG_ENCODING_PARAM;
4713 av_log_set_callback(log_callback_help);
4715 show_help_options(options, "Main options:\n",
4716 OPT_EXPERT | OPT_AUDIO | OPT_VIDEO | OPT_SUBTITLE | OPT_GRAB, 0);
4717 show_help_options(options, "\nAdvanced options:\n",
4718 OPT_EXPERT | OPT_AUDIO | OPT_VIDEO | OPT_SUBTITLE | OPT_GRAB,
4720 show_help_options(options, "\nVideo options:\n",
4721 OPT_EXPERT | OPT_AUDIO | OPT_VIDEO | OPT_GRAB,
4723 show_help_options(options, "\nAdvanced Video options:\n",
4724 OPT_EXPERT | OPT_AUDIO | OPT_VIDEO | OPT_GRAB,
4725 OPT_VIDEO | OPT_EXPERT);
4726 show_help_options(options, "\nAudio options:\n",
4727 OPT_EXPERT | OPT_AUDIO | OPT_VIDEO | OPT_GRAB,
4729 show_help_options(options, "\nAdvanced Audio options:\n",
4730 OPT_EXPERT | OPT_AUDIO | OPT_VIDEO | OPT_GRAB,
4731 OPT_AUDIO | OPT_EXPERT);
4732 show_help_options(options, "\nSubtitle options:\n",
4733 OPT_SUBTITLE | OPT_GRAB,
4735 show_help_options(options, "\nAudio/Video grab options:\n",
4739 show_help_children(avcodec_get_class(), flags);
4740 show_help_children(avformat_get_class(), flags);
4741 show_help_children(sws_get_class(), flags);
4746 static int opt_target(OptionsContext *o, const char *opt, const char *arg)
4748 enum { PAL, NTSC, FILM, UNKNOWN } norm = UNKNOWN;
4749 static const char *const frame_rates[] = { "25", "30000/1001", "24000/1001" };
4751 if (!strncmp(arg, "pal-", 4)) {
4754 } else if (!strncmp(arg, "ntsc-", 5)) {
4757 } else if (!strncmp(arg, "film-", 5)) {
4761 /* Try to determine PAL/NTSC by peeking in the input files */
4762 if (nb_input_files) {
4764 for (j = 0; j < nb_input_files; j++) {
4765 for (i = 0; i < input_files[j].nb_streams; i++) {
4766 AVCodecContext *c = input_files[j].ctx->streams[i]->codec;
4767 if (c->codec_type != AVMEDIA_TYPE_VIDEO)
4769 fr = c->time_base.den * 1000 / c->time_base.num;
4773 } else if ((fr == 29970) || (fr == 23976)) {
4778 if (norm != UNKNOWN)
4782 if (norm != UNKNOWN)
4783 av_log(NULL, AV_LOG_INFO, "Assuming %s for target.\n", norm == PAL ? "PAL" : "NTSC");
4786 if (norm == UNKNOWN) {
4787 av_log(NULL, AV_LOG_FATAL, "Could not determine norm (PAL/NTSC/NTSC-Film) for target.\n");
4788 av_log(NULL, AV_LOG_FATAL, "Please prefix target with \"pal-\", \"ntsc-\" or \"film-\",\n");
4789 av_log(NULL, AV_LOG_FATAL, "or set a framerate with \"-r xxx\".\n");
4793 if (!strcmp(arg, "vcd")) {
4794 opt_video_codec(o, "c:v", "mpeg1video");
4795 opt_audio_codec(o, "c:a", "mp2");
4796 parse_option(o, "f", "vcd", options);
4798 parse_option(o, "s", norm == PAL ? "352x288" : "352x240", options);
4799 parse_option(o, "r", frame_rates[norm], options);
4800 opt_default("g", norm == PAL ? "15" : "18");
4802 opt_default("b:v", "1150000");
4803 opt_default("maxrate", "1150000");
4804 opt_default("minrate", "1150000");
4805 opt_default("bufsize", "327680"); // 40*1024*8;
4807 opt_default("b:a", "224000");
4808 parse_option(o, "ar", "44100", options);
4809 parse_option(o, "ac", "2", options);
4811 opt_default("packetsize", "2324");
4812 opt_default("muxrate", "1411200"); // 2352 * 75 * 8;
4814 /* We have to offset the PTS, so that it is consistent with the SCR.
4815 SCR starts at 36000, but the first two packs contain only padding
4816 and the first pack from the other stream, respectively, may also have
4817 been written before.
4818 So the real data starts at SCR 36000+3*1200. */
4819 o->mux_preload = (36000 + 3 * 1200) / 90000.0; // 0.44
4820 } else if (!strcmp(arg, "svcd")) {
4822 opt_video_codec(o, "c:v", "mpeg2video");
4823 opt_audio_codec(o, "c:a", "mp2");
4824 parse_option(o, "f", "svcd", options);
4826 parse_option(o, "s", norm == PAL ? "480x576" : "480x480", options);
4827 parse_option(o, "r", frame_rates[norm], options);
4828 parse_option(o, "pix_fmt", "yuv420p", options);
4829 opt_default("g", norm == PAL ? "15" : "18");
4831 opt_default("b:v", "2040000");
4832 opt_default("maxrate", "2516000");
4833 opt_default("minrate", "0"); // 1145000;
4834 opt_default("bufsize", "1835008"); // 224*1024*8;
4835 opt_default("scan_offset", "1");
4838 opt_default("b:a", "224000");
4839 parse_option(o, "ar", "44100", options);
4841 opt_default("packetsize", "2324");
4843 } else if (!strcmp(arg, "dvd")) {
4845 opt_video_codec(o, "c:v", "mpeg2video");
4846 opt_audio_codec(o, "c:a", "ac3");
4847 parse_option(o, "f", "dvd", options);
4849 parse_option(o, "s", norm == PAL ? "720x576" : "720x480", options);
4850 parse_option(o, "r", frame_rates[norm], options);
4851 parse_option(o, "pix_fmt", "yuv420p", options);
4852 opt_default("g", norm == PAL ? "15" : "18");
4854 opt_default("b:v", "6000000");
4855 opt_default("maxrate", "9000000");
4856 opt_default("minrate", "0"); // 1500000;
4857 opt_default("bufsize", "1835008"); // 224*1024*8;
4859 opt_default("packetsize", "2048"); // from www.mpucoder.com: DVD sectors contain 2048 bytes of data, this is also the size of one pack.
4860 opt_default("muxrate", "10080000"); // from mplex project: data_rate = 1260000. mux_rate = data_rate * 8
4862 opt_default("b:a", "448000");
4863 parse_option(o, "ar", "48000", options);
4865 } else if (!strncmp(arg, "dv", 2)) {
4867 parse_option(o, "f", "dv", options);
4869 parse_option(o, "s", norm == PAL ? "720x576" : "720x480", options);
4870 parse_option(o, "pix_fmt", !strncmp(arg, "dv50", 4) ? "yuv422p" :
4871 norm == PAL ? "yuv420p" : "yuv411p", options);
4872 parse_option(o, "r", frame_rates[norm], options);
4874 parse_option(o, "ar", "48000", options);
4875 parse_option(o, "ac", "2", options);
4878 av_log(NULL, AV_LOG_ERROR, "Unknown target: %s\n", arg);
4879 return AVERROR(EINVAL);
4884 static int opt_vstats_file(const char *opt, const char *arg)
4886 av_free (vstats_filename);
4887 vstats_filename = av_strdup (arg);
4891 static int opt_vstats(const char *opt, const char *arg)
4894 time_t today2 = time(NULL);
4895 struct tm *today = localtime(&today2);
4897 snprintf(filename, sizeof(filename), "vstats_%02d%02d%02d.log", today->tm_hour, today->tm_min,
4899 return opt_vstats_file(opt, filename);
4902 static int opt_video_frames(OptionsContext *o, const char *opt, const char *arg)
4904 return parse_option(o, "frames:v", arg, options);
4907 static int opt_audio_frames(OptionsContext *o, const char *opt, const char *arg)
4909 return parse_option(o, "frames:a", arg, options);
4912 static int opt_data_frames(OptionsContext *o, const char *opt, const char *arg)
4914 return parse_option(o, "frames:d", arg, options);
4917 static int opt_preset(OptionsContext *o, const char *opt, const char *arg)
4920 char filename[1000], tmp[1000], tmp2[1000], line[1000];
4921 const char *codec_name = *opt == 'v' ? video_codec_name :
4922 *opt == 'a' ? audio_codec_name :
4923 subtitle_codec_name;
4925 if (!(f = get_preset_file(filename, sizeof(filename), arg, *opt == 'f', codec_name))) {
4926 if(!strncmp(arg, "libx264-lossless", strlen("libx264-lossless"))){
4927 av_log(NULL, AV_LOG_FATAL, "Please use -preset <speed> -qp 0\n");
4929 av_log(NULL, AV_LOG_FATAL, "File for preset '%s' not found\n", arg);
4934 int e= fscanf(f, "%999[^\n]\n", line) - 1;
4935 if(line[0] == '#' && !e)
4937 e|= sscanf(line, "%999[^=]=%999[^\n]\n", tmp, tmp2) - 2;
4939 av_log(NULL, AV_LOG_FATAL, "%s: Invalid syntax: '%s'\n", filename, line);
4942 if(!strcmp(tmp, "acodec")){
4943 opt_audio_codec(o, tmp, tmp2);
4944 }else if(!strcmp(tmp, "vcodec")){
4945 opt_video_codec(o, tmp, tmp2);
4946 }else if(!strcmp(tmp, "scodec")){
4947 opt_subtitle_codec(o, tmp, tmp2);
4948 }else if(!strcmp(tmp, "dcodec")){
4949 opt_data_codec(o, tmp, tmp2);
4950 }else if(opt_default(tmp, tmp2) < 0){
4951 av_log(NULL, AV_LOG_FATAL, "%s: Invalid option or argument: '%s', parsed as '%s' = '%s'\n", filename, line, tmp, tmp2);
4961 static void log_callback_null(void *ptr, int level, const char *fmt, va_list vl)
4965 static int opt_passlogfile(const char *opt, const char *arg)
4967 pass_logfilename_prefix = arg;
4968 #if CONFIG_LIBX264_ENCODER
4969 return opt_default(opt, arg);
4975 static int opt_old2new(OptionsContext *o, const char *opt, const char *arg)
4977 char *s = av_asprintf("%s:%c", opt + 1, *opt);
4978 int ret = parse_option(o, s, arg, options);
4983 static int opt_bitrate(OptionsContext *o, const char *opt, const char *arg)
4985 if(!strcmp(opt, "b")){
4986 av_log(NULL, AV_LOG_WARNING, "Please use -b:a or -b:v, -b is ambiguous\n");
4987 return parse_option(o, "b:v", arg, options);
4989 return opt_default(opt, arg);
4992 static int opt_qscale(OptionsContext *o, const char *opt, const char *arg)
4996 if(!strcmp(opt, "qscale")){
4997 av_log(NULL, AV_LOG_WARNING, "Please use -q:a or -q:v, -qscale is ambiguous\n");
4998 return parse_option(o, "q:v", arg, options);
5000 s = av_asprintf("q%s", opt + 6);
5001 ret = parse_option(o, s, arg, options);
5006 static int opt_profile(OptionsContext *o, const char *opt, const char *arg)
5008 if(!strcmp(opt, "profile")){
5009 av_log(NULL, AV_LOG_WARNING, "Please use -profile:a or -profile:v, -profile is ambiguous\n");
5010 return parse_option(o, "profile:v", arg, options);
5012 return opt_default(opt, arg);
5015 static int opt_video_filters(OptionsContext *o, const char *opt, const char *arg)
5017 return parse_option(o, "filter:v", arg, options);
5020 static int opt_vsync(const char *opt, const char *arg)
5022 if (!av_strcasecmp(arg, "cfr")) video_sync_method = VSYNC_CFR;
5023 else if (!av_strcasecmp(arg, "vfr")) video_sync_method = VSYNC_VFR;
5024 else if (!av_strcasecmp(arg, "passthrough")) video_sync_method = VSYNC_PASSTHROUGH;
5025 else if (!av_strcasecmp(arg, "drop")) video_sync_method = VSYNC_DROP;
5027 if (video_sync_method == VSYNC_AUTO)
5028 video_sync_method = parse_number_or_die("vsync", arg, OPT_INT, VSYNC_AUTO, VSYNC_VFR);
5032 static int opt_deinterlace(const char *opt, const char *arg)
5034 av_log(NULL, AV_LOG_WARNING, "-%s is deprecated, use -filter:v yadif instead\n", opt);
5039 static void parse_cpuflags(int argc, char **argv, const OptionDef *options)
5041 int idx = locate_option(argc, argv, options, "cpuflags");
5042 if (idx && argv[idx + 1])
5043 opt_cpuflags("cpuflags", argv[idx + 1]);
5046 static int opt_channel_layout(OptionsContext *o, const char *opt, const char *arg)
5048 char layout_str[32];
5051 int ret, channels, ac_str_size;
5054 layout = av_get_channel_layout(arg);
5056 av_log(NULL, AV_LOG_ERROR, "Unknown channel layout: %s\n", arg);
5057 return AVERROR(EINVAL);
5059 snprintf(layout_str, sizeof(layout_str), "%"PRIu64, layout);
5060 ret = opt_default(opt, layout_str);
5064 /* set 'ac' option based on channel layout */
5065 channels = av_get_channel_layout_nb_channels(layout);
5066 snprintf(layout_str, sizeof(layout_str), "%d", channels);
5067 stream_str = strchr(opt, ':');
5068 ac_str_size = 3 + (stream_str ? strlen(stream_str) : 0);
5069 ac_str = av_mallocz(ac_str_size);
5071 return AVERROR(ENOMEM);
5072 av_strlcpy(ac_str, "ac", 3);
5074 av_strlcat(ac_str, stream_str, ac_str_size);
5075 ret = parse_option(o, ac_str, layout_str, options);
5081 #define OFFSET(x) offsetof(OptionsContext, x)
5082 static const OptionDef options[] = {
5084 #include "cmdutils_common_opts.h"
5085 { "f", HAS_ARG | OPT_STRING | OPT_OFFSET, {.off = OFFSET(format)}, "force format", "fmt" },
5086 { "i", HAS_ARG | OPT_FUNC2, {(void*)opt_input_file}, "input file name", "filename" },
5087 { "y", OPT_BOOL, {(void*)&file_overwrite}, "overwrite output files" },
5088 { "n", OPT_BOOL, {(void*)&no_file_overwrite}, "do not overwrite output files" },
5089 { "c", HAS_ARG | OPT_STRING | OPT_SPEC, {.off = OFFSET(codec_names)}, "codec name", "codec" },
5090 { "codec", HAS_ARG | OPT_STRING | OPT_SPEC, {.off = OFFSET(codec_names)}, "codec name", "codec" },
5091 { "pre", HAS_ARG | OPT_STRING | OPT_SPEC, {.off = OFFSET(presets)}, "preset name", "preset" },
5092 { "map", HAS_ARG | OPT_EXPERT | OPT_FUNC2, {(void*)opt_map}, "set input stream mapping", "[-]input_file_id[:stream_specifier][,sync_file_id[:stream_specifier]]" },
5093 { "map_channel", HAS_ARG | OPT_EXPERT | OPT_FUNC2, {(void*)opt_map_channel}, "map an audio channel from one stream to another", "file.stream.channel[:syncfile.syncstream]" },
5094 { "map_metadata", HAS_ARG | OPT_STRING | OPT_SPEC, {.off = OFFSET(metadata_map)}, "set metadata information of outfile from infile",
5095 "outfile[,metadata]:infile[,metadata]" },
5096 { "map_chapters", OPT_INT | HAS_ARG | OPT_EXPERT | OPT_OFFSET, {.off = OFFSET(chapters_input_file)}, "set chapters mapping", "input_file_index" },
5097 { "t", HAS_ARG | OPT_TIME | OPT_OFFSET, {.off = OFFSET(recording_time)}, "record or transcode \"duration\" seconds of audio/video", "duration" },
5098 { "fs", HAS_ARG | OPT_INT64 | OPT_OFFSET, {.off = OFFSET(limit_filesize)}, "set the limit file size in bytes", "limit_size" }, //
5099 { "ss", HAS_ARG | OPT_TIME | OPT_OFFSET, {.off = OFFSET(start_time)}, "set the start time offset", "time_off" },
5100 { "itsoffset", HAS_ARG | OPT_TIME | OPT_OFFSET, {.off = OFFSET(input_ts_offset)}, "set the input ts offset", "time_off" },
5101 { "itsscale", HAS_ARG | OPT_DOUBLE | OPT_SPEC, {.off = OFFSET(ts_scale)}, "set the input ts scale", "scale" },
5102 { "timestamp", HAS_ARG | OPT_FUNC2, {(void*)opt_recording_timestamp}, "set the recording timestamp ('now' to set the current time)", "time" },
5103 { "metadata", HAS_ARG | OPT_STRING | OPT_SPEC, {.off = OFFSET(metadata)}, "add metadata", "string=string" },
5104 { "dframes", HAS_ARG | OPT_FUNC2, {(void*)opt_data_frames}, "set the number of data frames to record", "number" },
5105 { "benchmark", OPT_BOOL | OPT_EXPERT, {(void*)&do_benchmark},
5106 "add timings for benchmarking" },
5107 { "benchmark_all", OPT_BOOL | OPT_EXPERT, {(void*)&do_benchmark_all},
5108 "add timings for each task" },
5109 { "timelimit", HAS_ARG, {(void*)opt_timelimit}, "set max runtime in seconds", "limit" },
5110 { "dump", OPT_BOOL | OPT_EXPERT, {(void*)&do_pkt_dump},
5111 "dump each input packet" },
5112 { "hex", OPT_BOOL | OPT_EXPERT, {(void*)&do_hex_dump},
5113 "when dumping packets, also dump the payload" },
5114 { "re", OPT_BOOL | OPT_EXPERT | OPT_OFFSET, {.off = OFFSET(rate_emu)}, "read input at native frame rate", "" },
5115 { "target", HAS_ARG | OPT_FUNC2, {(void*)opt_target}, "specify target file type (\"vcd\", \"svcd\", \"dvd\", \"dv\", \"dv50\", \"pal-vcd\", \"ntsc-svcd\", ...)", "type" },
5116 { "vsync", HAS_ARG | OPT_EXPERT, {(void*)opt_vsync}, "video sync method", "" },
5117 { "async", HAS_ARG | OPT_INT | OPT_EXPERT, {(void*)&audio_sync_method}, "audio sync method", "" },
5118 { "adrift_threshold", HAS_ARG | OPT_FLOAT | OPT_EXPERT, {(void*)&audio_drift_threshold}, "audio drift threshold", "threshold" },
5119 { "copyts", OPT_BOOL | OPT_EXPERT, {(void*)©_ts}, "copy timestamps" },
5120 { "copytb", HAS_ARG | OPT_INT | OPT_EXPERT, {(void*)©_tb}, "copy input stream time base when stream copying", "mode" },
5121 { "shortest", OPT_BOOL | OPT_EXPERT, {(void*)&opt_shortest}, "finish encoding within shortest input" }, //
5122 { "dts_delta_threshold", HAS_ARG | OPT_FLOAT | OPT_EXPERT, {(void*)&dts_delta_threshold}, "timestamp discontinuity delta threshold", "threshold" },
5123 { "dts_error_threshold", HAS_ARG | OPT_FLOAT | OPT_EXPERT, {(void*)&dts_error_threshold}, "timestamp error delta threshold", "threshold" },
5124 { "xerror", OPT_BOOL, {(void*)&exit_on_error}, "exit on error", "error" },
5125 { "copyinkf", OPT_BOOL | OPT_EXPERT | OPT_SPEC, {.off = OFFSET(copy_initial_nonkeyframes)}, "copy initial non-keyframes" },
5126 { "frames", OPT_INT64 | HAS_ARG | OPT_SPEC, {.off = OFFSET(max_frames)}, "set the number of frames to record", "number" },
5127 { "tag", OPT_STRING | HAS_ARG | OPT_SPEC, {.off = OFFSET(codec_tags)}, "force codec tag/fourcc", "fourcc/tag" },
5128 { "q", HAS_ARG | OPT_EXPERT | OPT_DOUBLE | OPT_SPEC, {.off = OFFSET(qscale)}, "use fixed quality scale (VBR)", "q" },
5129 { "qscale", HAS_ARG | OPT_EXPERT | OPT_FUNC2, {(void*)opt_qscale}, "use fixed quality scale (VBR)", "q" },
5130 { "profile", HAS_ARG | OPT_EXPERT | OPT_FUNC2, {(void*)opt_profile}, "set profile", "profile" },
5131 { "filter", HAS_ARG | OPT_STRING | OPT_SPEC, {.off = OFFSET(filters)}, "set stream filterchain", "filter_list" },
5132 { "stats", OPT_BOOL, {&print_stats}, "print progress report during encoding", },
5133 { "attach", HAS_ARG | OPT_FUNC2, {(void*)opt_attach}, "add an attachment to the output file", "filename" },
5134 { "dump_attachment", HAS_ARG | OPT_STRING | OPT_SPEC, {.off = OFFSET(dump_attachment)}, "extract an attachment into a file", "filename" },
5135 { "debug_ts", OPT_BOOL | OPT_EXPERT, {&debug_ts}, "print timestamp debugging info" },
5138 { "vframes", HAS_ARG | OPT_VIDEO | OPT_FUNC2, {(void*)opt_video_frames}, "set the number of video frames to record", "number" },
5139 { "r", HAS_ARG | OPT_VIDEO | OPT_STRING | OPT_SPEC, {.off = OFFSET(frame_rates)}, "set frame rate (Hz value, fraction or abbreviation)", "rate" },
5140 { "s", HAS_ARG | OPT_VIDEO | OPT_STRING | OPT_SPEC, {.off = OFFSET(frame_sizes)}, "set frame size (WxH or abbreviation)", "size" },
5141 { "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" },
5142 { "pix_fmt", HAS_ARG | OPT_EXPERT | OPT_VIDEO | OPT_STRING | OPT_SPEC, {.off = OFFSET(frame_pix_fmts)}, "set pixel format", "format" },
5143 { "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" },
5144 { "croptop", HAS_ARG | OPT_VIDEO, {(void*)opt_frame_crop}, "Removed, use the crop filter instead", "size" },
5145 { "cropbottom", HAS_ARG | OPT_VIDEO, {(void*)opt_frame_crop}, "Removed, use the crop filter instead", "size" },
5146 { "cropleft", HAS_ARG | OPT_VIDEO, {(void*)opt_frame_crop}, "Removed, use the crop filter instead", "size" },
5147 { "cropright", HAS_ARG | OPT_VIDEO, {(void*)opt_frame_crop}, "Removed, use the crop filter instead", "size" },
5148 { "padtop", HAS_ARG | OPT_VIDEO, {(void*)opt_pad}, "Removed, use the pad filter instead", "size" },
5149 { "padbottom", HAS_ARG | OPT_VIDEO, {(void*)opt_pad}, "Removed, use the pad filter instead", "size" },
5150 { "padleft", HAS_ARG | OPT_VIDEO, {(void*)opt_pad}, "Removed, use the pad filter instead", "size" },
5151 { "padright", HAS_ARG | OPT_VIDEO, {(void*)opt_pad}, "Removed, use the pad filter instead", "size" },
5152 { "padcolor", HAS_ARG | OPT_VIDEO, {(void*)opt_pad}, "Removed, use the pad filter instead", "color" },
5153 { "intra", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, {(void*)&intra_only}, "deprecated use -g 1"},
5154 { "vn", OPT_BOOL | OPT_VIDEO | OPT_OFFSET, {.off = OFFSET(video_disable)}, "disable video" },
5155 { "vdt", OPT_INT | HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)&video_discard}, "discard threshold", "n" },
5156 { "rc_override", HAS_ARG | OPT_EXPERT | OPT_VIDEO | OPT_STRING | OPT_SPEC, {.off = OFFSET(rc_overrides)}, "rate control override for specific intervals", "override" },
5157 { "vcodec", HAS_ARG | OPT_VIDEO | OPT_FUNC2, {(void*)opt_video_codec}, "force video codec ('copy' to copy stream)", "codec" },
5158 { "sameq", OPT_BOOL | OPT_VIDEO, {(void*)&same_quant}, "use same quantizer as source (implies VBR)" },
5159 { "same_quant", OPT_BOOL | OPT_VIDEO, {(void*)&same_quant},
5160 "use same quantizer as source (implies VBR)" },
5161 { "pass", HAS_ARG | OPT_VIDEO, {(void*)opt_pass}, "select the pass number (1 or 2)", "n" },
5162 { "passlogfile", HAS_ARG | OPT_VIDEO, {(void*)&opt_passlogfile}, "select two pass log file name prefix", "prefix" },
5163 { "deinterlace", OPT_EXPERT | OPT_VIDEO, {(void*)opt_deinterlace},
5164 "this option is deprecated, use the yadif filter instead" },
5165 { "psnr", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, {(void*)&do_psnr}, "calculate PSNR of compressed frames" },
5166 { "vstats", OPT_EXPERT | OPT_VIDEO, {(void*)&opt_vstats}, "dump video coding statistics to file" },
5167 { "vstats_file", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_vstats_file}, "dump video coding statistics to file", "file" },
5168 { "vf", HAS_ARG | OPT_VIDEO | OPT_FUNC2, {(void*)opt_video_filters}, "video filters", "filter list" },
5169 { "intra_matrix", HAS_ARG | OPT_EXPERT | OPT_VIDEO | OPT_STRING | OPT_SPEC, {.off = OFFSET(intra_matrices)}, "specify intra matrix coeffs", "matrix" },
5170 { "inter_matrix", HAS_ARG | OPT_EXPERT | OPT_VIDEO | OPT_STRING | OPT_SPEC, {.off = OFFSET(inter_matrices)}, "specify inter matrix coeffs", "matrix" },
5171 { "top", HAS_ARG | OPT_EXPERT | OPT_VIDEO | OPT_INT| OPT_SPEC, {.off = OFFSET(top_field_first)}, "top=1/bottom=0/auto=-1 field first", "" },
5172 { "dc", OPT_INT | HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)&intra_dc_precision}, "intra_dc_precision", "precision" },
5173 { "vtag", HAS_ARG | OPT_EXPERT | OPT_VIDEO | OPT_FUNC2, {(void*)opt_old2new}, "force video tag/fourcc", "fourcc/tag" },
5174 { "qphist", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, { (void *)&qp_hist }, "show QP histogram" },
5175 { "force_fps", OPT_BOOL | OPT_EXPERT | OPT_VIDEO | OPT_SPEC, {.off = OFFSET(force_fps)}, "force the selected framerate, disable the best supported framerate selection" },
5176 { "streamid", HAS_ARG | OPT_EXPERT | OPT_FUNC2, {(void*)opt_streamid}, "set the value of an outfile streamid", "streamIndex:value" },
5177 { "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" },
5178 { "b", HAS_ARG | OPT_VIDEO | OPT_FUNC2, {(void*)opt_bitrate}, "video bitrate (please use -b:v)", "bitrate" },
5181 { "aframes", HAS_ARG | OPT_AUDIO | OPT_FUNC2, {(void*)opt_audio_frames}, "set the number of audio frames to record", "number" },
5182 { "aq", HAS_ARG | OPT_AUDIO | OPT_FUNC2, {(void*)opt_audio_qscale}, "set audio quality (codec-specific)", "quality", },
5183 { "ar", HAS_ARG | OPT_AUDIO | OPT_INT | OPT_SPEC, {.off = OFFSET(audio_sample_rate)}, "set audio sampling rate (in Hz)", "rate" },
5184 { "ac", HAS_ARG | OPT_AUDIO | OPT_INT | OPT_SPEC, {.off = OFFSET(audio_channels)}, "set number of audio channels", "channels" },
5185 { "an", OPT_BOOL | OPT_AUDIO | OPT_OFFSET, {.off = OFFSET(audio_disable)}, "disable audio" },
5186 { "acodec", HAS_ARG | OPT_AUDIO | OPT_FUNC2, {(void*)opt_audio_codec}, "force audio codec ('copy' to copy stream)", "codec" },
5187 { "atag", HAS_ARG | OPT_EXPERT | OPT_AUDIO | OPT_FUNC2, {(void*)opt_old2new}, "force audio tag/fourcc", "fourcc/tag" },
5188 { "vol", OPT_INT | HAS_ARG | OPT_AUDIO, {(void*)&audio_volume}, "change audio volume (256=normal)" , "volume" }, //
5189 { "sample_fmt", HAS_ARG | OPT_EXPERT | OPT_AUDIO | OPT_SPEC | OPT_STRING, {.off = OFFSET(sample_fmts)}, "set sample format", "format" },
5190 { "rmvol", HAS_ARG | OPT_AUDIO | OPT_FLOAT | OPT_SPEC, {.off = OFFSET(rematrix_volume)}, "rematrix volume (as factor)", "volume" },
5191 { "channel_layout", HAS_ARG | OPT_EXPERT | OPT_AUDIO | OPT_FUNC2, {(void*)opt_channel_layout}, "set channel layout", "layout" },
5193 /* subtitle options */
5194 { "sn", OPT_BOOL | OPT_SUBTITLE | OPT_OFFSET, {.off = OFFSET(subtitle_disable)}, "disable subtitle" },
5195 { "scodec", HAS_ARG | OPT_SUBTITLE | OPT_FUNC2, {(void*)opt_subtitle_codec}, "force subtitle codec ('copy' to copy stream)", "codec" },
5196 { "stag", HAS_ARG | OPT_EXPERT | OPT_SUBTITLE | OPT_FUNC2, {(void*)opt_old2new}, "force subtitle tag/fourcc", "fourcc/tag" },
5199 { "vc", HAS_ARG | OPT_EXPERT | OPT_VIDEO | OPT_GRAB, {(void*)opt_video_channel}, "deprecated, use -channel", "channel" },
5200 { "tvstd", HAS_ARG | OPT_EXPERT | OPT_VIDEO | OPT_GRAB, {(void*)opt_video_standard}, "deprecated, use -standard", "standard" },
5201 { "isync", OPT_BOOL | OPT_EXPERT | OPT_GRAB, {(void*)&input_sync}, "sync read on input", "" },
5204 { "muxdelay", OPT_FLOAT | HAS_ARG | OPT_EXPERT | OPT_OFFSET, {.off = OFFSET(mux_max_delay)}, "set the maximum demux-decode delay", "seconds" },
5205 { "muxpreload", OPT_FLOAT | HAS_ARG | OPT_EXPERT | OPT_OFFSET, {.off = OFFSET(mux_preload)}, "set the initial demux-decode delay", "seconds" },
5207 { "bsf", HAS_ARG | OPT_STRING | OPT_SPEC, {.off = OFFSET(bitstream_filters)}, "A comma-separated list of bitstream filters", "bitstream_filters" },
5208 { "absf", HAS_ARG | OPT_AUDIO | OPT_EXPERT| OPT_FUNC2, {(void*)opt_old2new}, "deprecated", "audio bitstream_filters" },
5209 { "vbsf", HAS_ARG | OPT_VIDEO | OPT_EXPERT| OPT_FUNC2, {(void*)opt_old2new}, "deprecated", "video bitstream_filters" },
5211 { "apre", HAS_ARG | OPT_AUDIO | OPT_EXPERT| OPT_FUNC2, {(void*)opt_preset}, "set the audio options to the indicated preset", "preset" },
5212 { "vpre", HAS_ARG | OPT_VIDEO | OPT_EXPERT| OPT_FUNC2, {(void*)opt_preset}, "set the video options to the indicated preset", "preset" },
5213 { "spre", HAS_ARG | OPT_SUBTITLE | OPT_EXPERT| OPT_FUNC2, {(void*)opt_preset}, "set the subtitle options to the indicated preset", "preset" },
5214 { "fpre", HAS_ARG | OPT_EXPERT| OPT_FUNC2, {(void*)opt_preset}, "set options from indicated preset file", "filename" },
5215 /* data codec support */
5216 { "dcodec", HAS_ARG | OPT_DATA | OPT_FUNC2, {(void*)opt_data_codec}, "force data codec ('copy' to copy stream)", "codec" },
5217 { "dn", OPT_BOOL | OPT_VIDEO | OPT_OFFSET, {.off = OFFSET(data_disable)}, "disable data" },
5219 { "default", HAS_ARG | OPT_AUDIO | OPT_VIDEO | OPT_EXPERT, {(void*)opt_default}, "generic catch all option", "" },
5223 int main(int argc, char **argv)
5225 OptionsContext o = { 0 };
5228 reset_options(&o, 0);
5230 av_log_set_flags(AV_LOG_SKIP_REPEATED);
5231 parse_loglevel(argc, argv, options);
5233 if(argc>1 && !strcmp(argv[1], "-d")){
5235 av_log_set_callback(log_callback_null);
5240 avcodec_register_all();
5242 avdevice_register_all();
5244 avfilter_register_all();
5246 avformat_network_init();
5248 show_banner(argc, argv, options);
5252 parse_cpuflags(argc, argv, options);
5255 parse_options(&o, argc, argv, options, opt_output_file);
5257 if (nb_output_files <= 0 && nb_input_files == 0) {
5259 av_log(NULL, AV_LOG_WARNING, "Use -h to get full help or, even better, run 'man %s'\n", program_name);
5263 /* file converter / grab */
5264 if (nb_output_files <= 0) {
5265 av_log(NULL, AV_LOG_FATAL, "At least one output file must be specified\n");
5269 if (nb_input_files == 0) {
5270 av_log(NULL, AV_LOG_FATAL, "At least one input file must be specified\n");
5274 current_time = ti = getutime();
5275 if (transcode(output_files, nb_output_files, input_files, nb_input_files) < 0)
5277 ti = getutime() - ti;
5279 int maxrss = getmaxrss() / 1024;
5280 printf("bench: utime=%0.3fs maxrss=%ikB\n", ti / 1000000.0, maxrss);