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 "libavutil/audioconvert.h"
40 #include "libavutil/parseutils.h"
41 #include "libavutil/samplefmt.h"
42 #include "libavutil/colorspace.h"
43 #include "libavutil/fifo.h"
44 #include "libavutil/intreadwrite.h"
45 #include "libavutil/dict.h"
46 #include "libavutil/mathematics.h"
47 #include "libavutil/pixdesc.h"
48 #include "libavutil/avstring.h"
49 #include "libavutil/libm.h"
50 #include "libavutil/imgutils.h"
51 #include "libavutil/timestamp.h"
52 #include "libavformat/os_support.h"
53 #include "libswresample/swresample.h"
55 #include "libavformat/ffm.h" // not public API
57 # include "libavfilter/avcodec.h"
58 # include "libavfilter/avfilter.h"
59 # include "libavfilter/avfiltergraph.h"
60 # include "libavfilter/buffersink.h"
61 # include "libavfilter/buffersrc.h"
63 #if HAVE_SYS_RESOURCE_H
64 #include <sys/types.h>
66 #include <sys/resource.h>
67 #elif HAVE_GETPROCESSTIMES
70 #if HAVE_GETPROCESSMEMORYINFO
76 #include <sys/select.h>
81 #include <sys/ioctl.h>
91 #include "libavutil/avassert.h"
94 #define VSYNC_PASSTHROUGH 0
97 #define VSYNC_DROP 0xff
99 const char program_name[] = "ffmpeg";
100 const int program_birth_year = 2000;
102 /* select an input stream for an output stream */
103 typedef struct StreamMap {
104 int disabled; /** 1 is this mapping is disabled by a negative map */
108 int sync_stream_index;
109 char *linklabel; /** name of an output link, for mapping lavfi outputs */
113 int file_idx, stream_idx, channel_idx; // input
114 int ofile_idx, ostream_idx; // output
117 static const OptionDef options[];
119 #define MAX_STREAMS 1024 /* arbitrary sanity check value */
121 static int frame_bits_per_raw_sample = 0;
122 static int video_discard = 0;
123 static int same_quant = 0;
124 static int do_deinterlace = 0;
125 static int intra_dc_precision = 8;
126 static int qp_hist = 0;
127 static int intra_only = 0;
128 static const char *video_codec_name = NULL;
129 static const char *audio_codec_name = NULL;
130 static const char *subtitle_codec_name = NULL;
132 static int file_overwrite = 0;
133 static int no_file_overwrite = 0;
134 static int do_benchmark = 0;
135 static int do_benchmark_all = 0;
136 static int do_hex_dump = 0;
137 static int do_pkt_dump = 0;
138 static int do_psnr = 0;
139 static int do_pass = 0;
140 static const char *pass_logfilename_prefix;
141 static int video_sync_method = VSYNC_AUTO;
142 static int audio_sync_method = 0;
143 static float audio_drift_threshold = 0.1;
144 static int copy_ts = 0;
145 static int copy_tb = -1;
146 static int opt_shortest = 0;
147 static char *vstats_filename;
148 static FILE *vstats_file;
150 static int audio_volume = 256;
152 static int exit_on_error = 0;
153 static int using_stdin = 0;
154 static int run_as_daemon = 0;
155 static volatile int received_nb_signals = 0;
156 static int64_t video_size = 0;
157 static int64_t audio_size = 0;
158 static int64_t extra_size = 0;
159 static int nb_frames_dup = 0;
160 static int nb_frames_drop = 0;
161 static int input_sync;
163 static float dts_delta_threshold = 10;
164 static float dts_error_threshold = 3600*30;
166 static int print_stats = 1;
167 static int debug_ts = 0;
168 static int current_time;
170 static uint8_t *audio_buf;
171 static unsigned int allocated_audio_buf_size;
172 static uint8_t *async_buf;
173 static unsigned int allocated_async_buf_size;
175 #define DEFAULT_PASS_LOGFILENAME_PREFIX "ffmpeg2pass"
177 typedef struct InputFilter {
178 AVFilterContext *filter;
179 struct InputStream *ist;
180 struct FilterGraph *graph;
183 typedef struct OutputFilter {
184 AVFilterContext *filter;
185 struct OutputStream *ost;
186 struct FilterGraph *graph;
188 /* temporary storage until stream maps are processed */
189 AVFilterInOut *out_tmp;
192 typedef struct FilterGraph {
194 const char *graph_desc;
196 AVFilterGraph *graph;
198 InputFilter **inputs;
200 OutputFilter **outputs;
204 typedef struct FrameBuffer {
210 enum PixelFormat pix_fmt;
213 struct InputStream *ist;
214 struct FrameBuffer *next;
217 typedef struct InputStream {
220 int discard; /* true if stream data should be discarded */
221 int decoding_needed; /* true if the packets must be decoded in 'raw_fifo' */
223 AVFrame *decoded_frame;
225 int64_t start; /* time when read started */
226 /* predicted dts of the next packet read for this stream or (when there are
227 * several frames in a packet) of the next frame in current packet */
229 /* dts of the last packet read for this stream */
232 int64_t next_pts; ///< synthetic pts for the next decode frame
233 int64_t pts; ///< current pts of the decoded frame
235 int is_start; /* is 1 at the start and after a discontinuity */
237 int showed_multi_packet_warning;
242 int resample_pix_fmt;
244 /* a pool of free buffers for decoded data */
245 FrameBuffer *buffer_pool;
248 /* decoded data from this stream goes into all those filters
249 * currently video only */
250 InputFilter **filters;
254 typedef struct InputFile {
255 AVFormatContext *ctx;
256 int eof_reached; /* true if eof reached */
257 int ist_index; /* index of first stream in input_streams */
258 int buffer_size; /* current total buffer size */
260 int nb_streams; /* number of stream that ffmpeg is aware of; may be different
261 from ctx.nb_streams if new streams appear during av_read_frame() */
265 typedef struct OutputStream {
266 int file_index; /* file index */
267 int index; /* stream index in the output file */
268 int source_index; /* InputStream index */
269 AVStream *st; /* stream in the output file */
270 int encoding_needed; /* true if encoding needed for this stream */
272 /* input pts and corresponding output pts
274 struct InputStream *sync_ist; /* input stream to sync against */
275 int64_t sync_opts; /* output frame counter, could be changed to some true timestamp */ // FIXME look at frame_number
276 AVBitStreamFilterContext *bitstream_filters;
279 AVFrame *output_frame;
280 AVFrame *filtered_frame;
283 AVRational frame_rate;
287 float frame_aspect_ratio;
290 /* forced key frames */
291 int64_t *forced_kf_pts;
297 int audio_channels_map[SWR_CH_MAX]; ///< list of the channels id to pick from the source stream
298 int audio_channels_mapped; ///< number of channels in audio_channels_map
299 int resample_sample_fmt;
300 int resample_channels;
301 uint64_t resample_channel_layout;
302 int resample_sample_rate;
303 float rematrix_volume;
304 AVFifoBuffer *fifo; /* for compression: one audio fifo per codec */
309 OutputFilter *filter;
313 int64_t swr_dither_method;
314 double swr_dither_scale;
316 int is_past_recording_time;
318 const char *attachment_filename;
319 int copy_initial_nonkeyframes;
321 enum PixelFormat pix_fmts[2];
328 /* init terminal so that we can grab keys */
329 static struct termios oldtty;
330 static int restore_tty;
333 typedef struct OutputFile {
334 AVFormatContext *ctx;
336 int ost_index; /* index of the first stream in output_streams */
337 int64_t recording_time; /* desired length of the resulting file in microseconds */
338 int64_t start_time; /* start time in microseconds */
339 uint64_t limit_filesize; /* filesize limit expressed in bytes */
342 static InputStream **input_streams = NULL;
343 static int nb_input_streams = 0;
344 static InputFile **input_files = NULL;
345 static int nb_input_files = 0;
347 static OutputStream **output_streams = NULL;
348 static int nb_output_streams = 0;
349 static OutputFile **output_files = NULL;
350 static int nb_output_files = 0;
352 static FilterGraph **filtergraphs;
355 typedef struct OptionsContext {
356 /* input/output options */
360 SpecifierOpt *codec_names;
362 SpecifierOpt *audio_channels;
363 int nb_audio_channels;
364 SpecifierOpt *audio_sample_rate;
365 int nb_audio_sample_rate;
366 SpecifierOpt *rematrix_volume;
367 int nb_rematrix_volume;
368 SpecifierOpt *frame_rates;
370 SpecifierOpt *frame_sizes;
372 SpecifierOpt *frame_pix_fmts;
373 int nb_frame_pix_fmts;
376 int64_t input_ts_offset;
379 SpecifierOpt *ts_scale;
381 SpecifierOpt *dump_attachment;
382 int nb_dump_attachment;
385 StreamMap *stream_maps;
387 AudioChannelMap *audio_channel_maps; ///< one info entry per -map_channel
388 int nb_audio_channel_maps; ///< number of (valid) -map_channel settings
389 int metadata_global_manual;
390 int metadata_streams_manual;
391 int metadata_chapters_manual;
392 const char **attachments;
395 int chapters_input_file;
397 int64_t recording_time;
398 uint64_t limit_filesize;
404 int subtitle_disable;
407 /* indexed by output file stream index */
411 SpecifierOpt *metadata;
413 SpecifierOpt *max_frames;
415 SpecifierOpt *bitstream_filters;
416 int nb_bitstream_filters;
417 SpecifierOpt *codec_tags;
419 SpecifierOpt *sample_fmts;
421 SpecifierOpt *qscale;
423 SpecifierOpt *forced_key_frames;
424 int nb_forced_key_frames;
425 SpecifierOpt *force_fps;
427 SpecifierOpt *frame_aspect_ratios;
428 int nb_frame_aspect_ratios;
429 SpecifierOpt *rc_overrides;
431 SpecifierOpt *intra_matrices;
432 int nb_intra_matrices;
433 SpecifierOpt *inter_matrices;
434 int nb_inter_matrices;
435 SpecifierOpt *top_field_first;
436 int nb_top_field_first;
437 SpecifierOpt *metadata_map;
439 SpecifierOpt *presets;
441 SpecifierOpt *copy_initial_nonkeyframes;
442 int nb_copy_initial_nonkeyframes;
443 SpecifierOpt *filters;
447 #define MATCH_PER_STREAM_OPT(name, type, outvar, fmtctx, st)\
450 for (i = 0; i < o->nb_ ## name; i++) {\
451 char *spec = o->name[i].specifier;\
452 if ((ret = check_stream_specifier(fmtctx, st, spec)) > 0)\
453 outvar = o->name[i].u.type;\
459 static int64_t getutime(void)
462 struct rusage rusage;
464 getrusage(RUSAGE_SELF, &rusage);
465 return (rusage.ru_utime.tv_sec * 1000000LL) + rusage.ru_utime.tv_usec;
466 #elif HAVE_GETPROCESSTIMES
469 proc = GetCurrentProcess();
470 GetProcessTimes(proc, &c, &e, &k, &u);
471 return ((int64_t) u.dwHighDateTime << 32 | u.dwLowDateTime) / 10;
477 static void update_benchmark(const char *fmt, ...)
479 if (do_benchmark_all) {
480 int64_t t = getutime();
486 vsnprintf(buf, sizeof(buf), fmt, va);
488 printf("bench: %8"PRIu64" %s \n", t - current_time, buf);
494 static void reset_options(OptionsContext *o, int is_input)
496 const OptionDef *po = options;
497 OptionsContext bak= *o;
500 /* all OPT_SPEC and OPT_STRING can be freed in generic way */
502 void *dst = (uint8_t*)o + po->u.off;
504 if (po->flags & OPT_SPEC) {
505 SpecifierOpt **so = dst;
506 int i, *count = (int*)(so + 1);
507 for (i = 0; i < *count; i++) {
508 av_freep(&(*so)[i].specifier);
509 if (po->flags & OPT_STRING)
510 av_freep(&(*so)[i].u.str);
514 } else if (po->flags & OPT_OFFSET && po->flags & OPT_STRING)
519 for (i = 0; i < o->nb_stream_maps; i++)
520 av_freep(&o->stream_maps[i].linklabel);
521 av_freep(&o->stream_maps);
522 av_freep(&o->audio_channel_maps);
523 av_freep(&o->streamid_map);
525 memset(o, 0, sizeof(*o));
527 if(is_input) o->recording_time = bak.recording_time;
528 else o->recording_time = INT64_MAX;
529 o->mux_max_delay = 0.7;
530 o->limit_filesize = UINT64_MAX;
531 o->chapters_input_file = INT_MAX;
537 static int alloc_buffer(InputStream *ist, AVCodecContext *s, FrameBuffer **pbuf)
539 FrameBuffer *buf = av_mallocz(sizeof(*buf));
541 const int pixel_size = av_pix_fmt_descriptors[s->pix_fmt].comp[0].step_minus1+1;
542 int h_chroma_shift, v_chroma_shift;
543 int edge = 32; // XXX should be avcodec_get_edge_width(), but that fails on svq1
544 int w = s->width, h = s->height;
547 return AVERROR(ENOMEM);
549 avcodec_align_dimensions(s, &w, &h);
551 if (!(s->flags & CODEC_FLAG_EMU_EDGE)) {
556 if ((ret = av_image_alloc(buf->base, buf->linesize, w, h,
557 s->pix_fmt, 32)) < 0) {
561 /* XXX this shouldn't be needed, but some tests break without this line
562 * those decoders are buggy and need to be fixed.
563 * the following tests fail:
564 * cdgraphics, ansi, aasc, fraps-v1, qtrle-1bit
566 memset(buf->base[0], 128, ret);
568 avcodec_get_chroma_sub_sample(s->pix_fmt, &h_chroma_shift, &v_chroma_shift);
569 for (i = 0; i < FF_ARRAY_ELEMS(buf->data); i++) {
570 const int h_shift = i==0 ? 0 : h_chroma_shift;
571 const int v_shift = i==0 ? 0 : v_chroma_shift;
572 if ((s->flags & CODEC_FLAG_EMU_EDGE) || !buf->linesize[1] || !buf->base[i])
573 buf->data[i] = buf->base[i];
575 buf->data[i] = buf->base[i] +
576 FFALIGN((buf->linesize[i]*edge >> v_shift) +
577 (pixel_size*edge >> h_shift), 32);
581 buf->pix_fmt = s->pix_fmt;
588 static void free_buffer_pool(InputStream *ist)
590 FrameBuffer *buf = ist->buffer_pool;
592 ist->buffer_pool = buf->next;
593 av_freep(&buf->base[0]);
595 buf = ist->buffer_pool;
599 static void unref_buffer(InputStream *ist, FrameBuffer *buf)
601 av_assert0(buf->refcount > 0);
603 if (!buf->refcount) {
605 for(tmp= ist->buffer_pool; tmp; tmp= tmp->next)
606 av_assert1(tmp != buf);
607 buf->next = ist->buffer_pool;
608 ist->buffer_pool = buf;
612 static int codec_get_buffer(AVCodecContext *s, AVFrame *frame)
614 InputStream *ist = s->opaque;
618 if(av_image_check_size(s->width, s->height, 0, s) || s->pix_fmt<0)
621 if (!ist->buffer_pool && (ret = alloc_buffer(ist, s, &ist->buffer_pool)) < 0)
624 buf = ist->buffer_pool;
625 ist->buffer_pool = buf->next;
627 if (buf->w != s->width || buf->h != s->height || buf->pix_fmt != s->pix_fmt) {
628 av_freep(&buf->base[0]);
630 if ((ret = alloc_buffer(ist, s, &buf)) < 0)
633 av_assert0(!buf->refcount);
637 frame->type = FF_BUFFER_TYPE_USER;
638 frame->extended_data = frame->data;
639 frame->pkt_pts = s->pkt ? s->pkt->pts : AV_NOPTS_VALUE;
640 frame->width = buf->w;
641 frame->height = buf->h;
642 frame->format = buf->pix_fmt;
643 frame->sample_aspect_ratio = s->sample_aspect_ratio;
645 for (i = 0; i < FF_ARRAY_ELEMS(buf->data); i++) {
646 frame->base[i] = buf->base[i]; // XXX h264.c uses base though it shouldn't
647 frame->data[i] = buf->data[i];
648 frame->linesize[i] = buf->linesize[i];
654 static void codec_release_buffer(AVCodecContext *s, AVFrame *frame)
656 InputStream *ist = s->opaque;
657 FrameBuffer *buf = frame->opaque;
660 if(frame->type!=FF_BUFFER_TYPE_USER)
661 return avcodec_default_release_buffer(s, frame);
663 for (i = 0; i < FF_ARRAY_ELEMS(frame->data); i++)
664 frame->data[i] = NULL;
666 unref_buffer(ist, buf);
669 static void filter_release_buffer(AVFilterBuffer *fb)
671 FrameBuffer *buf = fb->priv;
673 unref_buffer(buf->ist, buf);
676 static enum PixelFormat choose_pixel_fmt(AVStream *st, AVCodec *codec, enum PixelFormat target)
678 if (codec && codec->pix_fmts) {
679 const enum PixelFormat *p = codec->pix_fmts;
680 int has_alpha= av_pix_fmt_descriptors[target].nb_components % 2 == 0;
681 enum PixelFormat best= PIX_FMT_NONE;
682 if (st->codec->strict_std_compliance <= FF_COMPLIANCE_UNOFFICIAL) {
683 if (st->codec->codec_id == CODEC_ID_MJPEG) {
684 p = (const enum PixelFormat[]) { PIX_FMT_YUVJ420P, PIX_FMT_YUVJ422P, PIX_FMT_YUV420P, PIX_FMT_YUV422P, PIX_FMT_NONE };
685 } else if (st->codec->codec_id == CODEC_ID_LJPEG) {
686 p = (const enum PixelFormat[]) { PIX_FMT_YUVJ420P, PIX_FMT_YUVJ422P, PIX_FMT_YUVJ444P, PIX_FMT_YUV420P,
687 PIX_FMT_YUV422P, PIX_FMT_YUV444P, PIX_FMT_BGRA, PIX_FMT_NONE };
690 for (; *p != PIX_FMT_NONE; p++) {
691 best= avcodec_find_best_pix_fmt2(best, *p, target, has_alpha, NULL);
695 if (*p == PIX_FMT_NONE) {
696 if (target != PIX_FMT_NONE)
697 av_log(NULL, AV_LOG_WARNING,
698 "Incompatible pixel format '%s' for codec '%s', auto-selecting format '%s'\n",
699 av_pix_fmt_descriptors[target].name,
701 av_pix_fmt_descriptors[best].name);
708 static char *choose_pixel_fmts(OutputStream *ost)
710 if (ost->keep_pix_fmt) {
712 avfilter_graph_set_auto_convert(ost->filter->graph->graph,
713 AVFILTER_AUTO_CONVERT_NONE);
714 if (ost->st->codec->pix_fmt == PIX_FMT_NONE)
716 ost->pix_fmts[0] = ost->st->codec->pix_fmt;
717 return ost->pix_fmts;
719 if (ost->st->codec->pix_fmt != PIX_FMT_NONE) {
720 return av_strdup(av_get_pix_fmt_name(choose_pixel_fmt(ost->st, ost->enc, ost->st->codec->pix_fmt)));
721 } else if (ost->enc->pix_fmts) {
722 const enum PixelFormat *p;
723 AVIOContext *s = NULL;
727 if (avio_open_dyn_buf(&s) < 0)
730 p = ost->enc->pix_fmts;
731 if (ost->st->codec->strict_std_compliance <= FF_COMPLIANCE_UNOFFICIAL) {
732 if (ost->st->codec->codec_id == CODEC_ID_MJPEG) {
733 p = (const enum PixelFormat[]) { PIX_FMT_YUVJ420P, PIX_FMT_YUVJ422P, PIX_FMT_YUV420P, PIX_FMT_YUV422P, PIX_FMT_NONE };
734 } else if (ost->st->codec->codec_id == CODEC_ID_LJPEG) {
735 p = (const enum PixelFormat[]) { PIX_FMT_YUVJ420P, PIX_FMT_YUVJ422P, PIX_FMT_YUVJ444P, PIX_FMT_YUV420P,
736 PIX_FMT_YUV422P, PIX_FMT_YUV444P, PIX_FMT_BGRA, PIX_FMT_NONE };
740 for (; *p != PIX_FMT_NONE; p++)
741 avio_printf(s, "%s:", av_get_pix_fmt_name(*p));
742 len = avio_close_dyn_buf(s, &ret);
749 static int configure_video_filters(FilterGraph *fg)
751 InputStream *ist = fg->inputs[0]->ist;
752 OutputStream *ost = fg->outputs[0]->ost;
753 AVFilterContext *in_filter, *out_filter, *filter;
754 AVCodecContext *codec = ost->st->codec;
755 AVBufferSinkParams *buffersink_params = av_buffersink_params_alloc();
757 AVRational sample_aspect_ratio;
761 avfilter_graph_free(&fg->graph);
762 fg->graph = avfilter_graph_alloc();
764 return AVERROR(ENOMEM);
766 if (ist->st->sample_aspect_ratio.num) {
767 sample_aspect_ratio = ist->st->sample_aspect_ratio;
769 sample_aspect_ratio = ist->st->codec->sample_aspect_ratio;
771 snprintf(args, 255, "%d:%d:%d:%d:%d:%d:%d:flags=%d", ist->st->codec->width,
772 ist->st->codec->height, ist->st->codec->pix_fmt, 1, AV_TIME_BASE,
773 sample_aspect_ratio.num, sample_aspect_ratio.den, SWS_BILINEAR + ((ist->st->codec->flags&CODEC_FLAG_BITEXACT) ? SWS_BITEXACT:0));
775 ret = avfilter_graph_create_filter(&fg->inputs[0]->filter,
776 avfilter_get_by_name("buffer"),
777 "src", args, NULL, fg->graph);
781 #if FF_API_OLD_VSINK_API
782 ret = avfilter_graph_create_filter(&fg->outputs[0]->filter,
783 avfilter_get_by_name("buffersink"),
784 "out", NULL, NULL, fg->graph);
786 ret = avfilter_graph_create_filter(&fg->outputs[0]->filter,
787 avfilter_get_by_name("buffersink"),
788 "out", NULL, buffersink_params, fg->graph);
790 av_freep(&buffersink_params);
794 in_filter = fg->inputs[0]->filter;
795 out_filter = fg->outputs[0]->filter;
797 if (codec->width || codec->height) {
798 snprintf(args, 255, "%d:%d:flags=0x%X",
801 (unsigned)ost->sws_flags);
802 if ((ret = avfilter_graph_create_filter(&filter, avfilter_get_by_name("scale"),
803 NULL, args, NULL, fg->graph)) < 0)
805 if ((ret = avfilter_link(in_filter, 0, filter, 0)) < 0)
810 if ((pix_fmts = choose_pixel_fmts(ost))) {
811 if ((ret = avfilter_graph_create_filter(&filter,
812 avfilter_get_by_name("format"),
813 "format", pix_fmts, NULL,
816 if ((ret = avfilter_link(filter, 0, out_filter, 0)) < 0)
823 snprintf(args, sizeof(args), "flags=0x%X", (unsigned)ost->sws_flags);
824 fg->graph->scale_sws_opts = av_strdup(args);
827 AVFilterInOut *outputs = avfilter_inout_alloc();
828 AVFilterInOut *inputs = avfilter_inout_alloc();
830 outputs->name = av_strdup("in");
831 outputs->filter_ctx = in_filter;
832 outputs->pad_idx = 0;
833 outputs->next = NULL;
835 inputs->name = av_strdup("out");
836 inputs->filter_ctx = out_filter;
840 if ((ret = avfilter_graph_parse(fg->graph, ost->avfilter, &inputs, &outputs, NULL)) < 0)
842 av_freep(&ost->avfilter);
844 if ((ret = avfilter_link(in_filter, 0, out_filter, 0)) < 0)
848 if (ost->keep_pix_fmt)
849 avfilter_graph_set_auto_convert(fg->graph,
850 AVFILTER_AUTO_CONVERT_NONE);
852 if ((ret = avfilter_graph_config(fg->graph, NULL)) < 0)
855 ost->filter = fg->outputs[0];
860 static FilterGraph *init_simple_filtergraph(InputStream *ist, OutputStream *ost)
862 FilterGraph *fg = av_mallocz(sizeof(*fg));
866 fg->index = nb_filtergraphs;
868 fg->outputs = grow_array(fg->outputs, sizeof(*fg->outputs), &fg->nb_outputs,
870 if (!(fg->outputs[0] = av_mallocz(sizeof(*fg->outputs[0]))))
872 fg->outputs[0]->ost = ost;
873 fg->outputs[0]->graph = fg;
875 fg->inputs = grow_array(fg->inputs, sizeof(*fg->inputs), &fg->nb_inputs,
877 if (!(fg->inputs[0] = av_mallocz(sizeof(*fg->inputs[0]))))
879 fg->inputs[0]->ist = ist;
880 fg->inputs[0]->graph = fg;
882 ist->filters = grow_array(ist->filters, sizeof(*ist->filters),
883 &ist->nb_filters, ist->nb_filters + 1);
884 ist->filters[ist->nb_filters - 1] = fg->inputs[0];
886 filtergraphs = grow_array(filtergraphs, sizeof(*filtergraphs),
887 &nb_filtergraphs, nb_filtergraphs + 1);
888 filtergraphs[nb_filtergraphs - 1] = fg;
893 static void init_input_filter(FilterGraph *fg, AVFilterInOut *in)
895 InputStream *ist = NULL;
896 enum AVMediaType type = in->filter_ctx->input_pads[in->pad_idx].type;
899 // TODO: support other filter types
900 if (type != AVMEDIA_TYPE_VIDEO) {
901 av_log(NULL, AV_LOG_FATAL, "Only video filters supported currently.\n");
909 int file_idx = strtol(in->name, &p, 0);
911 if (file_idx < 0 || file_idx >= nb_input_files) {
912 av_log(NULL, AV_LOG_FATAL, "Invalid file index %d in filtergraph description %s.\n",
913 file_idx, fg->graph_desc);
916 s = input_files[file_idx]->ctx;
918 for (i = 0; i < s->nb_streams; i++) {
919 if (s->streams[i]->codec->codec_type != type)
921 if (check_stream_specifier(s, s->streams[i], *p == ':' ? p + 1 : p) == 1) {
927 av_log(NULL, AV_LOG_FATAL, "Stream specifier '%s' in filtergraph description %s "
928 "matches no streams.\n", p, fg->graph_desc);
931 ist = input_streams[input_files[file_idx]->ist_index + st->index];
933 /* find the first unused stream of corresponding type */
934 for (i = 0; i < nb_input_streams; i++) {
935 ist = input_streams[i];
936 if (ist->st->codec->codec_type == type && ist->discard)
939 if (i == nb_input_streams) {
940 av_log(NULL, AV_LOG_FATAL, "Cannot find a matching stream for "
941 "unlabeled input pad %d on filter %s", in->pad_idx,
942 in->filter_ctx->name);
947 ist->decoding_needed = 1;
948 ist->st->discard = AVDISCARD_NONE;
950 fg->inputs = grow_array(fg->inputs, sizeof(*fg->inputs),
951 &fg->nb_inputs, fg->nb_inputs + 1);
952 if (!(fg->inputs[fg->nb_inputs - 1] = av_mallocz(sizeof(*fg->inputs[0]))))
954 fg->inputs[fg->nb_inputs - 1]->ist = ist;
955 fg->inputs[fg->nb_inputs - 1]->graph = fg;
957 ist->filters = grow_array(ist->filters, sizeof(*ist->filters),
958 &ist->nb_filters, ist->nb_filters + 1);
959 ist->filters[ist->nb_filters - 1] = fg->inputs[fg->nb_inputs - 1];
962 static int configure_output_filter(FilterGraph *fg, OutputFilter *ofilter, AVFilterInOut *out)
965 AVCodecContext *codec = ofilter->ost->st->codec;
966 AVFilterContext *last_filter = out->filter_ctx;
967 int pad_idx = out->pad_idx;
969 AVBufferSinkParams *buffersink_params = av_buffersink_params_alloc();
971 #if FF_API_OLD_VSINK_API
972 ret = avfilter_graph_create_filter(&ofilter->filter,
973 avfilter_get_by_name("buffersink"),
974 "out", NULL, NULL, fg->graph);
976 ret = avfilter_graph_create_filter(&ofilter->filter,
977 avfilter_get_by_name("buffersink"),
978 "out", NULL, buffersink_params, fg->graph);
980 av_freep(&buffersink_params);
985 if (codec->width || codec->height) {
987 AVFilterContext *filter;
989 snprintf(args, sizeof(args), "%d:%d:flags=0x%X",
992 (unsigned)ofilter->ost->sws_flags);
993 if ((ret = avfilter_graph_create_filter(&filter, avfilter_get_by_name("scale"),
994 NULL, args, NULL, fg->graph)) < 0)
996 if ((ret = avfilter_link(last_filter, pad_idx, filter, 0)) < 0)
999 last_filter = filter;
1003 if ((pix_fmts = choose_pixel_fmts(ofilter->ost))) {
1004 AVFilterContext *filter;
1005 if ((ret = avfilter_graph_create_filter(&filter,
1006 avfilter_get_by_name("format"),
1007 "format", pix_fmts, NULL,
1010 if ((ret = avfilter_link(last_filter, pad_idx, filter, 0)) < 0)
1013 last_filter = filter;
1015 av_freep(&pix_fmts);
1018 if ((ret = avfilter_link(last_filter, pad_idx, ofilter->filter, 0)) < 0)
1024 static int configure_complex_filter(FilterGraph *fg)
1026 AVFilterInOut *inputs, *outputs, *cur;
1027 int ret, i, init = !fg->graph;
1029 avfilter_graph_free(&fg->graph);
1030 if (!(fg->graph = avfilter_graph_alloc()))
1031 return AVERROR(ENOMEM);
1033 if ((ret = avfilter_graph_parse2(fg->graph, fg->graph_desc, &inputs, &outputs)) < 0)
1036 for (cur = inputs; init && cur; cur = cur->next)
1037 init_input_filter(fg, cur);
1039 for (cur = inputs, i = 0; cur; cur = cur->next, i++) {
1040 InputFilter *ifilter = fg->inputs[i];
1041 InputStream *ist = ifilter->ist;
1045 sar = ist->st->sample_aspect_ratio.num ? ist->st->sample_aspect_ratio :
1046 ist->st->codec->sample_aspect_ratio;
1047 snprintf(args, sizeof(args), "%d:%d:%d:%d:%d:%d:%d", ist->st->codec->width,
1048 ist->st->codec->height, ist->st->codec->pix_fmt, 1, AV_TIME_BASE,
1051 if ((ret = avfilter_graph_create_filter(&ifilter->filter,
1052 avfilter_get_by_name("buffer"), cur->name,
1053 args, NULL, fg->graph)) < 0)
1055 if ((ret = avfilter_link(ifilter->filter, 0,
1056 cur->filter_ctx, cur->pad_idx)) < 0)
1059 avfilter_inout_free(&inputs);
1062 /* we already know the mappings between lavfi outputs and output streams,
1063 * so we can finish the setup */
1064 for (cur = outputs, i = 0; cur; cur = cur->next, i++)
1065 configure_output_filter(fg, fg->outputs[i], cur);
1066 avfilter_inout_free(&outputs);
1068 if ((ret = avfilter_graph_config(fg->graph, NULL)) < 0)
1071 /* wait until output mappings are processed */
1072 for (cur = outputs; cur;) {
1073 fg->outputs = grow_array(fg->outputs, sizeof(*fg->outputs),
1074 &fg->nb_outputs, fg->nb_outputs + 1);
1075 if (!(fg->outputs[fg->nb_outputs - 1] = av_mallocz(sizeof(*fg->outputs[0]))))
1077 fg->outputs[fg->nb_outputs - 1]->graph = fg;
1078 fg->outputs[fg->nb_outputs - 1]->out_tmp = cur;
1080 fg->outputs[fg->nb_outputs - 1]->out_tmp->next = NULL;
1087 static int configure_complex_filters(void)
1091 for (i = 0; i < nb_filtergraphs; i++)
1092 if (!filtergraphs[i]->graph &&
1093 (ret = configure_complex_filter(filtergraphs[i])) < 0)
1098 static int configure_filtergraph(FilterGraph *fg)
1100 return fg->graph_desc ? configure_complex_filter(fg) : configure_video_filters(fg);
1103 static int ist_in_filtergraph(FilterGraph *fg, InputStream *ist)
1106 for (i = 0; i < fg->nb_inputs; i++)
1107 if (fg->inputs[i]->ist == ist)
1112 static void term_exit(void)
1114 av_log(NULL, AV_LOG_QUIET, "%s", "");
1117 tcsetattr (0, TCSANOW, &oldtty);
1121 static volatile int received_sigterm = 0;
1123 static void sigterm_handler(int sig)
1125 received_sigterm = sig;
1126 received_nb_signals++;
1128 if(received_nb_signals > 3)
1132 static void term_init(void)
1138 if (tcgetattr (0, &tty) == 0) {
1143 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
1144 |INLCR|IGNCR|ICRNL|IXON);
1145 tty.c_oflag |= OPOST;
1146 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
1147 tty.c_cflag &= ~(CSIZE|PARENB);
1150 tty.c_cc[VTIME] = 0;
1152 tcsetattr (0, TCSANOW, &tty);
1154 signal(SIGQUIT, sigterm_handler); /* Quit (POSIX). */
1157 avformat_network_deinit();
1159 signal(SIGINT , sigterm_handler); /* Interrupt (ANSI). */
1160 signal(SIGTERM, sigterm_handler); /* Termination (ANSI). */
1162 signal(SIGXCPU, sigterm_handler);
1166 /* read a key without blocking */
1167 static int read_key(void)
1179 n = select(1, &rfds, NULL, NULL, &tv);
1181 n = read(0, &ch, 1);
1188 # if HAVE_PEEKNAMEDPIPE
1190 static HANDLE input_handle;
1193 input_handle = GetStdHandle(STD_INPUT_HANDLE);
1194 is_pipe = !GetConsoleMode(input_handle, &dw);
1197 if (stdin->_cnt > 0) {
1202 /* When running under a GUI, you will end here. */
1203 if (!PeekNamedPipe(input_handle, NULL, 0, NULL, &nchars, NULL))
1220 static int decode_interrupt_cb(void *ctx)
1222 return received_nb_signals > 1;
1225 static const AVIOInterruptCB int_cb = { decode_interrupt_cb, NULL };
1227 void av_noreturn exit_program(int ret)
1231 for (i = 0; i < nb_filtergraphs; i++) {
1232 avfilter_graph_free(&filtergraphs[i]->graph);
1233 for (j = 0; j < filtergraphs[i]->nb_inputs; j++)
1234 av_freep(&filtergraphs[i]->inputs[j]);
1235 av_freep(&filtergraphs[i]->inputs);
1236 for (j = 0; j < filtergraphs[i]->nb_outputs; j++)
1237 av_freep(&filtergraphs[i]->outputs[j]);
1238 av_freep(&filtergraphs[i]->outputs);
1239 av_freep(&filtergraphs[i]);
1241 av_freep(&filtergraphs);
1244 for (i = 0; i < nb_output_files; i++) {
1245 AVFormatContext *s = output_files[i]->ctx;
1246 if (!(s->oformat->flags & AVFMT_NOFILE) && s->pb)
1248 avformat_free_context(s);
1249 av_dict_free(&output_files[i]->opts);
1250 av_freep(&output_files[i]);
1252 for (i = 0; i < nb_output_streams; i++) {
1253 AVBitStreamFilterContext *bsfc = output_streams[i]->bitstream_filters;
1255 AVBitStreamFilterContext *next = bsfc->next;
1256 av_bitstream_filter_close(bsfc);
1259 output_streams[i]->bitstream_filters = NULL;
1261 if (output_streams[i]->output_frame) {
1262 AVFrame *frame = output_streams[i]->output_frame;
1263 if (frame->extended_data != frame->data)
1264 av_freep(&frame->extended_data);
1267 av_freep(&output_streams[i]->filtered_frame);
1268 av_freep(&output_streams[i]);
1270 for (i = 0; i < nb_input_files; i++) {
1271 avformat_close_input(&input_files[i]->ctx);
1272 av_freep(&input_files[i]);
1274 for (i = 0; i < nb_input_streams; i++) {
1275 av_freep(&input_streams[i]->decoded_frame);
1276 av_dict_free(&input_streams[i]->opts);
1277 free_buffer_pool(input_streams[i]);
1278 av_freep(&input_streams[i]->filters);
1279 av_freep(&input_streams[i]);
1283 fclose(vstats_file);
1284 av_free(vstats_filename);
1286 av_freep(&input_streams);
1287 av_freep(&input_files);
1288 av_freep(&output_streams);
1289 av_freep(&output_files);
1292 av_freep(&audio_buf);
1293 allocated_audio_buf_size = 0;
1294 av_freep(&async_buf);
1295 allocated_async_buf_size = 0;
1298 avformat_network_deinit();
1300 if (received_sigterm) {
1301 av_log(NULL, AV_LOG_INFO, "Received signal %d: terminating.\n",
1302 (int) received_sigterm);
1306 exit(ret); /* not all OS-es handle main() return value */
1309 static void assert_avoptions(AVDictionary *m)
1311 AVDictionaryEntry *t;
1312 if ((t = av_dict_get(m, "", NULL, AV_DICT_IGNORE_SUFFIX))) {
1313 av_log(NULL, AV_LOG_FATAL, "Option %s not found.\n", t->key);
1318 static void assert_codec_experimental(AVCodecContext *c, int encoder)
1320 const char *codec_string = encoder ? "encoder" : "decoder";
1322 if (c->codec->capabilities & CODEC_CAP_EXPERIMENTAL &&
1323 c->strict_std_compliance > FF_COMPLIANCE_EXPERIMENTAL) {
1324 av_log(NULL, AV_LOG_FATAL, "%s '%s' is experimental and might produce bad "
1325 "results.\nAdd '-strict experimental' if you want to use it.\n",
1326 codec_string, c->codec->name);
1327 codec = encoder ? avcodec_find_encoder(c->codec->id) : avcodec_find_decoder(c->codec->id);
1328 if (!(codec->capabilities & CODEC_CAP_EXPERIMENTAL))
1329 av_log(NULL, AV_LOG_FATAL, "Or use the non experimental %s '%s'.\n",
1330 codec_string, codec->name);
1335 static void choose_sample_fmt(AVStream *st, AVCodec *codec)
1337 if (codec && codec->sample_fmts) {
1338 const enum AVSampleFormat *p = codec->sample_fmts;
1339 for (; *p != -1; p++) {
1340 if (*p == st->codec->sample_fmt)
1344 if((codec->capabilities & CODEC_CAP_LOSSLESS) && av_get_sample_fmt_name(st->codec->sample_fmt) > av_get_sample_fmt_name(codec->sample_fmts[0]))
1345 av_log(NULL, AV_LOG_ERROR, "Conversion will not be lossless.\n");
1346 if(av_get_sample_fmt_name(st->codec->sample_fmt))
1347 av_log(NULL, AV_LOG_WARNING,
1348 "Incompatible sample format '%s' for codec '%s', auto-selecting format '%s'\n",
1349 av_get_sample_fmt_name(st->codec->sample_fmt),
1351 av_get_sample_fmt_name(codec->sample_fmts[0]));
1352 st->codec->sample_fmt = codec->sample_fmts[0];
1357 static void choose_sample_rate(AVStream *st, AVCodec *codec)
1359 if (codec && codec->supported_samplerates) {
1360 const int *p = codec->supported_samplerates;
1362 int best_dist = INT_MAX;
1364 int dist = abs(st->codec->sample_rate - *p);
1365 if (dist < best_dist) {
1372 const int *sample_rates = codec->supported_samplerates;
1373 av_log(st->codec, AV_LOG_WARNING,
1374 "Requested sampling rate (%dHz) unsupported, using %dHz instead\n"
1375 "Available sampling rates for %s:",
1376 st->codec->sample_rate, best, codec->name);
1377 for (i = 0; sample_rates[i]; i++) {
1378 if (!sample_rates[i + 1]) av_log(st->codec, AV_LOG_WARNING, " and");
1379 else if (i) av_log(st->codec, AV_LOG_WARNING, ",");
1380 av_log(st->codec, AV_LOG_WARNING, " %d", sample_rates[i]);
1382 av_log(st->codec, AV_LOG_WARNING, ".\n");
1384 st->codec->sample_rate = best;
1389 get_sync_ipts(const OutputStream *ost, int64_t pts)
1391 OutputFile *of = output_files[ost->file_index];
1392 return (double)(pts - of->start_time) / AV_TIME_BASE;
1395 static void write_frame(AVFormatContext *s, AVPacket *pkt, OutputStream *ost)
1397 AVBitStreamFilterContext *bsfc = ost->bitstream_filters;
1398 AVCodecContext *avctx = ost->st->codec;
1401 if ((avctx->codec_type == AVMEDIA_TYPE_VIDEO && video_sync_method == VSYNC_DROP) ||
1402 (avctx->codec_type == AVMEDIA_TYPE_AUDIO && audio_sync_method < 0))
1403 pkt->pts = pkt->dts = AV_NOPTS_VALUE;
1406 * Audio encoders may split the packets -- #frames in != #packets out.
1407 * But there is no reordering, so we can limit the number of output packets
1408 * by simply dropping them here.
1409 * Counting encoded video frames needs to be done separately because of
1410 * reordering, see do_video_out()
1412 if (!(avctx->codec_type == AVMEDIA_TYPE_VIDEO && avctx->codec)) {
1413 if (ost->frame_number >= ost->max_frames) {
1414 av_free_packet(pkt);
1417 ost->frame_number++;
1421 AVPacket new_pkt = *pkt;
1422 int a = av_bitstream_filter_filter(bsfc, avctx, NULL,
1423 &new_pkt.data, &new_pkt.size,
1424 pkt->data, pkt->size,
1425 pkt->flags & AV_PKT_FLAG_KEY);
1427 av_free_packet(pkt);
1428 new_pkt.destruct = av_destruct_packet;
1430 av_log(NULL, AV_LOG_ERROR, "Failed to open bitstream filter %s for stream %d with codec %s",
1431 bsfc->filter->name, pkt->stream_index,
1432 avctx->codec ? avctx->codec->name : "copy");
1442 pkt->stream_index = ost->index;
1443 ret = av_interleaved_write_frame(s, pkt);
1445 print_error("av_interleaved_write_frame()", ret);
1450 static void get_default_channel_layouts(OutputStream *ost, InputStream *ist)
1452 char layout_name[256];
1453 AVCodecContext *enc = ost->st->codec;
1454 AVCodecContext *dec = ist->st->codec;
1456 if (dec->channel_layout &&
1457 av_get_channel_layout_nb_channels(dec->channel_layout) != dec->channels) {
1458 av_get_channel_layout_string(layout_name, sizeof(layout_name),
1459 dec->channels, dec->channel_layout);
1460 av_log(NULL, AV_LOG_ERROR, "New channel layout (%s) is invalid\n",
1462 dec->channel_layout = 0;
1464 if (!dec->channel_layout) {
1465 if (enc->channel_layout && dec->channels == enc->channels) {
1466 dec->channel_layout = enc->channel_layout;
1468 dec->channel_layout = av_get_default_channel_layout(dec->channels);
1470 if (!dec->channel_layout) {
1471 av_log(NULL, AV_LOG_FATAL, "Unable to find default channel "
1472 "layout for Input Stream #%d.%d\n", ist->file_index,
1477 av_get_channel_layout_string(layout_name, sizeof(layout_name),
1478 dec->channels, dec->channel_layout);
1479 av_log(NULL, AV_LOG_WARNING, "Guessed Channel Layout for Input Stream "
1480 "#%d.%d : %s\n", ist->file_index, ist->st->index, layout_name);
1482 if (!enc->channel_layout) {
1483 if (dec->channels == enc->channels) {
1484 enc->channel_layout = dec->channel_layout;
1487 enc->channel_layout = av_get_default_channel_layout(enc->channels);
1489 if (!enc->channel_layout) {
1490 av_log(NULL, AV_LOG_FATAL, "Unable to find default channel layout "
1491 "for Output Stream #%d.%d\n", ost->file_index,
1495 av_get_channel_layout_string(layout_name, sizeof(layout_name),
1496 enc->channels, enc->channel_layout);
1497 av_log(NULL, AV_LOG_WARNING, "Guessed Channel Layout for Output Stream "
1498 "#%d.%d : %s\n", ost->file_index, ost->st->index, layout_name);
1502 static void generate_silence(uint8_t* buf, enum AVSampleFormat sample_fmt, size_t size)
1504 int fill_char = 0x00;
1505 if (sample_fmt == AV_SAMPLE_FMT_U8)
1507 memset(buf, fill_char, size);
1510 static int encode_audio_frame(AVFormatContext *s, OutputStream *ost,
1511 const uint8_t *buf, int buf_size)
1513 AVCodecContext *enc = ost->st->codec;
1514 AVFrame *frame = NULL;
1516 int ret, got_packet;
1518 av_init_packet(&pkt);
1522 if (buf && buf_size) {
1523 if (!ost->output_frame) {
1524 ost->output_frame = avcodec_alloc_frame();
1525 if (!ost->output_frame) {
1526 av_log(NULL, AV_LOG_FATAL, "out-of-memory in encode_audio_frame()\n");
1530 frame = ost->output_frame;
1531 if (frame->extended_data != frame->data)
1532 av_freep(&frame->extended_data);
1533 avcodec_get_frame_defaults(frame);
1535 frame->nb_samples = buf_size /
1536 (enc->channels * av_get_bytes_per_sample(enc->sample_fmt));
1537 if ((ret = avcodec_fill_audio_frame(frame, enc->channels, enc->sample_fmt,
1538 buf, buf_size, 1)) < 0) {
1539 av_log(NULL, AV_LOG_FATAL, "Audio encoding failed (avcodec_fill_audio_frame)\n");
1543 frame->pts = ost->sync_opts;
1544 ost->sync_opts += frame->nb_samples;
1548 update_benchmark(NULL);
1549 if (avcodec_encode_audio2(enc, &pkt, frame, &got_packet) < 0) {
1550 av_log(NULL, AV_LOG_FATAL, "Audio encoding failed (avcodec_encode_audio2)\n");
1553 update_benchmark("encode_audio %d.%d", ost->file_index, ost->index);
1558 if (pkt.pts != AV_NOPTS_VALUE)
1559 pkt.pts = av_rescale_q(pkt.pts, enc->time_base, ost->st->time_base);
1560 if (pkt.dts != AV_NOPTS_VALUE) {
1561 int64_t max = ost->st->cur_dts + !(s->oformat->flags & AVFMT_TS_NONSTRICT);
1562 pkt.dts = av_rescale_q(pkt.dts, enc->time_base, ost->st->time_base);
1563 if (ost->st->cur_dts && ost->st->cur_dts != AV_NOPTS_VALUE && max > pkt.dts) {
1564 av_log(s, max - pkt.dts > 2 ? AV_LOG_WARNING : AV_LOG_DEBUG, "Audio timestamp %"PRId64" < %"PRId64" invalid, cliping\n", pkt.dts, max);
1565 pkt.pts = pkt.dts = max;
1568 if (pkt.duration > 0)
1569 pkt.duration = av_rescale_q(pkt.duration, enc->time_base, ost->st->time_base);
1571 write_frame(s, &pkt, ost);
1573 audio_size += pkt.size;
1575 av_free_packet(&pkt);
1579 av_log(NULL, AV_LOG_INFO, "encoder -> type:audio "
1580 "pkt_pts:%s pkt_pts_time:%s pkt_dts:%s pkt_dts_time:%s\n",
1581 av_ts2str(pkt.pts), av_ts2timestr(pkt.pts, &ost->st->time_base),
1582 av_ts2str(pkt.dts), av_ts2timestr(pkt.dts, &ost->st->time_base));
1588 static int alloc_audio_output_buf(AVCodecContext *dec, AVCodecContext *enc,
1589 int nb_samples, int *buf_linesize)
1591 int64_t audio_buf_samples;
1594 /* calculate required number of samples to allocate */
1595 audio_buf_samples = ((int64_t)nb_samples * enc->sample_rate + dec->sample_rate) /
1597 audio_buf_samples = 4 * audio_buf_samples + 10000; // safety factors for resampling
1598 audio_buf_samples = FFMAX(audio_buf_samples, enc->frame_size);
1599 if (audio_buf_samples > INT_MAX)
1600 return AVERROR(EINVAL);
1602 audio_buf_size = av_samples_get_buffer_size(buf_linesize, enc->channels,
1604 enc->sample_fmt, 0);
1605 if (audio_buf_size < 0)
1606 return audio_buf_size;
1608 av_fast_malloc(&audio_buf, &allocated_audio_buf_size, audio_buf_size);
1610 return AVERROR(ENOMEM);
1615 static void do_audio_out(AVFormatContext *s, OutputStream *ost,
1616 InputStream *ist, AVFrame *decoded_frame)
1621 int frame_bytes, resample_changed;
1622 AVCodecContext *enc = ost->st->codec;
1623 AVCodecContext *dec = ist->st->codec;
1624 int osize = av_get_bytes_per_sample(enc->sample_fmt);
1625 int isize = av_get_bytes_per_sample(dec->sample_fmt);
1626 uint8_t *buf[AV_NUM_DATA_POINTERS];
1627 int size = decoded_frame->nb_samples * dec->channels * isize;
1628 int planes = av_sample_fmt_is_planar(dec->sample_fmt) ? dec->channels : 1;
1630 int out_linesize = 0;
1632 av_assert0(planes <= AV_NUM_DATA_POINTERS);
1634 for(i=0; i<planes; i++)
1635 buf[i]= decoded_frame->data[i];
1638 get_default_channel_layouts(ost, ist);
1640 if (alloc_audio_output_buf(dec, enc, decoded_frame->nb_samples, &out_linesize) < 0) {
1641 av_log(NULL, AV_LOG_FATAL, "Error allocating audio buffer\n");
1645 if (audio_sync_method > 1 ||
1646 enc->channels != dec->channels ||
1647 enc->channel_layout != dec->channel_layout ||
1648 enc->sample_rate != dec->sample_rate ||
1649 dec->sample_fmt != enc->sample_fmt)
1650 ost->audio_resample = 1;
1652 resample_changed = ost->resample_sample_fmt != dec->sample_fmt ||
1653 ost->resample_channels != dec->channels ||
1654 ost->resample_channel_layout != dec->channel_layout ||
1655 ost->resample_sample_rate != dec->sample_rate;
1657 if ((ost->audio_resample && !ost->swr) || resample_changed || ost->audio_channels_mapped) {
1659 if (resample_changed) {
1660 av_log(NULL, AV_LOG_INFO, "Input stream #%d:%d frame changed from rate:%d fmt:%s ch:%d chl:0x%"PRIx64" to rate:%d fmt:%s ch:%d chl:0x%"PRIx64"\n",
1661 ist->file_index, ist->st->index,
1662 ost->resample_sample_rate, av_get_sample_fmt_name(ost->resample_sample_fmt),
1663 ost->resample_channels, ost->resample_channel_layout,
1664 dec->sample_rate, av_get_sample_fmt_name(dec->sample_fmt),
1665 dec->channels, dec->channel_layout);
1666 ost->resample_sample_fmt = dec->sample_fmt;
1667 ost->resample_channels = dec->channels;
1668 ost->resample_channel_layout = dec->channel_layout;
1669 ost->resample_sample_rate = dec->sample_rate;
1670 swr_free(&ost->swr);
1672 /* if audio_sync_method is >1 the resampler is needed for audio drift compensation */
1673 if (audio_sync_method <= 1 && !ost->audio_channels_mapped &&
1674 ost->resample_sample_fmt == enc->sample_fmt &&
1675 ost->resample_channels == enc->channels &&
1676 ost->resample_channel_layout == enc->channel_layout &&
1677 ost->resample_sample_rate == enc->sample_rate) {
1679 ost->audio_resample = 0;
1681 ost->swr = swr_alloc_set_opts(ost->swr,
1682 enc->channel_layout, enc->sample_fmt, enc->sample_rate,
1683 dec->channel_layout, dec->sample_fmt, dec->sample_rate,
1685 av_opt_set_int(ost->swr, "dither_method", ost->swr_dither_method,0);
1686 av_opt_set_double(ost->swr, "dither_scale", ost->swr_dither_scale,0);
1687 if (ost->audio_channels_mapped)
1688 swr_set_channel_mapping(ost->swr, ost->audio_channels_map);
1689 av_opt_set_double(ost->swr, "rmvol", ost->rematrix_volume, 0);
1690 if (ost->audio_channels_mapped) {
1691 av_opt_set_int(ost->swr, "icl", av_get_default_channel_layout(ost->audio_channels_mapped), 0);
1692 av_opt_set_int(ost->swr, "uch", ost->audio_channels_mapped, 0);
1694 if (av_opt_set_int(ost->swr, "ich", dec->channels, 0) < 0) {
1695 av_log(NULL, AV_LOG_FATAL, "Unsupported number of input channels\n");
1698 if (av_opt_set_int(ost->swr, "och", enc->channels, 0) < 0) {
1699 av_log(NULL, AV_LOG_FATAL, "Unsupported number of output channels\n");
1702 if(audio_sync_method>1) av_opt_set_int(ost->swr, "flags", SWR_FLAG_RESAMPLE, 0);
1703 if(ost->swr && swr_init(ost->swr) < 0){
1704 av_log(NULL, AV_LOG_FATAL, "swr_init() failed\n");
1705 swr_free(&ost->swr);
1709 av_log(NULL, AV_LOG_FATAL, "Can not resample %d channels @ %d Hz to %d channels @ %d Hz\n",
1710 dec->channels, dec->sample_rate,
1711 enc->channels, enc->sample_rate);
1717 av_assert0(ost->audio_resample || dec->sample_fmt==enc->sample_fmt);
1719 if (audio_sync_method > 0) {
1720 double delta = get_sync_ipts(ost, ist->pts) * enc->sample_rate - ost->sync_opts -
1721 av_fifo_size(ost->fifo) / (enc->channels * osize);
1722 int idelta = delta * dec->sample_rate / enc->sample_rate;
1723 int byte_delta = idelta * isize * dec->channels;
1725 // FIXME resample delay
1726 if (fabs(delta) > 50) {
1727 if (ist->is_start || fabs(delta) > audio_drift_threshold*enc->sample_rate) {
1728 if (byte_delta < 0) {
1729 byte_delta = FFMAX(byte_delta, -size);
1731 for (i=0; i<planes; i++)
1732 buf[i] -= byte_delta/planes;
1733 av_log(NULL, AV_LOG_VERBOSE, "discarding %d audio samples\n",
1734 -byte_delta / (isize * dec->channels));
1739 av_fast_malloc(&async_buf, &allocated_async_buf_size,
1742 av_log(NULL, AV_LOG_FATAL, "Out of memory in do_audio_out\n");
1746 if (alloc_audio_output_buf(dec, enc, decoded_frame->nb_samples + idelta, &out_linesize) < 0) {
1747 av_log(NULL, AV_LOG_FATAL, "Error allocating audio buffer\n");
1752 for (i=0; i<planes; i++) {
1753 uint8_t *t = async_buf + i*((byte_delta + size)/planes);
1754 generate_silence(t, dec->sample_fmt, byte_delta/planes);
1755 memcpy(t + byte_delta/planes, buf[i], size/planes);
1759 av_log(NULL, AV_LOG_VERBOSE, "adding %d audio samples of silence\n", idelta);
1761 } else if (audio_sync_method > 1) {
1762 int comp = av_clip(delta, -audio_sync_method, audio_sync_method);
1763 av_log(NULL, AV_LOG_VERBOSE, "compensating audio timestamp drift:%f compensation:%d in:%d\n",
1764 delta, comp, enc->sample_rate);
1765 // 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));
1766 swr_set_compensation(ost->swr, comp, enc->sample_rate);
1769 } else if (audio_sync_method == 0)
1770 ost->sync_opts = lrintf(get_sync_ipts(ost, ist->pts) * enc->sample_rate) -
1771 av_fifo_size(ost->fifo) / (enc->channels * osize); // FIXME wrong
1773 if (ost->audio_resample || ost->audio_channels_mapped) {
1775 size_out = swr_convert(ost->swr, ( uint8_t*[]){buftmp},
1776 allocated_audio_buf_size / (enc->channels * osize),
1777 (const uint8_t **)buf,
1778 size / (dec->channels * isize));
1780 av_log(NULL, AV_LOG_FATAL, "swr_convert failed\n");
1783 size_out = size_out * enc->channels * osize;
1789 av_assert0(ost->audio_resample || dec->sample_fmt==enc->sample_fmt);
1791 /* now encode as many frames as possible */
1792 if (!(enc->codec->capabilities & CODEC_CAP_VARIABLE_FRAME_SIZE)) {
1793 /* output resampled raw samples */
1794 if (av_fifo_realloc2(ost->fifo, av_fifo_size(ost->fifo) + size_out) < 0) {
1795 av_log(NULL, AV_LOG_FATAL, "av_fifo_realloc2() failed\n");
1798 av_fifo_generic_write(ost->fifo, buftmp, size_out, NULL);
1800 frame_bytes = enc->frame_size * osize * enc->channels;
1802 while (av_fifo_size(ost->fifo) >= frame_bytes) {
1803 av_fifo_generic_read(ost->fifo, audio_buf, frame_bytes, NULL);
1804 encode_audio_frame(s, ost, audio_buf, frame_bytes);
1807 encode_audio_frame(s, ost, buftmp, size_out);
1811 static void pre_process_video_frame(InputStream *ist, AVPicture *picture, void **bufp)
1813 AVCodecContext *dec;
1814 AVPicture *picture2;
1815 AVPicture picture_tmp;
1818 dec = ist->st->codec;
1820 /* deinterlace : must be done before any resize */
1821 if (do_deinterlace) {
1824 /* create temporary picture */
1825 size = avpicture_get_size(dec->pix_fmt, dec->width, dec->height);
1826 buf = av_malloc(size);
1830 picture2 = &picture_tmp;
1831 avpicture_fill(picture2, buf, dec->pix_fmt, dec->width, dec->height);
1833 if (avpicture_deinterlace(picture2, picture,
1834 dec->pix_fmt, dec->width, dec->height) < 0) {
1835 /* if error, do not deinterlace */
1836 av_log(NULL, AV_LOG_WARNING, "Deinterlacing failed\n");
1845 if (picture != picture2)
1846 *picture = *picture2;
1850 static void do_subtitle_out(AVFormatContext *s,
1856 static uint8_t *subtitle_out = NULL;
1857 int subtitle_out_max_size = 1024 * 1024;
1858 int subtitle_out_size, nb, i;
1859 AVCodecContext *enc;
1862 if (pts == AV_NOPTS_VALUE) {
1863 av_log(NULL, AV_LOG_ERROR, "Subtitle packets must have a pts\n");
1869 enc = ost->st->codec;
1871 if (!subtitle_out) {
1872 subtitle_out = av_malloc(subtitle_out_max_size);
1875 /* Note: DVB subtitle need one packet to draw them and one other
1876 packet to clear them */
1877 /* XXX: signal it in the codec context ? */
1878 if (enc->codec_id == CODEC_ID_DVB_SUBTITLE)
1883 for (i = 0; i < nb; i++) {
1884 ost->sync_opts = av_rescale_q(pts, ist->st->time_base, enc->time_base);
1886 sub->pts = av_rescale_q(pts, ist->st->time_base, AV_TIME_BASE_Q);
1887 // start_display_time is required to be 0
1888 sub->pts += av_rescale_q(sub->start_display_time, (AVRational){ 1, 1000 }, AV_TIME_BASE_Q);
1889 sub->end_display_time -= sub->start_display_time;
1890 sub->start_display_time = 0;
1891 subtitle_out_size = avcodec_encode_subtitle(enc, subtitle_out,
1892 subtitle_out_max_size, sub);
1893 if (subtitle_out_size < 0) {
1894 av_log(NULL, AV_LOG_FATAL, "Subtitle encoding failed\n");
1898 av_init_packet(&pkt);
1899 pkt.data = subtitle_out;
1900 pkt.size = subtitle_out_size;
1901 pkt.pts = av_rescale_q(sub->pts, AV_TIME_BASE_Q, ost->st->time_base);
1902 if (enc->codec_id == CODEC_ID_DVB_SUBTITLE) {
1903 /* XXX: the pts correction is handled here. Maybe handling
1904 it in the codec would be better */
1906 pkt.pts += 90 * sub->start_display_time;
1908 pkt.pts += 90 * sub->end_display_time;
1910 write_frame(s, &pkt, ost);
1914 static double psnr(double d)
1916 return -10.0 * log(d) / log(10.0);
1919 static void do_video_stats(AVFormatContext *os, OutputStream *ost,
1922 AVCodecContext *enc;
1924 double ti1, bitrate, avg_bitrate;
1926 /* this is executed just the first time do_video_stats is called */
1928 vstats_file = fopen(vstats_filename, "w");
1935 enc = ost->st->codec;
1936 if (enc->codec_type == AVMEDIA_TYPE_VIDEO) {
1937 frame_number = ost->frame_number;
1938 fprintf(vstats_file, "frame= %5d q= %2.1f ", frame_number, enc->coded_frame->quality / (float)FF_QP2LAMBDA);
1939 if (enc->flags&CODEC_FLAG_PSNR)
1940 fprintf(vstats_file, "PSNR= %6.2f ", psnr(enc->coded_frame->error[0] / (enc->width * enc->height * 255.0 * 255.0)));
1942 fprintf(vstats_file,"f_size= %6d ", frame_size);
1943 /* compute pts value */
1944 ti1 = ost->sync_opts * av_q2d(enc->time_base);
1948 bitrate = (frame_size * 8) / av_q2d(enc->time_base) / 1000.0;
1949 avg_bitrate = (double)(video_size * 8) / ti1 / 1000.0;
1950 fprintf(vstats_file, "s_size= %8.0fkB time= %0.3f br= %7.1fkbits/s avg_br= %7.1fkbits/s ",
1951 (double)video_size / 1024, ti1, bitrate, avg_bitrate);
1952 fprintf(vstats_file, "type= %c\n", av_get_picture_type_char(enc->coded_frame->pict_type));
1957 static void do_video_out(AVFormatContext *s, OutputStream *ost,
1958 AVFrame *in_picture, float quality)
1960 int nb_frames, i, ret, format_video_sync;
1961 AVCodecContext *enc;
1962 double sync_ipts, delta;
1963 double duration = 0;
1965 InputStream *ist = NULL;
1967 if (ost->source_index >= 0)
1968 ist = input_streams[ost->source_index];
1970 enc = ost->st->codec;
1972 if(ist && ist->st->start_time != AV_NOPTS_VALUE && ist->st->first_dts != AV_NOPTS_VALUE && ost->frame_rate.num)
1973 duration = 1/(av_q2d(ost->frame_rate) * av_q2d(enc->time_base));
1975 sync_ipts = get_sync_ipts(ost, in_picture->pts) / av_q2d(enc->time_base);
1976 delta = sync_ipts - ost->sync_opts + duration;
1978 /* by default, we output a single frame */
1981 format_video_sync = video_sync_method;
1982 if (format_video_sync == VSYNC_AUTO)
1983 format_video_sync = (s->oformat->flags & AVFMT_VARIABLE_FPS) ? ((s->oformat->flags & AVFMT_NOTIMESTAMPS) ? VSYNC_PASSTHROUGH : VSYNC_VFR) : 1;
1985 switch (format_video_sync) {
1987 // FIXME set to 0.5 after we fix some dts/pts bugs like in avidec.c
1990 else if (delta > 1.1)
1991 nb_frames = lrintf(delta);
1996 else if (delta > 0.6)
1997 ost->sync_opts = lrint(sync_ipts);
2000 case VSYNC_PASSTHROUGH:
2001 ost->sync_opts = lrint(sync_ipts);
2007 nb_frames = FFMIN(nb_frames, ost->max_frames - ost->frame_number);
2008 if (nb_frames == 0) {
2010 av_log(NULL, AV_LOG_VERBOSE, "*** drop!\n");
2012 } else if (nb_frames > 1) {
2013 nb_frames_dup += nb_frames - 1;
2014 av_log(NULL, AV_LOG_VERBOSE, "*** %d dup!\n", nb_frames - 1);
2017 /* duplicates frame if needed */
2018 for (i = 0; i < nb_frames; i++) {
2020 av_init_packet(&pkt);
2024 if (s->oformat->flags & AVFMT_RAWPICTURE &&
2025 enc->codec->id == CODEC_ID_RAWVIDEO) {
2026 /* raw pictures are written as AVPicture structure to
2027 avoid any copies. We support temporarily the older
2029 enc->coded_frame->interlaced_frame = in_picture->interlaced_frame;
2030 enc->coded_frame->top_field_first = in_picture->top_field_first;
2031 pkt.data = (uint8_t *)in_picture;
2032 pkt.size = sizeof(AVPicture);
2033 pkt.pts = av_rescale_q(ost->sync_opts, enc->time_base, ost->st->time_base);
2034 pkt.flags |= AV_PKT_FLAG_KEY;
2036 write_frame(s, &pkt, ost);
2039 AVFrame big_picture;
2041 big_picture = *in_picture;
2042 /* better than nothing: use input picture interlaced
2044 big_picture.interlaced_frame = in_picture->interlaced_frame;
2045 if (ost->st->codec->flags & (CODEC_FLAG_INTERLACED_DCT|CODEC_FLAG_INTERLACED_ME)) {
2046 if (ost->top_field_first == -1)
2047 big_picture.top_field_first = in_picture->top_field_first;
2049 big_picture.top_field_first = !!ost->top_field_first;
2052 /* handles same_quant here. This is not correct because it may
2053 not be a global option */
2054 big_picture.quality = quality;
2055 if (!enc->me_threshold)
2056 big_picture.pict_type = 0;
2057 big_picture.pts = ost->sync_opts;
2058 if (ost->forced_kf_index < ost->forced_kf_count &&
2059 big_picture.pts >= ost->forced_kf_pts[ost->forced_kf_index]) {
2060 big_picture.pict_type = AV_PICTURE_TYPE_I;
2061 ost->forced_kf_index++;
2063 update_benchmark(NULL);
2064 ret = avcodec_encode_video2(enc, &pkt, &big_picture, &got_packet);
2065 update_benchmark("encode_video %d.%d", ost->file_index, ost->index);
2067 av_log(NULL, AV_LOG_FATAL, "Video encoding failed\n");
2072 if (pkt.pts == AV_NOPTS_VALUE && !(enc->codec->capabilities & CODEC_CAP_DELAY))
2073 pkt.pts = ost->sync_opts;
2075 if (pkt.pts != AV_NOPTS_VALUE)
2076 pkt.pts = av_rescale_q(pkt.pts, enc->time_base, ost->st->time_base);
2077 if (pkt.dts != AV_NOPTS_VALUE)
2078 pkt.dts = av_rescale_q(pkt.dts, enc->time_base, ost->st->time_base);
2081 av_log(NULL, AV_LOG_INFO, "encoder -> type:video "
2082 "pkt_pts:%s pkt_pts_time:%s pkt_dts:%s pkt_dts_time:%s\n",
2083 av_ts2str(pkt.pts), av_ts2timestr(pkt.pts, &ost->st->time_base),
2084 av_ts2str(pkt.dts), av_ts2timestr(pkt.dts, &ost->st->time_base));
2087 write_frame(s, &pkt, ost);
2088 frame_size = pkt.size;
2089 video_size += pkt.size;
2090 av_free_packet(&pkt);
2092 /* if two pass, output log */
2093 if (ost->logfile && enc->stats_out) {
2094 fprintf(ost->logfile, "%s", enc->stats_out);
2100 * For video, number of frames in == number of packets out.
2101 * But there may be reordering, so we can't throw away frames on encoder
2102 * flush, we need to limit them here, before they go into encoder.
2104 ost->frame_number++;
2106 if (vstats_filename && frame_size)
2107 do_video_stats(output_files[ost->file_index]->ctx, ost, frame_size);
2110 /* check for new output on any of the filtergraphs */
2111 static int poll_filters(void)
2113 AVFilterBufferRef *picref;
2114 AVFrame *filtered_frame = NULL;
2115 int i, ret, ret_all;
2116 unsigned nb_success, nb_eof;
2120 /* Reap all buffers present in the buffer sinks */
2121 for (i = 0; i < nb_output_streams; i++) {
2122 OutputStream *ost = output_streams[i];
2123 OutputFile *of = output_files[ost->file_index];
2125 if (!ost->filter || ost->is_past_recording_time)
2128 if (!ost->filtered_frame && !(ost->filtered_frame = avcodec_alloc_frame())) {
2129 return AVERROR(ENOMEM);
2131 avcodec_get_frame_defaults(ost->filtered_frame);
2132 filtered_frame = ost->filtered_frame;
2135 AVRational ist_pts_tb = ost->filter->filter->inputs[0]->time_base;
2136 ret = av_buffersink_get_buffer_ref(ost->filter->filter, &picref,
2137 AV_BUFFERSINK_FLAG_NO_REQUEST);
2139 if (ret != AVERROR(EAGAIN)) {
2141 av_strerror(ret, buf, sizeof(buf));
2142 av_log(NULL, AV_LOG_WARNING,
2143 "Error in av_buffersink_get_buffer_ref(): %s\n", buf);
2147 filtered_frame->pts = frame_pts = av_rescale_q(picref->pts, ist_pts_tb, AV_TIME_BASE_Q);
2148 //if (ost->source_index >= 0)
2149 // *filtered_frame= *input_streams[ost->source_index]->decoded_frame; //for me_threshold
2151 if (of->start_time && filtered_frame->pts < of->start_time)
2154 switch (ost->filter->filter->inputs[0]->type) {
2155 case AVMEDIA_TYPE_VIDEO:
2156 avfilter_fill_frame_from_video_buffer_ref(filtered_frame, picref);
2157 filtered_frame->pts = frame_pts;
2158 if (!ost->frame_aspect_ratio)
2159 ost->st->codec->sample_aspect_ratio = picref->video->sample_aspect_ratio;
2161 do_video_out(of->ctx, ost, filtered_frame,
2162 same_quant ? ost->last_quality :
2163 ost->st->codec->global_quality);
2166 // TODO support audio/subtitle filters
2170 avfilter_unref_buffer(picref);
2173 /* Request frames through all the graphs */
2174 ret_all = nb_success = nb_eof = 0;
2175 for (i = 0; i < nb_filtergraphs; i++) {
2176 ret = avfilter_graph_request_oldest(filtergraphs[i]->graph);
2179 } else if (ret == AVERROR_EOF) {
2181 } else if (ret != AVERROR(EAGAIN)) {
2183 av_strerror(ret, buf, sizeof(buf));
2184 av_log(NULL, AV_LOG_WARNING,
2185 "Error in request_frame(): %s\n", buf);
2191 /* Try again if anything succeeded */
2193 return nb_eof == nb_filtergraphs ? AVERROR_EOF : ret_all;
2196 static void print_report(int is_last_report, int64_t timer_start, int64_t cur_time)
2200 AVFormatContext *oc;
2202 AVCodecContext *enc;
2203 int frame_number, vid, i;
2205 int64_t pts = INT64_MAX;
2206 static int64_t last_time = -1;
2207 static int qp_histogram[52];
2208 int hours, mins, secs, us;
2210 if (!print_stats && !is_last_report)
2213 if (!is_last_report) {
2214 if (last_time == -1) {
2215 last_time = cur_time;
2218 if ((cur_time - last_time) < 500000)
2220 last_time = cur_time;
2224 oc = output_files[0]->ctx;
2226 total_size = avio_size(oc->pb);
2227 if (total_size < 0) { // FIXME improve avio_size() so it works with non seekable output too
2228 total_size = avio_tell(oc->pb);
2235 for (i = 0; i < nb_output_streams; i++) {
2237 ost = output_streams[i];
2238 enc = ost->st->codec;
2239 if (!ost->stream_copy && enc->coded_frame)
2240 q = enc->coded_frame->quality / (float)FF_QP2LAMBDA;
2241 if (vid && enc->codec_type == AVMEDIA_TYPE_VIDEO) {
2242 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "q=%2.1f ", q);
2244 if (!vid && enc->codec_type == AVMEDIA_TYPE_VIDEO) {
2245 float fps, t = (cur_time-timer_start) / 1000000.0;
2247 frame_number = ost->frame_number;
2248 fps = t > 1 ? frame_number / t : 0;
2249 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "frame=%5d fps=%3.*f q=%3.1f ",
2250 frame_number, fps < 9.95, fps, q);
2252 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "L");
2256 if (qp >= 0 && qp < FF_ARRAY_ELEMS(qp_histogram))
2258 for (j = 0; j < 32; j++)
2259 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "%X", (int)lrintf(log(qp_histogram[j] + 1) / log(2)));
2261 if (enc->flags&CODEC_FLAG_PSNR) {
2263 double error, error_sum = 0;
2264 double scale, scale_sum = 0;
2265 char type[3] = { 'Y','U','V' };
2266 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "PSNR=");
2267 for (j = 0; j < 3; j++) {
2268 if (is_last_report) {
2269 error = enc->error[j];
2270 scale = enc->width * enc->height * 255.0 * 255.0 * frame_number;
2272 error = enc->coded_frame->error[j];
2273 scale = enc->width * enc->height * 255.0 * 255.0;
2279 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "%c:%2.2f ", type[j], psnr(error / scale));
2281 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "*:%2.2f ", psnr(error_sum / scale_sum));
2285 /* compute min output value */
2286 pts = FFMIN(pts, av_rescale_q(ost->st->pts.val,
2287 ost->st->time_base, AV_TIME_BASE_Q));
2290 secs = pts / AV_TIME_BASE;
2291 us = pts % AV_TIME_BASE;
2297 bitrate = pts ? total_size * 8 / (pts / 1000.0) : 0;
2299 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
2300 "size=%8.0fkB time=", total_size / 1024.0);
2301 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
2302 "%02d:%02d:%02d.%02d ", hours, mins, secs,
2303 (100 * us) / AV_TIME_BASE);
2304 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
2305 "bitrate=%6.1fkbits/s", bitrate);
2307 if (nb_frames_dup || nb_frames_drop)
2308 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), " dup=%d drop=%d",
2309 nb_frames_dup, nb_frames_drop);
2311 av_log(NULL, AV_LOG_INFO, "%s \r", buf);
2315 if (is_last_report) {
2316 int64_t raw= audio_size + video_size + extra_size;
2317 av_log(NULL, AV_LOG_INFO, "\n");
2318 av_log(NULL, AV_LOG_INFO, "video:%1.0fkB audio:%1.0fkB global headers:%1.0fkB muxing overhead %f%%\n",
2319 video_size / 1024.0,
2320 audio_size / 1024.0,
2321 extra_size / 1024.0,
2322 100.0 * (total_size - raw) / raw
2324 if(video_size + audio_size + extra_size == 0){
2325 av_log(NULL, AV_LOG_WARNING, "Output file is empty, nothing was encoded (check -ss / -t / -frames parameters if used)\n");
2330 static void flush_encoders(void)
2334 for (i = 0; i < nb_output_streams; i++) {
2335 OutputStream *ost = output_streams[i];
2336 AVCodecContext *enc = ost->st->codec;
2337 AVFormatContext *os = output_files[ost->file_index]->ctx;
2338 int stop_encoding = 0;
2340 if (!ost->encoding_needed)
2343 if (ost->st->codec->codec_type == AVMEDIA_TYPE_AUDIO && enc->frame_size <= 1)
2345 if (ost->st->codec->codec_type == AVMEDIA_TYPE_VIDEO && (os->oformat->flags & AVFMT_RAWPICTURE) && enc->codec->id == CODEC_ID_RAWVIDEO)
2350 int fifo_bytes, got_packet;
2351 av_init_packet(&pkt);
2355 switch (ost->st->codec->codec_type) {
2356 case AVMEDIA_TYPE_AUDIO:
2357 fifo_bytes = av_fifo_size(ost->fifo);
2358 if (fifo_bytes > 0) {
2359 /* encode any samples remaining in fifo */
2360 int frame_bytes = fifo_bytes;
2362 av_fifo_generic_read(ost->fifo, audio_buf, fifo_bytes, NULL);
2364 encode_audio_frame(os, ost, audio_buf, frame_bytes);
2366 /* flush encoder with NULL frames until it is done
2367 returning packets */
2368 if (encode_audio_frame(os, ost, NULL, 0) == 0) {
2374 case AVMEDIA_TYPE_VIDEO:
2375 update_benchmark(NULL);
2376 ret = avcodec_encode_video2(enc, &pkt, NULL, &got_packet);
2377 update_benchmark("encode_video %d.%d", ost->file_index, ost->index);
2379 av_log(NULL, AV_LOG_FATAL, "Video encoding failed\n");
2382 video_size += pkt.size;
2383 if (ost->logfile && enc->stats_out) {
2384 fprintf(ost->logfile, "%s", enc->stats_out);
2390 if (pkt.pts != AV_NOPTS_VALUE)
2391 pkt.pts = av_rescale_q(pkt.pts, enc->time_base, ost->st->time_base);
2392 if (pkt.dts != AV_NOPTS_VALUE)
2393 pkt.dts = av_rescale_q(pkt.dts, enc->time_base, ost->st->time_base);
2394 write_frame(os, &pkt, ost);
2406 * Check whether a packet from ist should be written into ost at this time
2408 static int check_output_constraints(InputStream *ist, OutputStream *ost)
2410 OutputFile *of = output_files[ost->file_index];
2411 int ist_index = input_files[ist->file_index]->ist_index + ist->st->index;
2413 if (ost->source_index != ist_index)
2416 if (of->start_time && ist->pts < of->start_time)
2419 if (of->recording_time != INT64_MAX &&
2420 av_compare_ts(ist->pts, AV_TIME_BASE_Q, of->recording_time + of->start_time,
2421 (AVRational){ 1, 1000000 }) >= 0) {
2422 ost->is_past_recording_time = 1;
2429 static void do_streamcopy(InputStream *ist, OutputStream *ost, const AVPacket *pkt)
2431 OutputFile *of = output_files[ost->file_index];
2432 int64_t ost_tb_start_time = av_rescale_q(of->start_time, AV_TIME_BASE_Q, ost->st->time_base);
2436 av_init_packet(&opkt);
2438 if ((!ost->frame_number && !(pkt->flags & AV_PKT_FLAG_KEY)) &&
2439 !ost->copy_initial_nonkeyframes)
2442 /* force the input stream PTS */
2443 if (ost->st->codec->codec_type == AVMEDIA_TYPE_AUDIO)
2444 audio_size += pkt->size;
2445 else if (ost->st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
2446 video_size += pkt->size;
2450 if (pkt->pts != AV_NOPTS_VALUE)
2451 opkt.pts = av_rescale_q(pkt->pts, ist->st->time_base, ost->st->time_base) - ost_tb_start_time;
2453 opkt.pts = AV_NOPTS_VALUE;
2455 if (pkt->dts == AV_NOPTS_VALUE)
2456 opkt.dts = av_rescale_q(ist->dts, AV_TIME_BASE_Q, ost->st->time_base);
2458 opkt.dts = av_rescale_q(pkt->dts, ist->st->time_base, ost->st->time_base);
2459 opkt.dts -= ost_tb_start_time;
2461 opkt.duration = av_rescale_q(pkt->duration, ist->st->time_base, ost->st->time_base);
2462 opkt.flags = pkt->flags;
2464 // FIXME remove the following 2 lines they shall be replaced by the bitstream filters
2465 if ( ost->st->codec->codec_id != CODEC_ID_H264
2466 && ost->st->codec->codec_id != CODEC_ID_MPEG1VIDEO
2467 && ost->st->codec->codec_id != CODEC_ID_MPEG2VIDEO
2468 && ost->st->codec->codec_id != CODEC_ID_VC1
2470 if (av_parser_change(ist->st->parser, ost->st->codec, &opkt.data, &opkt.size, pkt->data, pkt->size, pkt->flags & AV_PKT_FLAG_KEY))
2471 opkt.destruct = av_destruct_packet;
2473 opkt.data = pkt->data;
2474 opkt.size = pkt->size;
2476 if (of->ctx->oformat->flags & AVFMT_RAWPICTURE) {
2477 /* store AVPicture in AVPacket, as expected by the output format */
2478 avpicture_fill(&pict, opkt.data, ost->st->codec->pix_fmt, ost->st->codec->width, ost->st->codec->height);
2479 opkt.data = (uint8_t *)&pict;
2480 opkt.size = sizeof(AVPicture);
2481 opkt.flags |= AV_PKT_FLAG_KEY;
2484 write_frame(of->ctx, &opkt, ost);
2485 ost->st->codec->frame_number++;
2486 av_free_packet(&opkt);
2489 static void rate_emu_sleep(InputStream *ist)
2491 if (input_files[ist->file_index]->rate_emu) {
2492 int64_t pts = av_rescale(ist->dts, 1000000, AV_TIME_BASE);
2493 int64_t now = av_gettime() - ist->start;
2499 static int transcode_audio(InputStream *ist, AVPacket *pkt, int *got_output)
2501 AVFrame *decoded_frame;
2502 AVCodecContext *avctx = ist->st->codec;
2503 int bps = av_get_bytes_per_sample(ist->st->codec->sample_fmt);
2506 if (!ist->decoded_frame && !(ist->decoded_frame = avcodec_alloc_frame()))
2507 return AVERROR(ENOMEM);
2509 avcodec_get_frame_defaults(ist->decoded_frame);
2510 decoded_frame = ist->decoded_frame;
2512 update_benchmark(NULL);
2513 ret = avcodec_decode_audio4(avctx, decoded_frame, got_output, pkt);
2514 update_benchmark("decode_audio %d.%d", ist->file_index, ist->st->index);
2518 if (avctx->sample_rate <= 0) {
2519 av_log(avctx, AV_LOG_ERROR, "Sample rate %d invalid\n", avctx->sample_rate);
2520 return AVERROR_INVALIDDATA;
2524 /* no audio frame */
2528 /* if the decoder provides a pts, use it instead of the last packet pts.
2529 the decoder could be delaying output by a packet or more. */
2530 if (decoded_frame->pts != AV_NOPTS_VALUE)
2531 ist->dts = ist->next_dts = ist->pts = ist->next_pts = decoded_frame->pts;
2533 /* increment next_dts to use for the case where the input stream does not
2534 have timestamps or there are multiple frames in the packet */
2535 ist->next_pts += ((int64_t)AV_TIME_BASE * decoded_frame->nb_samples) /
2537 ist->next_dts += ((int64_t)AV_TIME_BASE * decoded_frame->nb_samples) /
2541 // preprocess audio (volume)
2542 if (audio_volume != 256) {
2543 int decoded_data_size = decoded_frame->nb_samples * avctx->channels * bps;
2544 void *samples = decoded_frame->data[0];
2545 switch (avctx->sample_fmt) {
2546 case AV_SAMPLE_FMT_U8:
2548 uint8_t *volp = samples;
2549 for (i = 0; i < (decoded_data_size / sizeof(*volp)); i++) {
2550 int v = (((*volp - 128) * audio_volume + 128) >> 8) + 128;
2551 *volp++ = av_clip_uint8(v);
2555 case AV_SAMPLE_FMT_S16:
2557 int16_t *volp = samples;
2558 for (i = 0; i < (decoded_data_size / sizeof(*volp)); i++) {
2559 int v = ((*volp) * audio_volume + 128) >> 8;
2560 *volp++ = av_clip_int16(v);
2564 case AV_SAMPLE_FMT_S32:
2566 int32_t *volp = samples;
2567 for (i = 0; i < (decoded_data_size / sizeof(*volp)); i++) {
2568 int64_t v = (((int64_t)*volp * audio_volume + 128) >> 8);
2569 *volp++ = av_clipl_int32(v);
2573 case AV_SAMPLE_FMT_FLT:
2575 float *volp = samples;
2576 float scale = audio_volume / 256.f;
2577 for (i = 0; i < (decoded_data_size / sizeof(*volp)); i++) {
2582 case AV_SAMPLE_FMT_DBL:
2584 double *volp = samples;
2585 double scale = audio_volume / 256.;
2586 for (i = 0; i < (decoded_data_size / sizeof(*volp)); i++) {
2592 av_log(NULL, AV_LOG_FATAL,
2593 "Audio volume adjustment on sample format %s is not supported.\n",
2594 av_get_sample_fmt_name(ist->st->codec->sample_fmt));
2599 rate_emu_sleep(ist);
2601 for (i = 0; i < nb_output_streams; i++) {
2602 OutputStream *ost = output_streams[i];
2604 if (!check_output_constraints(ist, ost) || !ost->encoding_needed)
2606 do_audio_out(output_files[ost->file_index]->ctx, ost, ist, decoded_frame);
2612 static int transcode_video(InputStream *ist, AVPacket *pkt, int *got_output, int64_t *pkt_pts)
2614 AVFrame *decoded_frame;
2615 void *buffer_to_free = NULL;
2616 int i, ret = 0, resample_changed;
2617 int64_t best_effort_timestamp;
2618 AVRational *frame_sample_aspect;
2621 if (!ist->decoded_frame && !(ist->decoded_frame = avcodec_alloc_frame()))
2622 return AVERROR(ENOMEM);
2624 avcodec_get_frame_defaults(ist->decoded_frame);
2625 decoded_frame = ist->decoded_frame;
2626 pkt->pts = *pkt_pts;
2627 pkt->dts = ist->dts;
2628 *pkt_pts = AV_NOPTS_VALUE;
2630 update_benchmark(NULL);
2631 ret = avcodec_decode_video2(ist->st->codec,
2632 decoded_frame, got_output, pkt);
2633 update_benchmark("decode_video %d.%d", ist->file_index, ist->st->index);
2637 quality = same_quant ? decoded_frame->quality : 0;
2639 /* no picture yet */
2641 for (i = 0; i < ist->nb_filters; i++)
2642 av_buffersrc_add_ref(ist->filters[i]->filter, NULL, 0);
2646 best_effort_timestamp= av_frame_get_best_effort_timestamp(decoded_frame);
2647 if(best_effort_timestamp != AV_NOPTS_VALUE)
2648 ist->next_pts = ist->pts = decoded_frame->pts = best_effort_timestamp;
2652 pre_process_video_frame(ist, (AVPicture *)decoded_frame, &buffer_to_free);
2654 rate_emu_sleep(ist);
2656 if (ist->st->sample_aspect_ratio.num)
2657 decoded_frame->sample_aspect_ratio = ist->st->sample_aspect_ratio;
2659 resample_changed = ist->resample_width != decoded_frame->width ||
2660 ist->resample_height != decoded_frame->height ||
2661 ist->resample_pix_fmt != decoded_frame->format;
2662 if (resample_changed) {
2663 av_log(NULL, AV_LOG_INFO,
2664 "Input stream #%d:%d frame changed from size:%dx%d fmt:%s to size:%dx%d fmt:%s\n",
2665 ist->file_index, ist->st->index,
2666 ist->resample_width, ist->resample_height, av_get_pix_fmt_name(ist->resample_pix_fmt),
2667 decoded_frame->width, decoded_frame->height, av_get_pix_fmt_name(decoded_frame->format));
2669 ist->resample_width = decoded_frame->width;
2670 ist->resample_height = decoded_frame->height;
2671 ist->resample_pix_fmt = decoded_frame->format;
2673 for (i = 0; i < nb_filtergraphs; i++)
2674 if (ist_in_filtergraph(filtergraphs[i], ist) &&
2675 configure_filtergraph(filtergraphs[i]) < 0) {
2676 av_log(NULL, AV_LOG_FATAL, "Error reinitializing filters!\n");
2681 frame_sample_aspect= av_opt_ptr(avcodec_get_frame_class(), decoded_frame, "sample_aspect_ratio");
2682 for (i = 0; i < ist->nb_filters; i++) {
2683 int changed = ist->st->codec->width != ist->filters[i]->filter->outputs[0]->w
2684 || ist->st->codec->height != ist->filters[i]->filter->outputs[0]->h
2685 || ist->st->codec->pix_fmt != ist->filters[i]->filter->outputs[0]->format;
2686 // XXX what an ugly hack
2687 if (ist->filters[i]->graph->nb_outputs == 1)
2688 ist->filters[i]->graph->outputs[0]->ost->last_quality = quality;
2690 if (!frame_sample_aspect->num)
2691 *frame_sample_aspect = ist->st->sample_aspect_ratio;
2692 if (ist->dr1 && decoded_frame->type==FF_BUFFER_TYPE_USER && !changed) {
2693 FrameBuffer *buf = decoded_frame->opaque;
2694 AVFilterBufferRef *fb = avfilter_get_video_buffer_ref_from_arrays(
2695 decoded_frame->data, decoded_frame->linesize,
2696 AV_PERM_READ | AV_PERM_PRESERVE,
2697 ist->st->codec->width, ist->st->codec->height,
2698 ist->st->codec->pix_fmt);
2700 avfilter_copy_frame_props(fb, decoded_frame);
2701 fb->buf->priv = buf;
2702 fb->buf->free = filter_release_buffer;
2704 av_assert0(buf->refcount>0);
2706 av_buffersrc_add_ref(ist->filters[i]->filter, fb,
2707 AV_BUFFERSRC_FLAG_NO_CHECK_FORMAT |
2708 AV_BUFFERSRC_FLAG_NO_COPY);
2710 if(av_buffersrc_add_frame(ist->filters[i]->filter, decoded_frame, 0)<0) {
2711 av_log(NULL, AV_LOG_FATAL, "Failed to inject frame into filter network\n");
2717 av_free(buffer_to_free);
2721 static int transcode_subtitles(InputStream *ist, AVPacket *pkt, int *got_output)
2723 AVSubtitle subtitle;
2724 int i, ret = avcodec_decode_subtitle2(ist->st->codec,
2725 &subtitle, got_output, pkt);
2731 rate_emu_sleep(ist);
2733 for (i = 0; i < nb_output_streams; i++) {
2734 OutputStream *ost = output_streams[i];
2736 if (!check_output_constraints(ist, ost) || !ost->encoding_needed)
2739 do_subtitle_out(output_files[ost->file_index]->ctx, ost, ist, &subtitle, pkt->pts);
2742 avsubtitle_free(&subtitle);
2746 /* pkt = NULL means EOF (needed to flush decoder buffers) */
2747 static int output_packet(InputStream *ist, const AVPacket *pkt)
2751 int64_t pkt_pts = AV_NOPTS_VALUE;
2754 if (!ist->saw_first_ts) {
2755 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;
2757 if (pkt != NULL && pkt->pts != AV_NOPTS_VALUE && !ist->decoding_needed) {
2758 ist->dts += av_rescale_q(pkt->pts, ist->st->time_base, AV_TIME_BASE_Q);
2759 ist->pts = ist->dts; //unused but better to set it to a value thats not totally wrong
2761 ist->saw_first_ts = 1;
2764 if (ist->next_dts == AV_NOPTS_VALUE)
2765 ist->next_dts = ist->dts;
2766 if (ist->next_pts == AV_NOPTS_VALUE)
2767 ist->next_pts = ist->pts;
2771 av_init_packet(&avpkt);
2779 if (pkt->dts != AV_NOPTS_VALUE) {
2780 ist->next_dts = ist->dts = av_rescale_q(pkt->dts, ist->st->time_base, AV_TIME_BASE_Q);
2781 if (ist->st->codec->codec_type != AVMEDIA_TYPE_VIDEO || !ist->decoding_needed)
2782 ist->next_pts = ist->pts = av_rescale_q(pkt->dts, ist->st->time_base, AV_TIME_BASE_Q);
2784 if(pkt->pts != AV_NOPTS_VALUE)
2785 pkt_pts = av_rescale_q(pkt->pts, ist->st->time_base, AV_TIME_BASE_Q);
2787 // while we have more to decode or while the decoder did output something on EOF
2788 while (ist->decoding_needed && (avpkt.size > 0 || (!pkt && got_output))) {
2792 ist->pts = ist->next_pts;
2793 ist->dts = ist->next_dts;
2795 if (avpkt.size && avpkt.size != pkt->size) {
2796 av_log(NULL, ist->showed_multi_packet_warning ? AV_LOG_VERBOSE : AV_LOG_WARNING,
2797 "Multiple frames in a packet from stream %d\n", pkt->stream_index);
2798 ist->showed_multi_packet_warning = 1;
2801 switch (ist->st->codec->codec_type) {
2802 case AVMEDIA_TYPE_AUDIO:
2803 ret = transcode_audio (ist, &avpkt, &got_output);
2805 case AVMEDIA_TYPE_VIDEO:
2806 ret = transcode_video (ist, &avpkt, &got_output, &pkt_pts);
2807 if (avpkt.duration) {
2808 duration = av_rescale_q(avpkt.duration, ist->st->time_base, AV_TIME_BASE_Q);
2809 } else if(ist->st->codec->time_base.num != 0 && ist->st->codec->time_base.den != 0) {
2810 int ticks= ist->st->parser ? ist->st->parser->repeat_pict+1 : ist->st->codec->ticks_per_frame;
2811 duration = ((int64_t)AV_TIME_BASE *
2812 ist->st->codec->time_base.num * ticks) /
2813 ist->st->codec->time_base.den;
2817 if(ist->dts != AV_NOPTS_VALUE && duration) {
2818 ist->next_dts += duration;
2820 ist->next_dts = AV_NOPTS_VALUE;
2823 ist->next_pts += duration; //FIXME the duration is not correct in some cases
2825 case AVMEDIA_TYPE_SUBTITLE:
2826 ret = transcode_subtitles(ist, &avpkt, &got_output);
2836 avpkt.pts= AV_NOPTS_VALUE;
2838 // touch data and size only if not EOF
2840 if(ist->st->codec->codec_type != AVMEDIA_TYPE_AUDIO)
2850 /* handle stream copy */
2851 if (!ist->decoding_needed) {
2852 rate_emu_sleep(ist);
2853 ist->dts = ist->next_dts;
2854 switch (ist->st->codec->codec_type) {
2855 case AVMEDIA_TYPE_AUDIO:
2856 ist->next_dts += ((int64_t)AV_TIME_BASE * ist->st->codec->frame_size) /
2857 ist->st->codec->sample_rate;
2859 case AVMEDIA_TYPE_VIDEO:
2860 if (pkt->duration) {
2861 ist->next_dts += av_rescale_q(pkt->duration, ist->st->time_base, AV_TIME_BASE_Q);
2862 } else if(ist->st->codec->time_base.num != 0) {
2863 int ticks= ist->st->parser ? ist->st->parser->repeat_pict + 1 : ist->st->codec->ticks_per_frame;
2864 ist->next_dts += ((int64_t)AV_TIME_BASE *
2865 ist->st->codec->time_base.num * ticks) /
2866 ist->st->codec->time_base.den;
2870 ist->pts = ist->dts;
2871 ist->next_pts = ist->next_dts;
2873 for (i = 0; pkt && i < nb_output_streams; i++) {
2874 OutputStream *ost = output_streams[i];
2876 if (!check_output_constraints(ist, ost) || ost->encoding_needed)
2879 do_streamcopy(ist, ost, pkt);
2885 static void print_sdp(void)
2889 AVFormatContext **avc = av_malloc(sizeof(*avc) * nb_output_files);
2893 for (i = 0; i < nb_output_files; i++)
2894 avc[i] = output_files[i]->ctx;
2896 av_sdp_create(avc, nb_output_files, sdp, sizeof(sdp));
2897 printf("SDP:\n%s\n", sdp);
2902 static int init_input_stream(int ist_index, char *error, int error_len)
2905 InputStream *ist = input_streams[ist_index];
2907 if (ist->decoding_needed) {
2908 AVCodec *codec = ist->dec;
2910 snprintf(error, error_len, "Decoder (codec %s) not found for input stream #%d:%d",
2911 avcodec_get_name(ist->st->codec->codec_id), ist->file_index, ist->st->index);
2912 return AVERROR(EINVAL);
2915 ist->dr1 = (codec->capabilities & CODEC_CAP_DR1) && !do_deinterlace;
2916 if (codec->type == AVMEDIA_TYPE_VIDEO && ist->dr1) {
2917 ist->st->codec->get_buffer = codec_get_buffer;
2918 ist->st->codec->release_buffer = codec_release_buffer;
2919 ist->st->codec->opaque = ist;
2922 if (!av_dict_get(ist->opts, "threads", NULL, 0))
2923 av_dict_set(&ist->opts, "threads", "auto", 0);
2924 if (avcodec_open2(ist->st->codec, codec, &ist->opts) < 0) {
2925 snprintf(error, error_len, "Error while opening decoder for input stream #%d:%d",
2926 ist->file_index, ist->st->index);
2927 return AVERROR(EINVAL);
2929 assert_codec_experimental(ist->st->codec, 0);
2930 assert_avoptions(ist->opts);
2932 if (ist->st->codec->codec_type == AVMEDIA_TYPE_AUDIO) {
2933 for (i = 0; i < nb_output_streams; i++) {
2934 OutputStream *ost = output_streams[i];
2935 if (ost->source_index == ist_index) {
2936 if (!ist->st->codec->channel_layout || !ost->st->codec->channel_layout)
2937 get_default_channel_layouts(ost, ist);
2944 ist->next_pts = AV_NOPTS_VALUE;
2945 ist->next_dts = AV_NOPTS_VALUE;
2951 static InputStream *get_input_stream(OutputStream *ost)
2953 if (ost->source_index >= 0)
2954 return input_streams[ost->source_index];
2957 FilterGraph *fg = ost->filter->graph;
2960 for (i = 0; i < fg->nb_inputs; i++)
2961 if (fg->inputs[i]->ist->st->codec->codec_type == ost->st->codec->codec_type)
2962 return fg->inputs[i]->ist;
2968 static int transcode_init(void)
2970 int ret = 0, i, j, k;
2971 AVFormatContext *oc;
2972 AVCodecContext *codec, *icodec;
2978 /* init framerate emulation */
2979 for (i = 0; i < nb_input_files; i++) {
2980 InputFile *ifile = input_files[i];
2981 if (ifile->rate_emu)
2982 for (j = 0; j < ifile->nb_streams; j++)
2983 input_streams[j + ifile->ist_index]->start = av_gettime();
2986 /* output stream init */
2987 for (i = 0; i < nb_output_files; i++) {
2988 oc = output_files[i]->ctx;
2989 if (!oc->nb_streams && !(oc->oformat->flags & AVFMT_NOSTREAMS)) {
2990 av_dump_format(oc, i, oc->filename, 1);
2991 av_log(NULL, AV_LOG_ERROR, "Output file #%d does not contain any stream\n", i);
2992 return AVERROR(EINVAL);
2996 /* init complex filtergraphs */
2997 for (i = 0; i < nb_filtergraphs; i++)
2998 if ((ret = avfilter_graph_config(filtergraphs[i]->graph, NULL)) < 0)
3001 /* for each output stream, we compute the right encoding parameters */
3002 for (i = 0; i < nb_output_streams; i++) {
3003 ost = output_streams[i];
3004 oc = output_files[ost->file_index]->ctx;
3005 ist = get_input_stream(ost);
3007 if (ost->attachment_filename)
3010 codec = ost->st->codec;
3013 icodec = ist->st->codec;
3015 ost->st->disposition = ist->st->disposition;
3016 codec->bits_per_raw_sample = icodec->bits_per_raw_sample;
3017 codec->chroma_sample_location = icodec->chroma_sample_location;
3020 if (ost->stream_copy) {
3021 uint64_t extra_size;
3023 av_assert0(ist && !ost->filter);
3025 extra_size = (uint64_t)icodec->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE;
3027 if (extra_size > INT_MAX) {
3028 return AVERROR(EINVAL);
3031 /* if stream_copy is selected, no need to decode or encode */
3032 codec->codec_id = icodec->codec_id;
3033 codec->codec_type = icodec->codec_type;
3035 if (!codec->codec_tag) {
3036 if (!oc->oformat->codec_tag ||
3037 av_codec_get_id (oc->oformat->codec_tag, icodec->codec_tag) == codec->codec_id ||
3038 av_codec_get_tag(oc->oformat->codec_tag, icodec->codec_id) <= 0)
3039 codec->codec_tag = icodec->codec_tag;
3042 codec->bit_rate = icodec->bit_rate;
3043 codec->rc_max_rate = icodec->rc_max_rate;
3044 codec->rc_buffer_size = icodec->rc_buffer_size;
3045 codec->field_order = icodec->field_order;
3046 codec->extradata = av_mallocz(extra_size);
3047 if (!codec->extradata) {
3048 return AVERROR(ENOMEM);
3050 memcpy(codec->extradata, icodec->extradata, icodec->extradata_size);
3051 codec->extradata_size= icodec->extradata_size;
3052 codec->bits_per_coded_sample = icodec->bits_per_coded_sample;
3054 codec->time_base = ist->st->time_base;
3056 * Avi is a special case here because it supports variable fps but
3057 * having the fps and timebase differe significantly adds quite some
3060 if(!strcmp(oc->oformat->name, "avi")) {
3061 if ( copy_tb<0 && av_q2d(icodec->time_base)*icodec->ticks_per_frame > 2*av_q2d(ist->st->time_base)
3062 && av_q2d(ist->st->time_base) < 1.0/500
3064 codec->time_base = icodec->time_base;
3065 codec->time_base.num *= icodec->ticks_per_frame;
3066 codec->time_base.den *= 2;
3067 codec->ticks_per_frame = 2;
3069 } else if(!(oc->oformat->flags & AVFMT_VARIABLE_FPS)
3070 && strcmp(oc->oformat->name, "mov") && strcmp(oc->oformat->name, "mp4") && strcmp(oc->oformat->name, "3gp")
3071 && strcmp(oc->oformat->name, "3g2") && strcmp(oc->oformat->name, "psp") && strcmp(oc->oformat->name, "ipod")
3073 if( copy_tb<0 && av_q2d(icodec->time_base)*icodec->ticks_per_frame > av_q2d(ist->st->time_base)
3074 && av_q2d(ist->st->time_base) < 1.0/500
3076 codec->time_base = icodec->time_base;
3077 codec->time_base.num *= icodec->ticks_per_frame;
3080 av_reduce(&codec->time_base.num, &codec->time_base.den,
3081 codec->time_base.num, codec->time_base.den, INT_MAX);
3083 switch (codec->codec_type) {
3084 case AVMEDIA_TYPE_AUDIO:
3085 if (audio_volume != 256) {
3086 av_log(NULL, AV_LOG_FATAL, "-acodec copy and -vol are incompatible (frames are not decoded)\n");
3089 codec->channel_layout = icodec->channel_layout;
3090 codec->sample_rate = icodec->sample_rate;
3091 codec->channels = icodec->channels;
3092 codec->frame_size = icodec->frame_size;
3093 codec->audio_service_type = icodec->audio_service_type;
3094 codec->block_align = icodec->block_align;
3095 if(codec->block_align == 1 && codec->codec_id == CODEC_ID_MP3)
3096 codec->block_align= 0;
3097 if(codec->codec_id == CODEC_ID_AC3)
3098 codec->block_align= 0;
3100 case AVMEDIA_TYPE_VIDEO:
3101 codec->pix_fmt = icodec->pix_fmt;
3102 codec->width = icodec->width;
3103 codec->height = icodec->height;
3104 codec->has_b_frames = icodec->has_b_frames;
3105 if (!codec->sample_aspect_ratio.num) {
3106 codec->sample_aspect_ratio =
3107 ost->st->sample_aspect_ratio =
3108 ist->st->sample_aspect_ratio.num ? ist->st->sample_aspect_ratio :
3109 ist->st->codec->sample_aspect_ratio.num ?
3110 ist->st->codec->sample_aspect_ratio : (AVRational){0, 1};
3112 ost->st->avg_frame_rate = ist->st->avg_frame_rate;
3114 case AVMEDIA_TYPE_SUBTITLE:
3115 codec->width = icodec->width;
3116 codec->height = icodec->height;
3118 case AVMEDIA_TYPE_DATA:
3119 case AVMEDIA_TYPE_ATTACHMENT:
3126 ost->enc = avcodec_find_encoder(codec->codec_id);
3128 /* should only happen when a default codec is not present. */
3129 snprintf(error, sizeof(error), "Encoder (codec %s) not found for output stream #%d:%d",
3130 avcodec_get_name(ost->st->codec->codec_id), ost->file_index, ost->index);
3131 ret = AVERROR(EINVAL);
3136 ist->decoding_needed = 1;
3137 ost->encoding_needed = 1;
3139 switch (codec->codec_type) {
3140 case AVMEDIA_TYPE_AUDIO:
3141 ost->fifo = av_fifo_alloc(1024);
3143 return AVERROR(ENOMEM);
3146 if (!codec->sample_rate)
3147 codec->sample_rate = icodec->sample_rate;
3148 choose_sample_rate(ost->st, ost->enc);
3149 codec->time_base = (AVRational){ 1, codec->sample_rate };
3151 if (codec->sample_fmt == AV_SAMPLE_FMT_NONE)
3152 codec->sample_fmt = icodec->sample_fmt;
3153 choose_sample_fmt(ost->st, ost->enc);
3155 if (ost->audio_channels_mapped) {
3156 /* the requested output channel is set to the number of
3157 * -map_channel only if no -ac are specified */
3158 if (!codec->channels) {
3159 codec->channels = ost->audio_channels_mapped;
3160 codec->channel_layout = av_get_default_channel_layout(codec->channels);
3161 if (!codec->channel_layout) {
3162 av_log(NULL, AV_LOG_FATAL, "Unable to find an appropriate channel layout for requested number of channel\n");
3166 /* fill unused channel mapping with -1 (which means a muted
3167 * channel in case the number of output channels is bigger
3168 * than the number of mapped channel) */
3169 for (j = ost->audio_channels_mapped; j < FF_ARRAY_ELEMS(ost->audio_channels_map); j++)
3170 ost->audio_channels_map[j] = -1;
3171 } else if (!codec->channels) {
3172 codec->channels = icodec->channels;
3173 codec->channel_layout = icodec->channel_layout;
3175 if (av_get_channel_layout_nb_channels(codec->channel_layout) != codec->channels)
3176 codec->channel_layout = 0;
3179 // ost->audio_resample = codec->sample_rate != icodec->sample_rate || audio_sync_method > 1;
3180 // ost->audio_resample |= codec->sample_fmt != icodec->sample_fmt
3181 // || codec->channel_layout != icodec->channel_layout;
3182 icodec->request_channels = codec-> channels;
3183 ost->resample_sample_fmt = icodec->sample_fmt;
3184 ost->resample_sample_rate = icodec->sample_rate;
3185 ost->resample_channels = icodec->channels;
3186 ost->resample_channel_layout = icodec->channel_layout;
3188 case AVMEDIA_TYPE_VIDEO:
3191 fg = init_simple_filtergraph(ist, ost);
3192 if (configure_video_filters(fg)) {
3193 av_log(NULL, AV_LOG_FATAL, "Error opening filters!\n");
3198 if (ist && !ost->frame_rate.num)
3199 ost->frame_rate = ist->st->r_frame_rate.num ? ist->st->r_frame_rate : (AVRational) { 25, 1 };
3200 if (ost->enc && ost->enc->supported_framerates && !ost->force_fps) {
3201 int idx = av_find_nearest_q_idx(ost->frame_rate, ost->enc->supported_framerates);
3202 ost->frame_rate = ost->enc->supported_framerates[idx];
3204 codec->time_base = (AVRational){ost->frame_rate.den, ost->frame_rate.num};
3205 if ( av_q2d(codec->time_base) < 0.001 && video_sync_method != VSYNC_PASSTHROUGH
3206 && (video_sync_method == VSYNC_CFR || (video_sync_method == VSYNC_AUTO && !(oc->oformat->flags & AVFMT_VARIABLE_FPS)))){
3207 av_log(oc, AV_LOG_WARNING, "Frame rate very high for a muxer not efficiently supporting it.\n"
3208 "Please consider specifying a lower framerate, a different muxer or -vsync 2\n");
3210 for (j = 0; j < ost->forced_kf_count; j++)
3211 ost->forced_kf_pts[j] = av_rescale_q(ost->forced_kf_pts[j],
3215 codec->width = ost->filter->filter->inputs[0]->w;
3216 codec->height = ost->filter->filter->inputs[0]->h;
3217 codec->sample_aspect_ratio = ost->st->sample_aspect_ratio =
3218 ost->frame_aspect_ratio ? // overridden by the -aspect cli option
3219 av_d2q(ost->frame_aspect_ratio * codec->height/codec->width, 255) :
3220 ost->filter->filter->inputs[0]->sample_aspect_ratio;
3221 codec->pix_fmt = ost->filter->filter->inputs[0]->format;
3223 if (codec->width != icodec->width ||
3224 codec->height != icodec->height ||
3225 codec->pix_fmt != icodec->pix_fmt) {
3226 codec->bits_per_raw_sample = frame_bits_per_raw_sample;
3230 case AVMEDIA_TYPE_SUBTITLE:
3231 codec->time_base = (AVRational){1, 1000};
3238 if (codec->flags & (CODEC_FLAG_PASS1 | CODEC_FLAG_PASS2)) {
3239 char logfilename[1024];
3242 snprintf(logfilename, sizeof(logfilename), "%s-%d.log",
3243 pass_logfilename_prefix ? pass_logfilename_prefix : DEFAULT_PASS_LOGFILENAME_PREFIX,
3245 if (!strcmp(ost->enc->name, "libx264")) {
3246 av_dict_set(&ost->opts, "stats", logfilename, AV_DICT_DONT_OVERWRITE);
3248 if (codec->flags & CODEC_FLAG_PASS2) {
3250 size_t logbuffer_size;
3251 if (cmdutils_read_file(logfilename, &logbuffer, &logbuffer_size) < 0) {
3252 av_log(NULL, AV_LOG_FATAL, "Error reading log file '%s' for pass-2 encoding\n",
3256 codec->stats_in = logbuffer;
3258 if (codec->flags & CODEC_FLAG_PASS1) {
3259 f = fopen(logfilename, "wb");
3261 av_log(NULL, AV_LOG_FATAL, "Cannot write log file '%s' for pass-1 encoding: %s\n",
3262 logfilename, strerror(errno));
3272 /* open each encoder */
3273 for (i = 0; i < nb_output_streams; i++) {
3274 ost = output_streams[i];
3275 if (ost->encoding_needed) {
3276 AVCodec *codec = ost->enc;
3277 AVCodecContext *dec = NULL;
3279 if ((ist = get_input_stream(ost)))
3280 dec = ist->st->codec;
3281 if (dec && dec->subtitle_header) {
3282 ost->st->codec->subtitle_header = av_malloc(dec->subtitle_header_size);
3283 if (!ost->st->codec->subtitle_header) {
3284 ret = AVERROR(ENOMEM);
3287 memcpy(ost->st->codec->subtitle_header, dec->subtitle_header, dec->subtitle_header_size);
3288 ost->st->codec->subtitle_header_size = dec->subtitle_header_size;
3290 if (!av_dict_get(ost->opts, "threads", NULL, 0))
3291 av_dict_set(&ost->opts, "threads", "auto", 0);
3292 if (avcodec_open2(ost->st->codec, codec, &ost->opts) < 0) {
3293 snprintf(error, sizeof(error), "Error while opening encoder for output stream #%d:%d - maybe incorrect parameters such as bit_rate, rate, width or height",
3294 ost->file_index, ost->index);
3295 ret = AVERROR(EINVAL);
3298 assert_codec_experimental(ost->st->codec, 1);
3299 assert_avoptions(ost->opts);
3300 if (ost->st->codec->bit_rate && ost->st->codec->bit_rate < 1000)
3301 av_log(NULL, AV_LOG_WARNING, "The bitrate parameter is set too low."
3302 " It takes bits/s as argument, not kbits/s\n");
3303 extra_size += ost->st->codec->extradata_size;
3305 if (ost->st->codec->me_threshold)
3306 input_streams[ost->source_index]->st->codec->debug |= FF_DEBUG_MV;
3310 /* init input streams */
3311 for (i = 0; i < nb_input_streams; i++)
3312 if ((ret = init_input_stream(i, error, sizeof(error))) < 0)
3315 /* discard unused programs */
3316 for (i = 0; i < nb_input_files; i++) {
3317 InputFile *ifile = input_files[i];
3318 for (j = 0; j < ifile->ctx->nb_programs; j++) {
3319 AVProgram *p = ifile->ctx->programs[j];
3320 int discard = AVDISCARD_ALL;
3322 for (k = 0; k < p->nb_stream_indexes; k++)
3323 if (!input_streams[ifile->ist_index + p->stream_index[k]]->discard) {
3324 discard = AVDISCARD_DEFAULT;
3327 p->discard = discard;
3331 /* open files and write file headers */
3332 for (i = 0; i < nb_output_files; i++) {
3333 oc = output_files[i]->ctx;
3334 oc->interrupt_callback = int_cb;
3335 if (avformat_write_header(oc, &output_files[i]->opts) < 0) {
3336 snprintf(error, sizeof(error), "Could not write header for output file #%d (incorrect codec parameters ?)", i);
3337 ret = AVERROR(EINVAL);
3340 // assert_avoptions(output_files[i]->opts);
3341 if (strcmp(oc->oformat->name, "rtp")) {
3347 /* dump the file output parameters - cannot be done before in case
3349 for (i = 0; i < nb_output_files; i++) {
3350 av_dump_format(output_files[i]->ctx, i, output_files[i]->ctx->filename, 1);
3353 /* dump the stream mapping */
3354 av_log(NULL, AV_LOG_INFO, "Stream mapping:\n");
3355 for (i = 0; i < nb_input_streams; i++) {
3356 ist = input_streams[i];
3358 for (j = 0; j < ist->nb_filters; j++) {
3359 AVFilterLink *link = ist->filters[j]->filter->outputs[0];
3360 if (ist->filters[j]->graph->graph_desc) {
3361 av_log(NULL, AV_LOG_INFO, " Stream #%d:%d (%s) -> %s",
3362 ist->file_index, ist->st->index, ist->dec ? ist->dec->name : "?",
3363 link->dst->filter->name);
3364 if (link->dst->input_count > 1)
3365 av_log(NULL, AV_LOG_INFO, ":%s", link->dstpad->name);
3366 if (nb_filtergraphs > 1)
3367 av_log(NULL, AV_LOG_INFO, " (graph %d)", ist->filters[j]->graph->index);
3368 av_log(NULL, AV_LOG_INFO, "\n");
3373 for (i = 0; i < nb_output_streams; i++) {
3374 ost = output_streams[i];
3376 if (ost->attachment_filename) {
3377 /* an attached file */
3378 av_log(NULL, AV_LOG_INFO, " File %s -> Stream #%d:%d\n",
3379 ost->attachment_filename, ost->file_index, ost->index);
3383 if (ost->filter && ost->filter->graph->graph_desc) {
3384 /* output from a complex graph */
3385 AVFilterLink *link = ost->filter->filter->inputs[0];
3386 av_log(NULL, AV_LOG_INFO, " %s", link->src->filter->name);
3387 if (link->src->output_count > 1)
3388 av_log(NULL, AV_LOG_INFO, ":%s", link->srcpad->name);
3389 if (nb_filtergraphs > 1)
3390 av_log(NULL, AV_LOG_INFO, " (graph %d)", ost->filter->graph->index);
3392 av_log(NULL, AV_LOG_INFO, " -> Stream #%d:%d (%s)\n", ost->file_index,
3393 ost->index, ost->enc ? ost->enc->name : "?");
3397 av_log(NULL, AV_LOG_INFO, " Stream #%d:%d -> #%d:%d",
3398 input_streams[ost->source_index]->file_index,
3399 input_streams[ost->source_index]->st->index,
3402 if (ost->audio_channels_mapped) {
3403 av_log(NULL, AV_LOG_INFO, " [ch:");
3404 for (j = 0; j < ost->audio_channels_mapped; j++)
3405 if (ost->audio_channels_map[j] == -1)
3406 av_log(NULL, AV_LOG_INFO, " M");
3408 av_log(NULL, AV_LOG_INFO, " %d", ost->audio_channels_map[j]);
3409 av_log(NULL, AV_LOG_INFO, "]");
3411 if (ost->sync_ist != input_streams[ost->source_index])
3412 av_log(NULL, AV_LOG_INFO, " [sync #%d:%d]",
3413 ost->sync_ist->file_index,
3414 ost->sync_ist->st->index);
3415 if (ost->stream_copy)
3416 av_log(NULL, AV_LOG_INFO, " (copy)");
3418 av_log(NULL, AV_LOG_INFO, " (%s -> %s)", input_streams[ost->source_index]->dec ?
3419 input_streams[ost->source_index]->dec->name : "?",
3420 ost->enc ? ost->enc->name : "?");
3421 av_log(NULL, AV_LOG_INFO, "\n");
3425 av_log(NULL, AV_LOG_ERROR, "%s\n", error);
3437 * The following code is the main loop of the file converter
3439 static int transcode(void)
3442 AVFormatContext *is, *os;
3446 int no_packet_count = 0;
3447 int64_t timer_start;
3450 if (!(no_packet = av_mallocz(nb_input_files)))
3453 ret = transcode_init();
3458 av_log(NULL, AV_LOG_INFO, "Press [q] to stop, [?] for help\n");
3461 timer_start = av_gettime();
3463 for (; received_sigterm == 0;) {
3464 int file_index, ist_index, past_recording_time = 1;
3467 int64_t cur_time= av_gettime();
3469 ipts_min = INT64_MAX;
3470 /* if 'q' pressed, exits */
3472 static int64_t last_time;
3473 if (received_nb_signals)
3475 /* read_key() returns 0 on EOF */
3476 if(cur_time - last_time >= 100000 && !run_as_daemon){
3478 last_time = cur_time;
3483 if (key == '+') av_log_set_level(av_log_get_level()+10);
3484 if (key == '-') av_log_set_level(av_log_get_level()-10);
3485 if (key == 's') qp_hist ^= 1;
3488 do_hex_dump = do_pkt_dump = 0;
3489 } else if(do_pkt_dump){
3493 av_log_set_level(AV_LOG_DEBUG);
3495 if (key == 'c' || key == 'C'){
3496 char buf[4096], target[64], command[256], arg[256] = {0};
3499 fprintf(stderr, "\nEnter command: <target> <time> <command>[ <argument>]\n");
3501 while ((k = read_key()) != '\n' && k != '\r' && i < sizeof(buf)-1)
3506 (n = sscanf(buf, "%63[^ ] %lf %255[^ ] %255[^\n]", target, &time, command, arg)) >= 3) {
3507 av_log(NULL, AV_LOG_DEBUG, "Processing command target:%s time:%f command:%s arg:%s",
3508 target, time, command, arg);
3509 for (i = 0; i < nb_filtergraphs; i++) {
3510 FilterGraph *fg = filtergraphs[i];
3513 ret = avfilter_graph_send_command(fg->graph, target, command, arg, buf, sizeof(buf),
3514 key == 'c' ? AVFILTER_CMD_FLAG_ONE : 0);
3515 fprintf(stderr, "Command reply for stream %d: ret:%d res:%s\n", i, ret, buf);
3517 ret = avfilter_graph_queue_command(fg->graph, target, command, arg, 0, time);
3522 av_log(NULL, AV_LOG_ERROR,
3523 "Parse error, at least 3 arguments were expected, "
3524 "only %d given in string '%s'\n", n, buf);
3527 if (key == 'd' || key == 'D'){
3530 debug = input_streams[0]->st->codec->debug<<1;
3531 if(!debug) debug = 1;
3532 while(debug & (FF_DEBUG_DCT_COEFF|FF_DEBUG_VIS_QP|FF_DEBUG_VIS_MB_TYPE)) //unsupported, would just crash
3535 if(scanf("%d", &debug)!=1)
3536 fprintf(stderr,"error parsing debug value\n");
3537 for(i=0;i<nb_input_streams;i++) {
3538 input_streams[i]->st->codec->debug = debug;
3540 for(i=0;i<nb_output_streams;i++) {
3541 ost = output_streams[i];
3542 ost->st->codec->debug = debug;
3544 if(debug) av_log_set_level(AV_LOG_DEBUG);
3545 fprintf(stderr,"debug=%d\n", debug);
3548 fprintf(stderr, "key function\n"
3549 "? show this help\n"
3550 "+ increase verbosity\n"
3551 "- decrease verbosity\n"
3552 "c Send command to filtergraph\n"
3553 "D cycle through available debug modes\n"
3554 "h dump packets/hex press to cycle through the 3 states\n"
3556 "s Show QP histogram\n"
3561 /* check if there's any stream where output is still needed */
3562 for (i = 0; i < nb_output_streams; i++) {
3564 ost = output_streams[i];
3565 of = output_files[ost->file_index];
3566 os = output_files[ost->file_index]->ctx;
3567 if (ost->is_past_recording_time ||
3568 (os->pb && avio_tell(os->pb) >= of->limit_filesize))
3570 if (ost->frame_number >= ost->max_frames) {
3572 for (j = 0; j < of->ctx->nb_streams; j++)
3573 output_streams[of->ost_index + j]->is_past_recording_time = 1;
3576 past_recording_time = 0;
3578 if (past_recording_time)
3581 /* select the stream that we must read now by looking at the
3582 smallest output pts */
3584 for (i = 0; i < nb_input_streams; i++) {
3586 ist = input_streams[i];
3588 if (ist->discard || no_packet[ist->file_index])
3590 if (!input_files[ist->file_index]->eof_reached) {
3591 if (ipts < ipts_min) {
3593 file_index = ist->file_index;
3597 /* if none, if is finished */
3598 if (file_index < 0) {
3599 if (no_packet_count) {
3600 no_packet_count = 0;
3601 memset(no_packet, 0, nb_input_files);
3608 /* read a frame from it and output it in the fifo */
3609 is = input_files[file_index]->ctx;
3610 ret = av_read_frame(is, &pkt);
3611 if (ret == AVERROR(EAGAIN)) {
3612 no_packet[file_index] = 1;
3617 input_files[file_index]->eof_reached = 1;
3619 for (i = 0; i < input_files[file_index]->nb_streams; i++) {
3620 ist = input_streams[input_files[file_index]->ist_index + i];
3621 if (ist->decoding_needed)
3622 output_packet(ist, NULL);
3631 no_packet_count = 0;
3632 memset(no_packet, 0, nb_input_files);
3635 av_pkt_dump_log2(NULL, AV_LOG_DEBUG, &pkt, do_hex_dump,
3636 is->streams[pkt.stream_index]);
3638 /* the following test is needed in case new streams appear
3639 dynamically in stream : we ignore them */
3640 if (pkt.stream_index >= input_files[file_index]->nb_streams)
3641 goto discard_packet;
3642 ist_index = input_files[file_index]->ist_index + pkt.stream_index;
3643 ist = input_streams[ist_index];
3645 goto discard_packet;
3647 if (pkt.dts != AV_NOPTS_VALUE)
3648 pkt.dts += av_rescale_q(input_files[ist->file_index]->ts_offset, AV_TIME_BASE_Q, ist->st->time_base);
3649 if (pkt.pts != AV_NOPTS_VALUE)
3650 pkt.pts += av_rescale_q(input_files[ist->file_index]->ts_offset, AV_TIME_BASE_Q, ist->st->time_base);
3652 if (pkt.pts != AV_NOPTS_VALUE)
3653 pkt.pts *= ist->ts_scale;
3654 if (pkt.dts != AV_NOPTS_VALUE)
3655 pkt.dts *= ist->ts_scale;
3658 av_log(NULL, AV_LOG_INFO, "demuxer -> ist_index:%d type:%s "
3659 "next_dts:%s next_dts_time:%s next_pts:%s next_pts_time:%s pkt_pts:%s pkt_pts_time:%s pkt_dts:%s pkt_dts_time:%s off:%"PRId64"\n",
3660 ist_index, av_get_media_type_string(ist->st->codec->codec_type),
3661 av_ts2str(ist->next_dts), av_ts2timestr(ist->next_dts, &ist->st->time_base),
3662 av_ts2str(ist->next_pts), av_ts2timestr(ist->next_pts, &ist->st->time_base),
3663 av_ts2str(pkt.pts), av_ts2timestr(pkt.pts, &ist->st->time_base),
3664 av_ts2str(pkt.dts), av_ts2timestr(pkt.dts, &ist->st->time_base),
3665 input_files[ist->file_index]->ts_offset);
3668 if (pkt.dts != AV_NOPTS_VALUE && ist->next_dts != AV_NOPTS_VALUE && !copy_ts) {
3669 int64_t pkt_dts = av_rescale_q(pkt.dts, ist->st->time_base, AV_TIME_BASE_Q);
3670 int64_t delta = pkt_dts - ist->next_dts;
3671 if (is->iformat->flags & AVFMT_TS_DISCONT) {
3672 if(delta < -1LL*dts_delta_threshold*AV_TIME_BASE ||
3673 (delta > 1LL*dts_delta_threshold*AV_TIME_BASE &&
3674 ist->st->codec->codec_type != AVMEDIA_TYPE_SUBTITLE) ||
3675 pkt_dts+1<ist->pts){
3676 input_files[ist->file_index]->ts_offset -= delta;
3677 av_log(NULL, AV_LOG_DEBUG,
3678 "timestamp discontinuity %"PRId64", new offset= %"PRId64"\n",
3679 delta, input_files[ist->file_index]->ts_offset);
3680 pkt.dts-= av_rescale_q(delta, AV_TIME_BASE_Q, ist->st->time_base);
3681 if (pkt.pts != AV_NOPTS_VALUE)
3682 pkt.pts-= av_rescale_q(delta, AV_TIME_BASE_Q, ist->st->time_base);
3685 if ( delta < -1LL*dts_error_threshold*AV_TIME_BASE ||
3686 (delta > 1LL*dts_error_threshold*AV_TIME_BASE && ist->st->codec->codec_type != AVMEDIA_TYPE_SUBTITLE) ||
3687 pkt_dts+1<ist->pts){
3688 av_log(NULL, AV_LOG_WARNING, "DTS %"PRId64", next:%"PRId64" st:%d invalid dropping\n", pkt.dts, ist->next_dts, pkt.stream_index);
3689 pkt.dts = AV_NOPTS_VALUE;
3691 if (pkt.pts != AV_NOPTS_VALUE){
3692 int64_t pkt_pts = av_rescale_q(pkt.pts, ist->st->time_base, AV_TIME_BASE_Q);
3693 delta = pkt_pts - ist->next_dts;
3694 if ( delta < -1LL*dts_error_threshold*AV_TIME_BASE ||
3695 (delta > 1LL*dts_error_threshold*AV_TIME_BASE && ist->st->codec->codec_type != AVMEDIA_TYPE_SUBTITLE) ||
3696 pkt_pts+1<ist->pts) {
3697 av_log(NULL, AV_LOG_WARNING, "PTS %"PRId64", next:%"PRId64" invalid dropping st:%d\n", pkt.pts, ist->next_dts, pkt.stream_index);
3698 pkt.pts = AV_NOPTS_VALUE;
3704 // fprintf(stderr,"read #%d.%d size=%d\n", ist->file_index, ist->st->index, pkt.size);
3705 if (output_packet(ist, &pkt) < 0 ||
3706 ((ret = poll_filters()) < 0 && ret != AVERROR_EOF)) {
3707 av_log(NULL, AV_LOG_ERROR, "Error while decoding stream #%d:%d\n",
3708 ist->file_index, ist->st->index);
3711 av_free_packet(&pkt);
3716 av_free_packet(&pkt);
3718 /* dump report by using the output first video and audio streams */
3719 print_report(0, timer_start, cur_time);
3722 /* at the end of stream, we must flush the decoder buffers */
3723 for (i = 0; i < nb_input_streams; i++) {
3724 ist = input_streams[i];
3725 if (!input_files[ist->file_index]->eof_reached && ist->decoding_needed) {
3726 output_packet(ist, NULL);
3734 /* write the trailer if needed and close file */
3735 for (i = 0; i < nb_output_files; i++) {
3736 os = output_files[i]->ctx;
3737 av_write_trailer(os);
3740 /* dump report by using the first video and audio streams */
3741 print_report(1, timer_start, av_gettime());
3743 /* close each encoder */
3744 for (i = 0; i < nb_output_streams; i++) {
3745 ost = output_streams[i];
3746 if (ost->encoding_needed) {
3747 av_freep(&ost->st->codec->stats_in);
3748 avcodec_close(ost->st->codec);
3752 /* close each decoder */
3753 for (i = 0; i < nb_input_streams; i++) {
3754 ist = input_streams[i];
3755 if (ist->decoding_needed) {
3756 avcodec_close(ist->st->codec);
3764 av_freep(&no_packet);
3766 if (output_streams) {
3767 for (i = 0; i < nb_output_streams; i++) {
3768 ost = output_streams[i];
3770 if (ost->stream_copy)
3771 av_freep(&ost->st->codec->extradata);
3773 fclose(ost->logfile);
3774 ost->logfile = NULL;
3776 av_fifo_free(ost->fifo); /* works even if fifo is not
3777 initialized but set to zero */
3778 av_freep(&ost->st->codec->subtitle_header);
3779 av_free(ost->forced_kf_pts);
3780 swr_free(&ost->swr);
3781 av_dict_free(&ost->opts);
3788 static int opt_frame_crop(const char *opt, const char *arg)
3790 av_log(NULL, AV_LOG_FATAL, "Option '%s' has been removed, use the crop filter instead\n", opt);
3791 return AVERROR(EINVAL);
3794 static int opt_pad(const char *opt, const char *arg)
3796 av_log(NULL, AV_LOG_FATAL, "Option '%s' has been removed, use the pad filter instead\n", opt);
3800 static int opt_video_channel(const char *opt, const char *arg)
3802 av_log(NULL, AV_LOG_WARNING, "This option is deprecated, use -channel.\n");
3803 return opt_default("channel", arg);
3806 static int opt_video_standard(const char *opt, const char *arg)
3808 av_log(NULL, AV_LOG_WARNING, "This option is deprecated, use -standard.\n");
3809 return opt_default("standard", arg);
3812 static int opt_audio_codec(OptionsContext *o, const char *opt, const char *arg)
3814 audio_codec_name = arg;
3815 return parse_option(o, "codec:a", arg, options);
3818 static int opt_video_codec(OptionsContext *o, const char *opt, const char *arg)
3820 video_codec_name = arg;
3821 return parse_option(o, "codec:v", arg, options);
3824 static int opt_subtitle_codec(OptionsContext *o, const char *opt, const char *arg)
3826 subtitle_codec_name = arg;
3827 return parse_option(o, "codec:s", arg, options);
3830 static int opt_data_codec(OptionsContext *o, const char *opt, const char *arg)
3832 return parse_option(o, "codec:d", arg, options);
3835 static int opt_map(OptionsContext *o, const char *opt, const char *arg)
3837 StreamMap *m = NULL;
3838 int i, negative = 0, file_idx;
3839 int sync_file_idx = -1, sync_stream_idx = 0;
3847 map = av_strdup(arg);
3849 /* parse sync stream first, just pick first matching stream */
3850 if (sync = strchr(map, ',')) {
3852 sync_file_idx = strtol(sync + 1, &sync, 0);
3853 if (sync_file_idx >= nb_input_files || sync_file_idx < 0) {
3854 av_log(NULL, AV_LOG_FATAL, "Invalid sync file index: %d.\n", sync_file_idx);
3859 for (i = 0; i < input_files[sync_file_idx]->nb_streams; i++)
3860 if (check_stream_specifier(input_files[sync_file_idx]->ctx,
3861 input_files[sync_file_idx]->ctx->streams[i], sync) == 1) {
3862 sync_stream_idx = i;
3865 if (i == input_files[sync_file_idx]->nb_streams) {
3866 av_log(NULL, AV_LOG_FATAL, "Sync stream specification in map %s does not "
3867 "match any streams.\n", arg);
3873 if (map[0] == '[') {
3874 /* this mapping refers to lavfi output */
3875 const char *c = map + 1;
3876 o->stream_maps = grow_array(o->stream_maps, sizeof(*o->stream_maps),
3877 &o->nb_stream_maps, o->nb_stream_maps + 1);
3878 m = &o->stream_maps[o->nb_stream_maps - 1];
3879 m->linklabel = av_get_token(&c, "]");
3880 if (!m->linklabel) {
3881 av_log(NULL, AV_LOG_ERROR, "Invalid output link label: %s.\n", map);
3885 file_idx = strtol(map, &p, 0);
3886 if (file_idx >= nb_input_files || file_idx < 0) {
3887 av_log(NULL, AV_LOG_FATAL, "Invalid input file index: %d.\n", file_idx);
3891 /* disable some already defined maps */
3892 for (i = 0; i < o->nb_stream_maps; i++) {
3893 m = &o->stream_maps[i];
3894 if (file_idx == m->file_index &&
3895 check_stream_specifier(input_files[m->file_index]->ctx,
3896 input_files[m->file_index]->ctx->streams[m->stream_index],
3897 *p == ':' ? p + 1 : p) > 0)
3901 for (i = 0; i < input_files[file_idx]->nb_streams; i++) {
3902 if (check_stream_specifier(input_files[file_idx]->ctx, input_files[file_idx]->ctx->streams[i],
3903 *p == ':' ? p + 1 : p) <= 0)
3905 o->stream_maps = grow_array(o->stream_maps, sizeof(*o->stream_maps),
3906 &o->nb_stream_maps, o->nb_stream_maps + 1);
3907 m = &o->stream_maps[o->nb_stream_maps - 1];
3909 m->file_index = file_idx;
3910 m->stream_index = i;
3912 if (sync_file_idx >= 0) {
3913 m->sync_file_index = sync_file_idx;
3914 m->sync_stream_index = sync_stream_idx;
3916 m->sync_file_index = file_idx;
3917 m->sync_stream_index = i;
3923 av_log(NULL, AV_LOG_FATAL, "Stream map '%s' matches no streams.\n", arg);
3931 static int opt_attach(OptionsContext *o, const char *opt, const char *arg)
3933 o->attachments = grow_array(o->attachments, sizeof(*o->attachments),
3934 &o->nb_attachments, o->nb_attachments + 1);
3935 o->attachments[o->nb_attachments - 1] = arg;
3939 static int opt_map_channel(OptionsContext *o, const char *opt, const char *arg)
3945 o->audio_channel_maps =
3946 grow_array(o->audio_channel_maps, sizeof(*o->audio_channel_maps),
3947 &o->nb_audio_channel_maps, o->nb_audio_channel_maps + 1);
3948 m = &o->audio_channel_maps[o->nb_audio_channel_maps - 1];
3950 /* muted channel syntax */
3951 n = sscanf(arg, "%d:%d.%d", &m->channel_idx, &m->ofile_idx, &m->ostream_idx);
3952 if ((n == 1 || n == 3) && m->channel_idx == -1) {
3953 m->file_idx = m->stream_idx = -1;
3955 m->ofile_idx = m->ostream_idx = -1;
3960 n = sscanf(arg, "%d.%d.%d:%d.%d",
3961 &m->file_idx, &m->stream_idx, &m->channel_idx,
3962 &m->ofile_idx, &m->ostream_idx);
3964 if (n != 3 && n != 5) {
3965 av_log(NULL, AV_LOG_FATAL, "Syntax error, mapchan usage: "
3966 "[file.stream.channel|-1][:syncfile:syncstream]\n");
3970 if (n != 5) // only file.stream.channel specified
3971 m->ofile_idx = m->ostream_idx = -1;
3974 if (m->file_idx < 0 || m->file_idx >= nb_input_files) {
3975 av_log(NULL, AV_LOG_FATAL, "mapchan: invalid input file index: %d\n",
3979 if (m->stream_idx < 0 ||
3980 m->stream_idx >= input_files[m->file_idx]->nb_streams) {
3981 av_log(NULL, AV_LOG_FATAL, "mapchan: invalid input file stream index #%d.%d\n",
3982 m->file_idx, m->stream_idx);
3985 st = input_files[m->file_idx]->ctx->streams[m->stream_idx];
3986 if (st->codec->codec_type != AVMEDIA_TYPE_AUDIO) {
3987 av_log(NULL, AV_LOG_FATAL, "mapchan: stream #%d.%d is not an audio stream.\n",
3988 m->file_idx, m->stream_idx);
3991 if (m->channel_idx < 0 || m->channel_idx >= st->codec->channels) {
3992 av_log(NULL, AV_LOG_FATAL, "mapchan: invalid audio channel #%d.%d.%d\n",
3993 m->file_idx, m->stream_idx, m->channel_idx);
4000 * Parse a metadata specifier in arg.
4001 * @param type metadata type is written here -- g(lobal)/s(tream)/c(hapter)/p(rogram)
4002 * @param index for type c/p, chapter/program index is written here
4003 * @param stream_spec for type s, the stream specifier is written here
4005 static void parse_meta_type(char *arg, char *type, int *index, const char **stream_spec)
4013 if (*(++arg) && *arg != ':') {
4014 av_log(NULL, AV_LOG_FATAL, "Invalid metadata specifier %s.\n", arg);
4017 *stream_spec = *arg == ':' ? arg + 1 : "";
4021 if (*(++arg) == ':')
4022 *index = strtol(++arg, NULL, 0);
4025 av_log(NULL, AV_LOG_FATAL, "Invalid metadata type %c.\n", *arg);
4032 static int copy_metadata(char *outspec, char *inspec, AVFormatContext *oc, AVFormatContext *ic, OptionsContext *o)
4034 AVDictionary **meta_in = NULL;
4035 AVDictionary **meta_out = NULL;
4037 char type_in, type_out;
4038 const char *istream_spec = NULL, *ostream_spec = NULL;
4039 int idx_in = 0, idx_out = 0;
4041 parse_meta_type(inspec, &type_in, &idx_in, &istream_spec);
4042 parse_meta_type(outspec, &type_out, &idx_out, &ostream_spec);
4045 if (type_out == 'g' || !*outspec)
4046 o->metadata_global_manual = 1;
4047 if (type_out == 's' || !*outspec)
4048 o->metadata_streams_manual = 1;
4049 if (type_out == 'c' || !*outspec)
4050 o->metadata_chapters_manual = 1;
4054 if (type_in == 'g' || type_out == 'g')
4055 o->metadata_global_manual = 1;
4056 if (type_in == 's' || type_out == 's')
4057 o->metadata_streams_manual = 1;
4058 if (type_in == 'c' || type_out == 'c')
4059 o->metadata_chapters_manual = 1;
4061 #define METADATA_CHECK_INDEX(index, nb_elems, desc)\
4062 if ((index) < 0 || (index) >= (nb_elems)) {\
4063 av_log(NULL, AV_LOG_FATAL, "Invalid %s index %d while processing metadata maps.\n",\
4068 #define SET_DICT(type, meta, context, index)\
4071 meta = &context->metadata;\
4074 METADATA_CHECK_INDEX(index, context->nb_chapters, "chapter")\
4075 meta = &context->chapters[index]->metadata;\
4078 METADATA_CHECK_INDEX(index, context->nb_programs, "program")\
4079 meta = &context->programs[index]->metadata;\
4083 SET_DICT(type_in, meta_in, ic, idx_in);
4084 SET_DICT(type_out, meta_out, oc, idx_out);
4086 /* for input streams choose first matching stream */
4087 if (type_in == 's') {
4088 for (i = 0; i < ic->nb_streams; i++) {
4089 if ((ret = check_stream_specifier(ic, ic->streams[i], istream_spec)) > 0) {
4090 meta_in = &ic->streams[i]->metadata;
4096 av_log(NULL, AV_LOG_FATAL, "Stream specifier %s does not match any streams.\n", istream_spec);
4101 if (type_out == 's') {
4102 for (i = 0; i < oc->nb_streams; i++) {
4103 if ((ret = check_stream_specifier(oc, oc->streams[i], ostream_spec)) > 0) {
4104 meta_out = &oc->streams[i]->metadata;
4105 av_dict_copy(meta_out, *meta_in, AV_DICT_DONT_OVERWRITE);
4110 av_dict_copy(meta_out, *meta_in, AV_DICT_DONT_OVERWRITE);
4115 static int opt_recording_timestamp(OptionsContext *o, const char *opt, const char *arg)
4118 int64_t recording_timestamp = parse_time_or_die(opt, arg, 0) / 1E6;
4119 struct tm time = *gmtime((time_t*)&recording_timestamp);
4120 strftime(buf, sizeof(buf), "creation_time=%FT%T%z", &time);
4121 parse_option(o, "metadata", buf, options);
4123 av_log(NULL, AV_LOG_WARNING, "%s is deprecated, set the 'creation_time' metadata "
4124 "tag instead.\n", opt);
4128 static AVCodec *find_codec_or_die(const char *name, enum AVMediaType type, int encoder)
4130 const char *codec_string = encoder ? "encoder" : "decoder";
4134 avcodec_find_encoder_by_name(name) :
4135 avcodec_find_decoder_by_name(name);
4137 av_log(NULL, AV_LOG_FATAL, "Unknown %s '%s'\n", codec_string, name);
4140 if (codec->type != type) {
4141 av_log(NULL, AV_LOG_FATAL, "Invalid %s type '%s'\n", codec_string, name);
4147 static AVCodec *choose_decoder(OptionsContext *o, AVFormatContext *s, AVStream *st)
4149 char *codec_name = NULL;
4151 MATCH_PER_STREAM_OPT(codec_names, str, codec_name, s, st);
4153 AVCodec *codec = find_codec_or_die(codec_name, st->codec->codec_type, 0);
4154 st->codec->codec_id = codec->id;
4157 return avcodec_find_decoder(st->codec->codec_id);
4161 * Add all the streams from the given input file to the global
4162 * list of input streams.
4164 static void add_input_streams(OptionsContext *o, AVFormatContext *ic)
4167 char *next, *codec_tag = NULL;
4169 for (i = 0; i < ic->nb_streams; i++) {
4170 AVStream *st = ic->streams[i];
4171 AVCodecContext *dec = st->codec;
4172 InputStream *ist = av_mallocz(sizeof(*ist));
4177 input_streams = grow_array(input_streams, sizeof(*input_streams), &nb_input_streams, nb_input_streams + 1);
4178 input_streams[nb_input_streams - 1] = ist;
4181 ist->file_index = nb_input_files;
4183 st->discard = AVDISCARD_ALL;
4184 ist->opts = filter_codec_opts(codec_opts, choose_decoder(o, ic, st), ic, st);
4186 ist->ts_scale = 1.0;
4187 MATCH_PER_STREAM_OPT(ts_scale, dbl, ist->ts_scale, ic, st);
4189 MATCH_PER_STREAM_OPT(codec_tags, str, codec_tag, ic, st);
4191 uint32_t tag = strtol(codec_tag, &next, 0);
4193 tag = AV_RL32(codec_tag);
4194 st->codec->codec_tag = tag;
4197 ist->dec = choose_decoder(o, ic, st);
4199 switch (dec->codec_type) {
4200 case AVMEDIA_TYPE_VIDEO:
4202 ist->dec = avcodec_find_decoder(dec->codec_id);
4204 dec->flags |= CODEC_FLAG_EMU_EDGE;
4207 ist->resample_height = dec->height;
4208 ist->resample_width = dec->width;
4209 ist->resample_pix_fmt = dec->pix_fmt;
4212 case AVMEDIA_TYPE_AUDIO:
4213 case AVMEDIA_TYPE_DATA:
4214 case AVMEDIA_TYPE_SUBTITLE:
4216 ist->dec = avcodec_find_decoder(dec->codec_id);
4218 case AVMEDIA_TYPE_ATTACHMENT:
4219 case AVMEDIA_TYPE_UNKNOWN:
4227 static void assert_file_overwrite(const char *filename)
4229 if ((!file_overwrite || no_file_overwrite) &&
4230 (strchr(filename, ':') == NULL || filename[1] == ':' ||
4231 av_strstart(filename, "file:", NULL))) {
4232 if (avio_check(filename, 0) == 0) {
4233 if (!using_stdin && (!no_file_overwrite || file_overwrite)) {
4234 fprintf(stderr,"File '%s' already exists. Overwrite ? [y/N] ", filename);
4237 signal(SIGINT, SIG_DFL);
4238 if (!read_yesno()) {
4239 av_log(NULL, AV_LOG_FATAL, "Not overwriting - exiting\n");
4245 av_log(NULL, AV_LOG_FATAL, "File '%s' already exists. Exiting.\n", filename);
4252 static void dump_attachment(AVStream *st, const char *filename)
4255 AVIOContext *out = NULL;
4256 AVDictionaryEntry *e;
4258 if (!st->codec->extradata_size) {
4259 av_log(NULL, AV_LOG_WARNING, "No extradata to dump in stream #%d:%d.\n",
4260 nb_input_files - 1, st->index);
4263 if (!*filename && (e = av_dict_get(st->metadata, "filename", NULL, 0)))
4264 filename = e->value;
4266 av_log(NULL, AV_LOG_FATAL, "No filename specified and no 'filename' tag"
4267 "in stream #%d:%d.\n", nb_input_files - 1, st->index);
4271 assert_file_overwrite(filename);
4273 if ((ret = avio_open2(&out, filename, AVIO_FLAG_WRITE, &int_cb, NULL)) < 0) {
4274 av_log(NULL, AV_LOG_FATAL, "Could not open file %s for writing.\n",
4279 avio_write(out, st->codec->extradata, st->codec->extradata_size);
4284 static int opt_input_file(OptionsContext *o, const char *opt, const char *filename)
4286 AVFormatContext *ic;
4287 AVInputFormat *file_iformat = NULL;
4291 AVDictionary **opts;
4292 int orig_nb_streams; // number of streams before avformat_find_stream_info
4295 if (!(file_iformat = av_find_input_format(o->format))) {
4296 av_log(NULL, AV_LOG_FATAL, "Unknown input format: '%s'\n", o->format);
4301 if (!strcmp(filename, "-"))
4304 using_stdin |= !strncmp(filename, "pipe:", 5) ||
4305 !strcmp(filename, "/dev/stdin");
4307 /* get default parameters from command line */
4308 ic = avformat_alloc_context();
4310 print_error(filename, AVERROR(ENOMEM));
4313 if (o->nb_audio_sample_rate) {
4314 snprintf(buf, sizeof(buf), "%d", o->audio_sample_rate[o->nb_audio_sample_rate - 1].u.i);
4315 av_dict_set(&format_opts, "sample_rate", buf, 0);
4317 if (o->nb_audio_channels) {
4318 /* because we set audio_channels based on both the "ac" and
4319 * "channel_layout" options, we need to check that the specified
4320 * demuxer actually has the "channels" option before setting it */
4321 if (file_iformat && file_iformat->priv_class &&
4322 av_opt_find(&file_iformat->priv_class, "channels", NULL, 0,
4323 AV_OPT_SEARCH_FAKE_OBJ)) {
4324 snprintf(buf, sizeof(buf), "%d",
4325 o->audio_channels[o->nb_audio_channels - 1].u.i);
4326 av_dict_set(&format_opts, "channels", buf, 0);
4329 if (o->nb_frame_rates) {
4330 av_dict_set(&format_opts, "framerate", o->frame_rates[o->nb_frame_rates - 1].u.str, 0);
4332 if (o->nb_frame_sizes) {
4333 av_dict_set(&format_opts, "video_size", o->frame_sizes[o->nb_frame_sizes - 1].u.str, 0);
4335 if (o->nb_frame_pix_fmts)
4336 av_dict_set(&format_opts, "pixel_format", o->frame_pix_fmts[o->nb_frame_pix_fmts - 1].u.str, 0);
4338 ic->video_codec_id = video_codec_name ?
4339 find_codec_or_die(video_codec_name , AVMEDIA_TYPE_VIDEO , 0)->id : CODEC_ID_NONE;
4340 ic->audio_codec_id = audio_codec_name ?
4341 find_codec_or_die(audio_codec_name , AVMEDIA_TYPE_AUDIO , 0)->id : CODEC_ID_NONE;
4342 ic->subtitle_codec_id= subtitle_codec_name ?
4343 find_codec_or_die(subtitle_codec_name, AVMEDIA_TYPE_SUBTITLE, 0)->id : CODEC_ID_NONE;
4344 ic->flags |= AVFMT_FLAG_NONBLOCK;
4345 ic->interrupt_callback = int_cb;
4347 /* open the input file with generic avformat function */
4348 err = avformat_open_input(&ic, filename, file_iformat, &format_opts);
4350 print_error(filename, err);
4353 assert_avoptions(format_opts);
4355 /* apply forced codec ids */
4356 for (i = 0; i < ic->nb_streams; i++)
4357 choose_decoder(o, ic, ic->streams[i]);
4359 /* Set AVCodecContext options for avformat_find_stream_info */
4360 opts = setup_find_stream_info_opts(ic, codec_opts);
4361 orig_nb_streams = ic->nb_streams;
4363 /* If not enough info to get the stream parameters, we decode the
4364 first frames to get it. (used in mpeg case for example) */
4365 ret = avformat_find_stream_info(ic, opts);
4367 av_log(NULL, AV_LOG_FATAL, "%s: could not find codec parameters\n", filename);
4368 avformat_close_input(&ic);
4372 timestamp = o->start_time;
4373 /* add the stream start time */
4374 if (ic->start_time != AV_NOPTS_VALUE)
4375 timestamp += ic->start_time;
4377 /* if seeking requested, we execute it */
4378 if (o->start_time != 0) {
4379 ret = av_seek_frame(ic, -1, timestamp, AVSEEK_FLAG_BACKWARD);
4381 av_log(NULL, AV_LOG_WARNING, "%s: could not seek to position %0.3f\n",
4382 filename, (double)timestamp / AV_TIME_BASE);
4386 /* update the current parameters so that they match the one of the input stream */
4387 add_input_streams(o, ic);
4389 /* dump the file content */
4390 av_dump_format(ic, nb_input_files, filename, 0);
4392 input_files = grow_array(input_files, sizeof(*input_files), &nb_input_files, nb_input_files + 1);
4393 if (!(input_files[nb_input_files - 1] = av_mallocz(sizeof(*input_files[0]))))
4396 input_files[nb_input_files - 1]->ctx = ic;
4397 input_files[nb_input_files - 1]->ist_index = nb_input_streams - ic->nb_streams;
4398 input_files[nb_input_files - 1]->ts_offset = o->input_ts_offset - (copy_ts ? 0 : timestamp);
4399 input_files[nb_input_files - 1]->nb_streams = ic->nb_streams;
4400 input_files[nb_input_files - 1]->rate_emu = o->rate_emu;
4402 for (i = 0; i < o->nb_dump_attachment; i++) {
4405 for (j = 0; j < ic->nb_streams; j++) {
4406 AVStream *st = ic->streams[j];
4408 if (check_stream_specifier(ic, st, o->dump_attachment[i].specifier) == 1)
4409 dump_attachment(st, o->dump_attachment[i].u.str);
4413 for (i = 0; i < orig_nb_streams; i++)
4414 av_dict_free(&opts[i]);
4417 reset_options(o, 1);
4421 static void parse_forced_key_frames(char *kf, OutputStream *ost)
4426 for (p = kf; *p; p++)
4429 ost->forced_kf_count = n;
4430 ost->forced_kf_pts = av_malloc(sizeof(*ost->forced_kf_pts) * n);
4431 if (!ost->forced_kf_pts) {
4432 av_log(NULL, AV_LOG_FATAL, "Could not allocate forced key frames array.\n");
4436 for (i = 0; i < n; i++) {
4437 char *next = strchr(p, ',');
4438 if (next) *next++ = 0;
4439 ost->forced_kf_pts[i] = parse_time_or_die("force_key_frames", p, 1);
4444 static uint8_t *get_line(AVIOContext *s)
4450 if (avio_open_dyn_buf(&line) < 0) {
4451 av_log(NULL, AV_LOG_FATAL, "Could not alloc buffer for reading preset.\n");
4455 while ((c = avio_r8(s)) && c != '\n')
4458 avio_close_dyn_buf(line, &buf);
4463 static int get_preset_file_2(const char *preset_name, const char *codec_name, AVIOContext **s)
4466 char filename[1000];
4467 const char *base[3] = { getenv("AVCONV_DATADIR"),
4472 for (i = 0; i < FF_ARRAY_ELEMS(base) && ret; i++) {
4476 snprintf(filename, sizeof(filename), "%s%s/%s-%s.avpreset", base[i],
4477 i != 1 ? "" : "/.avconv", codec_name, preset_name);
4478 ret = avio_open2(s, filename, AVIO_FLAG_READ, &int_cb, NULL);
4481 snprintf(filename, sizeof(filename), "%s%s/%s.avpreset", base[i],
4482 i != 1 ? "" : "/.avconv", preset_name);
4483 ret = avio_open2(s, filename, AVIO_FLAG_READ, &int_cb, NULL);
4489 static void choose_encoder(OptionsContext *o, AVFormatContext *s, OutputStream *ost)
4491 char *codec_name = NULL;
4493 MATCH_PER_STREAM_OPT(codec_names, str, codec_name, s, ost->st);
4495 ost->st->codec->codec_id = av_guess_codec(s->oformat, NULL, s->filename,
4496 NULL, ost->st->codec->codec_type);
4497 ost->enc = avcodec_find_encoder(ost->st->codec->codec_id);
4498 } else if (!strcmp(codec_name, "copy"))
4499 ost->stream_copy = 1;
4501 ost->enc = find_codec_or_die(codec_name, ost->st->codec->codec_type, 1);
4502 ost->st->codec->codec_id = ost->enc->id;
4506 static OutputStream *new_output_stream(OptionsContext *o, AVFormatContext *oc, enum AVMediaType type, int source_index)
4509 AVStream *st = avformat_new_stream(oc, NULL);
4510 int idx = oc->nb_streams - 1, ret = 0;
4511 char *bsf = NULL, *next, *codec_tag = NULL;
4512 AVBitStreamFilterContext *bsfc, *bsfc_prev = NULL;
4514 char *buf = NULL, *arg = NULL, *preset = NULL;
4515 AVIOContext *s = NULL;
4518 av_log(NULL, AV_LOG_FATAL, "Could not alloc stream.\n");
4522 if (oc->nb_streams - 1 < o->nb_streamid_map)
4523 st->id = o->streamid_map[oc->nb_streams - 1];
4525 output_streams = grow_array(output_streams, sizeof(*output_streams), &nb_output_streams,
4526 nb_output_streams + 1);
4527 if (!(ost = av_mallocz(sizeof(*ost))))
4529 output_streams[nb_output_streams - 1] = ost;
4531 ost->file_index = nb_output_files;
4534 st->codec->codec_type = type;
4535 choose_encoder(o, oc, ost);
4537 ost->opts = filter_codec_opts(codec_opts, ost->enc, oc, st);
4540 avcodec_get_context_defaults3(st->codec, ost->enc);
4541 st->codec->codec_type = type; // XXX hack, avcodec_get_context_defaults2() sets type to unknown for stream copy
4543 MATCH_PER_STREAM_OPT(presets, str, preset, oc, st);
4544 if (preset && (!(ret = get_preset_file_2(preset, ost->enc->name, &s)))) {
4547 if (!buf[0] || buf[0] == '#') {
4551 if (!(arg = strchr(buf, '='))) {
4552 av_log(NULL, AV_LOG_FATAL, "Invalid line found in the preset file.\n");
4556 av_dict_set(&ost->opts, buf, arg, AV_DICT_DONT_OVERWRITE);
4558 } while (!s->eof_reached);
4562 av_log(NULL, AV_LOG_FATAL,
4563 "Preset %s specified for stream %d:%d, but could not be opened.\n",
4564 preset, ost->file_index, ost->index);
4568 ost->max_frames = INT64_MAX;
4569 MATCH_PER_STREAM_OPT(max_frames, i64, ost->max_frames, oc, st);
4571 MATCH_PER_STREAM_OPT(bitstream_filters, str, bsf, oc, st);
4573 if (next = strchr(bsf, ','))
4575 if (!(bsfc = av_bitstream_filter_init(bsf))) {
4576 av_log(NULL, AV_LOG_FATAL, "Unknown bitstream filter %s\n", bsf);
4580 bsfc_prev->next = bsfc;
4582 ost->bitstream_filters = bsfc;
4588 MATCH_PER_STREAM_OPT(codec_tags, str, codec_tag, oc, st);
4590 uint32_t tag = strtol(codec_tag, &next, 0);
4592 tag = AV_RL32(codec_tag);
4593 st->codec->codec_tag = tag;
4596 MATCH_PER_STREAM_OPT(qscale, dbl, qscale, oc, st);
4597 if (qscale >= 0 || same_quant) {
4598 st->codec->flags |= CODEC_FLAG_QSCALE;
4599 st->codec->global_quality = FF_QP2LAMBDA * qscale;
4602 if (oc->oformat->flags & AVFMT_GLOBALHEADER)
4603 st->codec->flags |= CODEC_FLAG_GLOBAL_HEADER;
4605 av_opt_get_int(sws_opts, "sws_flags", 0, &ost->sws_flags);
4606 av_opt_get_int (swr_opts, "dither_method", 0, &ost->swr_dither_method);
4607 av_opt_get_double(swr_opts, "dither_scale" , 0, &ost->swr_dither_scale);
4609 ost->source_index = source_index;
4610 if (source_index >= 0) {
4611 ost->sync_ist = input_streams[source_index];
4612 input_streams[source_index]->discard = 0;
4613 input_streams[source_index]->st->discard = AVDISCARD_NONE;
4616 ost->pix_fmts[0] = ost->pix_fmts[1] = PIX_FMT_NONE;
4621 static void parse_matrix_coeffs(uint16_t *dest, const char *str)
4624 const char *p = str;
4631 av_log(NULL, AV_LOG_FATAL, "Syntax error in matrix \"%s\" at coeff %d\n", str, i);
4638 static OutputStream *new_video_stream(OptionsContext *o, AVFormatContext *oc, int source_index)
4642 AVCodecContext *video_enc;
4644 ost = new_output_stream(o, oc, AVMEDIA_TYPE_VIDEO, source_index);
4646 video_enc = st->codec;
4648 if (!ost->stream_copy) {
4649 const char *p = NULL;
4650 char *forced_key_frames = NULL, *frame_rate = NULL, *frame_size = NULL;
4651 char *frame_aspect_ratio = NULL, *frame_pix_fmt = NULL;
4652 char *intra_matrix = NULL, *inter_matrix = NULL, *filters = NULL;
4655 MATCH_PER_STREAM_OPT(frame_rates, str, frame_rate, oc, st);
4656 if (frame_rate && av_parse_video_rate(&ost->frame_rate, frame_rate) < 0) {
4657 av_log(NULL, AV_LOG_FATAL, "Invalid framerate value: %s\n", frame_rate);
4661 MATCH_PER_STREAM_OPT(frame_sizes, str, frame_size, oc, st);
4662 if (frame_size && av_parse_video_size(&video_enc->width, &video_enc->height, frame_size) < 0) {
4663 av_log(NULL, AV_LOG_FATAL, "Invalid frame size: %s.\n", frame_size);
4667 MATCH_PER_STREAM_OPT(frame_aspect_ratios, str, frame_aspect_ratio, oc, st);
4668 if (frame_aspect_ratio) {
4670 if (av_parse_ratio(&q, frame_aspect_ratio, 255, 0, NULL) < 0 ||
4671 q.num <= 0 || q.den <= 0) {
4672 av_log(NULL, AV_LOG_FATAL, "Invalid aspect ratio: %s\n", frame_aspect_ratio);
4675 ost->frame_aspect_ratio = av_q2d(q);
4678 video_enc->bits_per_raw_sample = frame_bits_per_raw_sample;
4679 MATCH_PER_STREAM_OPT(frame_pix_fmts, str, frame_pix_fmt, oc, st);
4680 if (frame_pix_fmt && *frame_pix_fmt == '+') {
4681 ost->keep_pix_fmt = 1;
4682 if (!*++frame_pix_fmt)
4683 frame_pix_fmt = NULL;
4685 if (frame_pix_fmt && (video_enc->pix_fmt = av_get_pix_fmt(frame_pix_fmt)) == PIX_FMT_NONE) {
4686 av_log(NULL, AV_LOG_FATAL, "Unknown pixel format requested: %s.\n", frame_pix_fmt);
4689 st->sample_aspect_ratio = video_enc->sample_aspect_ratio;
4692 video_enc->gop_size = 0;
4693 MATCH_PER_STREAM_OPT(intra_matrices, str, intra_matrix, oc, st);
4695 if (!(video_enc->intra_matrix = av_mallocz(sizeof(*video_enc->intra_matrix) * 64))) {
4696 av_log(NULL, AV_LOG_FATAL, "Could not allocate memory for intra matrix.\n");
4699 parse_matrix_coeffs(video_enc->intra_matrix, intra_matrix);
4701 MATCH_PER_STREAM_OPT(inter_matrices, str, inter_matrix, oc, st);
4703 if (!(video_enc->inter_matrix = av_mallocz(sizeof(*video_enc->inter_matrix) * 64))) {
4704 av_log(NULL, AV_LOG_FATAL, "Could not allocate memory for inter matrix.\n");
4707 parse_matrix_coeffs(video_enc->inter_matrix, inter_matrix);
4710 MATCH_PER_STREAM_OPT(rc_overrides, str, p, oc, st);
4711 for (i = 0; p; i++) {
4713 int e = sscanf(p, "%d,%d,%d", &start, &end, &q);
4715 av_log(NULL, AV_LOG_FATAL, "error parsing rc_override\n");
4718 /* FIXME realloc failure */
4719 video_enc->rc_override =
4720 av_realloc(video_enc->rc_override,
4721 sizeof(RcOverride) * (i + 1));
4722 video_enc->rc_override[i].start_frame = start;
4723 video_enc->rc_override[i].end_frame = end;
4725 video_enc->rc_override[i].qscale = q;
4726 video_enc->rc_override[i].quality_factor = 1.0;
4729 video_enc->rc_override[i].qscale = 0;
4730 video_enc->rc_override[i].quality_factor = -q/100.0;
4735 video_enc->rc_override_count = i;
4736 if (!video_enc->rc_initial_buffer_occupancy)
4737 video_enc->rc_initial_buffer_occupancy = video_enc->rc_buffer_size * 3 / 4;
4738 video_enc->intra_dc_precision = intra_dc_precision - 8;
4741 video_enc->flags|= CODEC_FLAG_PSNR;
4746 video_enc->flags |= CODEC_FLAG_PASS1;
4749 video_enc->flags |= CODEC_FLAG_PASS2;
4753 MATCH_PER_STREAM_OPT(forced_key_frames, str, forced_key_frames, oc, st);
4754 if (forced_key_frames)
4755 parse_forced_key_frames(forced_key_frames, ost);
4757 MATCH_PER_STREAM_OPT(force_fps, i, ost->force_fps, oc, st);
4759 ost->top_field_first = -1;
4760 MATCH_PER_STREAM_OPT(top_field_first, i, ost->top_field_first, oc, st);
4762 MATCH_PER_STREAM_OPT(filters, str, filters, oc, st);
4764 ost->avfilter = av_strdup(filters);
4766 MATCH_PER_STREAM_OPT(copy_initial_nonkeyframes, i, ost->copy_initial_nonkeyframes, oc ,st);
4772 static OutputStream *new_audio_stream(OptionsContext *o, AVFormatContext *oc, int source_index)
4777 AVCodecContext *audio_enc;
4779 ost = new_output_stream(o, oc, AVMEDIA_TYPE_AUDIO, source_index);
4782 audio_enc = st->codec;
4783 audio_enc->codec_type = AVMEDIA_TYPE_AUDIO;
4785 if (!ost->stream_copy) {
4786 char *sample_fmt = NULL;
4788 MATCH_PER_STREAM_OPT(audio_channels, i, audio_enc->channels, oc, st);
4790 MATCH_PER_STREAM_OPT(sample_fmts, str, sample_fmt, oc, st);
4792 (audio_enc->sample_fmt = av_get_sample_fmt(sample_fmt)) == AV_SAMPLE_FMT_NONE) {
4793 av_log(NULL, AV_LOG_FATAL, "Invalid sample format '%s'\n", sample_fmt);
4797 MATCH_PER_STREAM_OPT(audio_sample_rate, i, audio_enc->sample_rate, oc, st);
4799 ost->rematrix_volume=1.0;
4800 MATCH_PER_STREAM_OPT(rematrix_volume, f, ost->rematrix_volume, oc, st);
4803 /* check for channel mapping for this audio stream */
4804 for (n = 0; n < o->nb_audio_channel_maps; n++) {
4805 AudioChannelMap *map = &o->audio_channel_maps[n];
4806 InputStream *ist = input_streams[ost->source_index];
4807 if ((map->channel_idx == -1 || (ist->file_index == map->file_idx && ist->st->index == map->stream_idx)) &&
4808 (map->ofile_idx == -1 || ost->file_index == map->ofile_idx) &&
4809 (map->ostream_idx == -1 || ost->st->index == map->ostream_idx)) {
4810 if (ost->audio_channels_mapped < FF_ARRAY_ELEMS(ost->audio_channels_map))
4811 ost->audio_channels_map[ost->audio_channels_mapped++] = map->channel_idx;
4813 av_log(NULL, AV_LOG_FATAL, "Max channel mapping for output %d.%d reached\n",
4814 ost->file_index, ost->st->index);
4821 static OutputStream *new_data_stream(OptionsContext *o, AVFormatContext *oc, int source_index)
4825 ost = new_output_stream(o, oc, AVMEDIA_TYPE_DATA, source_index);
4826 if (!ost->stream_copy) {
4827 av_log(NULL, AV_LOG_FATAL, "Data stream encoding not supported yet (only streamcopy)\n");
4834 static OutputStream *new_attachment_stream(OptionsContext *o, AVFormatContext *oc, int source_index)
4836 OutputStream *ost = new_output_stream(o, oc, AVMEDIA_TYPE_ATTACHMENT, source_index);
4837 ost->stream_copy = 1;
4841 static OutputStream *new_subtitle_stream(OptionsContext *o, AVFormatContext *oc, int source_index)
4845 AVCodecContext *subtitle_enc;
4847 ost = new_output_stream(o, oc, AVMEDIA_TYPE_SUBTITLE, source_index);
4849 subtitle_enc = st->codec;
4851 subtitle_enc->codec_type = AVMEDIA_TYPE_SUBTITLE;
4853 MATCH_PER_STREAM_OPT(copy_initial_nonkeyframes, i, ost->copy_initial_nonkeyframes, oc, st);
4858 /* arg format is "output-stream-index:streamid-value". */
4859 static int opt_streamid(OptionsContext *o, const char *opt, const char *arg)
4865 av_strlcpy(idx_str, arg, sizeof(idx_str));
4866 p = strchr(idx_str, ':');
4868 av_log(NULL, AV_LOG_FATAL,
4869 "Invalid value '%s' for option '%s', required syntax is 'index:value'\n",
4874 idx = parse_number_or_die(opt, idx_str, OPT_INT, 0, MAX_STREAMS-1);
4875 o->streamid_map = grow_array(o->streamid_map, sizeof(*o->streamid_map), &o->nb_streamid_map, idx+1);
4876 o->streamid_map[idx] = parse_number_or_die(opt, p, OPT_INT, 0, INT_MAX);
4880 static int copy_chapters(InputFile *ifile, OutputFile *ofile, int copy_metadata)
4882 AVFormatContext *is = ifile->ctx;
4883 AVFormatContext *os = ofile->ctx;
4886 for (i = 0; i < is->nb_chapters; i++) {
4887 AVChapter *in_ch = is->chapters[i], *out_ch;
4888 int64_t ts_off = av_rescale_q(ofile->start_time - ifile->ts_offset,
4889 AV_TIME_BASE_Q, in_ch->time_base);
4890 int64_t rt = (ofile->recording_time == INT64_MAX) ? INT64_MAX :
4891 av_rescale_q(ofile->recording_time, AV_TIME_BASE_Q, in_ch->time_base);
4894 if (in_ch->end < ts_off)
4896 if (rt != INT64_MAX && in_ch->start > rt + ts_off)
4899 out_ch = av_mallocz(sizeof(AVChapter));
4901 return AVERROR(ENOMEM);
4903 out_ch->id = in_ch->id;
4904 out_ch->time_base = in_ch->time_base;
4905 out_ch->start = FFMAX(0, in_ch->start - ts_off);
4906 out_ch->end = FFMIN(rt, in_ch->end - ts_off);
4909 av_dict_copy(&out_ch->metadata, in_ch->metadata, 0);
4912 os->chapters = av_realloc_f(os->chapters, os->nb_chapters, sizeof(AVChapter));
4914 return AVERROR(ENOMEM);
4915 os->chapters[os->nb_chapters - 1] = out_ch;
4920 static int read_ffserver_streams(OptionsContext *o, AVFormatContext *s, const char *filename)
4923 AVFormatContext *ic = avformat_alloc_context();
4925 ic->interrupt_callback = int_cb;
4926 err = avformat_open_input(&ic, filename, NULL, NULL);
4929 /* copy stream format */
4930 for(i=0;i<ic->nb_streams;i++) {
4934 AVCodecContext *avctx;
4936 codec = avcodec_find_encoder(ic->streams[i]->codec->codec_id);
4937 ost = new_output_stream(o, s, codec->type, -1);
4942 // FIXME: a more elegant solution is needed
4943 memcpy(st, ic->streams[i], sizeof(AVStream));
4945 st->info = av_malloc(sizeof(*st->info));
4946 memcpy(st->info, ic->streams[i]->info, sizeof(*st->info));
4948 avcodec_copy_context(st->codec, ic->streams[i]->codec);
4950 if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO && !ost->stream_copy)
4951 choose_sample_fmt(st, codec);
4952 else if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO && !ost->stream_copy)
4953 choose_pixel_fmt(st, codec, st->codec->pix_fmt);
4956 avformat_close_input(&ic);
4960 static void init_output_filter(OutputFilter *ofilter, OptionsContext *o,
4961 AVFormatContext *oc)
4965 if (ofilter->out_tmp->filter_ctx->output_pads[ofilter->out_tmp->pad_idx].type != AVMEDIA_TYPE_VIDEO) {
4966 av_log(NULL, AV_LOG_FATAL, "Only video filters are supported currently.\n");
4970 ost = new_video_stream(o, oc, -1);
4971 ost->source_index = -1;
4972 ost->filter = ofilter;
4976 if (ost->stream_copy) {
4977 av_log(NULL, AV_LOG_ERROR, "Streamcopy requested for output stream %d:%d, "
4978 "which is fed from a complex filtergraph. Filtering and streamcopy "
4979 "cannot be used together.\n", ost->file_index, ost->index);
4983 if (configure_output_filter(ofilter->graph, ofilter, ofilter->out_tmp) < 0) {
4984 av_log(NULL, AV_LOG_FATAL, "Error configuring filter.\n");
4987 avfilter_inout_free(&ofilter->out_tmp);
4990 static void opt_output_file(void *optctx, const char *filename)
4992 OptionsContext *o = optctx;
4993 AVFormatContext *oc;
4995 AVOutputFormat *file_oformat;
4999 if (configure_complex_filters() < 0) {
5000 av_log(NULL, AV_LOG_FATAL, "Error configuring filters.\n");
5004 if (!strcmp(filename, "-"))
5007 err = avformat_alloc_output_context2(&oc, NULL, o->format, filename);
5009 print_error(filename, err);
5012 file_oformat= oc->oformat;
5013 oc->interrupt_callback = int_cb;
5015 /* create streams for all unlabeled output pads */
5016 for (i = 0; i < nb_filtergraphs; i++) {
5017 FilterGraph *fg = filtergraphs[i];
5018 for (j = 0; j < fg->nb_outputs; j++) {
5019 OutputFilter *ofilter = fg->outputs[j];
5021 if (!ofilter->out_tmp || ofilter->out_tmp->name)
5024 switch (ofilter->out_tmp->filter_ctx->output_pads[ofilter->out_tmp->pad_idx].type) {
5025 case AVMEDIA_TYPE_VIDEO: o->video_disable = 1; break;
5026 case AVMEDIA_TYPE_AUDIO: o->audio_disable = 1; break;
5027 case AVMEDIA_TYPE_SUBTITLE: o->subtitle_disable = 1; break;
5029 init_output_filter(ofilter, o, oc);
5033 if (!strcmp(file_oformat->name, "ffm") &&
5034 av_strstart(filename, "http:", NULL)) {
5036 /* special case for files sent to ffserver: we get the stream
5037 parameters from ffserver */
5038 int err = read_ffserver_streams(o, oc, filename);
5040 print_error(filename, err);
5043 for(j = nb_output_streams - oc->nb_streams; j < nb_output_streams; j++) {
5044 ost = output_streams[j];
5045 for (i = 0; i < nb_input_streams; i++) {
5046 ist = input_streams[i];
5047 if(ist->st->codec->codec_type == ost->st->codec->codec_type){
5049 ost->source_index= i;
5051 ist->st->discard = AVDISCARD_NONE;
5056 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));
5060 } else if (!o->nb_stream_maps) {
5061 /* pick the "best" stream of each type */
5063 /* video: highest resolution */
5064 if (!o->video_disable && oc->oformat->video_codec != CODEC_ID_NONE) {
5065 int area = 0, idx = -1;
5066 for (i = 0; i < nb_input_streams; i++) {
5067 ist = input_streams[i];
5068 if (ist->st->codec->codec_type == AVMEDIA_TYPE_VIDEO &&
5069 ist->st->codec->width * ist->st->codec->height > area) {
5070 area = ist->st->codec->width * ist->st->codec->height;
5075 new_video_stream(o, oc, idx);
5078 /* audio: most channels */
5079 if (!o->audio_disable && oc->oformat->audio_codec != CODEC_ID_NONE) {
5080 int channels = 0, idx = -1;
5081 for (i = 0; i < nb_input_streams; i++) {
5082 ist = input_streams[i];
5083 if (ist->st->codec->codec_type == AVMEDIA_TYPE_AUDIO &&
5084 ist->st->codec->channels > channels) {
5085 channels = ist->st->codec->channels;
5090 new_audio_stream(o, oc, idx);
5093 /* subtitles: pick first */
5094 if (!o->subtitle_disable && (oc->oformat->subtitle_codec != CODEC_ID_NONE || subtitle_codec_name)) {
5095 for (i = 0; i < nb_input_streams; i++)
5096 if (input_streams[i]->st->codec->codec_type == AVMEDIA_TYPE_SUBTITLE) {
5097 new_subtitle_stream(o, oc, i);
5101 /* do something with data? */
5103 for (i = 0; i < o->nb_stream_maps; i++) {
5104 StreamMap *map = &o->stream_maps[i];
5105 int src_idx = input_files[map->file_index]->ist_index + map->stream_index;
5110 if (map->linklabel) {
5112 OutputFilter *ofilter = NULL;
5115 for (j = 0; j < nb_filtergraphs; j++) {
5116 fg = filtergraphs[j];
5117 for (k = 0; k < fg->nb_outputs; k++) {
5118 AVFilterInOut *out = fg->outputs[k]->out_tmp;
5119 if (out && !strcmp(out->name, map->linklabel)) {
5120 ofilter = fg->outputs[k];
5127 av_log(NULL, AV_LOG_FATAL, "Output with label '%s' does not exist "
5128 "in any defined filter graph.\n", map->linklabel);
5131 init_output_filter(ofilter, o, oc);
5133 ist = input_streams[input_files[map->file_index]->ist_index + map->stream_index];
5134 if(o->subtitle_disable && ist->st->codec->codec_type == AVMEDIA_TYPE_SUBTITLE)
5136 if(o-> audio_disable && ist->st->codec->codec_type == AVMEDIA_TYPE_AUDIO)
5138 if(o-> video_disable && ist->st->codec->codec_type == AVMEDIA_TYPE_VIDEO)
5140 if(o-> data_disable && ist->st->codec->codec_type == AVMEDIA_TYPE_DATA)
5143 switch (ist->st->codec->codec_type) {
5144 case AVMEDIA_TYPE_VIDEO: ost = new_video_stream (o, oc, src_idx); break;
5145 case AVMEDIA_TYPE_AUDIO: ost = new_audio_stream (o, oc, src_idx); break;
5146 case AVMEDIA_TYPE_SUBTITLE: ost = new_subtitle_stream (o, oc, src_idx); break;
5147 case AVMEDIA_TYPE_DATA: ost = new_data_stream (o, oc, src_idx); break;
5148 case AVMEDIA_TYPE_ATTACHMENT: ost = new_attachment_stream(o, oc, src_idx); break;
5150 av_log(NULL, AV_LOG_FATAL, "Cannot map stream #%d:%d - unsupported type.\n",
5151 map->file_index, map->stream_index);
5159 for (i = nb_output_streams - oc->nb_streams; i < nb_output_streams; i++) { //for all streams of this output file
5160 AVDictionaryEntry *e;
5161 ost = output_streams[i];
5163 if ( ost->stream_copy
5164 && (e = av_dict_get(codec_opts, "flags", NULL, AV_DICT_IGNORE_SUFFIX))
5165 && (!e->key[5] || check_stream_specifier(oc, ost->st, e->key+6)))
5166 if (av_opt_set(ost->st->codec, "flags", e->value, 0) < 0)
5170 /* handle attached files */
5171 for (i = 0; i < o->nb_attachments; i++) {
5173 uint8_t *attachment;
5177 if ((err = avio_open2(&pb, o->attachments[i], AVIO_FLAG_READ, &int_cb, NULL)) < 0) {
5178 av_log(NULL, AV_LOG_FATAL, "Could not open attachment file %s.\n",
5182 if ((len = avio_size(pb)) <= 0) {
5183 av_log(NULL, AV_LOG_FATAL, "Could not get size of the attachment %s.\n",
5187 if (!(attachment = av_malloc(len))) {
5188 av_log(NULL, AV_LOG_FATAL, "Attachment %s too large to fit into memory.\n",
5192 avio_read(pb, attachment, len);
5194 ost = new_attachment_stream(o, oc, -1);
5195 ost->stream_copy = 0;
5196 ost->attachment_filename = o->attachments[i];
5197 ost->st->codec->extradata = attachment;
5198 ost->st->codec->extradata_size = len;
5200 p = strrchr(o->attachments[i], '/');
5201 av_dict_set(&ost->st->metadata, "filename", (p && *p) ? p + 1 : o->attachments[i], AV_DICT_DONT_OVERWRITE);
5205 output_files = grow_array(output_files, sizeof(*output_files), &nb_output_files, nb_output_files + 1);
5206 if (!(output_files[nb_output_files - 1] = av_mallocz(sizeof(*output_files[0]))))
5209 output_files[nb_output_files - 1]->ctx = oc;
5210 output_files[nb_output_files - 1]->ost_index = nb_output_streams - oc->nb_streams;
5211 output_files[nb_output_files - 1]->recording_time = o->recording_time;
5212 if (o->recording_time != INT64_MAX)
5213 oc->duration = o->recording_time;
5214 output_files[nb_output_files - 1]->start_time = o->start_time;
5215 output_files[nb_output_files - 1]->limit_filesize = o->limit_filesize;
5216 av_dict_copy(&output_files[nb_output_files - 1]->opts, format_opts, 0);
5218 /* check filename in case of an image number is expected */
5219 if (oc->oformat->flags & AVFMT_NEEDNUMBER) {
5220 if (!av_filename_number_test(oc->filename)) {
5221 print_error(oc->filename, AVERROR(EINVAL));
5226 if (!(oc->oformat->flags & AVFMT_NOFILE)) {
5227 /* test if it already exists to avoid losing precious files */
5228 assert_file_overwrite(filename);
5231 if ((err = avio_open2(&oc->pb, filename, AVIO_FLAG_WRITE,
5232 &oc->interrupt_callback,
5233 &output_files[nb_output_files - 1]->opts)) < 0) {
5234 print_error(filename, err);
5239 if (o->mux_preload) {
5241 snprintf(buf, sizeof(buf), "%d", (int)(o->mux_preload*AV_TIME_BASE));
5242 av_dict_set(&output_files[nb_output_files - 1]->opts, "preload", buf, 0);
5244 oc->max_delay = (int)(o->mux_max_delay * AV_TIME_BASE);
5247 for (i = 0; i < o->nb_metadata_map; i++) {
5249 int in_file_index = strtol(o->metadata_map[i].u.str, &p, 0);
5251 if (in_file_index >= nb_input_files) {
5252 av_log(NULL, AV_LOG_FATAL, "Invalid input file index %d while processing metadata maps\n", in_file_index);
5255 copy_metadata(o->metadata_map[i].specifier, *p ? p + 1 : p, oc, in_file_index >= 0 ? input_files[in_file_index]->ctx : NULL, o);
5259 if (o->chapters_input_file >= nb_input_files) {
5260 if (o->chapters_input_file == INT_MAX) {
5261 /* copy chapters from the first input file that has them*/
5262 o->chapters_input_file = -1;
5263 for (i = 0; i < nb_input_files; i++)
5264 if (input_files[i]->ctx->nb_chapters) {
5265 o->chapters_input_file = i;
5269 av_log(NULL, AV_LOG_FATAL, "Invalid input file index %d in chapter mapping.\n",
5270 o->chapters_input_file);
5274 if (o->chapters_input_file >= 0)
5275 copy_chapters(input_files[o->chapters_input_file], output_files[nb_output_files - 1],
5276 !o->metadata_chapters_manual);
5278 /* copy global metadata by default */
5279 if (!o->metadata_global_manual && nb_input_files){
5280 av_dict_copy(&oc->metadata, input_files[0]->ctx->metadata,
5281 AV_DICT_DONT_OVERWRITE);
5282 if(o->recording_time != INT64_MAX)
5283 av_dict_set(&oc->metadata, "duration", NULL, 0);
5285 if (!o->metadata_streams_manual)
5286 for (i = output_files[nb_output_files - 1]->ost_index; i < nb_output_streams; i++) {
5288 if (output_streams[i]->source_index < 0) /* this is true e.g. for attached files */
5290 ist = input_streams[output_streams[i]->source_index];
5291 av_dict_copy(&output_streams[i]->st->metadata, ist->st->metadata, AV_DICT_DONT_OVERWRITE);
5294 /* process manually set metadata */
5295 for (i = 0; i < o->nb_metadata; i++) {
5298 const char *stream_spec;
5299 int index = 0, j, ret = 0;
5301 val = strchr(o->metadata[i].u.str, '=');
5303 av_log(NULL, AV_LOG_FATAL, "No '=' character in metadata string %s.\n",
5304 o->metadata[i].u.str);
5309 parse_meta_type(o->metadata[i].specifier, &type, &index, &stream_spec);
5311 for (j = 0; j < oc->nb_streams; j++) {
5312 if ((ret = check_stream_specifier(oc, oc->streams[j], stream_spec)) > 0) {
5313 av_dict_set(&oc->streams[j]->metadata, o->metadata[i].u.str, *val ? val : NULL, 0);
5317 printf("ret %d, stream_spec %s\n", ret, stream_spec);
5325 if (index < 0 || index >= oc->nb_chapters) {
5326 av_log(NULL, AV_LOG_FATAL, "Invalid chapter index %d in metadata specifier.\n", index);
5329 m = &oc->chapters[index]->metadata;
5332 av_log(NULL, AV_LOG_FATAL, "Invalid metadata specifier %s.\n", o->metadata[i].specifier);
5335 av_dict_set(m, o->metadata[i].u.str, *val ? val : NULL, 0);
5339 reset_options(o, 0);
5342 /* same option as mencoder */
5343 static int opt_pass(const char *opt, const char *arg)
5345 do_pass = parse_number_or_die(opt, arg, OPT_INT, 1, 3);
5349 static int64_t getmaxrss(void)
5351 #if HAVE_GETRUSAGE && HAVE_STRUCT_RUSAGE_RU_MAXRSS
5352 struct rusage rusage;
5353 getrusage(RUSAGE_SELF, &rusage);
5354 return (int64_t)rusage.ru_maxrss * 1024;
5355 #elif HAVE_GETPROCESSMEMORYINFO
5357 PROCESS_MEMORY_COUNTERS memcounters;
5358 proc = GetCurrentProcess();
5359 memcounters.cb = sizeof(memcounters);
5360 GetProcessMemoryInfo(proc, &memcounters, sizeof(memcounters));
5361 return memcounters.PeakPagefileUsage;
5367 static int opt_audio_qscale(OptionsContext *o, const char *opt, const char *arg)
5369 return parse_option(o, "q:a", arg, options);
5372 static void show_usage(void)
5374 av_log(NULL, AV_LOG_INFO, "Hyper fast Audio and Video encoder\n");
5375 av_log(NULL, AV_LOG_INFO, "usage: %s [options] [[infile options] -i infile]... {[outfile options] outfile}...\n", program_name);
5376 av_log(NULL, AV_LOG_INFO, "\n");
5379 static int opt_help(const char *opt, const char *arg)
5381 int flags = AV_OPT_FLAG_DECODING_PARAM | AV_OPT_FLAG_ENCODING_PARAM;
5382 av_log_set_callback(log_callback_help);
5384 show_help_options(options, "Main options:\n",
5385 OPT_EXPERT | OPT_AUDIO | OPT_VIDEO | OPT_SUBTITLE | OPT_GRAB, 0);
5386 show_help_options(options, "\nAdvanced options:\n",
5387 OPT_EXPERT | OPT_AUDIO | OPT_VIDEO | OPT_SUBTITLE | OPT_GRAB,
5389 show_help_options(options, "\nVideo options:\n",
5390 OPT_EXPERT | OPT_AUDIO | OPT_VIDEO | OPT_GRAB,
5392 show_help_options(options, "\nAdvanced Video options:\n",
5393 OPT_EXPERT | OPT_AUDIO | OPT_VIDEO | OPT_GRAB,
5394 OPT_VIDEO | OPT_EXPERT);
5395 show_help_options(options, "\nAudio options:\n",
5396 OPT_EXPERT | OPT_AUDIO | OPT_VIDEO | OPT_GRAB,
5398 show_help_options(options, "\nAdvanced Audio options:\n",
5399 OPT_EXPERT | OPT_AUDIO | OPT_VIDEO | OPT_GRAB,
5400 OPT_AUDIO | OPT_EXPERT);
5401 show_help_options(options, "\nSubtitle options:\n",
5402 OPT_SUBTITLE | OPT_GRAB,
5404 show_help_options(options, "\nAudio/Video grab options:\n",
5408 show_help_children(avcodec_get_class(), flags);
5409 show_help_children(avformat_get_class(), flags);
5410 show_help_children(sws_get_class(), flags);
5415 static int opt_target(OptionsContext *o, const char *opt, const char *arg)
5417 enum { PAL, NTSC, FILM, UNKNOWN } norm = UNKNOWN;
5418 static const char *const frame_rates[] = { "25", "30000/1001", "24000/1001" };
5420 if (!strncmp(arg, "pal-", 4)) {
5423 } else if (!strncmp(arg, "ntsc-", 5)) {
5426 } else if (!strncmp(arg, "film-", 5)) {
5430 /* Try to determine PAL/NTSC by peeking in the input files */
5431 if (nb_input_files) {
5433 for (j = 0; j < nb_input_files; j++) {
5434 for (i = 0; i < input_files[j]->nb_streams; i++) {
5435 AVCodecContext *c = input_files[j]->ctx->streams[i]->codec;
5436 if (c->codec_type != AVMEDIA_TYPE_VIDEO)
5438 fr = c->time_base.den * 1000 / c->time_base.num;
5442 } else if ((fr == 29970) || (fr == 23976)) {
5447 if (norm != UNKNOWN)
5451 if (norm != UNKNOWN)
5452 av_log(NULL, AV_LOG_INFO, "Assuming %s for target.\n", norm == PAL ? "PAL" : "NTSC");
5455 if (norm == UNKNOWN) {
5456 av_log(NULL, AV_LOG_FATAL, "Could not determine norm (PAL/NTSC/NTSC-Film) for target.\n");
5457 av_log(NULL, AV_LOG_FATAL, "Please prefix target with \"pal-\", \"ntsc-\" or \"film-\",\n");
5458 av_log(NULL, AV_LOG_FATAL, "or set a framerate with \"-r xxx\".\n");
5462 if (!strcmp(arg, "vcd")) {
5463 opt_video_codec(o, "c:v", "mpeg1video");
5464 opt_audio_codec(o, "c:a", "mp2");
5465 parse_option(o, "f", "vcd", options);
5467 parse_option(o, "s", norm == PAL ? "352x288" : "352x240", options);
5468 parse_option(o, "r", frame_rates[norm], options);
5469 opt_default("g", norm == PAL ? "15" : "18");
5471 opt_default("b:v", "1150000");
5472 opt_default("maxrate", "1150000");
5473 opt_default("minrate", "1150000");
5474 opt_default("bufsize", "327680"); // 40*1024*8;
5476 opt_default("b:a", "224000");
5477 parse_option(o, "ar", "44100", options);
5478 parse_option(o, "ac", "2", options);
5480 opt_default("packetsize", "2324");
5481 opt_default("muxrate", "1411200"); // 2352 * 75 * 8;
5483 /* We have to offset the PTS, so that it is consistent with the SCR.
5484 SCR starts at 36000, but the first two packs contain only padding
5485 and the first pack from the other stream, respectively, may also have
5486 been written before.
5487 So the real data starts at SCR 36000+3*1200. */
5488 o->mux_preload = (36000 + 3 * 1200) / 90000.0; // 0.44
5489 } else if (!strcmp(arg, "svcd")) {
5491 opt_video_codec(o, "c:v", "mpeg2video");
5492 opt_audio_codec(o, "c:a", "mp2");
5493 parse_option(o, "f", "svcd", options);
5495 parse_option(o, "s", norm == PAL ? "480x576" : "480x480", options);
5496 parse_option(o, "r", frame_rates[norm], options);
5497 parse_option(o, "pix_fmt", "yuv420p", options);
5498 opt_default("g", norm == PAL ? "15" : "18");
5500 opt_default("b:v", "2040000");
5501 opt_default("maxrate", "2516000");
5502 opt_default("minrate", "0"); // 1145000;
5503 opt_default("bufsize", "1835008"); // 224*1024*8;
5504 opt_default("scan_offset", "1");
5507 opt_default("b:a", "224000");
5508 parse_option(o, "ar", "44100", options);
5510 opt_default("packetsize", "2324");
5512 } else if (!strcmp(arg, "dvd")) {
5514 opt_video_codec(o, "c:v", "mpeg2video");
5515 opt_audio_codec(o, "c:a", "ac3");
5516 parse_option(o, "f", "dvd", options);
5518 parse_option(o, "s", norm == PAL ? "720x576" : "720x480", options);
5519 parse_option(o, "r", frame_rates[norm], options);
5520 parse_option(o, "pix_fmt", "yuv420p", options);
5521 opt_default("g", norm == PAL ? "15" : "18");
5523 opt_default("b:v", "6000000");
5524 opt_default("maxrate", "9000000");
5525 opt_default("minrate", "0"); // 1500000;
5526 opt_default("bufsize", "1835008"); // 224*1024*8;
5528 opt_default("packetsize", "2048"); // from www.mpucoder.com: DVD sectors contain 2048 bytes of data, this is also the size of one pack.
5529 opt_default("muxrate", "10080000"); // from mplex project: data_rate = 1260000. mux_rate = data_rate * 8
5531 opt_default("b:a", "448000");
5532 parse_option(o, "ar", "48000", options);
5534 } else if (!strncmp(arg, "dv", 2)) {
5536 parse_option(o, "f", "dv", options);
5538 parse_option(o, "s", norm == PAL ? "720x576" : "720x480", options);
5539 parse_option(o, "pix_fmt", !strncmp(arg, "dv50", 4) ? "yuv422p" :
5540 norm == PAL ? "yuv420p" : "yuv411p", options);
5541 parse_option(o, "r", frame_rates[norm], options);
5543 parse_option(o, "ar", "48000", options);
5544 parse_option(o, "ac", "2", options);
5547 av_log(NULL, AV_LOG_ERROR, "Unknown target: %s\n", arg);
5548 return AVERROR(EINVAL);
5553 static int opt_vstats_file(const char *opt, const char *arg)
5555 av_free (vstats_filename);
5556 vstats_filename = av_strdup (arg);
5560 static int opt_vstats(const char *opt, const char *arg)
5563 time_t today2 = time(NULL);
5564 struct tm *today = localtime(&today2);
5566 snprintf(filename, sizeof(filename), "vstats_%02d%02d%02d.log", today->tm_hour, today->tm_min,
5568 return opt_vstats_file(opt, filename);
5571 static int opt_video_frames(OptionsContext *o, const char *opt, const char *arg)
5573 return parse_option(o, "frames:v", arg, options);
5576 static int opt_audio_frames(OptionsContext *o, const char *opt, const char *arg)
5578 return parse_option(o, "frames:a", arg, options);
5581 static int opt_data_frames(OptionsContext *o, const char *opt, const char *arg)
5583 return parse_option(o, "frames:d", arg, options);
5586 static int opt_preset(OptionsContext *o, const char *opt, const char *arg)
5589 char filename[1000], line[1000], tmp_line[1000];
5590 const char *codec_name = *opt == 'v' ? video_codec_name :
5591 *opt == 'a' ? audio_codec_name :
5592 subtitle_codec_name;
5594 if (!(f = get_preset_file(filename, sizeof(filename), arg, *opt == 'f', codec_name))) {
5595 if(!strncmp(arg, "libx264-lossless", strlen("libx264-lossless"))){
5596 av_log(NULL, AV_LOG_FATAL, "Please use -preset <speed> -qp 0\n");
5598 av_log(NULL, AV_LOG_FATAL, "File for preset '%s' not found\n", arg);
5602 while (fgets(line, sizeof(line), f)) {
5603 char *key = tmp_line, *value, *endptr;
5605 if (strcspn(line, "#\n\r") == 0)
5607 strcpy(tmp_line, line);
5608 if (!av_strtok(key, "=", &value) ||
5609 !av_strtok(value, "\r\n", &endptr)) {
5610 av_log(NULL, AV_LOG_FATAL, "%s: Invalid syntax: '%s'\n", filename, line);
5613 av_log(NULL, AV_LOG_DEBUG, "ffpreset[%s]: set '%s' = '%s'\n", filename, key, value);
5615 if (!strcmp(key, "acodec")) opt_audio_codec (o, key, value);
5616 else if (!strcmp(key, "vcodec")) opt_video_codec (o, key, value);
5617 else if (!strcmp(key, "scodec")) opt_subtitle_codec(o, key, value);
5618 else if (!strcmp(key, "dcodec")) opt_data_codec (o, key, value);
5619 else if (opt_default(key, value) < 0) {
5620 av_log(NULL, AV_LOG_FATAL, "%s: Invalid option or argument: '%s', parsed as '%s' = '%s'\n",
5621 filename, line, key, value);
5631 static void log_callback_null(void *ptr, int level, const char *fmt, va_list vl)
5635 static int opt_passlogfile(const char *opt, const char *arg)
5637 pass_logfilename_prefix = arg;
5638 #if CONFIG_LIBX264_ENCODER
5639 return opt_default(opt, arg);
5645 static int opt_old2new(OptionsContext *o, const char *opt, const char *arg)
5647 char *s = av_asprintf("%s:%c", opt + 1, *opt);
5648 int ret = parse_option(o, s, arg, options);
5653 static int opt_bitrate(OptionsContext *o, const char *opt, const char *arg)
5655 if(!strcmp(opt, "b")){
5656 av_log(NULL, AV_LOG_WARNING, "Please use -b:a or -b:v, -b is ambiguous\n");
5657 return parse_option(o, "b:v", arg, options);
5659 return opt_default(opt, arg);
5662 static int opt_qscale(OptionsContext *o, const char *opt, const char *arg)
5666 if(!strcmp(opt, "qscale")){
5667 av_log(NULL, AV_LOG_WARNING, "Please use -q:a or -q:v, -qscale is ambiguous\n");
5668 return parse_option(o, "q:v", arg, options);
5670 s = av_asprintf("q%s", opt + 6);
5671 ret = parse_option(o, s, arg, options);
5676 static int opt_profile(OptionsContext *o, const char *opt, const char *arg)
5678 if(!strcmp(opt, "profile")){
5679 av_log(NULL, AV_LOG_WARNING, "Please use -profile:a or -profile:v, -profile is ambiguous\n");
5680 return parse_option(o, "profile:v", arg, options);
5682 return opt_default(opt, arg);
5685 static int opt_video_filters(OptionsContext *o, const char *opt, const char *arg)
5687 return parse_option(o, "filter:v", arg, options);
5690 static int opt_vsync(const char *opt, const char *arg)
5692 if (!av_strcasecmp(arg, "cfr")) video_sync_method = VSYNC_CFR;
5693 else if (!av_strcasecmp(arg, "vfr")) video_sync_method = VSYNC_VFR;
5694 else if (!av_strcasecmp(arg, "passthrough")) video_sync_method = VSYNC_PASSTHROUGH;
5695 else if (!av_strcasecmp(arg, "drop")) video_sync_method = VSYNC_DROP;
5697 if (video_sync_method == VSYNC_AUTO)
5698 video_sync_method = parse_number_or_die("vsync", arg, OPT_INT, VSYNC_AUTO, VSYNC_VFR);
5702 static int opt_deinterlace(const char *opt, const char *arg)
5704 av_log(NULL, AV_LOG_WARNING, "-%s is deprecated, use -filter:v yadif instead\n", opt);
5709 static void parse_cpuflags(int argc, char **argv, const OptionDef *options)
5711 int idx = locate_option(argc, argv, options, "cpuflags");
5712 if (idx && argv[idx + 1])
5713 opt_cpuflags("cpuflags", argv[idx + 1]);
5716 static int opt_channel_layout(OptionsContext *o, const char *opt, const char *arg)
5718 char layout_str[32];
5721 int ret, channels, ac_str_size;
5724 layout = av_get_channel_layout(arg);
5726 av_log(NULL, AV_LOG_ERROR, "Unknown channel layout: %s\n", arg);
5727 return AVERROR(EINVAL);
5729 snprintf(layout_str, sizeof(layout_str), "%"PRIu64, layout);
5730 ret = opt_default(opt, layout_str);
5734 /* set 'ac' option based on channel layout */
5735 channels = av_get_channel_layout_nb_channels(layout);
5736 snprintf(layout_str, sizeof(layout_str), "%d", channels);
5737 stream_str = strchr(opt, ':');
5738 ac_str_size = 3 + (stream_str ? strlen(stream_str) : 0);
5739 ac_str = av_mallocz(ac_str_size);
5741 return AVERROR(ENOMEM);
5742 av_strlcpy(ac_str, "ac", 3);
5744 av_strlcat(ac_str, stream_str, ac_str_size);
5745 ret = parse_option(o, ac_str, layout_str, options);
5751 static int opt_filter_complex(const char *opt, const char *arg)
5753 filtergraphs = grow_array(filtergraphs, sizeof(*filtergraphs),
5754 &nb_filtergraphs, nb_filtergraphs + 1);
5755 if (!(filtergraphs[nb_filtergraphs - 1] = av_mallocz(sizeof(*filtergraphs[0]))))
5756 return AVERROR(ENOMEM);
5757 filtergraphs[nb_filtergraphs - 1]->index = nb_filtergraphs - 1;
5758 filtergraphs[nb_filtergraphs - 1]->graph_desc = arg;
5762 #define OFFSET(x) offsetof(OptionsContext, x)
5763 static const OptionDef options[] = {
5765 #include "cmdutils_common_opts.h"
5766 { "f", HAS_ARG | OPT_STRING | OPT_OFFSET, {.off = OFFSET(format)}, "force format", "fmt" },
5767 { "i", HAS_ARG | OPT_FUNC2, {(void*)opt_input_file}, "input file name", "filename" },
5768 { "y", OPT_BOOL, {(void*)&file_overwrite}, "overwrite output files" },
5769 { "n", OPT_BOOL, {(void*)&no_file_overwrite}, "do not overwrite output files" },
5770 { "c", HAS_ARG | OPT_STRING | OPT_SPEC, {.off = OFFSET(codec_names)}, "codec name", "codec" },
5771 { "codec", HAS_ARG | OPT_STRING | OPT_SPEC, {.off = OFFSET(codec_names)}, "codec name", "codec" },
5772 { "pre", HAS_ARG | OPT_STRING | OPT_SPEC, {.off = OFFSET(presets)}, "preset name", "preset" },
5773 { "map", HAS_ARG | OPT_EXPERT | OPT_FUNC2, {(void*)opt_map}, "set input stream mapping", "[-]input_file_id[:stream_specifier][,sync_file_id[:stream_specifier]]" },
5774 { "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]" },
5775 { "map_metadata", HAS_ARG | OPT_STRING | OPT_SPEC, {.off = OFFSET(metadata_map)}, "set metadata information of outfile from infile",
5776 "outfile[,metadata]:infile[,metadata]" },
5777 { "map_chapters", OPT_INT | HAS_ARG | OPT_EXPERT | OPT_OFFSET, {.off = OFFSET(chapters_input_file)}, "set chapters mapping", "input_file_index" },
5778 { "t", HAS_ARG | OPT_TIME | OPT_OFFSET, {.off = OFFSET(recording_time)}, "record or transcode \"duration\" seconds of audio/video", "duration" },
5779 { "fs", HAS_ARG | OPT_INT64 | OPT_OFFSET, {.off = OFFSET(limit_filesize)}, "set the limit file size in bytes", "limit_size" }, //
5780 { "ss", HAS_ARG | OPT_TIME | OPT_OFFSET, {.off = OFFSET(start_time)}, "set the start time offset", "time_off" },
5781 { "itsoffset", HAS_ARG | OPT_TIME | OPT_OFFSET, {.off = OFFSET(input_ts_offset)}, "set the input ts offset", "time_off" },
5782 { "itsscale", HAS_ARG | OPT_DOUBLE | OPT_SPEC, {.off = OFFSET(ts_scale)}, "set the input ts scale", "scale" },
5783 { "timestamp", HAS_ARG | OPT_FUNC2, {(void*)opt_recording_timestamp}, "set the recording timestamp ('now' to set the current time)", "time" },
5784 { "metadata", HAS_ARG | OPT_STRING | OPT_SPEC, {.off = OFFSET(metadata)}, "add metadata", "string=string" },
5785 { "dframes", HAS_ARG | OPT_FUNC2, {(void*)opt_data_frames}, "set the number of data frames to record", "number" },
5786 { "benchmark", OPT_BOOL | OPT_EXPERT, {(void*)&do_benchmark},
5787 "add timings for benchmarking" },
5788 { "benchmark_all", OPT_BOOL | OPT_EXPERT, {(void*)&do_benchmark_all},
5789 "add timings for each task" },
5790 { "timelimit", HAS_ARG, {(void*)opt_timelimit}, "set max runtime in seconds", "limit" },
5791 { "dump", OPT_BOOL | OPT_EXPERT, {(void*)&do_pkt_dump},
5792 "dump each input packet" },
5793 { "hex", OPT_BOOL | OPT_EXPERT, {(void*)&do_hex_dump},
5794 "when dumping packets, also dump the payload" },
5795 { "re", OPT_BOOL | OPT_EXPERT | OPT_OFFSET, {.off = OFFSET(rate_emu)}, "read input at native frame rate", "" },
5796 { "target", HAS_ARG | OPT_FUNC2, {(void*)opt_target}, "specify target file type (\"vcd\", \"svcd\", \"dvd\", \"dv\", \"dv50\", \"pal-vcd\", \"ntsc-svcd\", ...)", "type" },
5797 { "vsync", HAS_ARG | OPT_EXPERT, {(void*)opt_vsync}, "video sync method", "" },
5798 { "async", HAS_ARG | OPT_INT | OPT_EXPERT, {(void*)&audio_sync_method}, "audio sync method", "" },
5799 { "adrift_threshold", HAS_ARG | OPT_FLOAT | OPT_EXPERT, {(void*)&audio_drift_threshold}, "audio drift threshold", "threshold" },
5800 { "copyts", OPT_BOOL | OPT_EXPERT, {(void*)©_ts}, "copy timestamps" },
5801 { "copytb", HAS_ARG | OPT_INT | OPT_EXPERT, {(void*)©_tb}, "copy input stream time base when stream copying", "mode" },
5802 { "shortest", OPT_BOOL | OPT_EXPERT, {(void*)&opt_shortest}, "finish encoding within shortest input" }, //
5803 { "dts_delta_threshold", HAS_ARG | OPT_FLOAT | OPT_EXPERT, {(void*)&dts_delta_threshold}, "timestamp discontinuity delta threshold", "threshold" },
5804 { "dts_error_threshold", HAS_ARG | OPT_FLOAT | OPT_EXPERT, {(void*)&dts_error_threshold}, "timestamp error delta threshold", "threshold" },
5805 { "xerror", OPT_BOOL, {(void*)&exit_on_error}, "exit on error", "error" },
5806 { "copyinkf", OPT_BOOL | OPT_EXPERT | OPT_SPEC, {.off = OFFSET(copy_initial_nonkeyframes)}, "copy initial non-keyframes" },
5807 { "frames", OPT_INT64 | HAS_ARG | OPT_SPEC, {.off = OFFSET(max_frames)}, "set the number of frames to record", "number" },
5808 { "tag", OPT_STRING | HAS_ARG | OPT_SPEC, {.off = OFFSET(codec_tags)}, "force codec tag/fourcc", "fourcc/tag" },
5809 { "q", HAS_ARG | OPT_EXPERT | OPT_DOUBLE | OPT_SPEC, {.off = OFFSET(qscale)}, "use fixed quality scale (VBR)", "q" },
5810 { "qscale", HAS_ARG | OPT_EXPERT | OPT_FUNC2, {(void*)opt_qscale}, "use fixed quality scale (VBR)", "q" },
5811 { "profile", HAS_ARG | OPT_EXPERT | OPT_FUNC2, {(void*)opt_profile}, "set profile", "profile" },
5812 { "filter", HAS_ARG | OPT_STRING | OPT_SPEC, {.off = OFFSET(filters)}, "set stream filterchain", "filter_list" },
5813 { "filter_complex", HAS_ARG | OPT_EXPERT, {(void*)opt_filter_complex}, "create a complex filtergraph", "graph_description" },
5814 { "stats", OPT_BOOL, {&print_stats}, "print progress report during encoding", },
5815 { "attach", HAS_ARG | OPT_FUNC2, {(void*)opt_attach}, "add an attachment to the output file", "filename" },
5816 { "dump_attachment", HAS_ARG | OPT_STRING | OPT_SPEC, {.off = OFFSET(dump_attachment)}, "extract an attachment into a file", "filename" },
5817 { "debug_ts", OPT_BOOL | OPT_EXPERT, {&debug_ts}, "print timestamp debugging info" },
5820 { "vframes", HAS_ARG | OPT_VIDEO | OPT_FUNC2, {(void*)opt_video_frames}, "set the number of video frames to record", "number" },
5821 { "r", HAS_ARG | OPT_VIDEO | OPT_STRING | OPT_SPEC, {.off = OFFSET(frame_rates)}, "set frame rate (Hz value, fraction or abbreviation)", "rate" },
5822 { "s", HAS_ARG | OPT_VIDEO | OPT_STRING | OPT_SPEC, {.off = OFFSET(frame_sizes)}, "set frame size (WxH or abbreviation)", "size" },
5823 { "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" },
5824 { "pix_fmt", HAS_ARG | OPT_EXPERT | OPT_VIDEO | OPT_STRING | OPT_SPEC, {.off = OFFSET(frame_pix_fmts)}, "set pixel format", "format" },
5825 { "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" },
5826 { "croptop", HAS_ARG | OPT_VIDEO, {(void*)opt_frame_crop}, "Removed, use the crop filter instead", "size" },
5827 { "cropbottom", HAS_ARG | OPT_VIDEO, {(void*)opt_frame_crop}, "Removed, use the crop filter instead", "size" },
5828 { "cropleft", HAS_ARG | OPT_VIDEO, {(void*)opt_frame_crop}, "Removed, use the crop filter instead", "size" },
5829 { "cropright", HAS_ARG | OPT_VIDEO, {(void*)opt_frame_crop}, "Removed, use the crop filter instead", "size" },
5830 { "padtop", HAS_ARG | OPT_VIDEO, {(void*)opt_pad}, "Removed, use the pad filter instead", "size" },
5831 { "padbottom", HAS_ARG | OPT_VIDEO, {(void*)opt_pad}, "Removed, use the pad filter instead", "size" },
5832 { "padleft", HAS_ARG | OPT_VIDEO, {(void*)opt_pad}, "Removed, use the pad filter instead", "size" },
5833 { "padright", HAS_ARG | OPT_VIDEO, {(void*)opt_pad}, "Removed, use the pad filter instead", "size" },
5834 { "padcolor", HAS_ARG | OPT_VIDEO, {(void*)opt_pad}, "Removed, use the pad filter instead", "color" },
5835 { "intra", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, {(void*)&intra_only}, "deprecated use -g 1"},
5836 { "vn", OPT_BOOL | OPT_VIDEO | OPT_OFFSET, {.off = OFFSET(video_disable)}, "disable video" },
5837 { "vdt", OPT_INT | HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)&video_discard}, "discard threshold", "n" },
5838 { "rc_override", HAS_ARG | OPT_EXPERT | OPT_VIDEO | OPT_STRING | OPT_SPEC, {.off = OFFSET(rc_overrides)}, "rate control override for specific intervals", "override" },
5839 { "vcodec", HAS_ARG | OPT_VIDEO | OPT_FUNC2, {(void*)opt_video_codec}, "force video codec ('copy' to copy stream)", "codec" },
5840 { "sameq", OPT_BOOL | OPT_VIDEO, {(void*)&same_quant}, "use same quantizer as source (implies VBR)" },
5841 { "same_quant", OPT_BOOL | OPT_VIDEO, {(void*)&same_quant},
5842 "use same quantizer as source (implies VBR)" },
5843 { "pass", HAS_ARG | OPT_VIDEO, {(void*)opt_pass}, "select the pass number (1 or 2)", "n" },
5844 { "passlogfile", HAS_ARG | OPT_VIDEO, {(void*)&opt_passlogfile}, "select two pass log file name prefix", "prefix" },
5845 { "deinterlace", OPT_EXPERT | OPT_VIDEO, {(void*)opt_deinterlace},
5846 "this option is deprecated, use the yadif filter instead" },
5847 { "psnr", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, {(void*)&do_psnr}, "calculate PSNR of compressed frames" },
5848 { "vstats", OPT_EXPERT | OPT_VIDEO, {(void*)&opt_vstats}, "dump video coding statistics to file" },
5849 { "vstats_file", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_vstats_file}, "dump video coding statistics to file", "file" },
5850 { "vf", HAS_ARG | OPT_VIDEO | OPT_FUNC2, {(void*)opt_video_filters}, "video filters", "filter list" },
5851 { "intra_matrix", HAS_ARG | OPT_EXPERT | OPT_VIDEO | OPT_STRING | OPT_SPEC, {.off = OFFSET(intra_matrices)}, "specify intra matrix coeffs", "matrix" },
5852 { "inter_matrix", HAS_ARG | OPT_EXPERT | OPT_VIDEO | OPT_STRING | OPT_SPEC, {.off = OFFSET(inter_matrices)}, "specify inter matrix coeffs", "matrix" },
5853 { "top", HAS_ARG | OPT_EXPERT | OPT_VIDEO | OPT_INT| OPT_SPEC, {.off = OFFSET(top_field_first)}, "top=1/bottom=0/auto=-1 field first", "" },
5854 { "dc", OPT_INT | HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)&intra_dc_precision}, "intra_dc_precision", "precision" },
5855 { "vtag", HAS_ARG | OPT_EXPERT | OPT_VIDEO | OPT_FUNC2, {(void*)opt_old2new}, "force video tag/fourcc", "fourcc/tag" },
5856 { "qphist", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, { (void *)&qp_hist }, "show QP histogram" },
5857 { "force_fps", OPT_BOOL | OPT_EXPERT | OPT_VIDEO | OPT_SPEC, {.off = OFFSET(force_fps)}, "force the selected framerate, disable the best supported framerate selection" },
5858 { "streamid", HAS_ARG | OPT_EXPERT | OPT_FUNC2, {(void*)opt_streamid}, "set the value of an outfile streamid", "streamIndex:value" },
5859 { "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" },
5860 { "b", HAS_ARG | OPT_VIDEO | OPT_FUNC2, {(void*)opt_bitrate}, "video bitrate (please use -b:v)", "bitrate" },
5863 { "aframes", HAS_ARG | OPT_AUDIO | OPT_FUNC2, {(void*)opt_audio_frames}, "set the number of audio frames to record", "number" },
5864 { "aq", HAS_ARG | OPT_AUDIO | OPT_FUNC2, {(void*)opt_audio_qscale}, "set audio quality (codec-specific)", "quality", },
5865 { "ar", HAS_ARG | OPT_AUDIO | OPT_INT | OPT_SPEC, {.off = OFFSET(audio_sample_rate)}, "set audio sampling rate (in Hz)", "rate" },
5866 { "ac", HAS_ARG | OPT_AUDIO | OPT_INT | OPT_SPEC, {.off = OFFSET(audio_channels)}, "set number of audio channels", "channels" },
5867 { "an", OPT_BOOL | OPT_AUDIO | OPT_OFFSET, {.off = OFFSET(audio_disable)}, "disable audio" },
5868 { "acodec", HAS_ARG | OPT_AUDIO | OPT_FUNC2, {(void*)opt_audio_codec}, "force audio codec ('copy' to copy stream)", "codec" },
5869 { "atag", HAS_ARG | OPT_EXPERT | OPT_AUDIO | OPT_FUNC2, {(void*)opt_old2new}, "force audio tag/fourcc", "fourcc/tag" },
5870 { "vol", OPT_INT | HAS_ARG | OPT_AUDIO, {(void*)&audio_volume}, "change audio volume (256=normal)" , "volume" }, //
5871 { "sample_fmt", HAS_ARG | OPT_EXPERT | OPT_AUDIO | OPT_SPEC | OPT_STRING, {.off = OFFSET(sample_fmts)}, "set sample format", "format" },
5872 { "rmvol", HAS_ARG | OPT_AUDIO | OPT_FLOAT | OPT_SPEC, {.off = OFFSET(rematrix_volume)}, "rematrix volume (as factor)", "volume" },
5873 { "channel_layout", HAS_ARG | OPT_EXPERT | OPT_AUDIO | OPT_FUNC2, {(void*)opt_channel_layout}, "set channel layout", "layout" },
5875 /* subtitle options */
5876 { "sn", OPT_BOOL | OPT_SUBTITLE | OPT_OFFSET, {.off = OFFSET(subtitle_disable)}, "disable subtitle" },
5877 { "scodec", HAS_ARG | OPT_SUBTITLE | OPT_FUNC2, {(void*)opt_subtitle_codec}, "force subtitle codec ('copy' to copy stream)", "codec" },
5878 { "stag", HAS_ARG | OPT_EXPERT | OPT_SUBTITLE | OPT_FUNC2, {(void*)opt_old2new}, "force subtitle tag/fourcc", "fourcc/tag" },
5881 { "vc", HAS_ARG | OPT_EXPERT | OPT_VIDEO | OPT_GRAB, {(void*)opt_video_channel}, "deprecated, use -channel", "channel" },
5882 { "tvstd", HAS_ARG | OPT_EXPERT | OPT_VIDEO | OPT_GRAB, {(void*)opt_video_standard}, "deprecated, use -standard", "standard" },
5883 { "isync", OPT_BOOL | OPT_EXPERT | OPT_GRAB, {(void*)&input_sync}, "sync read on input", "" },
5886 { "muxdelay", OPT_FLOAT | HAS_ARG | OPT_EXPERT | OPT_OFFSET, {.off = OFFSET(mux_max_delay)}, "set the maximum demux-decode delay", "seconds" },
5887 { "muxpreload", OPT_FLOAT | HAS_ARG | OPT_EXPERT | OPT_OFFSET, {.off = OFFSET(mux_preload)}, "set the initial demux-decode delay", "seconds" },
5889 { "bsf", HAS_ARG | OPT_STRING | OPT_SPEC, {.off = OFFSET(bitstream_filters)}, "A comma-separated list of bitstream filters", "bitstream_filters" },
5890 { "absf", HAS_ARG | OPT_AUDIO | OPT_EXPERT| OPT_FUNC2, {(void*)opt_old2new}, "deprecated", "audio bitstream_filters" },
5891 { "vbsf", HAS_ARG | OPT_VIDEO | OPT_EXPERT| OPT_FUNC2, {(void*)opt_old2new}, "deprecated", "video bitstream_filters" },
5893 { "apre", HAS_ARG | OPT_AUDIO | OPT_EXPERT| OPT_FUNC2, {(void*)opt_preset}, "set the audio options to the indicated preset", "preset" },
5894 { "vpre", HAS_ARG | OPT_VIDEO | OPT_EXPERT| OPT_FUNC2, {(void*)opt_preset}, "set the video options to the indicated preset", "preset" },
5895 { "spre", HAS_ARG | OPT_SUBTITLE | OPT_EXPERT| OPT_FUNC2, {(void*)opt_preset}, "set the subtitle options to the indicated preset", "preset" },
5896 { "fpre", HAS_ARG | OPT_EXPERT| OPT_FUNC2, {(void*)opt_preset}, "set options from indicated preset file", "filename" },
5897 /* data codec support */
5898 { "dcodec", HAS_ARG | OPT_DATA | OPT_FUNC2, {(void*)opt_data_codec}, "force data codec ('copy' to copy stream)", "codec" },
5899 { "dn", OPT_BOOL | OPT_VIDEO | OPT_OFFSET, {.off = OFFSET(data_disable)}, "disable data" },
5901 { "default", HAS_ARG | OPT_AUDIO | OPT_VIDEO | OPT_EXPERT, {(void*)opt_default}, "generic catch all option", "" },
5905 int main(int argc, char **argv)
5907 OptionsContext o = { 0 };
5910 reset_options(&o, 0);
5912 av_log_set_flags(AV_LOG_SKIP_REPEATED);
5913 parse_loglevel(argc, argv, options);
5915 if(argc>1 && !strcmp(argv[1], "-d")){
5917 av_log_set_callback(log_callback_null);
5922 avcodec_register_all();
5924 avdevice_register_all();
5926 avfilter_register_all();
5928 avformat_network_init();
5930 show_banner(argc, argv, options);
5934 parse_cpuflags(argc, argv, options);
5937 parse_options(&o, argc, argv, options, opt_output_file);
5939 if (nb_output_files <= 0 && nb_input_files == 0) {
5941 av_log(NULL, AV_LOG_WARNING, "Use -h to get full help or, even better, run 'man %s'\n", program_name);
5945 /* file converter / grab */
5946 if (nb_output_files <= 0) {
5947 av_log(NULL, AV_LOG_FATAL, "At least one output file must be specified\n");
5951 if (nb_input_files == 0) {
5952 av_log(NULL, AV_LOG_FATAL, "At least one input file must be specified\n");
5956 current_time = ti = getutime();
5957 if (transcode() < 0)
5959 ti = getutime() - ti;
5961 int maxrss = getmaxrss() / 1024;
5962 printf("bench: utime=%0.3fs maxrss=%ikB\n", ti / 1000000.0, maxrss);