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"
62 # include "libavfilter/vsrc_buffer.h"
64 #if HAVE_SYS_RESOURCE_H
65 #include <sys/types.h>
67 #include <sys/resource.h>
68 #elif HAVE_GETPROCESSTIMES
71 #if HAVE_GETPROCESSMEMORYINFO
77 #include <sys/select.h>
82 #include <sys/ioctl.h>
92 #include "libavutil/avassert.h"
95 #define VSYNC_PASSTHROUGH 0
98 #define VSYNC_DROP 0xff
100 const char program_name[] = "ffmpeg";
101 const int program_birth_year = 2000;
103 /* select an input stream for an output stream */
104 typedef struct StreamMap {
105 int disabled; /** 1 is this mapping is disabled by a negative map */
109 int sync_stream_index;
110 char *linklabel; /** name of an output link, for mapping lavfi outputs */
114 int file_idx, stream_idx, channel_idx; // input
115 int ofile_idx, ostream_idx; // output
118 static const OptionDef options[];
120 #define MAX_STREAMS 1024 /* arbitrary sanity check value */
122 static int frame_bits_per_raw_sample = 0;
123 static int video_discard = 0;
124 static int same_quant = 0;
125 static int do_deinterlace = 0;
126 static int intra_dc_precision = 8;
127 static int qp_hist = 0;
128 static int intra_only = 0;
129 static const char *video_codec_name = NULL;
130 static const char *audio_codec_name = NULL;
131 static const char *subtitle_codec_name = NULL;
133 static int file_overwrite = 0;
134 static int no_file_overwrite = 0;
135 static int do_benchmark = 0;
136 static int do_benchmark_all = 0;
137 static int do_hex_dump = 0;
138 static int do_pkt_dump = 0;
139 static int do_psnr = 0;
140 static int do_pass = 0;
141 static const char *pass_logfilename_prefix;
142 static int video_sync_method = VSYNC_AUTO;
143 static int audio_sync_method = 0;
144 static float audio_drift_threshold = 0.1;
145 static int copy_ts = 0;
146 static int copy_tb = -1;
147 static int opt_shortest = 0;
148 static char *vstats_filename;
149 static FILE *vstats_file;
151 static int audio_volume = 256;
153 static int exit_on_error = 0;
154 static int using_stdin = 0;
155 static int run_as_daemon = 0;
156 static volatile int received_nb_signals = 0;
157 static int64_t video_size = 0;
158 static int64_t audio_size = 0;
159 static int64_t extra_size = 0;
160 static int nb_frames_dup = 0;
161 static int nb_frames_drop = 0;
162 static int input_sync;
164 static float dts_delta_threshold = 10;
165 static float dts_error_threshold = 3600*30;
167 static int print_stats = 1;
168 static int debug_ts = 0;
169 static int current_time;
171 static uint8_t *audio_buf;
172 static unsigned int allocated_audio_buf_size;
173 static uint8_t *async_buf;
174 static unsigned int allocated_async_buf_size;
176 #define DEFAULT_PASS_LOGFILENAME_PREFIX "ffmpeg2pass"
178 typedef struct InputFilter {
179 AVFilterContext *filter;
180 struct InputStream *ist;
181 struct FilterGraph *graph;
184 typedef struct OutputFilter {
185 AVFilterContext *filter;
186 struct OutputStream *ost;
187 struct FilterGraph *graph;
189 /* temporary storage until stream maps are processed */
190 AVFilterInOut *out_tmp;
193 typedef struct FilterGraph {
195 const char *graph_desc;
197 AVFilterGraph *graph;
199 InputFilter **inputs;
201 OutputFilter **outputs;
205 typedef struct FrameBuffer {
211 enum PixelFormat pix_fmt;
214 struct InputStream *ist;
215 struct FrameBuffer *next;
218 typedef struct InputStream {
221 int discard; /* true if stream data should be discarded */
222 int decoding_needed; /* true if the packets must be decoded in 'raw_fifo' */
224 AVFrame *decoded_frame;
226 int64_t start; /* time when read started */
227 /* predicted dts of the next packet read for this stream or (when there are
228 * several frames in a packet) of the next frame in current packet */
230 /* dts of the last packet read for this stream */
233 int64_t next_pts; ///< synthetic pts for the next decode frame
234 int64_t pts; ///< current pts of the decoded frame
236 int is_start; /* is 1 at the start and after a discontinuity */
238 int showed_multi_packet_warning;
243 int resample_pix_fmt;
245 /* a pool of free buffers for decoded data */
246 FrameBuffer *buffer_pool;
249 /* decoded data from this stream goes into all those filters
250 * currently video only */
251 InputFilter **filters;
255 typedef struct InputFile {
256 AVFormatContext *ctx;
257 int eof_reached; /* true if eof reached */
258 int ist_index; /* index of first stream in input_streams */
259 int buffer_size; /* current total buffer size */
261 int nb_streams; /* number of stream that ffmpeg is aware of; may be different
262 from ctx.nb_streams if new streams appear during av_read_frame() */
266 typedef struct OutputStream {
267 int file_index; /* file index */
268 int index; /* stream index in the output file */
269 int source_index; /* InputStream index */
270 AVStream *st; /* stream in the output file */
271 int encoding_needed; /* true if encoding needed for this stream */
273 /* input pts and corresponding output pts
275 struct InputStream *sync_ist; /* input stream to sync against */
276 int64_t sync_opts; /* output frame counter, could be changed to some true timestamp */ // FIXME look at frame_number
277 AVBitStreamFilterContext *bitstream_filters;
280 AVFrame *output_frame;
281 AVFrame *filtered_frame;
284 AVRational frame_rate;
288 float frame_aspect_ratio;
291 /* forced key frames */
292 int64_t *forced_kf_pts;
298 int audio_channels_map[SWR_CH_MAX]; ///< list of the channels id to pick from the source stream
299 int audio_channels_mapped; ///< number of channels in audio_channels_map
300 int resample_sample_fmt;
301 int resample_channels;
302 uint64_t resample_channel_layout;
303 int resample_sample_rate;
304 float rematrix_volume;
305 AVFifoBuffer *fifo; /* for compression: one audio fifo per codec */
310 OutputFilter *filter;
314 int64_t swr_dither_method;
315 double swr_dither_scale;
317 int is_past_recording_time;
319 const char *attachment_filename;
320 int copy_initial_nonkeyframes;
322 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 const enum PixelFormat *choose_pixel_fmts(OutputStream *ost)
710 if (ost->st->codec->pix_fmt != PIX_FMT_NONE) {
711 ost->pix_fmts[0] = choose_pixel_fmt(ost->st, ost->enc, ost->st->codec->pix_fmt);
712 return ost->pix_fmts;
713 } else if (ost->enc->pix_fmts) {
714 if (ost->st->codec->strict_std_compliance <= FF_COMPLIANCE_UNOFFICIAL) {
715 if (ost->st->codec->codec_id == CODEC_ID_MJPEG) {
716 return (const enum PixelFormat[]) { PIX_FMT_YUVJ420P, PIX_FMT_YUVJ422P, PIX_FMT_YUV420P, PIX_FMT_YUV422P, PIX_FMT_NONE };
717 } else if (ost->st->codec->codec_id == CODEC_ID_LJPEG) {
718 return (const enum PixelFormat[]) { PIX_FMT_YUVJ420P, PIX_FMT_YUVJ422P, PIX_FMT_YUVJ444P, PIX_FMT_YUV420P,
719 PIX_FMT_YUV422P, PIX_FMT_YUV444P, PIX_FMT_BGRA, PIX_FMT_NONE };
722 return ost->enc->pix_fmts;
727 static int configure_video_filters(FilterGraph *fg)
729 InputStream *ist = fg->inputs[0]->ist;
730 OutputStream *ost = fg->outputs[0]->ost;
731 AVFilterContext *last_filter, *filter;
732 /** filter graph containing all filters including input & output */
733 AVCodecContext *codec = ost->st->codec;
734 enum PixelFormat *pix_fmts = choose_pixel_fmts(ost);
735 AVBufferSinkParams *buffersink_params = av_buffersink_params_alloc();
736 AVRational sample_aspect_ratio;
740 avfilter_graph_free(&fg->graph);
741 fg->graph = avfilter_graph_alloc();
743 return AVERROR(ENOMEM);
745 if (ist->st->sample_aspect_ratio.num) {
746 sample_aspect_ratio = ist->st->sample_aspect_ratio;
748 sample_aspect_ratio = ist->st->codec->sample_aspect_ratio;
750 snprintf(args, 255, "%d:%d:%d:%d:%d:%d:%d:flags=%d", ist->st->codec->width,
751 ist->st->codec->height, ist->st->codec->pix_fmt, 1, AV_TIME_BASE,
752 sample_aspect_ratio.num, sample_aspect_ratio.den, SWS_BILINEAR + ((ist->st->codec->flags&CODEC_FLAG_BITEXACT) ? SWS_BITEXACT:0));
754 ret = avfilter_graph_create_filter(&fg->inputs[0]->filter,
755 avfilter_get_by_name("buffer"),
756 "src", args, NULL, fg->graph);
760 #if FF_API_OLD_VSINK_API
761 ret = avfilter_graph_create_filter(&fg->outputs[0]->filter, avfilter_get_by_name("buffersink"),
762 "out", NULL, pix_fmts, fg->graph);
764 buffersink_params->pixel_fmts = pix_fmts;
765 ret = avfilter_graph_create_filter(&fg->outputs[0]->filter, avfilter_get_by_name("buffersink"),
766 "out", NULL, buffersink_params, fg->graph);
768 av_freep(&buffersink_params);
772 last_filter = fg->inputs[0]->filter;
774 if (codec->width || codec->height) {
775 snprintf(args, 255, "%d:%d:flags=0x%X",
778 (unsigned)ost->sws_flags);
779 if ((ret = avfilter_graph_create_filter(&filter, avfilter_get_by_name("scale"),
780 NULL, args, NULL, fg->graph)) < 0)
782 if ((ret = avfilter_link(last_filter, 0, filter, 0)) < 0)
784 last_filter = filter;
787 snprintf(args, sizeof(args), "flags=0x%X", (unsigned)ost->sws_flags);
788 fg->graph->scale_sws_opts = av_strdup(args);
791 AVFilterInOut *outputs = avfilter_inout_alloc();
792 AVFilterInOut *inputs = avfilter_inout_alloc();
794 outputs->name = av_strdup("in");
795 outputs->filter_ctx = last_filter;
796 outputs->pad_idx = 0;
797 outputs->next = NULL;
799 inputs->name = av_strdup("out");
800 inputs->filter_ctx = fg->outputs[0]->filter;
804 if ((ret = avfilter_graph_parse(fg->graph, ost->avfilter, &inputs, &outputs, NULL)) < 0)
806 av_freep(&ost->avfilter);
808 if ((ret = avfilter_link(last_filter, 0, fg->outputs[0]->filter, 0)) < 0)
812 if ((ret = avfilter_graph_config(fg->graph, NULL)) < 0)
815 ost->filter = fg->outputs[0];
820 static FilterGraph *init_simple_filtergraph(InputStream *ist, OutputStream *ost)
822 FilterGraph *fg = av_mallocz(sizeof(*fg));
826 fg->index = nb_filtergraphs;
828 fg->outputs = grow_array(fg->outputs, sizeof(*fg->outputs), &fg->nb_outputs,
830 if (!(fg->outputs[0] = av_mallocz(sizeof(*fg->outputs[0]))))
832 fg->outputs[0]->ost = ost;
833 fg->outputs[0]->graph = fg;
835 fg->inputs = grow_array(fg->inputs, sizeof(*fg->inputs), &fg->nb_inputs,
837 if (!(fg->inputs[0] = av_mallocz(sizeof(*fg->inputs[0]))))
839 fg->inputs[0]->ist = ist;
840 fg->inputs[0]->graph = fg;
842 ist->filters = grow_array(ist->filters, sizeof(*ist->filters),
843 &ist->nb_filters, ist->nb_filters + 1);
844 ist->filters[ist->nb_filters - 1] = fg->inputs[0];
846 filtergraphs = grow_array(filtergraphs, sizeof(*filtergraphs),
847 &nb_filtergraphs, nb_filtergraphs + 1);
848 filtergraphs[nb_filtergraphs - 1] = fg;
853 static void init_input_filter(FilterGraph *fg, AVFilterInOut *in)
856 enum AVMediaType type = in->filter_ctx->input_pads[in->pad_idx].type;
859 // TODO: support other filter types
860 if (type != AVMEDIA_TYPE_VIDEO) {
861 av_log(NULL, AV_LOG_FATAL, "Only video filters supported currently.\n");
869 int file_idx = strtol(in->name, &p, 0);
871 if (file_idx < 0 || file_idx >= nb_input_files) {
872 av_log(NULL, AV_LOG_FATAL, "Invalid file index %d in filtergraph description %s.\n",
873 file_idx, fg->graph_desc);
876 s = input_files[file_idx]->ctx;
878 for (i = 0; i < s->nb_streams; i++) {
879 if (s->streams[i]->codec->codec_type != type)
881 if (check_stream_specifier(s, s->streams[i], *p == ':' ? p + 1 : p) == 1) {
887 av_log(NULL, AV_LOG_FATAL, "Stream specifier '%s' in filtergraph description %s "
888 "matches no streams.\n", p, fg->graph_desc);
891 ist = input_streams[input_files[file_idx]->ist_index + st->index];
893 /* find the first unused stream of corresponding type */
894 for (i = 0; i < nb_input_streams; i++) {
895 ist = input_streams[i];
896 if (ist->st->codec->codec_type == type && ist->discard)
899 if (i == nb_input_streams) {
900 av_log(NULL, AV_LOG_FATAL, "Cannot find a matching stream for "
901 "unlabeled input pad %d on filter %s", in->pad_idx,
902 in->filter_ctx->name);
907 ist->decoding_needed = 1;
908 ist->st->discard = AVDISCARD_NONE;
910 fg->inputs = grow_array(fg->inputs, sizeof(*fg->inputs),
911 &fg->nb_inputs, fg->nb_inputs + 1);
912 if (!(fg->inputs[fg->nb_inputs - 1] = av_mallocz(sizeof(*fg->inputs[0]))))
914 fg->inputs[fg->nb_inputs - 1]->ist = ist;
915 fg->inputs[fg->nb_inputs - 1]->graph = fg;
917 ist->filters = grow_array(ist->filters, sizeof(*ist->filters),
918 &ist->nb_filters, ist->nb_filters + 1);
919 ist->filters[ist->nb_filters - 1] = fg->inputs[fg->nb_inputs - 1];
922 static int configure_output_filter(FilterGraph *fg, OutputFilter *ofilter, AVFilterInOut *out)
924 AVCodecContext *codec = ofilter->ost->st->codec;
925 AVFilterContext *last_filter = out->filter_ctx;
926 int pad_idx = out->pad_idx;
928 enum PixelFormat *pix_fmts = choose_pixel_fmts(ofilter->ost);
929 AVBufferSinkParams *buffersink_params = av_buffersink_params_alloc();
931 #if FF_API_OLD_VSINK_API
932 ret = avfilter_graph_create_filter(&ofilter->filter, avfilter_get_by_name("buffersink"),
933 "out", NULL, pix_fmts, fg->graph);
935 buffersink_params->pixel_fmts = pix_fmts;
936 ret = avfilter_graph_create_filter(&ofilter->filter, avfilter_get_by_name("buffersink"),
937 "out", NULL, buffersink_params, fg->graph);
939 av_freep(&buffersink_params);
944 if (codec->width || codec->height) {
946 snprintf(args, sizeof(args), "%d:%d:flags=0x%X",
949 (unsigned)ofilter->ost->sws_flags);
950 if ((ret = avfilter_graph_create_filter(&last_filter, avfilter_get_by_name("scale"),
951 NULL, args, NULL, fg->graph)) < 0)
953 if ((ret = avfilter_link(out->filter_ctx, out->pad_idx, last_filter, 0)) < 0)
958 if ((ret = avfilter_link(last_filter, pad_idx, ofilter->filter, 0)) < 0)
964 static int configure_complex_filter(FilterGraph *fg)
966 AVFilterInOut *inputs, *outputs, *cur;
967 int ret, i, init = !fg->graph;
969 avfilter_graph_free(&fg->graph);
970 if (!(fg->graph = avfilter_graph_alloc()))
971 return AVERROR(ENOMEM);
973 if ((ret = avfilter_graph_parse2(fg->graph, fg->graph_desc, &inputs, &outputs)) < 0)
976 for (cur = inputs; init && cur; cur = cur->next)
977 init_input_filter(fg, cur);
979 for (cur = inputs, i = 0; cur; cur = cur->next, i++) {
980 InputFilter *ifilter = fg->inputs[i];
981 InputStream *ist = ifilter->ist;
985 sar = ist->st->sample_aspect_ratio.num ? ist->st->sample_aspect_ratio :
986 ist->st->codec->sample_aspect_ratio;
987 snprintf(args, sizeof(args), "%d:%d:%d:%d:%d:%d:%d", ist->st->codec->width,
988 ist->st->codec->height, ist->st->codec->pix_fmt, 1, AV_TIME_BASE,
991 if ((ret = avfilter_graph_create_filter(&ifilter->filter,
992 avfilter_get_by_name("buffer"), cur->name,
993 args, NULL, fg->graph)) < 0)
995 if ((ret = avfilter_link(ifilter->filter, 0,
996 cur->filter_ctx, cur->pad_idx)) < 0)
999 avfilter_inout_free(&inputs);
1002 /* we already know the mappings between lavfi outputs and output streams,
1003 * so we can finish the setup */
1004 for (cur = outputs, i = 0; cur; cur = cur->next, i++)
1005 configure_output_filter(fg, fg->outputs[i], cur);
1006 avfilter_inout_free(&outputs);
1008 if ((ret = avfilter_graph_config(fg->graph, NULL)) < 0)
1011 /* wait until output mappings are processed */
1012 for (cur = outputs; cur;) {
1013 fg->outputs = grow_array(fg->outputs, sizeof(*fg->outputs),
1014 &fg->nb_outputs, fg->nb_outputs + 1);
1015 if (!(fg->outputs[fg->nb_outputs - 1] = av_mallocz(sizeof(*fg->outputs[0]))))
1017 fg->outputs[fg->nb_outputs - 1]->graph = fg;
1018 fg->outputs[fg->nb_outputs - 1]->out_tmp = cur;
1020 fg->outputs[fg->nb_outputs - 1]->out_tmp->next = NULL;
1027 static int configure_complex_filters(void)
1031 for (i = 0; i < nb_filtergraphs; i++)
1032 if (!filtergraphs[i]->graph &&
1033 (ret = configure_complex_filter(filtergraphs[i])) < 0)
1038 static int configure_filtergraph(FilterGraph *fg)
1040 return fg->graph_desc ? configure_complex_filter(fg) : configure_video_filters(fg);
1043 static int ist_in_filtergraph(FilterGraph *fg, InputStream *ist)
1046 for (i = 0; i < fg->nb_inputs; i++)
1047 if (fg->inputs[i]->ist == ist)
1052 static void term_exit(void)
1054 av_log(NULL, AV_LOG_QUIET, "%s", "");
1057 tcsetattr (0, TCSANOW, &oldtty);
1061 static volatile int received_sigterm = 0;
1063 static void sigterm_handler(int sig)
1065 received_sigterm = sig;
1066 received_nb_signals++;
1068 if(received_nb_signals > 3)
1072 static void term_init(void)
1078 if (tcgetattr (0, &tty) == 0) {
1083 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
1084 |INLCR|IGNCR|ICRNL|IXON);
1085 tty.c_oflag |= OPOST;
1086 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
1087 tty.c_cflag &= ~(CSIZE|PARENB);
1090 tty.c_cc[VTIME] = 0;
1092 tcsetattr (0, TCSANOW, &tty);
1094 signal(SIGQUIT, sigterm_handler); /* Quit (POSIX). */
1097 avformat_network_deinit();
1099 signal(SIGINT , sigterm_handler); /* Interrupt (ANSI). */
1100 signal(SIGTERM, sigterm_handler); /* Termination (ANSI). */
1102 signal(SIGXCPU, sigterm_handler);
1106 /* read a key without blocking */
1107 static int read_key(void)
1119 n = select(1, &rfds, NULL, NULL, &tv);
1121 n = read(0, &ch, 1);
1128 # if HAVE_PEEKNAMEDPIPE
1130 static HANDLE input_handle;
1133 input_handle = GetStdHandle(STD_INPUT_HANDLE);
1134 is_pipe = !GetConsoleMode(input_handle, &dw);
1137 if (stdin->_cnt > 0) {
1142 /* When running under a GUI, you will end here. */
1143 if (!PeekNamedPipe(input_handle, NULL, 0, NULL, &nchars, NULL))
1160 static int decode_interrupt_cb(void *ctx)
1162 return received_nb_signals > 1;
1165 static const AVIOInterruptCB int_cb = { decode_interrupt_cb, NULL };
1167 void av_noreturn exit_program(int ret)
1171 for (i = 0; i < nb_filtergraphs; i++) {
1172 avfilter_graph_free(&filtergraphs[i]->graph);
1173 for (j = 0; j < filtergraphs[i]->nb_inputs; j++)
1174 av_freep(&filtergraphs[i]->inputs[j]);
1175 av_freep(&filtergraphs[i]->inputs);
1176 for (j = 0; j < filtergraphs[i]->nb_outputs; j++)
1177 av_freep(&filtergraphs[i]->outputs[j]);
1178 av_freep(&filtergraphs[i]->outputs);
1179 av_freep(&filtergraphs[i]);
1181 av_freep(&filtergraphs);
1184 for (i = 0; i < nb_output_files; i++) {
1185 AVFormatContext *s = output_files[i]->ctx;
1186 if (!(s->oformat->flags & AVFMT_NOFILE) && s->pb)
1188 avformat_free_context(s);
1189 av_dict_free(&output_files[i]->opts);
1190 av_freep(&output_files[i]);
1192 for (i = 0; i < nb_output_streams; i++) {
1193 AVBitStreamFilterContext *bsfc = output_streams[i]->bitstream_filters;
1195 AVBitStreamFilterContext *next = bsfc->next;
1196 av_bitstream_filter_close(bsfc);
1199 output_streams[i]->bitstream_filters = NULL;
1201 if (output_streams[i]->output_frame) {
1202 AVFrame *frame = output_streams[i]->output_frame;
1203 if (frame->extended_data != frame->data)
1204 av_freep(&frame->extended_data);
1207 av_freep(&output_streams[i]->filtered_frame);
1208 av_freep(&output_streams[i]);
1210 for (i = 0; i < nb_input_files; i++) {
1211 avformat_close_input(&input_files[i]->ctx);
1212 av_freep(&input_files[i]);
1214 for (i = 0; i < nb_input_streams; i++) {
1215 av_freep(&input_streams[i]->decoded_frame);
1216 av_dict_free(&input_streams[i]->opts);
1217 free_buffer_pool(input_streams[i]);
1218 av_freep(&input_streams[i]->filters);
1219 av_freep(&input_streams[i]);
1223 fclose(vstats_file);
1224 av_free(vstats_filename);
1226 av_freep(&input_streams);
1227 av_freep(&input_files);
1228 av_freep(&output_streams);
1229 av_freep(&output_files);
1232 av_freep(&audio_buf);
1233 allocated_audio_buf_size = 0;
1234 av_freep(&async_buf);
1235 allocated_async_buf_size = 0;
1238 avformat_network_deinit();
1240 if (received_sigterm) {
1241 av_log(NULL, AV_LOG_INFO, "Received signal %d: terminating.\n",
1242 (int) received_sigterm);
1246 exit(ret); /* not all OS-es handle main() return value */
1249 static void assert_avoptions(AVDictionary *m)
1251 AVDictionaryEntry *t;
1252 if ((t = av_dict_get(m, "", NULL, AV_DICT_IGNORE_SUFFIX))) {
1253 av_log(NULL, AV_LOG_FATAL, "Option %s not found.\n", t->key);
1258 static void assert_codec_experimental(AVCodecContext *c, int encoder)
1260 const char *codec_string = encoder ? "encoder" : "decoder";
1262 if (c->codec->capabilities & CODEC_CAP_EXPERIMENTAL &&
1263 c->strict_std_compliance > FF_COMPLIANCE_EXPERIMENTAL) {
1264 av_log(NULL, AV_LOG_FATAL, "%s '%s' is experimental and might produce bad "
1265 "results.\nAdd '-strict experimental' if you want to use it.\n",
1266 codec_string, c->codec->name);
1267 codec = encoder ? avcodec_find_encoder(c->codec->id) : avcodec_find_decoder(c->codec->id);
1268 if (!(codec->capabilities & CODEC_CAP_EXPERIMENTAL))
1269 av_log(NULL, AV_LOG_FATAL, "Or use the non experimental %s '%s'.\n",
1270 codec_string, codec->name);
1275 static void choose_sample_fmt(AVStream *st, AVCodec *codec)
1277 if (codec && codec->sample_fmts) {
1278 const enum AVSampleFormat *p = codec->sample_fmts;
1279 for (; *p != -1; p++) {
1280 if (*p == st->codec->sample_fmt)
1284 if((codec->capabilities & CODEC_CAP_LOSSLESS) && av_get_sample_fmt_name(st->codec->sample_fmt) > av_get_sample_fmt_name(codec->sample_fmts[0]))
1285 av_log(NULL, AV_LOG_ERROR, "Conversion will not be lossless.\n");
1286 if(av_get_sample_fmt_name(st->codec->sample_fmt))
1287 av_log(NULL, AV_LOG_WARNING,
1288 "Incompatible sample format '%s' for codec '%s', auto-selecting format '%s'\n",
1289 av_get_sample_fmt_name(st->codec->sample_fmt),
1291 av_get_sample_fmt_name(codec->sample_fmts[0]));
1292 st->codec->sample_fmt = codec->sample_fmts[0];
1297 static void choose_sample_rate(AVStream *st, AVCodec *codec)
1299 if (codec && codec->supported_samplerates) {
1300 const int *p = codec->supported_samplerates;
1302 int best_dist = INT_MAX;
1304 int dist = abs(st->codec->sample_rate - *p);
1305 if (dist < best_dist) {
1312 const int *sample_rates = codec->supported_samplerates;
1313 av_log(st->codec, AV_LOG_WARNING,
1314 "Requested sampling rate (%dHz) unsupported, using %dHz instead\n"
1315 "Available sampling rates for %s:",
1316 st->codec->sample_rate, best, codec->name);
1317 for (i = 0; sample_rates[i]; i++) {
1318 if (!sample_rates[i + 1]) av_log(st->codec, AV_LOG_WARNING, " and");
1319 else if (i) av_log(st->codec, AV_LOG_WARNING, ",");
1320 av_log(st->codec, AV_LOG_WARNING, " %d", sample_rates[i]);
1322 av_log(st->codec, AV_LOG_WARNING, ".\n");
1324 st->codec->sample_rate = best;
1329 get_sync_ipts(const OutputStream *ost, int64_t pts)
1331 OutputFile *of = output_files[ost->file_index];
1332 return (double)(pts - of->start_time) / AV_TIME_BASE;
1335 static void write_frame(AVFormatContext *s, AVPacket *pkt, OutputStream *ost)
1337 AVBitStreamFilterContext *bsfc = ost->bitstream_filters;
1338 AVCodecContext *avctx = ost->st->codec;
1341 if ((avctx->codec_type == AVMEDIA_TYPE_VIDEO && video_sync_method == VSYNC_DROP) ||
1342 (avctx->codec_type == AVMEDIA_TYPE_AUDIO && audio_sync_method < 0))
1343 pkt->pts = pkt->dts = AV_NOPTS_VALUE;
1346 * Audio encoders may split the packets -- #frames in != #packets out.
1347 * But there is no reordering, so we can limit the number of output packets
1348 * by simply dropping them here.
1349 * Counting encoded video frames needs to be done separately because of
1350 * reordering, see do_video_out()
1352 if (!(avctx->codec_type == AVMEDIA_TYPE_VIDEO && avctx->codec)) {
1353 if (ost->frame_number >= ost->max_frames) {
1354 av_free_packet(pkt);
1357 ost->frame_number++;
1361 AVPacket new_pkt = *pkt;
1362 int a = av_bitstream_filter_filter(bsfc, avctx, NULL,
1363 &new_pkt.data, &new_pkt.size,
1364 pkt->data, pkt->size,
1365 pkt->flags & AV_PKT_FLAG_KEY);
1367 av_free_packet(pkt);
1368 new_pkt.destruct = av_destruct_packet;
1370 av_log(NULL, AV_LOG_ERROR, "Failed to open bitstream filter %s for stream %d with codec %s",
1371 bsfc->filter->name, pkt->stream_index,
1372 avctx->codec ? avctx->codec->name : "copy");
1382 pkt->stream_index = ost->index;
1383 ret = av_interleaved_write_frame(s, pkt);
1385 print_error("av_interleaved_write_frame()", ret);
1390 static void get_default_channel_layouts(OutputStream *ost, InputStream *ist)
1392 char layout_name[256];
1393 AVCodecContext *enc = ost->st->codec;
1394 AVCodecContext *dec = ist->st->codec;
1396 if (dec->channel_layout &&
1397 av_get_channel_layout_nb_channels(dec->channel_layout) != dec->channels) {
1398 av_get_channel_layout_string(layout_name, sizeof(layout_name),
1399 dec->channels, dec->channel_layout);
1400 av_log(NULL, AV_LOG_ERROR, "New channel layout (%s) is invalid\n",
1402 dec->channel_layout = 0;
1404 if (!dec->channel_layout) {
1405 if (enc->channel_layout && dec->channels == enc->channels) {
1406 dec->channel_layout = enc->channel_layout;
1408 dec->channel_layout = av_get_default_channel_layout(dec->channels);
1410 if (!dec->channel_layout) {
1411 av_log(NULL, AV_LOG_FATAL, "Unable to find default channel "
1412 "layout for Input Stream #%d.%d\n", ist->file_index,
1417 av_get_channel_layout_string(layout_name, sizeof(layout_name),
1418 dec->channels, dec->channel_layout);
1419 av_log(NULL, AV_LOG_WARNING, "Guessed Channel Layout for Input Stream "
1420 "#%d.%d : %s\n", ist->file_index, ist->st->index, layout_name);
1422 if (!enc->channel_layout) {
1423 if (dec->channels == enc->channels) {
1424 enc->channel_layout = dec->channel_layout;
1427 enc->channel_layout = av_get_default_channel_layout(enc->channels);
1429 if (!enc->channel_layout) {
1430 av_log(NULL, AV_LOG_FATAL, "Unable to find default channel layout "
1431 "for Output Stream #%d.%d\n", ost->file_index,
1435 av_get_channel_layout_string(layout_name, sizeof(layout_name),
1436 enc->channels, enc->channel_layout);
1437 av_log(NULL, AV_LOG_WARNING, "Guessed Channel Layout for Output Stream "
1438 "#%d.%d : %s\n", ost->file_index, ost->st->index, layout_name);
1442 static void generate_silence(uint8_t* buf, enum AVSampleFormat sample_fmt, size_t size)
1444 int fill_char = 0x00;
1445 if (sample_fmt == AV_SAMPLE_FMT_U8)
1447 memset(buf, fill_char, size);
1450 static int encode_audio_frame(AVFormatContext *s, OutputStream *ost,
1451 const uint8_t *buf, int buf_size)
1453 AVCodecContext *enc = ost->st->codec;
1454 AVFrame *frame = NULL;
1456 int ret, got_packet;
1458 av_init_packet(&pkt);
1462 if (buf && buf_size) {
1463 if (!ost->output_frame) {
1464 ost->output_frame = avcodec_alloc_frame();
1465 if (!ost->output_frame) {
1466 av_log(NULL, AV_LOG_FATAL, "out-of-memory in encode_audio_frame()\n");
1470 frame = ost->output_frame;
1471 if (frame->extended_data != frame->data)
1472 av_freep(&frame->extended_data);
1473 avcodec_get_frame_defaults(frame);
1475 frame->nb_samples = buf_size /
1476 (enc->channels * av_get_bytes_per_sample(enc->sample_fmt));
1477 if ((ret = avcodec_fill_audio_frame(frame, enc->channels, enc->sample_fmt,
1478 buf, buf_size, 1)) < 0) {
1479 av_log(NULL, AV_LOG_FATAL, "Audio encoding failed (avcodec_fill_audio_frame)\n");
1483 frame->pts = ost->sync_opts;
1484 ost->sync_opts += frame->nb_samples;
1488 update_benchmark(NULL);
1489 if (avcodec_encode_audio2(enc, &pkt, frame, &got_packet) < 0) {
1490 av_log(NULL, AV_LOG_FATAL, "Audio encoding failed (avcodec_encode_audio2)\n");
1493 update_benchmark("encode_audio %d.%d", ost->file_index, ost->index);
1498 if (pkt.pts != AV_NOPTS_VALUE)
1499 pkt.pts = av_rescale_q(pkt.pts, enc->time_base, ost->st->time_base);
1500 if (pkt.dts != AV_NOPTS_VALUE) {
1501 int64_t max = ost->st->cur_dts + !(s->oformat->flags & AVFMT_TS_NONSTRICT);
1502 pkt.dts = av_rescale_q(pkt.dts, enc->time_base, ost->st->time_base);
1503 if (ost->st->cur_dts && ost->st->cur_dts != AV_NOPTS_VALUE && max > pkt.dts) {
1504 av_log(s, max - pkt.dts > 2 ? AV_LOG_WARNING : AV_LOG_DEBUG, "Audio timestamp %"PRId64" < %"PRId64" invalid, cliping\n", pkt.dts, max);
1505 pkt.pts = pkt.dts = max;
1508 if (pkt.duration > 0)
1509 pkt.duration = av_rescale_q(pkt.duration, enc->time_base, ost->st->time_base);
1511 write_frame(s, &pkt, ost);
1513 audio_size += pkt.size;
1515 av_free_packet(&pkt);
1519 av_log(NULL, AV_LOG_INFO, "encoder -> type:audio "
1520 "pkt_pts:%s pkt_pts_time:%s pkt_dts:%s pkt_dts_time:%s\n",
1521 av_ts2str(pkt.pts), av_ts2timestr(pkt.pts, &ost->st->time_base),
1522 av_ts2str(pkt.dts), av_ts2timestr(pkt.dts, &ost->st->time_base));
1528 static int alloc_audio_output_buf(AVCodecContext *dec, AVCodecContext *enc,
1529 int nb_samples, int *buf_linesize)
1531 int64_t audio_buf_samples;
1534 /* calculate required number of samples to allocate */
1535 audio_buf_samples = ((int64_t)nb_samples * enc->sample_rate + dec->sample_rate) /
1537 audio_buf_samples = 4 * audio_buf_samples + 10000; // safety factors for resampling
1538 audio_buf_samples = FFMAX(audio_buf_samples, enc->frame_size);
1539 if (audio_buf_samples > INT_MAX)
1540 return AVERROR(EINVAL);
1542 audio_buf_size = av_samples_get_buffer_size(buf_linesize, enc->channels,
1544 enc->sample_fmt, 0);
1545 if (audio_buf_size < 0)
1546 return audio_buf_size;
1548 av_fast_malloc(&audio_buf, &allocated_audio_buf_size, audio_buf_size);
1550 return AVERROR(ENOMEM);
1555 static void do_audio_out(AVFormatContext *s, OutputStream *ost,
1556 InputStream *ist, AVFrame *decoded_frame)
1561 int frame_bytes, resample_changed, ret;
1562 AVCodecContext *enc = ost->st->codec;
1563 AVCodecContext *dec = ist->st->codec;
1564 int osize = av_get_bytes_per_sample(enc->sample_fmt);
1565 int isize = av_get_bytes_per_sample(dec->sample_fmt);
1566 uint8_t *buf[AV_NUM_DATA_POINTERS];
1567 int size = decoded_frame->nb_samples * dec->channels * isize;
1568 int planes = av_sample_fmt_is_planar(dec->sample_fmt) ? dec->channels : 1;
1570 int out_linesize = 0;
1571 int buf_linesize = decoded_frame->linesize[0];
1573 av_assert0(planes <= AV_NUM_DATA_POINTERS);
1575 for(i=0; i<planes; i++)
1576 buf[i]= decoded_frame->data[i];
1579 get_default_channel_layouts(ost, ist);
1581 if (alloc_audio_output_buf(dec, enc, decoded_frame->nb_samples, &out_linesize) < 0) {
1582 av_log(NULL, AV_LOG_FATAL, "Error allocating audio buffer\n");
1586 if (audio_sync_method > 1 ||
1587 enc->channels != dec->channels ||
1588 enc->channel_layout != dec->channel_layout ||
1589 enc->sample_rate != dec->sample_rate ||
1590 dec->sample_fmt != enc->sample_fmt)
1591 ost->audio_resample = 1;
1593 resample_changed = ost->resample_sample_fmt != dec->sample_fmt ||
1594 ost->resample_channels != dec->channels ||
1595 ost->resample_channel_layout != dec->channel_layout ||
1596 ost->resample_sample_rate != dec->sample_rate;
1598 if ((ost->audio_resample && !ost->swr) || resample_changed || ost->audio_channels_mapped) {
1600 if (resample_changed) {
1601 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",
1602 ist->file_index, ist->st->index,
1603 ost->resample_sample_rate, av_get_sample_fmt_name(ost->resample_sample_fmt),
1604 ost->resample_channels, ost->resample_channel_layout,
1605 dec->sample_rate, av_get_sample_fmt_name(dec->sample_fmt),
1606 dec->channels, dec->channel_layout);
1607 ost->resample_sample_fmt = dec->sample_fmt;
1608 ost->resample_channels = dec->channels;
1609 ost->resample_channel_layout = dec->channel_layout;
1610 ost->resample_sample_rate = dec->sample_rate;
1611 swr_free(&ost->swr);
1613 /* if audio_sync_method is >1 the resampler is needed for audio drift compensation */
1614 if (audio_sync_method <= 1 && !ost->audio_channels_mapped &&
1615 ost->resample_sample_fmt == enc->sample_fmt &&
1616 ost->resample_channels == enc->channels &&
1617 ost->resample_channel_layout == enc->channel_layout &&
1618 ost->resample_sample_rate == enc->sample_rate) {
1620 ost->audio_resample = 0;
1622 ost->swr = swr_alloc_set_opts(ost->swr,
1623 enc->channel_layout, enc->sample_fmt, enc->sample_rate,
1624 dec->channel_layout, dec->sample_fmt, dec->sample_rate,
1626 av_opt_set_int(ost->swr, "dither_method", ost->swr_dither_method,0);
1627 av_opt_set_double(ost->swr, "dither_scale", ost->swr_dither_scale,0);
1628 if (ost->audio_channels_mapped)
1629 swr_set_channel_mapping(ost->swr, ost->audio_channels_map);
1630 av_opt_set_double(ost->swr, "rmvol", ost->rematrix_volume, 0);
1631 if (ost->audio_channels_mapped) {
1632 av_opt_set_int(ost->swr, "icl", av_get_default_channel_layout(ost->audio_channels_mapped), 0);
1633 av_opt_set_int(ost->swr, "uch", ost->audio_channels_mapped, 0);
1635 if (av_opt_set_int(ost->swr, "ich", dec->channels, 0) < 0) {
1636 av_log(NULL, AV_LOG_FATAL, "Unsupported number of input channels\n");
1639 if (av_opt_set_int(ost->swr, "och", enc->channels, 0) < 0) {
1640 av_log(NULL, AV_LOG_FATAL, "Unsupported number of output channels\n");
1643 if(audio_sync_method>1) av_opt_set_int(ost->swr, "flags", SWR_FLAG_RESAMPLE, 0);
1644 if(ost->swr && swr_init(ost->swr) < 0){
1645 av_log(NULL, AV_LOG_FATAL, "swr_init() failed\n");
1646 swr_free(&ost->swr);
1650 av_log(NULL, AV_LOG_FATAL, "Can not resample %d channels @ %d Hz to %d channels @ %d Hz\n",
1651 dec->channels, dec->sample_rate,
1652 enc->channels, enc->sample_rate);
1658 av_assert0(ost->audio_resample || dec->sample_fmt==enc->sample_fmt);
1660 if (audio_sync_method > 0) {
1661 double delta = get_sync_ipts(ost, ist->pts) * enc->sample_rate - ost->sync_opts -
1662 av_fifo_size(ost->fifo) / (enc->channels * osize);
1663 int idelta = delta * dec->sample_rate / enc->sample_rate;
1664 int byte_delta = idelta * isize * dec->channels;
1666 // FIXME resample delay
1667 if (fabs(delta) > 50) {
1668 if (ist->is_start || fabs(delta) > audio_drift_threshold*enc->sample_rate) {
1669 if (byte_delta < 0) {
1670 byte_delta = FFMAX(byte_delta, -size);
1672 for (i=0; i<planes; i++)
1673 buf[i] -= byte_delta/planes;
1674 av_log(NULL, AV_LOG_VERBOSE, "discarding %d audio samples\n",
1675 -byte_delta / (isize * dec->channels));
1680 av_fast_malloc(&async_buf, &allocated_async_buf_size,
1683 av_log(NULL, AV_LOG_FATAL, "Out of memory in do_audio_out\n");
1687 if (alloc_audio_output_buf(dec, enc, decoded_frame->nb_samples + idelta, &out_linesize) < 0) {
1688 av_log(NULL, AV_LOG_FATAL, "Error allocating audio buffer\n");
1693 for (i=0; i<planes; i++) {
1694 uint8_t *t = async_buf + i*((byte_delta + size)/planes);
1695 generate_silence(t, dec->sample_fmt, byte_delta/planes);
1696 memcpy(t + byte_delta/planes, buf[i], size/planes);
1700 buf_linesize = allocated_async_buf_size;
1701 av_log(NULL, AV_LOG_VERBOSE, "adding %d audio samples of silence\n", idelta);
1703 } else if (audio_sync_method > 1) {
1704 int comp = av_clip(delta, -audio_sync_method, audio_sync_method);
1705 av_log(NULL, AV_LOG_VERBOSE, "compensating audio timestamp drift:%f compensation:%d in:%d\n",
1706 delta, comp, enc->sample_rate);
1707 // 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));
1708 swr_set_compensation(ost->swr, comp, enc->sample_rate);
1711 } else if (audio_sync_method == 0)
1712 ost->sync_opts = lrintf(get_sync_ipts(ost, ist->pts) * enc->sample_rate) -
1713 av_fifo_size(ost->fifo) / (enc->channels * osize); // FIXME wrong
1715 if (ost->audio_resample || ost->audio_channels_mapped) {
1717 size_out = swr_convert(ost->swr, ( uint8_t*[]){buftmp},
1718 allocated_audio_buf_size / (enc->channels * osize),
1720 size / (dec->channels * isize));
1722 av_log(NULL, AV_LOG_FATAL, "swr_convert failed\n");
1725 size_out = size_out * enc->channels * osize;
1731 av_assert0(ost->audio_resample || dec->sample_fmt==enc->sample_fmt);
1733 /* now encode as many frames as possible */
1734 if (!(enc->codec->capabilities & CODEC_CAP_VARIABLE_FRAME_SIZE)) {
1735 /* output resampled raw samples */
1736 if (av_fifo_realloc2(ost->fifo, av_fifo_size(ost->fifo) + size_out) < 0) {
1737 av_log(NULL, AV_LOG_FATAL, "av_fifo_realloc2() failed\n");
1740 av_fifo_generic_write(ost->fifo, buftmp, size_out, NULL);
1742 frame_bytes = enc->frame_size * osize * enc->channels;
1744 while (av_fifo_size(ost->fifo) >= frame_bytes) {
1745 av_fifo_generic_read(ost->fifo, audio_buf, frame_bytes, NULL);
1746 encode_audio_frame(s, ost, audio_buf, frame_bytes);
1749 encode_audio_frame(s, ost, buftmp, size_out);
1753 static void pre_process_video_frame(InputStream *ist, AVPicture *picture, void **bufp)
1755 AVCodecContext *dec;
1756 AVPicture *picture2;
1757 AVPicture picture_tmp;
1760 dec = ist->st->codec;
1762 /* deinterlace : must be done before any resize */
1763 if (do_deinterlace) {
1766 /* create temporary picture */
1767 size = avpicture_get_size(dec->pix_fmt, dec->width, dec->height);
1768 buf = av_malloc(size);
1772 picture2 = &picture_tmp;
1773 avpicture_fill(picture2, buf, dec->pix_fmt, dec->width, dec->height);
1775 if (avpicture_deinterlace(picture2, picture,
1776 dec->pix_fmt, dec->width, dec->height) < 0) {
1777 /* if error, do not deinterlace */
1778 av_log(NULL, AV_LOG_WARNING, "Deinterlacing failed\n");
1787 if (picture != picture2)
1788 *picture = *picture2;
1792 static void do_subtitle_out(AVFormatContext *s,
1798 static uint8_t *subtitle_out = NULL;
1799 int subtitle_out_max_size = 1024 * 1024;
1800 int subtitle_out_size, nb, i;
1801 AVCodecContext *enc;
1804 if (pts == AV_NOPTS_VALUE) {
1805 av_log(NULL, AV_LOG_ERROR, "Subtitle packets must have a pts\n");
1811 enc = ost->st->codec;
1813 if (!subtitle_out) {
1814 subtitle_out = av_malloc(subtitle_out_max_size);
1817 /* Note: DVB subtitle need one packet to draw them and one other
1818 packet to clear them */
1819 /* XXX: signal it in the codec context ? */
1820 if (enc->codec_id == CODEC_ID_DVB_SUBTITLE)
1825 for (i = 0; i < nb; i++) {
1826 ost->sync_opts = av_rescale_q(pts, ist->st->time_base, enc->time_base);
1828 sub->pts = av_rescale_q(pts, ist->st->time_base, AV_TIME_BASE_Q);
1829 // start_display_time is required to be 0
1830 sub->pts += av_rescale_q(sub->start_display_time, (AVRational){ 1, 1000 }, AV_TIME_BASE_Q);
1831 sub->end_display_time -= sub->start_display_time;
1832 sub->start_display_time = 0;
1833 subtitle_out_size = avcodec_encode_subtitle(enc, subtitle_out,
1834 subtitle_out_max_size, sub);
1835 if (subtitle_out_size < 0) {
1836 av_log(NULL, AV_LOG_FATAL, "Subtitle encoding failed\n");
1840 av_init_packet(&pkt);
1841 pkt.data = subtitle_out;
1842 pkt.size = subtitle_out_size;
1843 pkt.pts = av_rescale_q(sub->pts, AV_TIME_BASE_Q, ost->st->time_base);
1844 if (enc->codec_id == CODEC_ID_DVB_SUBTITLE) {
1845 /* XXX: the pts correction is handled here. Maybe handling
1846 it in the codec would be better */
1848 pkt.pts += 90 * sub->start_display_time;
1850 pkt.pts += 90 * sub->end_display_time;
1852 write_frame(s, &pkt, ost);
1856 static double psnr(double d)
1858 return -10.0 * log(d) / log(10.0);
1861 static void do_video_stats(AVFormatContext *os, OutputStream *ost,
1864 AVCodecContext *enc;
1866 double ti1, bitrate, avg_bitrate;
1868 /* this is executed just the first time do_video_stats is called */
1870 vstats_file = fopen(vstats_filename, "w");
1877 enc = ost->st->codec;
1878 if (enc->codec_type == AVMEDIA_TYPE_VIDEO) {
1879 frame_number = ost->frame_number;
1880 fprintf(vstats_file, "frame= %5d q= %2.1f ", frame_number, enc->coded_frame->quality / (float)FF_QP2LAMBDA);
1881 if (enc->flags&CODEC_FLAG_PSNR)
1882 fprintf(vstats_file, "PSNR= %6.2f ", psnr(enc->coded_frame->error[0] / (enc->width * enc->height * 255.0 * 255.0)));
1884 fprintf(vstats_file,"f_size= %6d ", frame_size);
1885 /* compute pts value */
1886 ti1 = ost->sync_opts * av_q2d(enc->time_base);
1890 bitrate = (frame_size * 8) / av_q2d(enc->time_base) / 1000.0;
1891 avg_bitrate = (double)(video_size * 8) / ti1 / 1000.0;
1892 fprintf(vstats_file, "s_size= %8.0fkB time= %0.3f br= %7.1fkbits/s avg_br= %7.1fkbits/s ",
1893 (double)video_size / 1024, ti1, bitrate, avg_bitrate);
1894 fprintf(vstats_file, "type= %c\n", av_get_picture_type_char(enc->coded_frame->pict_type));
1899 static void do_video_out(AVFormatContext *s, OutputStream *ost,
1900 AVFrame *in_picture, float quality)
1902 int nb_frames, i, ret, format_video_sync;
1903 AVCodecContext *enc;
1904 double sync_ipts, delta;
1905 double duration = 0;
1907 InputStream *ist = NULL;
1909 if (ost->source_index >= 0)
1910 ist = input_streams[ost->source_index];
1912 enc = ost->st->codec;
1914 if (ist && ist->st->start_time != AV_NOPTS_VALUE && ist->st->first_dts != AV_NOPTS_VALUE) {
1915 duration = FFMAX(av_q2d(ist->st->time_base), av_q2d(ist->st->codec->time_base));
1916 if(ist->st->r_frame_rate.num)
1917 duration= FFMAX(duration, 1/av_q2d(ist->st->r_frame_rate));
1918 if(ist->st->avg_frame_rate.num && 0)
1919 duration= FFMAX(duration, 1/av_q2d(ist->st->avg_frame_rate));
1921 duration /= av_q2d(enc->time_base);
1924 sync_ipts = get_sync_ipts(ost, in_picture->pts) / av_q2d(enc->time_base);
1925 delta = sync_ipts - ost->sync_opts + duration;
1927 /* by default, we output a single frame */
1930 format_video_sync = video_sync_method;
1931 if (format_video_sync == VSYNC_AUTO)
1932 format_video_sync = (s->oformat->flags & AVFMT_VARIABLE_FPS) ? ((s->oformat->flags & AVFMT_NOTIMESTAMPS) ? VSYNC_PASSTHROUGH : VSYNC_VFR) : 1;
1934 switch (format_video_sync) {
1936 // FIXME set to 0.5 after we fix some dts/pts bugs like in avidec.c
1939 else if (delta > 1.1)
1940 nb_frames = lrintf(delta);
1945 else if (delta > 0.6)
1946 ost->sync_opts = lrintf(sync_ipts);
1949 case VSYNC_PASSTHROUGH:
1950 ost->sync_opts = lrintf(sync_ipts);
1956 nb_frames = FFMIN(nb_frames, ost->max_frames - ost->frame_number);
1957 if (nb_frames == 0) {
1959 av_log(NULL, AV_LOG_VERBOSE, "*** drop!\n");
1961 } else if (nb_frames > 1) {
1962 nb_frames_dup += nb_frames - 1;
1963 av_log(NULL, AV_LOG_VERBOSE, "*** %d dup!\n", nb_frames - 1);
1966 /* duplicates frame if needed */
1967 for (i = 0; i < nb_frames; i++) {
1969 av_init_packet(&pkt);
1973 if (s->oformat->flags & AVFMT_RAWPICTURE &&
1974 enc->codec->id == CODEC_ID_RAWVIDEO) {
1975 /* raw pictures are written as AVPicture structure to
1976 avoid any copies. We support temporarily the older
1978 enc->coded_frame->interlaced_frame = in_picture->interlaced_frame;
1979 enc->coded_frame->top_field_first = in_picture->top_field_first;
1980 pkt.data = (uint8_t *)in_picture;
1981 pkt.size = sizeof(AVPicture);
1982 pkt.pts = av_rescale_q(ost->sync_opts, enc->time_base, ost->st->time_base);
1983 pkt.flags |= AV_PKT_FLAG_KEY;
1985 write_frame(s, &pkt, ost);
1988 AVFrame big_picture;
1990 big_picture = *in_picture;
1991 /* better than nothing: use input picture interlaced
1993 big_picture.interlaced_frame = in_picture->interlaced_frame;
1994 if (ost->st->codec->flags & (CODEC_FLAG_INTERLACED_DCT|CODEC_FLAG_INTERLACED_ME)) {
1995 if (ost->top_field_first == -1)
1996 big_picture.top_field_first = in_picture->top_field_first;
1998 big_picture.top_field_first = !!ost->top_field_first;
2001 /* handles same_quant here. This is not correct because it may
2002 not be a global option */
2003 big_picture.quality = quality;
2004 if (!enc->me_threshold)
2005 big_picture.pict_type = 0;
2006 big_picture.pts = ost->sync_opts;
2007 if (ost->forced_kf_index < ost->forced_kf_count &&
2008 big_picture.pts >= ost->forced_kf_pts[ost->forced_kf_index]) {
2009 big_picture.pict_type = AV_PICTURE_TYPE_I;
2010 ost->forced_kf_index++;
2012 update_benchmark(NULL);
2013 ret = avcodec_encode_video2(enc, &pkt, &big_picture, &got_packet);
2014 update_benchmark("encode_video %d.%d", ost->file_index, ost->index);
2016 av_log(NULL, AV_LOG_FATAL, "Video encoding failed\n");
2021 if (pkt.pts == AV_NOPTS_VALUE && !(enc->codec->capabilities & CODEC_CAP_DELAY))
2022 pkt.pts = ost->sync_opts;
2024 if (pkt.pts != AV_NOPTS_VALUE)
2025 pkt.pts = av_rescale_q(pkt.pts, enc->time_base, ost->st->time_base);
2026 if (pkt.dts != AV_NOPTS_VALUE)
2027 pkt.dts = av_rescale_q(pkt.dts, enc->time_base, ost->st->time_base);
2030 av_log(NULL, AV_LOG_INFO, "encoder -> type:video "
2031 "pkt_pts:%s pkt_pts_time:%s pkt_dts:%s pkt_dts_time:%s\n",
2032 av_ts2str(pkt.pts), av_ts2timestr(pkt.pts, &ost->st->time_base),
2033 av_ts2str(pkt.dts), av_ts2timestr(pkt.dts, &ost->st->time_base));
2036 write_frame(s, &pkt, ost);
2037 frame_size = pkt.size;
2038 video_size += pkt.size;
2039 av_free_packet(&pkt);
2041 /* if two pass, output log */
2042 if (ost->logfile && enc->stats_out) {
2043 fprintf(ost->logfile, "%s", enc->stats_out);
2049 * For video, number of frames in == number of packets out.
2050 * But there may be reordering, so we can't throw away frames on encoder
2051 * flush, we need to limit them here, before they go into encoder.
2053 ost->frame_number++;
2055 if (vstats_filename && frame_size)
2056 do_video_stats(output_files[ost->file_index]->ctx, ost, frame_size);
2059 /* check for new output on any of the filtergraphs */
2060 static int poll_filters(void)
2062 AVFilterBufferRef *picref;
2063 AVFrame *filtered_frame = NULL;
2064 int i, ret, ret_all;
2065 unsigned nb_success, nb_eof;
2068 /* Reap all buffers present in the buffer sinks */
2069 for (i = 0; i < nb_output_streams; i++) {
2070 OutputStream *ost = output_streams[i];
2071 OutputFile *of = output_files[ost->file_index];
2073 if (!ost->filter || ost->is_past_recording_time)
2076 if (!ost->filtered_frame && !(ost->filtered_frame = avcodec_alloc_frame())) {
2077 return AVERROR(ENOMEM);
2079 avcodec_get_frame_defaults(ost->filtered_frame);
2080 filtered_frame = ost->filtered_frame;
2083 AVRational ist_pts_tb = ost->filter->filter->inputs[0]->time_base;
2084 ret = av_buffersink_get_buffer_ref(ost->filter->filter, &picref,
2085 AV_BUFFERSINK_FLAG_NO_REQUEST);
2087 if (ret != AVERROR(EAGAIN)) {
2089 av_strerror(ret, buf, sizeof(buf));
2090 av_log(NULL, AV_LOG_WARNING,
2091 "Error in av_buffersink_get_buffer_ref(): %s\n", buf);
2095 filtered_frame->pts = av_rescale_q(picref->pts, ist_pts_tb, AV_TIME_BASE_Q);
2096 //if (ost->source_index >= 0)
2097 // *filtered_frame= *input_streams[ost->source_index]->decoded_frame; //for me_threshold
2099 if (of->start_time && filtered_frame->pts < of->start_time)
2102 switch (ost->filter->filter->inputs[0]->type) {
2103 case AVMEDIA_TYPE_VIDEO:
2104 avfilter_fill_frame_from_video_buffer_ref(filtered_frame, picref);
2105 if (!ost->frame_aspect_ratio)
2106 ost->st->codec->sample_aspect_ratio = picref->video->sample_aspect_ratio;
2108 do_video_out(of->ctx, ost, filtered_frame,
2109 same_quant ? ost->last_quality :
2110 ost->st->codec->global_quality);
2113 // TODO support audio/subtitle filters
2117 avfilter_unref_buffer(picref);
2120 /* Request frames through all the graphs */
2121 ret_all = nb_success = nb_eof = 0;
2122 for (i = 0; i < nb_filtergraphs; i++) {
2123 ret = avfilter_graph_request_oldest(filtergraphs[i]->graph);
2126 } else if (ret == AVERROR_EOF) {
2128 } else if (ret != AVERROR(EAGAIN)) {
2130 av_strerror(ret, buf, sizeof(buf));
2131 av_log(NULL, AV_LOG_WARNING,
2132 "Error in request_frame(): %s\n", buf);
2138 /* Try again if anything succeeded */
2140 return nb_eof == nb_filtergraphs ? AVERROR_EOF : ret_all;
2143 static void print_report(int is_last_report, int64_t timer_start, int64_t cur_time)
2147 AVFormatContext *oc;
2149 AVCodecContext *enc;
2150 int frame_number, vid, i;
2152 int64_t pts = INT64_MAX;
2153 static int64_t last_time = -1;
2154 static int qp_histogram[52];
2155 int hours, mins, secs, us;
2157 if (!print_stats && !is_last_report)
2160 if (!is_last_report) {
2161 if (last_time == -1) {
2162 last_time = cur_time;
2165 if ((cur_time - last_time) < 500000)
2167 last_time = cur_time;
2171 oc = output_files[0]->ctx;
2173 total_size = avio_size(oc->pb);
2174 if (total_size < 0) { // FIXME improve avio_size() so it works with non seekable output too
2175 total_size = avio_tell(oc->pb);
2182 for (i = 0; i < nb_output_streams; i++) {
2184 ost = output_streams[i];
2185 enc = ost->st->codec;
2186 if (!ost->stream_copy && enc->coded_frame)
2187 q = enc->coded_frame->quality / (float)FF_QP2LAMBDA;
2188 if (vid && enc->codec_type == AVMEDIA_TYPE_VIDEO) {
2189 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "q=%2.1f ", q);
2191 if (!vid && enc->codec_type == AVMEDIA_TYPE_VIDEO) {
2192 float fps, t = (cur_time-timer_start) / 1000000.0;
2194 frame_number = ost->frame_number;
2195 fps = t > 1 ? frame_number / t : 0;
2196 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "frame=%5d fps=%3.*f q=%3.1f ",
2197 frame_number, fps < 9.95, fps, q);
2199 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "L");
2203 if (qp >= 0 && qp < FF_ARRAY_ELEMS(qp_histogram))
2205 for (j = 0; j < 32; j++)
2206 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "%X", (int)lrintf(log(qp_histogram[j] + 1) / log(2)));
2208 if (enc->flags&CODEC_FLAG_PSNR) {
2210 double error, error_sum = 0;
2211 double scale, scale_sum = 0;
2212 char type[3] = { 'Y','U','V' };
2213 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "PSNR=");
2214 for (j = 0; j < 3; j++) {
2215 if (is_last_report) {
2216 error = enc->error[j];
2217 scale = enc->width * enc->height * 255.0 * 255.0 * frame_number;
2219 error = enc->coded_frame->error[j];
2220 scale = enc->width * enc->height * 255.0 * 255.0;
2226 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "%c:%2.2f ", type[j], psnr(error / scale));
2228 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "*:%2.2f ", psnr(error_sum / scale_sum));
2232 /* compute min output value */
2233 pts = FFMIN(pts, av_rescale_q(ost->st->pts.val,
2234 ost->st->time_base, AV_TIME_BASE_Q));
2237 secs = pts / AV_TIME_BASE;
2238 us = pts % AV_TIME_BASE;
2244 bitrate = pts ? total_size * 8 / (pts / 1000.0) : 0;
2246 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
2247 "size=%8.0fkB time=", total_size / 1024.0);
2248 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
2249 "%02d:%02d:%02d.%02d ", hours, mins, secs,
2250 (100 * us) / AV_TIME_BASE);
2251 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
2252 "bitrate=%6.1fkbits/s", bitrate);
2254 if (nb_frames_dup || nb_frames_drop)
2255 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), " dup=%d drop=%d",
2256 nb_frames_dup, nb_frames_drop);
2258 av_log(NULL, AV_LOG_INFO, "%s \r", buf);
2262 if (is_last_report) {
2263 int64_t raw= audio_size + video_size + extra_size;
2264 av_log(NULL, AV_LOG_INFO, "\n");
2265 av_log(NULL, AV_LOG_INFO, "video:%1.0fkB audio:%1.0fkB global headers:%1.0fkB muxing overhead %f%%\n",
2266 video_size / 1024.0,
2267 audio_size / 1024.0,
2268 extra_size / 1024.0,
2269 100.0 * (total_size - raw) / raw
2271 if(video_size + audio_size + extra_size == 0){
2272 av_log(NULL, AV_LOG_WARNING, "Output file is empty, nothing was encoded (check -ss / -t / -frames parameters if used)\n");
2277 static void flush_encoders(void)
2281 for (i = 0; i < nb_output_streams; i++) {
2282 OutputStream *ost = output_streams[i];
2283 AVCodecContext *enc = ost->st->codec;
2284 AVFormatContext *os = output_files[ost->file_index]->ctx;
2285 int stop_encoding = 0;
2287 if (!ost->encoding_needed)
2290 if (ost->st->codec->codec_type == AVMEDIA_TYPE_AUDIO && enc->frame_size <= 1)
2292 if (ost->st->codec->codec_type == AVMEDIA_TYPE_VIDEO && (os->oformat->flags & AVFMT_RAWPICTURE) && enc->codec->id == CODEC_ID_RAWVIDEO)
2297 int fifo_bytes, got_packet;
2298 av_init_packet(&pkt);
2302 switch (ost->st->codec->codec_type) {
2303 case AVMEDIA_TYPE_AUDIO:
2304 fifo_bytes = av_fifo_size(ost->fifo);
2305 if (fifo_bytes > 0) {
2306 /* encode any samples remaining in fifo */
2307 int frame_bytes = fifo_bytes;
2309 av_fifo_generic_read(ost->fifo, audio_buf, fifo_bytes, NULL);
2311 /* pad last frame with silence if needed */
2312 if (!(enc->codec->capabilities & CODEC_CAP_SMALL_LAST_FRAME)) {
2313 frame_bytes = enc->frame_size * enc->channels *
2314 av_get_bytes_per_sample(enc->sample_fmt);
2315 if (allocated_audio_buf_size < frame_bytes)
2317 generate_silence(audio_buf+fifo_bytes, enc->sample_fmt, frame_bytes - fifo_bytes);
2319 encode_audio_frame(os, ost, audio_buf, frame_bytes);
2321 /* flush encoder with NULL frames until it is done
2322 returning packets */
2323 if (encode_audio_frame(os, ost, NULL, 0) == 0) {
2329 case AVMEDIA_TYPE_VIDEO:
2330 update_benchmark(NULL);
2331 ret = avcodec_encode_video2(enc, &pkt, NULL, &got_packet);
2332 update_benchmark("encode_video %d.%d", ost->file_index, ost->index);
2334 av_log(NULL, AV_LOG_FATAL, "Video encoding failed\n");
2337 video_size += pkt.size;
2338 if (ost->logfile && enc->stats_out) {
2339 fprintf(ost->logfile, "%s", enc->stats_out);
2345 if (pkt.pts != AV_NOPTS_VALUE)
2346 pkt.pts = av_rescale_q(pkt.pts, enc->time_base, ost->st->time_base);
2347 if (pkt.dts != AV_NOPTS_VALUE)
2348 pkt.dts = av_rescale_q(pkt.dts, enc->time_base, ost->st->time_base);
2349 write_frame(os, &pkt, ost);
2361 * Check whether a packet from ist should be written into ost at this time
2363 static int check_output_constraints(InputStream *ist, OutputStream *ost)
2365 OutputFile *of = output_files[ost->file_index];
2366 int ist_index = input_files[ist->file_index]->ist_index + ist->st->index;
2368 if (ost->source_index != ist_index)
2371 if (of->start_time && ist->pts < of->start_time)
2374 if (of->recording_time != INT64_MAX &&
2375 av_compare_ts(ist->pts, AV_TIME_BASE_Q, of->recording_time + of->start_time,
2376 (AVRational){ 1, 1000000 }) >= 0) {
2377 ost->is_past_recording_time = 1;
2384 static void do_streamcopy(InputStream *ist, OutputStream *ost, const AVPacket *pkt)
2386 OutputFile *of = output_files[ost->file_index];
2387 int64_t ost_tb_start_time = av_rescale_q(of->start_time, AV_TIME_BASE_Q, ost->st->time_base);
2391 av_init_packet(&opkt);
2393 if ((!ost->frame_number && !(pkt->flags & AV_PKT_FLAG_KEY)) &&
2394 !ost->copy_initial_nonkeyframes)
2397 /* force the input stream PTS */
2398 if (ost->st->codec->codec_type == AVMEDIA_TYPE_AUDIO)
2399 audio_size += pkt->size;
2400 else if (ost->st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
2401 video_size += pkt->size;
2405 if (pkt->pts != AV_NOPTS_VALUE)
2406 opkt.pts = av_rescale_q(pkt->pts, ist->st->time_base, ost->st->time_base) - ost_tb_start_time;
2408 opkt.pts = AV_NOPTS_VALUE;
2410 if (pkt->dts == AV_NOPTS_VALUE)
2411 opkt.dts = av_rescale_q(ist->dts, AV_TIME_BASE_Q, ost->st->time_base);
2413 opkt.dts = av_rescale_q(pkt->dts, ist->st->time_base, ost->st->time_base);
2414 opkt.dts -= ost_tb_start_time;
2416 opkt.duration = av_rescale_q(pkt->duration, ist->st->time_base, ost->st->time_base);
2417 opkt.flags = pkt->flags;
2419 // FIXME remove the following 2 lines they shall be replaced by the bitstream filters
2420 if ( ost->st->codec->codec_id != CODEC_ID_H264
2421 && ost->st->codec->codec_id != CODEC_ID_MPEG1VIDEO
2422 && ost->st->codec->codec_id != CODEC_ID_MPEG2VIDEO
2423 && ost->st->codec->codec_id != CODEC_ID_VC1
2425 if (av_parser_change(ist->st->parser, ost->st->codec, &opkt.data, &opkt.size, pkt->data, pkt->size, pkt->flags & AV_PKT_FLAG_KEY))
2426 opkt.destruct = av_destruct_packet;
2428 opkt.data = pkt->data;
2429 opkt.size = pkt->size;
2431 if (of->ctx->oformat->flags & AVFMT_RAWPICTURE) {
2432 /* store AVPicture in AVPacket, as expected by the output format */
2433 avpicture_fill(&pict, opkt.data, ost->st->codec->pix_fmt, ost->st->codec->width, ost->st->codec->height);
2434 opkt.data = (uint8_t *)&pict;
2435 opkt.size = sizeof(AVPicture);
2436 opkt.flags |= AV_PKT_FLAG_KEY;
2439 write_frame(of->ctx, &opkt, ost);
2440 ost->st->codec->frame_number++;
2441 av_free_packet(&opkt);
2444 static void rate_emu_sleep(InputStream *ist)
2446 if (input_files[ist->file_index]->rate_emu) {
2447 int64_t pts = av_rescale(ist->dts, 1000000, AV_TIME_BASE);
2448 int64_t now = av_gettime() - ist->start;
2454 static int transcode_audio(InputStream *ist, AVPacket *pkt, int *got_output)
2456 AVFrame *decoded_frame;
2457 AVCodecContext *avctx = ist->st->codec;
2458 int bps = av_get_bytes_per_sample(ist->st->codec->sample_fmt);
2461 if (!ist->decoded_frame && !(ist->decoded_frame = avcodec_alloc_frame()))
2462 return AVERROR(ENOMEM);
2464 avcodec_get_frame_defaults(ist->decoded_frame);
2465 decoded_frame = ist->decoded_frame;
2467 update_benchmark(NULL);
2468 ret = avcodec_decode_audio4(avctx, decoded_frame, got_output, pkt);
2469 update_benchmark("decode_audio %d.%d", ist->file_index, ist->st->index);
2473 if (avctx->sample_rate <= 0) {
2474 av_log(avctx, AV_LOG_ERROR, "Sample rate %d invalid\n", avctx->sample_rate);
2475 return AVERROR_INVALIDDATA;
2479 /* no audio frame */
2483 /* if the decoder provides a pts, use it instead of the last packet pts.
2484 the decoder could be delaying output by a packet or more. */
2485 if (decoded_frame->pts != AV_NOPTS_VALUE)
2486 ist->dts = ist->next_dts = ist->pts = ist->next_pts = decoded_frame->pts;
2488 /* increment next_dts to use for the case where the input stream does not
2489 have timestamps or there are multiple frames in the packet */
2490 ist->next_pts += ((int64_t)AV_TIME_BASE * decoded_frame->nb_samples) /
2492 ist->next_dts += ((int64_t)AV_TIME_BASE * decoded_frame->nb_samples) /
2496 // preprocess audio (volume)
2497 if (audio_volume != 256) {
2498 int decoded_data_size = decoded_frame->nb_samples * avctx->channels * bps;
2499 void *samples = decoded_frame->data[0];
2500 switch (avctx->sample_fmt) {
2501 case AV_SAMPLE_FMT_U8:
2503 uint8_t *volp = samples;
2504 for (i = 0; i < (decoded_data_size / sizeof(*volp)); i++) {
2505 int v = (((*volp - 128) * audio_volume + 128) >> 8) + 128;
2506 *volp++ = av_clip_uint8(v);
2510 case AV_SAMPLE_FMT_S16:
2512 int16_t *volp = samples;
2513 for (i = 0; i < (decoded_data_size / sizeof(*volp)); i++) {
2514 int v = ((*volp) * audio_volume + 128) >> 8;
2515 *volp++ = av_clip_int16(v);
2519 case AV_SAMPLE_FMT_S32:
2521 int32_t *volp = samples;
2522 for (i = 0; i < (decoded_data_size / sizeof(*volp)); i++) {
2523 int64_t v = (((int64_t)*volp * audio_volume + 128) >> 8);
2524 *volp++ = av_clipl_int32(v);
2528 case AV_SAMPLE_FMT_FLT:
2530 float *volp = samples;
2531 float scale = audio_volume / 256.f;
2532 for (i = 0; i < (decoded_data_size / sizeof(*volp)); i++) {
2537 case AV_SAMPLE_FMT_DBL:
2539 double *volp = samples;
2540 double scale = audio_volume / 256.;
2541 for (i = 0; i < (decoded_data_size / sizeof(*volp)); i++) {
2547 av_log(NULL, AV_LOG_FATAL,
2548 "Audio volume adjustment on sample format %s is not supported.\n",
2549 av_get_sample_fmt_name(ist->st->codec->sample_fmt));
2554 rate_emu_sleep(ist);
2556 for (i = 0; i < nb_output_streams; i++) {
2557 OutputStream *ost = output_streams[i];
2559 if (!check_output_constraints(ist, ost) || !ost->encoding_needed)
2561 do_audio_out(output_files[ost->file_index]->ctx, ost, ist, decoded_frame);
2567 static int transcode_video(InputStream *ist, AVPacket *pkt, int *got_output, int64_t *pkt_pts)
2569 AVFrame *decoded_frame;
2570 void *buffer_to_free = NULL;
2571 int i, ret = 0, resample_changed;
2572 int64_t best_effort_timestamp;
2573 AVRational *frame_sample_aspect;
2576 if (!ist->decoded_frame && !(ist->decoded_frame = avcodec_alloc_frame()))
2577 return AVERROR(ENOMEM);
2579 avcodec_get_frame_defaults(ist->decoded_frame);
2580 decoded_frame = ist->decoded_frame;
2581 pkt->pts = *pkt_pts;
2582 pkt->dts = ist->dts;
2583 *pkt_pts = AV_NOPTS_VALUE;
2585 update_benchmark(NULL);
2586 ret = avcodec_decode_video2(ist->st->codec,
2587 decoded_frame, got_output, pkt);
2588 update_benchmark("decode_video %d.%d", ist->file_index, ist->st->index);
2592 quality = same_quant ? decoded_frame->quality : 0;
2594 /* no picture yet */
2596 for (i = 0; i < ist->nb_filters; i++)
2597 av_buffersrc_add_ref(ist->filters[i]->filter, NULL, 0);
2601 best_effort_timestamp= av_frame_get_best_effort_timestamp(decoded_frame);
2602 if(best_effort_timestamp != AV_NOPTS_VALUE)
2603 ist->next_pts = ist->pts = decoded_frame->pts = best_effort_timestamp;
2607 pre_process_video_frame(ist, (AVPicture *)decoded_frame, &buffer_to_free);
2609 rate_emu_sleep(ist);
2611 if (ist->st->sample_aspect_ratio.num)
2612 decoded_frame->sample_aspect_ratio = ist->st->sample_aspect_ratio;
2614 resample_changed = ist->resample_width != decoded_frame->width ||
2615 ist->resample_height != decoded_frame->height ||
2616 ist->resample_pix_fmt != decoded_frame->format;
2617 if (resample_changed) {
2618 av_log(NULL, AV_LOG_INFO,
2619 "Input stream #%d:%d frame changed from size:%dx%d fmt:%s to size:%dx%d fmt:%s\n",
2620 ist->file_index, ist->st->index,
2621 ist->resample_width, ist->resample_height, av_get_pix_fmt_name(ist->resample_pix_fmt),
2622 decoded_frame->width, decoded_frame->height, av_get_pix_fmt_name(decoded_frame->format));
2624 ist->resample_width = decoded_frame->width;
2625 ist->resample_height = decoded_frame->height;
2626 ist->resample_pix_fmt = decoded_frame->format;
2628 for (i = 0; i < nb_filtergraphs; i++)
2629 if (ist_in_filtergraph(filtergraphs[i], ist) &&
2630 configure_filtergraph(filtergraphs[i]) < 0) {
2631 av_log(NULL, AV_LOG_FATAL, "Error reinitializing filters!\n");
2636 frame_sample_aspect= av_opt_ptr(avcodec_get_frame_class(), decoded_frame, "sample_aspect_ratio");
2637 for (i = 0; i < ist->nb_filters; i++) {
2638 int changed = ist->st->codec->width != ist->filters[i]->filter->outputs[0]->w
2639 || ist->st->codec->height != ist->filters[i]->filter->outputs[0]->h
2640 || ist->st->codec->pix_fmt != ist->filters[i]->filter->outputs[0]->format;
2641 // XXX what an ugly hack
2642 if (ist->filters[i]->graph->nb_outputs == 1)
2643 ist->filters[i]->graph->outputs[0]->ost->last_quality = quality;
2645 if (!frame_sample_aspect->num)
2646 *frame_sample_aspect = ist->st->sample_aspect_ratio;
2647 if (ist->dr1 && decoded_frame->type==FF_BUFFER_TYPE_USER && !changed) {
2648 FrameBuffer *buf = decoded_frame->opaque;
2649 AVFilterBufferRef *fb = avfilter_get_video_buffer_ref_from_arrays(
2650 decoded_frame->data, decoded_frame->linesize,
2651 AV_PERM_READ | AV_PERM_PRESERVE,
2652 ist->st->codec->width, ist->st->codec->height,
2653 ist->st->codec->pix_fmt);
2655 avfilter_copy_frame_props(fb, decoded_frame);
2656 fb->buf->priv = buf;
2657 fb->buf->free = filter_release_buffer;
2659 av_assert0(buf->refcount>0);
2661 av_buffersrc_add_ref(ist->filters[i]->filter, fb,
2662 AV_BUFFERSRC_FLAG_NO_CHECK_FORMAT |
2663 AV_BUFFERSRC_FLAG_NO_COPY);
2665 if(av_buffersrc_add_frame(ist->filters[i]->filter, decoded_frame, 0)<0) {
2666 av_log(NULL, AV_LOG_FATAL, "Failed to inject frame into filter network\n");
2672 av_free(buffer_to_free);
2676 static int transcode_subtitles(InputStream *ist, AVPacket *pkt, int *got_output)
2678 AVSubtitle subtitle;
2679 int i, ret = avcodec_decode_subtitle2(ist->st->codec,
2680 &subtitle, got_output, pkt);
2686 rate_emu_sleep(ist);
2688 for (i = 0; i < nb_output_streams; i++) {
2689 OutputStream *ost = output_streams[i];
2691 if (!check_output_constraints(ist, ost) || !ost->encoding_needed)
2694 do_subtitle_out(output_files[ost->file_index]->ctx, ost, ist, &subtitle, pkt->pts);
2697 avsubtitle_free(&subtitle);
2701 /* pkt = NULL means EOF (needed to flush decoder buffers) */
2702 static int output_packet(InputStream *ist, const AVPacket *pkt)
2706 int64_t pkt_pts = AV_NOPTS_VALUE;
2709 if (!ist->saw_first_ts) {
2710 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;
2712 if (pkt != NULL && pkt->pts != AV_NOPTS_VALUE && !ist->decoding_needed) {
2713 ist->dts += av_rescale_q(pkt->pts, ist->st->time_base, AV_TIME_BASE_Q);
2714 ist->pts = ist->dts; //unused but better to set it to a value thats not totally wrong
2716 ist->saw_first_ts = 1;
2719 if (ist->next_dts == AV_NOPTS_VALUE)
2720 ist->next_dts = ist->dts;
2721 if (ist->next_pts == AV_NOPTS_VALUE)
2722 ist->next_pts = ist->pts;
2726 av_init_packet(&avpkt);
2734 if (pkt->dts != AV_NOPTS_VALUE) {
2735 ist->next_dts = ist->dts = av_rescale_q(pkt->dts, ist->st->time_base, AV_TIME_BASE_Q);
2736 if (ist->st->codec->codec_type != AVMEDIA_TYPE_VIDEO || !ist->decoding_needed)
2737 ist->next_pts = ist->pts = av_rescale_q(pkt->dts, ist->st->time_base, AV_TIME_BASE_Q);
2739 if(pkt->pts != AV_NOPTS_VALUE)
2740 pkt_pts = av_rescale_q(pkt->pts, ist->st->time_base, AV_TIME_BASE_Q);
2742 // while we have more to decode or while the decoder did output something on EOF
2743 while (ist->decoding_needed && (avpkt.size > 0 || (!pkt && got_output))) {
2747 ist->pts = ist->next_pts;
2748 ist->dts = ist->next_dts;
2750 if (avpkt.size && avpkt.size != pkt->size) {
2751 av_log(NULL, ist->showed_multi_packet_warning ? AV_LOG_VERBOSE : AV_LOG_WARNING,
2752 "Multiple frames in a packet from stream %d\n", pkt->stream_index);
2753 ist->showed_multi_packet_warning = 1;
2756 switch (ist->st->codec->codec_type) {
2757 case AVMEDIA_TYPE_AUDIO:
2758 ret = transcode_audio (ist, &avpkt, &got_output);
2760 case AVMEDIA_TYPE_VIDEO:
2761 ret = transcode_video (ist, &avpkt, &got_output, &pkt_pts);
2762 if (avpkt.duration) {
2763 duration = av_rescale_q(avpkt.duration, ist->st->time_base, AV_TIME_BASE_Q);
2764 } else if(ist->st->codec->time_base.num != 0 && ist->st->codec->time_base.den != 0) {
2765 int ticks= ist->st->parser ? ist->st->parser->repeat_pict+1 : ist->st->codec->ticks_per_frame;
2766 duration = ((int64_t)AV_TIME_BASE *
2767 ist->st->codec->time_base.num * ticks) /
2768 ist->st->codec->time_base.den;
2772 if(ist->dts != AV_NOPTS_VALUE && duration) {
2773 ist->next_dts += duration;
2775 ist->next_dts = AV_NOPTS_VALUE;
2778 ist->next_pts += duration; //FIXME the duration is not correct in some cases
2780 case AVMEDIA_TYPE_SUBTITLE:
2781 ret = transcode_subtitles(ist, &avpkt, &got_output);
2791 avpkt.pts= AV_NOPTS_VALUE;
2793 // touch data and size only if not EOF
2795 if(ist->st->codec->codec_type != AVMEDIA_TYPE_AUDIO)
2805 /* handle stream copy */
2806 if (!ist->decoding_needed) {
2807 rate_emu_sleep(ist);
2808 ist->dts = ist->next_dts;
2809 switch (ist->st->codec->codec_type) {
2810 case AVMEDIA_TYPE_AUDIO:
2811 ist->next_dts += ((int64_t)AV_TIME_BASE * ist->st->codec->frame_size) /
2812 ist->st->codec->sample_rate;
2814 case AVMEDIA_TYPE_VIDEO:
2815 if (pkt->duration) {
2816 ist->next_dts += av_rescale_q(pkt->duration, ist->st->time_base, AV_TIME_BASE_Q);
2817 } else if(ist->st->codec->time_base.num != 0) {
2818 int ticks= ist->st->parser ? ist->st->parser->repeat_pict + 1 : ist->st->codec->ticks_per_frame;
2819 ist->next_dts += ((int64_t)AV_TIME_BASE *
2820 ist->st->codec->time_base.num * ticks) /
2821 ist->st->codec->time_base.den;
2825 ist->pts = ist->dts;
2826 ist->next_pts = ist->next_dts;
2828 for (i = 0; pkt && i < nb_output_streams; i++) {
2829 OutputStream *ost = output_streams[i];
2831 if (!check_output_constraints(ist, ost) || ost->encoding_needed)
2834 do_streamcopy(ist, ost, pkt);
2840 static void print_sdp(void)
2844 AVFormatContext **avc = av_malloc(sizeof(*avc) * nb_output_files);
2848 for (i = 0; i < nb_output_files; i++)
2849 avc[i] = output_files[i]->ctx;
2851 av_sdp_create(avc, nb_output_files, sdp, sizeof(sdp));
2852 printf("SDP:\n%s\n", sdp);
2857 static int init_input_stream(int ist_index, char *error, int error_len)
2860 InputStream *ist = input_streams[ist_index];
2862 if (ist->decoding_needed) {
2863 AVCodec *codec = ist->dec;
2865 snprintf(error, error_len, "Decoder (codec %s) not found for input stream #%d:%d",
2866 avcodec_get_name(ist->st->codec->codec_id), ist->file_index, ist->st->index);
2867 return AVERROR(EINVAL);
2870 ist->dr1 = codec->capabilities & CODEC_CAP_DR1;
2871 if (codec->type == AVMEDIA_TYPE_VIDEO && ist->dr1) {
2872 ist->st->codec->get_buffer = codec_get_buffer;
2873 ist->st->codec->release_buffer = codec_release_buffer;
2874 ist->st->codec->opaque = ist;
2877 if (!av_dict_get(ist->opts, "threads", NULL, 0))
2878 av_dict_set(&ist->opts, "threads", "auto", 0);
2879 if (avcodec_open2(ist->st->codec, codec, &ist->opts) < 0) {
2880 snprintf(error, error_len, "Error while opening decoder for input stream #%d:%d",
2881 ist->file_index, ist->st->index);
2882 return AVERROR(EINVAL);
2884 assert_codec_experimental(ist->st->codec, 0);
2885 assert_avoptions(ist->opts);
2887 if (ist->st->codec->codec_type == AVMEDIA_TYPE_AUDIO) {
2888 for (i = 0; i < nb_output_streams; i++) {
2889 OutputStream *ost = output_streams[i];
2890 if (ost->source_index == ist_index) {
2891 if (!ist->st->codec->channel_layout || !ost->st->codec->channel_layout)
2892 get_default_channel_layouts(ost, ist);
2899 ist->next_pts = AV_NOPTS_VALUE;
2900 ist->next_dts = AV_NOPTS_VALUE;
2906 static InputStream *get_input_stream(OutputStream *ost)
2908 if (ost->source_index >= 0)
2909 return input_streams[ost->source_index];
2912 FilterGraph *fg = ost->filter->graph;
2915 for (i = 0; i < fg->nb_inputs; i++)
2916 if (fg->inputs[i]->ist->st->codec->codec_type == ost->st->codec->codec_type)
2917 return fg->inputs[i]->ist;
2923 static int transcode_init(void)
2925 int ret = 0, i, j, k;
2926 AVFormatContext *oc;
2927 AVCodecContext *codec, *icodec;
2933 /* init framerate emulation */
2934 for (i = 0; i < nb_input_files; i++) {
2935 InputFile *ifile = input_files[i];
2936 if (ifile->rate_emu)
2937 for (j = 0; j < ifile->nb_streams; j++)
2938 input_streams[j + ifile->ist_index]->start = av_gettime();
2941 /* output stream init */
2942 for (i = 0; i < nb_output_files; i++) {
2943 oc = output_files[i]->ctx;
2944 if (!oc->nb_streams && !(oc->oformat->flags & AVFMT_NOSTREAMS)) {
2945 av_dump_format(oc, i, oc->filename, 1);
2946 av_log(NULL, AV_LOG_ERROR, "Output file #%d does not contain any stream\n", i);
2947 return AVERROR(EINVAL);
2951 /* init complex filtergraphs */
2952 for (i = 0; i < nb_filtergraphs; i++)
2953 if ((ret = avfilter_graph_config(filtergraphs[i]->graph, NULL)) < 0)
2956 /* for each output stream, we compute the right encoding parameters */
2957 for (i = 0; i < nb_output_streams; i++) {
2958 ost = output_streams[i];
2959 oc = output_files[ost->file_index]->ctx;
2960 ist = get_input_stream(ost);
2962 if (ost->attachment_filename)
2965 codec = ost->st->codec;
2968 icodec = ist->st->codec;
2970 ost->st->disposition = ist->st->disposition;
2971 codec->bits_per_raw_sample = icodec->bits_per_raw_sample;
2972 codec->chroma_sample_location = icodec->chroma_sample_location;
2975 if (ost->stream_copy) {
2976 uint64_t extra_size;
2978 av_assert0(ist && !ost->filter);
2980 extra_size = (uint64_t)icodec->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE;
2982 if (extra_size > INT_MAX) {
2983 return AVERROR(EINVAL);
2986 /* if stream_copy is selected, no need to decode or encode */
2987 codec->codec_id = icodec->codec_id;
2988 codec->codec_type = icodec->codec_type;
2990 if (!codec->codec_tag) {
2991 if (!oc->oformat->codec_tag ||
2992 av_codec_get_id (oc->oformat->codec_tag, icodec->codec_tag) == codec->codec_id ||
2993 av_codec_get_tag(oc->oformat->codec_tag, icodec->codec_id) <= 0)
2994 codec->codec_tag = icodec->codec_tag;
2997 codec->bit_rate = icodec->bit_rate;
2998 codec->rc_max_rate = icodec->rc_max_rate;
2999 codec->rc_buffer_size = icodec->rc_buffer_size;
3000 codec->field_order = icodec->field_order;
3001 codec->extradata = av_mallocz(extra_size);
3002 if (!codec->extradata) {
3003 return AVERROR(ENOMEM);
3005 memcpy(codec->extradata, icodec->extradata, icodec->extradata_size);
3006 codec->extradata_size= icodec->extradata_size;
3008 codec->time_base = ist->st->time_base;
3010 * Avi is a special case here because it supports variable fps but
3011 * having the fps and timebase differe significantly adds quite some
3014 if(!strcmp(oc->oformat->name, "avi")) {
3015 if ( copy_tb<0 && av_q2d(icodec->time_base)*icodec->ticks_per_frame > 2*av_q2d(ist->st->time_base)
3016 && av_q2d(ist->st->time_base) < 1.0/500
3018 codec->time_base = icodec->time_base;
3019 codec->time_base.num *= icodec->ticks_per_frame;
3020 codec->time_base.den *= 2;
3021 codec->ticks_per_frame = 2;
3023 } else if(!(oc->oformat->flags & AVFMT_VARIABLE_FPS)
3024 && strcmp(oc->oformat->name, "mov") && strcmp(oc->oformat->name, "mp4") && strcmp(oc->oformat->name, "3gp")
3025 && strcmp(oc->oformat->name, "3g2") && strcmp(oc->oformat->name, "psp") && strcmp(oc->oformat->name, "ipod")
3027 if( copy_tb<0 && av_q2d(icodec->time_base)*icodec->ticks_per_frame > av_q2d(ist->st->time_base)
3028 && av_q2d(ist->st->time_base) < 1.0/500
3030 codec->time_base = icodec->time_base;
3031 codec->time_base.num *= icodec->ticks_per_frame;
3034 av_reduce(&codec->time_base.num, &codec->time_base.den,
3035 codec->time_base.num, codec->time_base.den, INT_MAX);
3037 switch (codec->codec_type) {
3038 case AVMEDIA_TYPE_AUDIO:
3039 if (audio_volume != 256) {
3040 av_log(NULL, AV_LOG_FATAL, "-acodec copy and -vol are incompatible (frames are not decoded)\n");
3043 codec->channel_layout = icodec->channel_layout;
3044 codec->sample_rate = icodec->sample_rate;
3045 codec->channels = icodec->channels;
3046 codec->frame_size = icodec->frame_size;
3047 codec->audio_service_type = icodec->audio_service_type;
3048 codec->block_align = icodec->block_align;
3050 case AVMEDIA_TYPE_VIDEO:
3051 codec->pix_fmt = icodec->pix_fmt;
3052 codec->width = icodec->width;
3053 codec->height = icodec->height;
3054 codec->has_b_frames = icodec->has_b_frames;
3055 if (!codec->sample_aspect_ratio.num) {
3056 codec->sample_aspect_ratio =
3057 ost->st->sample_aspect_ratio =
3058 ist->st->sample_aspect_ratio.num ? ist->st->sample_aspect_ratio :
3059 ist->st->codec->sample_aspect_ratio.num ?
3060 ist->st->codec->sample_aspect_ratio : (AVRational){0, 1};
3062 ost->st->avg_frame_rate = ist->st->avg_frame_rate;
3064 case AVMEDIA_TYPE_SUBTITLE:
3065 codec->width = icodec->width;
3066 codec->height = icodec->height;
3068 case AVMEDIA_TYPE_DATA:
3069 case AVMEDIA_TYPE_ATTACHMENT:
3076 ost->enc = avcodec_find_encoder(codec->codec_id);
3078 /* should only happen when a default codec is not present. */
3079 snprintf(error, sizeof(error), "Encoder (codec %s) not found for output stream #%d:%d",
3080 avcodec_get_name(ost->st->codec->codec_id), ost->file_index, ost->index);
3081 ret = AVERROR(EINVAL);
3086 ist->decoding_needed = 1;
3087 ost->encoding_needed = 1;
3089 switch (codec->codec_type) {
3090 case AVMEDIA_TYPE_AUDIO:
3091 ost->fifo = av_fifo_alloc(1024);
3093 return AVERROR(ENOMEM);
3096 if (!codec->sample_rate)
3097 codec->sample_rate = icodec->sample_rate;
3098 choose_sample_rate(ost->st, ost->enc);
3099 codec->time_base = (AVRational){ 1, codec->sample_rate };
3101 if (codec->sample_fmt == AV_SAMPLE_FMT_NONE)
3102 codec->sample_fmt = icodec->sample_fmt;
3103 choose_sample_fmt(ost->st, ost->enc);
3105 if (ost->audio_channels_mapped) {
3106 /* the requested output channel is set to the number of
3107 * -map_channel only if no -ac are specified */
3108 if (!codec->channels) {
3109 codec->channels = ost->audio_channels_mapped;
3110 codec->channel_layout = av_get_default_channel_layout(codec->channels);
3111 if (!codec->channel_layout) {
3112 av_log(NULL, AV_LOG_FATAL, "Unable to find an appropriate channel layout for requested number of channel\n");
3116 /* fill unused channel mapping with -1 (which means a muted
3117 * channel in case the number of output channels is bigger
3118 * than the number of mapped channel) */
3119 for (j = ost->audio_channels_mapped; j < FF_ARRAY_ELEMS(ost->audio_channels_map); j++)
3120 ost->audio_channels_map[j] = -1;
3121 } else if (!codec->channels) {
3122 codec->channels = icodec->channels;
3123 codec->channel_layout = icodec->channel_layout;
3125 if (av_get_channel_layout_nb_channels(codec->channel_layout) != codec->channels)
3126 codec->channel_layout = 0;
3129 // ost->audio_resample = codec->sample_rate != icodec->sample_rate || audio_sync_method > 1;
3130 // ost->audio_resample |= codec->sample_fmt != icodec->sample_fmt
3131 // || codec->channel_layout != icodec->channel_layout;
3132 icodec->request_channels = codec-> channels;
3133 ost->resample_sample_fmt = icodec->sample_fmt;
3134 ost->resample_sample_rate = icodec->sample_rate;
3135 ost->resample_channels = icodec->channels;
3136 ost->resample_channel_layout = icodec->channel_layout;
3138 case AVMEDIA_TYPE_VIDEO:
3141 fg = init_simple_filtergraph(ist, ost);
3142 if (configure_video_filters(fg)) {
3143 av_log(NULL, AV_LOG_FATAL, "Error opening filters!\n");
3148 if (ist && !ost->frame_rate.num)
3149 ost->frame_rate = ist->st->r_frame_rate.num ? ist->st->r_frame_rate : (AVRational) { 25, 1 };
3150 if (ost->enc && ost->enc->supported_framerates && !ost->force_fps) {
3151 int idx = av_find_nearest_q_idx(ost->frame_rate, ost->enc->supported_framerates);
3152 ost->frame_rate = ost->enc->supported_framerates[idx];
3154 codec->time_base = (AVRational){ost->frame_rate.den, ost->frame_rate.num};
3155 if ( av_q2d(codec->time_base) < 0.001 && video_sync_method != VSYNC_PASSTHROUGH
3156 && (video_sync_method == VSYNC_CFR || (video_sync_method == VSYNC_AUTO && !(oc->oformat->flags & AVFMT_VARIABLE_FPS)))){
3157 av_log(oc, AV_LOG_WARNING, "Frame rate very high for a muxer not efficiently supporting it.\n"
3158 "Please consider specifying a lower framerate, a different muxer or -vsync 2\n");
3160 for (j = 0; j < ost->forced_kf_count; j++)
3161 ost->forced_kf_pts[j] = av_rescale_q(ost->forced_kf_pts[j],
3165 codec->width = ost->filter->filter->inputs[0]->w;
3166 codec->height = ost->filter->filter->inputs[0]->h;
3167 codec->sample_aspect_ratio = ost->st->sample_aspect_ratio =
3168 ost->frame_aspect_ratio ? // overridden by the -aspect cli option
3169 av_d2q(ost->frame_aspect_ratio * codec->height/codec->width, 255) :
3170 ost->filter->filter->inputs[0]->sample_aspect_ratio;
3171 codec->pix_fmt = ost->filter->filter->inputs[0]->format;
3173 if (codec->width != icodec->width ||
3174 codec->height != icodec->height ||
3175 codec->pix_fmt != icodec->pix_fmt) {
3176 codec->bits_per_raw_sample = frame_bits_per_raw_sample;
3180 case AVMEDIA_TYPE_SUBTITLE:
3181 codec->time_base = (AVRational){1, 1000};
3188 if (codec->flags & (CODEC_FLAG_PASS1 | CODEC_FLAG_PASS2)) {
3189 char logfilename[1024];
3192 snprintf(logfilename, sizeof(logfilename), "%s-%d.log",
3193 pass_logfilename_prefix ? pass_logfilename_prefix : DEFAULT_PASS_LOGFILENAME_PREFIX,
3195 if (!strcmp(ost->enc->name, "libx264")) {
3196 av_dict_set(&ost->opts, "stats", logfilename, AV_DICT_DONT_OVERWRITE);
3198 if (codec->flags & CODEC_FLAG_PASS2) {
3200 size_t logbuffer_size;
3201 if (cmdutils_read_file(logfilename, &logbuffer, &logbuffer_size) < 0) {
3202 av_log(NULL, AV_LOG_FATAL, "Error reading log file '%s' for pass-2 encoding\n",
3206 codec->stats_in = logbuffer;
3208 if (codec->flags & CODEC_FLAG_PASS1) {
3209 f = fopen(logfilename, "wb");
3211 av_log(NULL, AV_LOG_FATAL, "Cannot write log file '%s' for pass-1 encoding: %s\n",
3212 logfilename, strerror(errno));
3222 /* open each encoder */
3223 for (i = 0; i < nb_output_streams; i++) {
3224 ost = output_streams[i];
3225 if (ost->encoding_needed) {
3226 AVCodec *codec = ost->enc;
3227 AVCodecContext *dec = NULL;
3229 if ((ist = get_input_stream(ost)))
3230 dec = ist->st->codec;
3231 if (dec && dec->subtitle_header) {
3232 ost->st->codec->subtitle_header = av_malloc(dec->subtitle_header_size);
3233 if (!ost->st->codec->subtitle_header) {
3234 ret = AVERROR(ENOMEM);
3237 memcpy(ost->st->codec->subtitle_header, dec->subtitle_header, dec->subtitle_header_size);
3238 ost->st->codec->subtitle_header_size = dec->subtitle_header_size;
3240 if (!av_dict_get(ost->opts, "threads", NULL, 0))
3241 av_dict_set(&ost->opts, "threads", "auto", 0);
3242 if (avcodec_open2(ost->st->codec, codec, &ost->opts) < 0) {
3243 snprintf(error, sizeof(error), "Error while opening encoder for output stream #%d:%d - maybe incorrect parameters such as bit_rate, rate, width or height",
3244 ost->file_index, ost->index);
3245 ret = AVERROR(EINVAL);
3248 assert_codec_experimental(ost->st->codec, 1);
3249 assert_avoptions(ost->opts);
3250 if (ost->st->codec->bit_rate && ost->st->codec->bit_rate < 1000)
3251 av_log(NULL, AV_LOG_WARNING, "The bitrate parameter is set too low."
3252 " It takes bits/s as argument, not kbits/s\n");
3253 extra_size += ost->st->codec->extradata_size;
3255 if (ost->st->codec->me_threshold)
3256 input_streams[ost->source_index]->st->codec->debug |= FF_DEBUG_MV;
3260 /* init input streams */
3261 for (i = 0; i < nb_input_streams; i++)
3262 if ((ret = init_input_stream(i, error, sizeof(error))) < 0)
3265 /* discard unused programs */
3266 for (i = 0; i < nb_input_files; i++) {
3267 InputFile *ifile = input_files[i];
3268 for (j = 0; j < ifile->ctx->nb_programs; j++) {
3269 AVProgram *p = ifile->ctx->programs[j];
3270 int discard = AVDISCARD_ALL;
3272 for (k = 0; k < p->nb_stream_indexes; k++)
3273 if (!input_streams[ifile->ist_index + p->stream_index[k]]->discard) {
3274 discard = AVDISCARD_DEFAULT;
3277 p->discard = discard;
3281 /* open files and write file headers */
3282 for (i = 0; i < nb_output_files; i++) {
3283 oc = output_files[i]->ctx;
3284 oc->interrupt_callback = int_cb;
3285 if (avformat_write_header(oc, &output_files[i]->opts) < 0) {
3286 snprintf(error, sizeof(error), "Could not write header for output file #%d (incorrect codec parameters ?)", i);
3287 ret = AVERROR(EINVAL);
3290 // assert_avoptions(output_files[i]->opts);
3291 if (strcmp(oc->oformat->name, "rtp")) {
3297 /* dump the file output parameters - cannot be done before in case
3299 for (i = 0; i < nb_output_files; i++) {
3300 av_dump_format(output_files[i]->ctx, i, output_files[i]->ctx->filename, 1);
3303 /* dump the stream mapping */
3304 av_log(NULL, AV_LOG_INFO, "Stream mapping:\n");
3305 for (i = 0; i < nb_input_streams; i++) {
3306 ist = input_streams[i];
3308 for (j = 0; j < ist->nb_filters; j++) {
3309 AVFilterLink *link = ist->filters[j]->filter->outputs[0];
3310 if (ist->filters[j]->graph->graph_desc) {
3311 av_log(NULL, AV_LOG_INFO, " Stream #%d:%d (%s) -> %s",
3312 ist->file_index, ist->st->index, ist->dec ? ist->dec->name : "?",
3313 link->dst->filter->name);
3314 if (link->dst->input_count > 1)
3315 av_log(NULL, AV_LOG_INFO, ":%s", link->dstpad->name);
3316 if (nb_filtergraphs > 1)
3317 av_log(NULL, AV_LOG_INFO, " (graph %d)", ist->filters[j]->graph->index);
3318 av_log(NULL, AV_LOG_INFO, "\n");
3323 for (i = 0; i < nb_output_streams; i++) {
3324 ost = output_streams[i];
3326 if (ost->attachment_filename) {
3327 /* an attached file */
3328 av_log(NULL, AV_LOG_INFO, " File %s -> Stream #%d:%d\n",
3329 ost->attachment_filename, ost->file_index, ost->index);
3333 if (ost->filter && ost->filter->graph->graph_desc) {
3334 /* output from a complex graph */
3335 AVFilterLink *link = ost->filter->filter->inputs[0];
3336 av_log(NULL, AV_LOG_INFO, " %s", link->src->filter->name);
3337 if (link->src->output_count > 1)
3338 av_log(NULL, AV_LOG_INFO, ":%s", link->srcpad->name);
3339 if (nb_filtergraphs > 1)
3340 av_log(NULL, AV_LOG_INFO, " (graph %d)", ost->filter->graph->index);
3342 av_log(NULL, AV_LOG_INFO, " -> Stream #%d:%d (%s)\n", ost->file_index,
3343 ost->index, ost->enc ? ost->enc->name : "?");
3347 av_log(NULL, AV_LOG_INFO, " Stream #%d:%d -> #%d:%d",
3348 input_streams[ost->source_index]->file_index,
3349 input_streams[ost->source_index]->st->index,
3352 if (ost->audio_channels_mapped) {
3353 av_log(NULL, AV_LOG_INFO, " [ch:");
3354 for (j = 0; j < ost->audio_channels_mapped; j++)
3355 if (ost->audio_channels_map[j] == -1)
3356 av_log(NULL, AV_LOG_INFO, " M");
3358 av_log(NULL, AV_LOG_INFO, " %d", ost->audio_channels_map[j]);
3359 av_log(NULL, AV_LOG_INFO, "]");
3361 if (ost->sync_ist != input_streams[ost->source_index])
3362 av_log(NULL, AV_LOG_INFO, " [sync #%d:%d]",
3363 ost->sync_ist->file_index,
3364 ost->sync_ist->st->index);
3365 if (ost->stream_copy)
3366 av_log(NULL, AV_LOG_INFO, " (copy)");
3368 av_log(NULL, AV_LOG_INFO, " (%s -> %s)", input_streams[ost->source_index]->dec ?
3369 input_streams[ost->source_index]->dec->name : "?",
3370 ost->enc ? ost->enc->name : "?");
3371 av_log(NULL, AV_LOG_INFO, "\n");
3375 av_log(NULL, AV_LOG_ERROR, "%s\n", error);
3387 * The following code is the main loop of the file converter
3389 static int transcode(void)
3392 AVFormatContext *is, *os;
3396 int no_packet_count = 0;
3397 int64_t timer_start;
3400 if (!(no_packet = av_mallocz(nb_input_files)))
3403 ret = transcode_init();
3408 av_log(NULL, AV_LOG_INFO, "Press [q] to stop, [?] for help\n");
3411 timer_start = av_gettime();
3413 for (; received_sigterm == 0;) {
3414 int file_index, ist_index, past_recording_time = 1;
3417 int64_t cur_time= av_gettime();
3419 ipts_min = INT64_MAX;
3420 /* if 'q' pressed, exits */
3422 static int64_t last_time;
3423 if (received_nb_signals)
3425 /* read_key() returns 0 on EOF */
3426 if(cur_time - last_time >= 100000 && !run_as_daemon){
3428 last_time = cur_time;
3433 if (key == '+') av_log_set_level(av_log_get_level()+10);
3434 if (key == '-') av_log_set_level(av_log_get_level()-10);
3435 if (key == 's') qp_hist ^= 1;
3438 do_hex_dump = do_pkt_dump = 0;
3439 } else if(do_pkt_dump){
3443 av_log_set_level(AV_LOG_DEBUG);
3445 if (key == 'c' || key == 'C'){
3446 char buf[4096], target[64], command[256], arg[256] = {0};
3449 fprintf(stderr, "\nEnter command: <target> <time> <command>[ <argument>]\n");
3451 while ((k = read_key()) != '\n' && k != '\r' && i < sizeof(buf)-1)
3456 (n = sscanf(buf, "%63[^ ] %lf %255[^ ] %255[^\n]", target, &time, command, arg)) >= 3) {
3457 av_log(NULL, AV_LOG_DEBUG, "Processing command target:%s time:%f command:%s arg:%s",
3458 target, time, command, arg);
3459 for (i = 0; i < nb_filtergraphs; i++) {
3460 FilterGraph *fg = filtergraphs[i];
3463 ret = avfilter_graph_send_command(fg->graph, target, command, arg, buf, sizeof(buf),
3464 key == 'c' ? AVFILTER_CMD_FLAG_ONE : 0);
3465 fprintf(stderr, "Command reply for stream %d: ret:%d res:%s\n", i, ret, buf);
3467 ret = avfilter_graph_queue_command(fg->graph, target, command, arg, 0, time);
3472 av_log(NULL, AV_LOG_ERROR,
3473 "Parse error, at least 3 arguments were expected, "
3474 "only %d given in string '%s'\n", n, buf);
3477 if (key == 'd' || key == 'D'){
3480 debug = input_streams[0]->st->codec->debug<<1;
3481 if(!debug) debug = 1;
3482 while(debug & (FF_DEBUG_DCT_COEFF|FF_DEBUG_VIS_QP|FF_DEBUG_VIS_MB_TYPE)) //unsupported, would just crash
3485 if(scanf("%d", &debug)!=1)
3486 fprintf(stderr,"error parsing debug value\n");
3487 for(i=0;i<nb_input_streams;i++) {
3488 input_streams[i]->st->codec->debug = debug;
3490 for(i=0;i<nb_output_streams;i++) {
3491 ost = output_streams[i];
3492 ost->st->codec->debug = debug;
3494 if(debug) av_log_set_level(AV_LOG_DEBUG);
3495 fprintf(stderr,"debug=%d\n", debug);
3498 fprintf(stderr, "key function\n"
3499 "? show this help\n"
3500 "+ increase verbosity\n"
3501 "- decrease verbosity\n"
3502 "c Send command to filtergraph\n"
3503 "D cycle through available debug modes\n"
3504 "h dump packets/hex press to cycle through the 3 states\n"
3506 "s Show QP histogram\n"
3511 /* check if there's any stream where output is still needed */
3512 for (i = 0; i < nb_output_streams; i++) {
3514 ost = output_streams[i];
3515 of = output_files[ost->file_index];
3516 os = output_files[ost->file_index]->ctx;
3517 if (ost->is_past_recording_time ||
3518 (os->pb && avio_tell(os->pb) >= of->limit_filesize))
3520 if (ost->frame_number >= ost->max_frames) {
3522 for (j = 0; j < of->ctx->nb_streams; j++)
3523 output_streams[of->ost_index + j]->is_past_recording_time = 1;
3526 past_recording_time = 0;
3528 if (past_recording_time)
3531 /* select the stream that we must read now by looking at the
3532 smallest output pts */
3534 for (i = 0; i < nb_input_streams; i++) {
3536 ist = input_streams[i];
3538 if (ist->discard || no_packet[ist->file_index])
3540 if (!input_files[ist->file_index]->eof_reached) {
3541 if (ipts < ipts_min) {
3543 file_index = ist->file_index;
3547 /* if none, if is finished */
3548 if (file_index < 0) {
3549 if (no_packet_count) {
3550 no_packet_count = 0;
3551 memset(no_packet, 0, nb_input_files);
3558 /* read a frame from it and output it in the fifo */
3559 is = input_files[file_index]->ctx;
3560 ret = av_read_frame(is, &pkt);
3561 if (ret == AVERROR(EAGAIN)) {
3562 no_packet[file_index] = 1;
3567 input_files[file_index]->eof_reached = 1;
3569 for (i = 0; i < input_files[file_index]->nb_streams; i++) {
3570 ist = input_streams[input_files[file_index]->ist_index + i];
3571 if (ist->decoding_needed)
3572 output_packet(ist, NULL);
3581 no_packet_count = 0;
3582 memset(no_packet, 0, nb_input_files);
3585 av_pkt_dump_log2(NULL, AV_LOG_DEBUG, &pkt, do_hex_dump,
3586 is->streams[pkt.stream_index]);
3588 /* the following test is needed in case new streams appear
3589 dynamically in stream : we ignore them */
3590 if (pkt.stream_index >= input_files[file_index]->nb_streams)
3591 goto discard_packet;
3592 ist_index = input_files[file_index]->ist_index + pkt.stream_index;
3593 ist = input_streams[ist_index];
3595 goto discard_packet;
3597 if (pkt.dts != AV_NOPTS_VALUE)
3598 pkt.dts += av_rescale_q(input_files[ist->file_index]->ts_offset, AV_TIME_BASE_Q, ist->st->time_base);
3599 if (pkt.pts != AV_NOPTS_VALUE)
3600 pkt.pts += av_rescale_q(input_files[ist->file_index]->ts_offset, AV_TIME_BASE_Q, ist->st->time_base);
3602 if (pkt.pts != AV_NOPTS_VALUE)
3603 pkt.pts *= ist->ts_scale;
3604 if (pkt.dts != AV_NOPTS_VALUE)
3605 pkt.dts *= ist->ts_scale;
3608 av_log(NULL, AV_LOG_INFO, "demuxer -> ist_index:%d type:%s "
3609 "next_pts:%s next_pts_time:%s pkt_pts:%s pkt_pts_time:%s pkt_dts:%s pkt_dts_time:%s off:%"PRId64"\n",
3610 ist_index, av_get_media_type_string(ist->st->codec->codec_type),
3611 av_ts2str(ist->next_pts), av_ts2timestr(ist->next_pts, &ist->st->time_base),
3612 av_ts2str(pkt.pts), av_ts2timestr(pkt.pts, &ist->st->time_base),
3613 av_ts2str(pkt.dts), av_ts2timestr(pkt.dts, &ist->st->time_base),
3614 input_files[ist->file_index]->ts_offset);
3617 if (pkt.dts != AV_NOPTS_VALUE && ist->next_dts != AV_NOPTS_VALUE && !copy_ts) {
3618 int64_t pkt_dts = av_rescale_q(pkt.dts, ist->st->time_base, AV_TIME_BASE_Q);
3619 int64_t delta = pkt_dts - ist->next_dts;
3620 if (is->iformat->flags & AVFMT_TS_DISCONT) {
3621 if(delta < -1LL*dts_delta_threshold*AV_TIME_BASE ||
3622 (delta > 1LL*dts_delta_threshold*AV_TIME_BASE &&
3623 ist->st->codec->codec_type != AVMEDIA_TYPE_SUBTITLE) ||
3624 pkt_dts+1<ist->pts){
3625 input_files[ist->file_index]->ts_offset -= delta;
3626 av_log(NULL, AV_LOG_DEBUG,
3627 "timestamp discontinuity %"PRId64", new offset= %"PRId64"\n",
3628 delta, input_files[ist->file_index]->ts_offset);
3629 pkt.dts-= av_rescale_q(delta, AV_TIME_BASE_Q, ist->st->time_base);
3630 if (pkt.pts != AV_NOPTS_VALUE)
3631 pkt.pts-= av_rescale_q(delta, AV_TIME_BASE_Q, ist->st->time_base);
3634 if ( delta < -1LL*dts_error_threshold*AV_TIME_BASE ||
3635 (delta > 1LL*dts_error_threshold*AV_TIME_BASE && ist->st->codec->codec_type != AVMEDIA_TYPE_SUBTITLE) ||
3636 pkt_dts+1<ist->pts){
3637 av_log(NULL, AV_LOG_WARNING, "DTS %"PRId64", next:%"PRId64" st:%d invalid dropping\n", pkt.dts, ist->next_dts, pkt.stream_index);
3638 pkt.dts = AV_NOPTS_VALUE;
3640 if (pkt.pts != AV_NOPTS_VALUE){
3641 int64_t pkt_pts = av_rescale_q(pkt.pts, ist->st->time_base, AV_TIME_BASE_Q);
3642 delta = pkt_pts - ist->next_dts;
3643 if ( delta < -1LL*dts_error_threshold*AV_TIME_BASE ||
3644 (delta > 1LL*dts_error_threshold*AV_TIME_BASE && ist->st->codec->codec_type != AVMEDIA_TYPE_SUBTITLE) ||
3645 pkt_pts+1<ist->pts) {
3646 av_log(NULL, AV_LOG_WARNING, "PTS %"PRId64", next:%"PRId64" invalid dropping st:%d\n", pkt.pts, ist->next_dts, pkt.stream_index);
3647 pkt.pts = AV_NOPTS_VALUE;
3653 // fprintf(stderr,"read #%d.%d size=%d\n", ist->file_index, ist->st->index, pkt.size);
3654 if (output_packet(ist, &pkt) < 0 ||
3655 ((ret = poll_filters()) < 0 && ret != AVERROR_EOF)) {
3656 av_log(NULL, AV_LOG_ERROR, "Error while decoding stream #%d:%d\n",
3657 ist->file_index, ist->st->index);
3660 av_free_packet(&pkt);
3665 av_free_packet(&pkt);
3667 /* dump report by using the output first video and audio streams */
3668 print_report(0, timer_start, cur_time);
3671 /* at the end of stream, we must flush the decoder buffers */
3672 for (i = 0; i < nb_input_streams; i++) {
3673 ist = input_streams[i];
3674 if (!input_files[ist->file_index]->eof_reached && ist->decoding_needed) {
3675 output_packet(ist, NULL);
3683 /* write the trailer if needed and close file */
3684 for (i = 0; i < nb_output_files; i++) {
3685 os = output_files[i]->ctx;
3686 av_write_trailer(os);
3689 /* dump report by using the first video and audio streams */
3690 print_report(1, timer_start, av_gettime());
3692 /* close each encoder */
3693 for (i = 0; i < nb_output_streams; i++) {
3694 ost = output_streams[i];
3695 if (ost->encoding_needed) {
3696 av_freep(&ost->st->codec->stats_in);
3697 avcodec_close(ost->st->codec);
3701 /* close each decoder */
3702 for (i = 0; i < nb_input_streams; i++) {
3703 ist = input_streams[i];
3704 if (ist->decoding_needed) {
3705 avcodec_close(ist->st->codec);
3713 av_freep(&no_packet);
3715 if (output_streams) {
3716 for (i = 0; i < nb_output_streams; i++) {
3717 ost = output_streams[i];
3719 if (ost->stream_copy)
3720 av_freep(&ost->st->codec->extradata);
3722 fclose(ost->logfile);
3723 ost->logfile = NULL;
3725 av_fifo_free(ost->fifo); /* works even if fifo is not
3726 initialized but set to zero */
3727 av_freep(&ost->st->codec->subtitle_header);
3728 av_free(ost->forced_kf_pts);
3729 swr_free(&ost->swr);
3730 av_dict_free(&ost->opts);
3737 static int opt_frame_crop(const char *opt, const char *arg)
3739 av_log(NULL, AV_LOG_FATAL, "Option '%s' has been removed, use the crop filter instead\n", opt);
3740 return AVERROR(EINVAL);
3743 static int opt_pad(const char *opt, const char *arg)
3745 av_log(NULL, AV_LOG_FATAL, "Option '%s' has been removed, use the pad filter instead\n", opt);
3749 static int opt_video_channel(const char *opt, const char *arg)
3751 av_log(NULL, AV_LOG_WARNING, "This option is deprecated, use -channel.\n");
3752 return opt_default("channel", arg);
3755 static int opt_video_standard(const char *opt, const char *arg)
3757 av_log(NULL, AV_LOG_WARNING, "This option is deprecated, use -standard.\n");
3758 return opt_default("standard", arg);
3761 static int opt_audio_codec(OptionsContext *o, const char *opt, const char *arg)
3763 audio_codec_name = arg;
3764 return parse_option(o, "codec:a", arg, options);
3767 static int opt_video_codec(OptionsContext *o, const char *opt, const char *arg)
3769 video_codec_name = arg;
3770 return parse_option(o, "codec:v", arg, options);
3773 static int opt_subtitle_codec(OptionsContext *o, const char *opt, const char *arg)
3775 subtitle_codec_name = arg;
3776 return parse_option(o, "codec:s", arg, options);
3779 static int opt_data_codec(OptionsContext *o, const char *opt, const char *arg)
3781 return parse_option(o, "codec:d", arg, options);
3784 static int opt_map(OptionsContext *o, const char *opt, const char *arg)
3786 StreamMap *m = NULL;
3787 int i, negative = 0, file_idx;
3788 int sync_file_idx = -1, sync_stream_idx = 0;
3796 map = av_strdup(arg);
3798 /* parse sync stream first, just pick first matching stream */
3799 if (sync = strchr(map, ',')) {
3801 sync_file_idx = strtol(sync + 1, &sync, 0);
3802 if (sync_file_idx >= nb_input_files || sync_file_idx < 0) {
3803 av_log(NULL, AV_LOG_FATAL, "Invalid sync file index: %d.\n", sync_file_idx);
3808 for (i = 0; i < input_files[sync_file_idx]->nb_streams; i++)
3809 if (check_stream_specifier(input_files[sync_file_idx]->ctx,
3810 input_files[sync_file_idx]->ctx->streams[i], sync) == 1) {
3811 sync_stream_idx = i;
3814 if (i == input_files[sync_file_idx]->nb_streams) {
3815 av_log(NULL, AV_LOG_FATAL, "Sync stream specification in map %s does not "
3816 "match any streams.\n", arg);
3822 if (map[0] == '[') {
3823 /* this mapping refers to lavfi output */
3824 const char *c = map + 1;
3825 o->stream_maps = grow_array(o->stream_maps, sizeof(*o->stream_maps),
3826 &o->nb_stream_maps, o->nb_stream_maps + 1);
3827 m = &o->stream_maps[o->nb_stream_maps - 1];
3828 m->linklabel = av_get_token(&c, "]");
3829 if (!m->linklabel) {
3830 av_log(NULL, AV_LOG_ERROR, "Invalid output link label: %s.\n", map);
3834 file_idx = strtol(map, &p, 0);
3835 if (file_idx >= nb_input_files || file_idx < 0) {
3836 av_log(NULL, AV_LOG_FATAL, "Invalid input file index: %d.\n", file_idx);
3840 /* disable some already defined maps */
3841 for (i = 0; i < o->nb_stream_maps; i++) {
3842 m = &o->stream_maps[i];
3843 if (file_idx == m->file_index &&
3844 check_stream_specifier(input_files[m->file_index]->ctx,
3845 input_files[m->file_index]->ctx->streams[m->stream_index],
3846 *p == ':' ? p + 1 : p) > 0)
3850 for (i = 0; i < input_files[file_idx]->nb_streams; i++) {
3851 if (check_stream_specifier(input_files[file_idx]->ctx, input_files[file_idx]->ctx->streams[i],
3852 *p == ':' ? p + 1 : p) <= 0)
3854 o->stream_maps = grow_array(o->stream_maps, sizeof(*o->stream_maps),
3855 &o->nb_stream_maps, o->nb_stream_maps + 1);
3856 m = &o->stream_maps[o->nb_stream_maps - 1];
3858 m->file_index = file_idx;
3859 m->stream_index = i;
3861 if (sync_file_idx >= 0) {
3862 m->sync_file_index = sync_file_idx;
3863 m->sync_stream_index = sync_stream_idx;
3865 m->sync_file_index = file_idx;
3866 m->sync_stream_index = i;
3872 av_log(NULL, AV_LOG_FATAL, "Stream map '%s' matches no streams.\n", arg);
3880 static int opt_attach(OptionsContext *o, const char *opt, const char *arg)
3882 o->attachments = grow_array(o->attachments, sizeof(*o->attachments),
3883 &o->nb_attachments, o->nb_attachments + 1);
3884 o->attachments[o->nb_attachments - 1] = arg;
3888 static int opt_map_channel(OptionsContext *o, const char *opt, const char *arg)
3894 o->audio_channel_maps =
3895 grow_array(o->audio_channel_maps, sizeof(*o->audio_channel_maps),
3896 &o->nb_audio_channel_maps, o->nb_audio_channel_maps + 1);
3897 m = &o->audio_channel_maps[o->nb_audio_channel_maps - 1];
3899 /* muted channel syntax */
3900 n = sscanf(arg, "%d:%d.%d", &m->channel_idx, &m->ofile_idx, &m->ostream_idx);
3901 if ((n == 1 || n == 3) && m->channel_idx == -1) {
3902 m->file_idx = m->stream_idx = -1;
3904 m->ofile_idx = m->ostream_idx = -1;
3909 n = sscanf(arg, "%d.%d.%d:%d.%d",
3910 &m->file_idx, &m->stream_idx, &m->channel_idx,
3911 &m->ofile_idx, &m->ostream_idx);
3913 if (n != 3 && n != 5) {
3914 av_log(NULL, AV_LOG_FATAL, "Syntax error, mapchan usage: "
3915 "[file.stream.channel|-1][:syncfile:syncstream]\n");
3919 if (n != 5) // only file.stream.channel specified
3920 m->ofile_idx = m->ostream_idx = -1;
3923 if (m->file_idx < 0 || m->file_idx >= nb_input_files) {
3924 av_log(NULL, AV_LOG_FATAL, "mapchan: invalid input file index: %d\n",
3928 if (m->stream_idx < 0 ||
3929 m->stream_idx >= input_files[m->file_idx]->nb_streams) {
3930 av_log(NULL, AV_LOG_FATAL, "mapchan: invalid input file stream index #%d.%d\n",
3931 m->file_idx, m->stream_idx);
3934 st = input_files[m->file_idx]->ctx->streams[m->stream_idx];
3935 if (st->codec->codec_type != AVMEDIA_TYPE_AUDIO) {
3936 av_log(NULL, AV_LOG_FATAL, "mapchan: stream #%d.%d is not an audio stream.\n",
3937 m->file_idx, m->stream_idx);
3940 if (m->channel_idx < 0 || m->channel_idx >= st->codec->channels) {
3941 av_log(NULL, AV_LOG_FATAL, "mapchan: invalid audio channel #%d.%d.%d\n",
3942 m->file_idx, m->stream_idx, m->channel_idx);
3949 * Parse a metadata specifier in arg.
3950 * @param type metadata type is written here -- g(lobal)/s(tream)/c(hapter)/p(rogram)
3951 * @param index for type c/p, chapter/program index is written here
3952 * @param stream_spec for type s, the stream specifier is written here
3954 static void parse_meta_type(char *arg, char *type, int *index, const char **stream_spec)
3962 if (*(++arg) && *arg != ':') {
3963 av_log(NULL, AV_LOG_FATAL, "Invalid metadata specifier %s.\n", arg);
3966 *stream_spec = *arg == ':' ? arg + 1 : "";
3970 if (*(++arg) == ':')
3971 *index = strtol(++arg, NULL, 0);
3974 av_log(NULL, AV_LOG_FATAL, "Invalid metadata type %c.\n", *arg);
3981 static int copy_metadata(char *outspec, char *inspec, AVFormatContext *oc, AVFormatContext *ic, OptionsContext *o)
3983 AVDictionary **meta_in = NULL;
3984 AVDictionary **meta_out = NULL;
3986 char type_in, type_out;
3987 const char *istream_spec = NULL, *ostream_spec = NULL;
3988 int idx_in = 0, idx_out = 0;
3990 parse_meta_type(inspec, &type_in, &idx_in, &istream_spec);
3991 parse_meta_type(outspec, &type_out, &idx_out, &ostream_spec);
3994 if (type_out == 'g' || !*outspec)
3995 o->metadata_global_manual = 1;
3996 if (type_out == 's' || !*outspec)
3997 o->metadata_streams_manual = 1;
3998 if (type_out == 'c' || !*outspec)
3999 o->metadata_chapters_manual = 1;
4003 if (type_in == 'g' || type_out == 'g')
4004 o->metadata_global_manual = 1;
4005 if (type_in == 's' || type_out == 's')
4006 o->metadata_streams_manual = 1;
4007 if (type_in == 'c' || type_out == 'c')
4008 o->metadata_chapters_manual = 1;
4010 #define METADATA_CHECK_INDEX(index, nb_elems, desc)\
4011 if ((index) < 0 || (index) >= (nb_elems)) {\
4012 av_log(NULL, AV_LOG_FATAL, "Invalid %s index %d while processing metadata maps.\n",\
4017 #define SET_DICT(type, meta, context, index)\
4020 meta = &context->metadata;\
4023 METADATA_CHECK_INDEX(index, context->nb_chapters, "chapter")\
4024 meta = &context->chapters[index]->metadata;\
4027 METADATA_CHECK_INDEX(index, context->nb_programs, "program")\
4028 meta = &context->programs[index]->metadata;\
4032 SET_DICT(type_in, meta_in, ic, idx_in);
4033 SET_DICT(type_out, meta_out, oc, idx_out);
4035 /* for input streams choose first matching stream */
4036 if (type_in == 's') {
4037 for (i = 0; i < ic->nb_streams; i++) {
4038 if ((ret = check_stream_specifier(ic, ic->streams[i], istream_spec)) > 0) {
4039 meta_in = &ic->streams[i]->metadata;
4045 av_log(NULL, AV_LOG_FATAL, "Stream specifier %s does not match any streams.\n", istream_spec);
4050 if (type_out == 's') {
4051 for (i = 0; i < oc->nb_streams; i++) {
4052 if ((ret = check_stream_specifier(oc, oc->streams[i], ostream_spec)) > 0) {
4053 meta_out = &oc->streams[i]->metadata;
4054 av_dict_copy(meta_out, *meta_in, AV_DICT_DONT_OVERWRITE);
4059 av_dict_copy(meta_out, *meta_in, AV_DICT_DONT_OVERWRITE);
4064 static int opt_recording_timestamp(OptionsContext *o, const char *opt, const char *arg)
4067 int64_t recording_timestamp = parse_time_or_die(opt, arg, 0) / 1E6;
4068 struct tm time = *gmtime((time_t*)&recording_timestamp);
4069 strftime(buf, sizeof(buf), "creation_time=%FT%T%z", &time);
4070 parse_option(o, "metadata", buf, options);
4072 av_log(NULL, AV_LOG_WARNING, "%s is deprecated, set the 'creation_time' metadata "
4073 "tag instead.\n", opt);
4077 static AVCodec *find_codec_or_die(const char *name, enum AVMediaType type, int encoder)
4079 const char *codec_string = encoder ? "encoder" : "decoder";
4083 avcodec_find_encoder_by_name(name) :
4084 avcodec_find_decoder_by_name(name);
4086 av_log(NULL, AV_LOG_FATAL, "Unknown %s '%s'\n", codec_string, name);
4089 if (codec->type != type) {
4090 av_log(NULL, AV_LOG_FATAL, "Invalid %s type '%s'\n", codec_string, name);
4096 static AVCodec *choose_decoder(OptionsContext *o, AVFormatContext *s, AVStream *st)
4098 char *codec_name = NULL;
4100 MATCH_PER_STREAM_OPT(codec_names, str, codec_name, s, st);
4102 AVCodec *codec = find_codec_or_die(codec_name, st->codec->codec_type, 0);
4103 st->codec->codec_id = codec->id;
4106 return avcodec_find_decoder(st->codec->codec_id);
4110 * Add all the streams from the given input file to the global
4111 * list of input streams.
4113 static void add_input_streams(OptionsContext *o, AVFormatContext *ic)
4116 char *next, *codec_tag = NULL;
4118 for (i = 0; i < ic->nb_streams; i++) {
4119 AVStream *st = ic->streams[i];
4120 AVCodecContext *dec = st->codec;
4121 InputStream *ist = av_mallocz(sizeof(*ist));
4126 input_streams = grow_array(input_streams, sizeof(*input_streams), &nb_input_streams, nb_input_streams + 1);
4127 input_streams[nb_input_streams - 1] = ist;
4130 ist->file_index = nb_input_files;
4132 st->discard = AVDISCARD_ALL;
4133 ist->opts = filter_codec_opts(codec_opts, choose_decoder(o, ic, st), ic, st);
4135 ist->ts_scale = 1.0;
4136 MATCH_PER_STREAM_OPT(ts_scale, dbl, ist->ts_scale, ic, st);
4138 MATCH_PER_STREAM_OPT(codec_tags, str, codec_tag, ic, st);
4140 uint32_t tag = strtol(codec_tag, &next, 0);
4142 tag = AV_RL32(codec_tag);
4143 st->codec->codec_tag = tag;
4146 ist->dec = choose_decoder(o, ic, st);
4148 switch (dec->codec_type) {
4149 case AVMEDIA_TYPE_VIDEO:
4151 ist->dec = avcodec_find_decoder(dec->codec_id);
4153 dec->flags |= CODEC_FLAG_EMU_EDGE;
4156 ist->resample_height = dec->height;
4157 ist->resample_width = dec->width;
4158 ist->resample_pix_fmt = dec->pix_fmt;
4161 case AVMEDIA_TYPE_AUDIO:
4162 case AVMEDIA_TYPE_DATA:
4163 case AVMEDIA_TYPE_SUBTITLE:
4165 ist->dec = avcodec_find_decoder(dec->codec_id);
4167 case AVMEDIA_TYPE_ATTACHMENT:
4168 case AVMEDIA_TYPE_UNKNOWN:
4176 static void assert_file_overwrite(const char *filename)
4178 if ((!file_overwrite || no_file_overwrite) &&
4179 (strchr(filename, ':') == NULL || filename[1] == ':' ||
4180 av_strstart(filename, "file:", NULL))) {
4181 if (avio_check(filename, 0) == 0) {
4182 if (!using_stdin && (!no_file_overwrite || file_overwrite)) {
4183 fprintf(stderr,"File '%s' already exists. Overwrite ? [y/N] ", filename);
4186 signal(SIGINT, SIG_DFL);
4187 if (!read_yesno()) {
4188 av_log(NULL, AV_LOG_FATAL, "Not overwriting - exiting\n");
4194 av_log(NULL, AV_LOG_FATAL, "File '%s' already exists. Exiting.\n", filename);
4201 static void dump_attachment(AVStream *st, const char *filename)
4204 AVIOContext *out = NULL;
4205 AVDictionaryEntry *e;
4207 if (!st->codec->extradata_size) {
4208 av_log(NULL, AV_LOG_WARNING, "No extradata to dump in stream #%d:%d.\n",
4209 nb_input_files - 1, st->index);
4212 if (!*filename && (e = av_dict_get(st->metadata, "filename", NULL, 0)))
4213 filename = e->value;
4215 av_log(NULL, AV_LOG_FATAL, "No filename specified and no 'filename' tag"
4216 "in stream #%d:%d.\n", nb_input_files - 1, st->index);
4220 assert_file_overwrite(filename);
4222 if ((ret = avio_open2(&out, filename, AVIO_FLAG_WRITE, &int_cb, NULL)) < 0) {
4223 av_log(NULL, AV_LOG_FATAL, "Could not open file %s for writing.\n",
4228 avio_write(out, st->codec->extradata, st->codec->extradata_size);
4233 static int opt_input_file(OptionsContext *o, const char *opt, const char *filename)
4235 AVFormatContext *ic;
4236 AVInputFormat *file_iformat = NULL;
4240 AVDictionary **opts;
4241 int orig_nb_streams; // number of streams before avformat_find_stream_info
4244 if (!(file_iformat = av_find_input_format(o->format))) {
4245 av_log(NULL, AV_LOG_FATAL, "Unknown input format: '%s'\n", o->format);
4250 if (!strcmp(filename, "-"))
4253 using_stdin |= !strncmp(filename, "pipe:", 5) ||
4254 !strcmp(filename, "/dev/stdin");
4256 /* get default parameters from command line */
4257 ic = avformat_alloc_context();
4259 print_error(filename, AVERROR(ENOMEM));
4262 if (o->nb_audio_sample_rate) {
4263 snprintf(buf, sizeof(buf), "%d", o->audio_sample_rate[o->nb_audio_sample_rate - 1].u.i);
4264 av_dict_set(&format_opts, "sample_rate", buf, 0);
4266 if (o->nb_audio_channels) {
4267 /* because we set audio_channels based on both the "ac" and
4268 * "channel_layout" options, we need to check that the specified
4269 * demuxer actually has the "channels" option before setting it */
4270 if (file_iformat && file_iformat->priv_class &&
4271 av_opt_find(&file_iformat->priv_class, "channels", NULL, 0,
4272 AV_OPT_SEARCH_FAKE_OBJ)) {
4273 snprintf(buf, sizeof(buf), "%d",
4274 o->audio_channels[o->nb_audio_channels - 1].u.i);
4275 av_dict_set(&format_opts, "channels", buf, 0);
4278 if (o->nb_frame_rates) {
4279 av_dict_set(&format_opts, "framerate", o->frame_rates[o->nb_frame_rates - 1].u.str, 0);
4281 if (o->nb_frame_sizes) {
4282 av_dict_set(&format_opts, "video_size", o->frame_sizes[o->nb_frame_sizes - 1].u.str, 0);
4284 if (o->nb_frame_pix_fmts)
4285 av_dict_set(&format_opts, "pixel_format", o->frame_pix_fmts[o->nb_frame_pix_fmts - 1].u.str, 0);
4287 ic->video_codec_id = video_codec_name ?
4288 find_codec_or_die(video_codec_name , AVMEDIA_TYPE_VIDEO , 0)->id : CODEC_ID_NONE;
4289 ic->audio_codec_id = audio_codec_name ?
4290 find_codec_or_die(audio_codec_name , AVMEDIA_TYPE_AUDIO , 0)->id : CODEC_ID_NONE;
4291 ic->subtitle_codec_id= subtitle_codec_name ?
4292 find_codec_or_die(subtitle_codec_name, AVMEDIA_TYPE_SUBTITLE, 0)->id : CODEC_ID_NONE;
4293 ic->flags |= AVFMT_FLAG_NONBLOCK;
4294 ic->interrupt_callback = int_cb;
4296 /* open the input file with generic avformat function */
4297 err = avformat_open_input(&ic, filename, file_iformat, &format_opts);
4299 print_error(filename, err);
4302 assert_avoptions(format_opts);
4304 /* apply forced codec ids */
4305 for (i = 0; i < ic->nb_streams; i++)
4306 choose_decoder(o, ic, ic->streams[i]);
4308 /* Set AVCodecContext options for avformat_find_stream_info */
4309 opts = setup_find_stream_info_opts(ic, codec_opts);
4310 orig_nb_streams = ic->nb_streams;
4312 /* If not enough info to get the stream parameters, we decode the
4313 first frames to get it. (used in mpeg case for example) */
4314 ret = avformat_find_stream_info(ic, opts);
4316 av_log(NULL, AV_LOG_FATAL, "%s: could not find codec parameters\n", filename);
4317 avformat_close_input(&ic);
4321 timestamp = o->start_time;
4322 /* add the stream start time */
4323 if (ic->start_time != AV_NOPTS_VALUE)
4324 timestamp += ic->start_time;
4326 /* if seeking requested, we execute it */
4327 if (o->start_time != 0) {
4328 ret = av_seek_frame(ic, -1, timestamp, AVSEEK_FLAG_BACKWARD);
4330 av_log(NULL, AV_LOG_WARNING, "%s: could not seek to position %0.3f\n",
4331 filename, (double)timestamp / AV_TIME_BASE);
4335 /* update the current parameters so that they match the one of the input stream */
4336 add_input_streams(o, ic);
4338 /* dump the file content */
4339 av_dump_format(ic, nb_input_files, filename, 0);
4341 input_files = grow_array(input_files, sizeof(*input_files), &nb_input_files, nb_input_files + 1);
4342 if (!(input_files[nb_input_files - 1] = av_mallocz(sizeof(*input_files[0]))))
4345 input_files[nb_input_files - 1]->ctx = ic;
4346 input_files[nb_input_files - 1]->ist_index = nb_input_streams - ic->nb_streams;
4347 input_files[nb_input_files - 1]->ts_offset = o->input_ts_offset - (copy_ts ? 0 : timestamp);
4348 input_files[nb_input_files - 1]->nb_streams = ic->nb_streams;
4349 input_files[nb_input_files - 1]->rate_emu = o->rate_emu;
4351 for (i = 0; i < o->nb_dump_attachment; i++) {
4354 for (j = 0; j < ic->nb_streams; j++) {
4355 AVStream *st = ic->streams[j];
4357 if (check_stream_specifier(ic, st, o->dump_attachment[i].specifier) == 1)
4358 dump_attachment(st, o->dump_attachment[i].u.str);
4362 for (i = 0; i < orig_nb_streams; i++)
4363 av_dict_free(&opts[i]);
4366 reset_options(o, 1);
4370 static void parse_forced_key_frames(char *kf, OutputStream *ost)
4375 for (p = kf; *p; p++)
4378 ost->forced_kf_count = n;
4379 ost->forced_kf_pts = av_malloc(sizeof(*ost->forced_kf_pts) * n);
4380 if (!ost->forced_kf_pts) {
4381 av_log(NULL, AV_LOG_FATAL, "Could not allocate forced key frames array.\n");
4385 for (i = 0; i < n; i++) {
4386 char *next = strchr(p, ',');
4387 if (next) *next++ = 0;
4388 ost->forced_kf_pts[i] = parse_time_or_die("force_key_frames", p, 1);
4393 static uint8_t *get_line(AVIOContext *s)
4399 if (avio_open_dyn_buf(&line) < 0) {
4400 av_log(NULL, AV_LOG_FATAL, "Could not alloc buffer for reading preset.\n");
4404 while ((c = avio_r8(s)) && c != '\n')
4407 avio_close_dyn_buf(line, &buf);
4412 static int get_preset_file_2(const char *preset_name, const char *codec_name, AVIOContext **s)
4415 char filename[1000];
4416 const char *base[3] = { getenv("AVCONV_DATADIR"),
4421 for (i = 0; i < FF_ARRAY_ELEMS(base) && ret; i++) {
4425 snprintf(filename, sizeof(filename), "%s%s/%s-%s.avpreset", base[i],
4426 i != 1 ? "" : "/.avconv", codec_name, preset_name);
4427 ret = avio_open2(s, filename, AVIO_FLAG_READ, &int_cb, NULL);
4430 snprintf(filename, sizeof(filename), "%s%s/%s.avpreset", base[i],
4431 i != 1 ? "" : "/.avconv", preset_name);
4432 ret = avio_open2(s, filename, AVIO_FLAG_READ, &int_cb, NULL);
4438 static void choose_encoder(OptionsContext *o, AVFormatContext *s, OutputStream *ost)
4440 char *codec_name = NULL;
4442 MATCH_PER_STREAM_OPT(codec_names, str, codec_name, s, ost->st);
4444 ost->st->codec->codec_id = av_guess_codec(s->oformat, NULL, s->filename,
4445 NULL, ost->st->codec->codec_type);
4446 ost->enc = avcodec_find_encoder(ost->st->codec->codec_id);
4447 } else if (!strcmp(codec_name, "copy"))
4448 ost->stream_copy = 1;
4450 ost->enc = find_codec_or_die(codec_name, ost->st->codec->codec_type, 1);
4451 ost->st->codec->codec_id = ost->enc->id;
4455 static OutputStream *new_output_stream(OptionsContext *o, AVFormatContext *oc, enum AVMediaType type, int source_index)
4458 AVStream *st = avformat_new_stream(oc, NULL);
4459 int idx = oc->nb_streams - 1, ret = 0;
4460 char *bsf = NULL, *next, *codec_tag = NULL;
4461 AVBitStreamFilterContext *bsfc, *bsfc_prev = NULL;
4463 char *buf = NULL, *arg = NULL, *preset = NULL;
4464 AVIOContext *s = NULL;
4467 av_log(NULL, AV_LOG_FATAL, "Could not alloc stream.\n");
4471 if (oc->nb_streams - 1 < o->nb_streamid_map)
4472 st->id = o->streamid_map[oc->nb_streams - 1];
4474 output_streams = grow_array(output_streams, sizeof(*output_streams), &nb_output_streams,
4475 nb_output_streams + 1);
4476 if (!(ost = av_mallocz(sizeof(*ost))))
4478 output_streams[nb_output_streams - 1] = ost;
4480 ost->file_index = nb_output_files;
4483 st->codec->codec_type = type;
4484 choose_encoder(o, oc, ost);
4486 ost->opts = filter_codec_opts(codec_opts, ost->enc, oc, st);
4489 avcodec_get_context_defaults3(st->codec, ost->enc);
4490 st->codec->codec_type = type; // XXX hack, avcodec_get_context_defaults2() sets type to unknown for stream copy
4492 MATCH_PER_STREAM_OPT(presets, str, preset, oc, st);
4493 if (preset && (!(ret = get_preset_file_2(preset, ost->enc->name, &s)))) {
4496 if (!buf[0] || buf[0] == '#') {
4500 if (!(arg = strchr(buf, '='))) {
4501 av_log(NULL, AV_LOG_FATAL, "Invalid line found in the preset file.\n");
4505 av_dict_set(&ost->opts, buf, arg, AV_DICT_DONT_OVERWRITE);
4507 } while (!s->eof_reached);
4511 av_log(NULL, AV_LOG_FATAL,
4512 "Preset %s specified for stream %d:%d, but could not be opened.\n",
4513 preset, ost->file_index, ost->index);
4517 ost->max_frames = INT64_MAX;
4518 MATCH_PER_STREAM_OPT(max_frames, i64, ost->max_frames, oc, st);
4520 MATCH_PER_STREAM_OPT(bitstream_filters, str, bsf, oc, st);
4522 if (next = strchr(bsf, ','))
4524 if (!(bsfc = av_bitstream_filter_init(bsf))) {
4525 av_log(NULL, AV_LOG_FATAL, "Unknown bitstream filter %s\n", bsf);
4529 bsfc_prev->next = bsfc;
4531 ost->bitstream_filters = bsfc;
4537 MATCH_PER_STREAM_OPT(codec_tags, str, codec_tag, oc, st);
4539 uint32_t tag = strtol(codec_tag, &next, 0);
4541 tag = AV_RL32(codec_tag);
4542 st->codec->codec_tag = tag;
4545 MATCH_PER_STREAM_OPT(qscale, dbl, qscale, oc, st);
4546 if (qscale >= 0 || same_quant) {
4547 st->codec->flags |= CODEC_FLAG_QSCALE;
4548 st->codec->global_quality = FF_QP2LAMBDA * qscale;
4551 if (oc->oformat->flags & AVFMT_GLOBALHEADER)
4552 st->codec->flags |= CODEC_FLAG_GLOBAL_HEADER;
4554 av_opt_get_int(sws_opts, "sws_flags", 0, &ost->sws_flags);
4555 av_opt_get_int (swr_opts, "dither_method", 0, &ost->swr_dither_method);
4556 av_opt_get_double(swr_opts, "dither_scale" , 0, &ost->swr_dither_scale);
4558 ost->source_index = source_index;
4559 if (source_index >= 0) {
4560 ost->sync_ist = input_streams[source_index];
4561 input_streams[source_index]->discard = 0;
4562 input_streams[source_index]->st->discard = AVDISCARD_NONE;
4565 ost->pix_fmts[0] = ost->pix_fmts[1] = PIX_FMT_NONE;
4570 static void parse_matrix_coeffs(uint16_t *dest, const char *str)
4573 const char *p = str;
4580 av_log(NULL, AV_LOG_FATAL, "Syntax error in matrix \"%s\" at coeff %d\n", str, i);
4587 static OutputStream *new_video_stream(OptionsContext *o, AVFormatContext *oc, int source_index)
4591 AVCodecContext *video_enc;
4593 ost = new_output_stream(o, oc, AVMEDIA_TYPE_VIDEO, source_index);
4595 video_enc = st->codec;
4597 if (!ost->stream_copy) {
4598 const char *p = NULL;
4599 char *forced_key_frames = NULL, *frame_rate = NULL, *frame_size = NULL;
4600 char *frame_aspect_ratio = NULL, *frame_pix_fmt = NULL;
4601 char *intra_matrix = NULL, *inter_matrix = NULL, *filters = NULL;
4604 MATCH_PER_STREAM_OPT(frame_rates, str, frame_rate, oc, st);
4605 if (frame_rate && av_parse_video_rate(&ost->frame_rate, frame_rate) < 0) {
4606 av_log(NULL, AV_LOG_FATAL, "Invalid framerate value: %s\n", frame_rate);
4610 MATCH_PER_STREAM_OPT(frame_sizes, str, frame_size, oc, st);
4611 if (frame_size && av_parse_video_size(&video_enc->width, &video_enc->height, frame_size) < 0) {
4612 av_log(NULL, AV_LOG_FATAL, "Invalid frame size: %s.\n", frame_size);
4616 MATCH_PER_STREAM_OPT(frame_aspect_ratios, str, frame_aspect_ratio, oc, st);
4617 if (frame_aspect_ratio) {
4619 if (av_parse_ratio(&q, frame_aspect_ratio, 255, 0, NULL) < 0 ||
4620 q.num <= 0 || q.den <= 0) {
4621 av_log(NULL, AV_LOG_FATAL, "Invalid aspect ratio: %s\n", frame_aspect_ratio);
4624 ost->frame_aspect_ratio = av_q2d(q);
4627 video_enc->bits_per_raw_sample = frame_bits_per_raw_sample;
4628 MATCH_PER_STREAM_OPT(frame_pix_fmts, str, frame_pix_fmt, oc, st);
4629 if (frame_pix_fmt && (video_enc->pix_fmt = av_get_pix_fmt(frame_pix_fmt)) == PIX_FMT_NONE) {
4630 av_log(NULL, AV_LOG_FATAL, "Unknown pixel format requested: %s.\n", frame_pix_fmt);
4633 st->sample_aspect_ratio = video_enc->sample_aspect_ratio;
4636 video_enc->gop_size = 0;
4637 MATCH_PER_STREAM_OPT(intra_matrices, str, intra_matrix, oc, st);
4639 if (!(video_enc->intra_matrix = av_mallocz(sizeof(*video_enc->intra_matrix) * 64))) {
4640 av_log(NULL, AV_LOG_FATAL, "Could not allocate memory for intra matrix.\n");
4643 parse_matrix_coeffs(video_enc->intra_matrix, intra_matrix);
4645 MATCH_PER_STREAM_OPT(inter_matrices, str, inter_matrix, oc, st);
4647 if (!(video_enc->inter_matrix = av_mallocz(sizeof(*video_enc->inter_matrix) * 64))) {
4648 av_log(NULL, AV_LOG_FATAL, "Could not allocate memory for inter matrix.\n");
4651 parse_matrix_coeffs(video_enc->inter_matrix, inter_matrix);
4654 MATCH_PER_STREAM_OPT(rc_overrides, str, p, oc, st);
4655 for (i = 0; p; i++) {
4657 int e = sscanf(p, "%d,%d,%d", &start, &end, &q);
4659 av_log(NULL, AV_LOG_FATAL, "error parsing rc_override\n");
4662 /* FIXME realloc failure */
4663 video_enc->rc_override =
4664 av_realloc(video_enc->rc_override,
4665 sizeof(RcOverride) * (i + 1));
4666 video_enc->rc_override[i].start_frame = start;
4667 video_enc->rc_override[i].end_frame = end;
4669 video_enc->rc_override[i].qscale = q;
4670 video_enc->rc_override[i].quality_factor = 1.0;
4673 video_enc->rc_override[i].qscale = 0;
4674 video_enc->rc_override[i].quality_factor = -q/100.0;
4679 video_enc->rc_override_count = i;
4680 if (!video_enc->rc_initial_buffer_occupancy)
4681 video_enc->rc_initial_buffer_occupancy = video_enc->rc_buffer_size * 3 / 4;
4682 video_enc->intra_dc_precision = intra_dc_precision - 8;
4685 video_enc->flags|= CODEC_FLAG_PSNR;
4690 video_enc->flags |= CODEC_FLAG_PASS1;
4693 video_enc->flags |= CODEC_FLAG_PASS2;
4697 MATCH_PER_STREAM_OPT(forced_key_frames, str, forced_key_frames, oc, st);
4698 if (forced_key_frames)
4699 parse_forced_key_frames(forced_key_frames, ost);
4701 MATCH_PER_STREAM_OPT(force_fps, i, ost->force_fps, oc, st);
4703 ost->top_field_first = -1;
4704 MATCH_PER_STREAM_OPT(top_field_first, i, ost->top_field_first, oc, st);
4706 MATCH_PER_STREAM_OPT(filters, str, filters, oc, st);
4708 ost->avfilter = av_strdup(filters);
4710 MATCH_PER_STREAM_OPT(copy_initial_nonkeyframes, i, ost->copy_initial_nonkeyframes, oc ,st);
4716 static OutputStream *new_audio_stream(OptionsContext *o, AVFormatContext *oc, int source_index)
4721 AVCodecContext *audio_enc;
4723 ost = new_output_stream(o, oc, AVMEDIA_TYPE_AUDIO, source_index);
4726 audio_enc = st->codec;
4727 audio_enc->codec_type = AVMEDIA_TYPE_AUDIO;
4729 if (!ost->stream_copy) {
4730 char *sample_fmt = NULL;
4732 MATCH_PER_STREAM_OPT(audio_channels, i, audio_enc->channels, oc, st);
4734 MATCH_PER_STREAM_OPT(sample_fmts, str, sample_fmt, oc, st);
4736 (audio_enc->sample_fmt = av_get_sample_fmt(sample_fmt)) == AV_SAMPLE_FMT_NONE) {
4737 av_log(NULL, AV_LOG_FATAL, "Invalid sample format '%s'\n", sample_fmt);
4741 MATCH_PER_STREAM_OPT(audio_sample_rate, i, audio_enc->sample_rate, oc, st);
4743 ost->rematrix_volume=1.0;
4744 MATCH_PER_STREAM_OPT(rematrix_volume, f, ost->rematrix_volume, oc, st);
4747 /* check for channel mapping for this audio stream */
4748 for (n = 0; n < o->nb_audio_channel_maps; n++) {
4749 AudioChannelMap *map = &o->audio_channel_maps[n];
4750 InputStream *ist = input_streams[ost->source_index];
4751 if ((map->channel_idx == -1 || (ist->file_index == map->file_idx && ist->st->index == map->stream_idx)) &&
4752 (map->ofile_idx == -1 || ost->file_index == map->ofile_idx) &&
4753 (map->ostream_idx == -1 || ost->st->index == map->ostream_idx)) {
4754 if (ost->audio_channels_mapped < FF_ARRAY_ELEMS(ost->audio_channels_map))
4755 ost->audio_channels_map[ost->audio_channels_mapped++] = map->channel_idx;
4757 av_log(NULL, AV_LOG_FATAL, "Max channel mapping for output %d.%d reached\n",
4758 ost->file_index, ost->st->index);
4765 static OutputStream *new_data_stream(OptionsContext *o, AVFormatContext *oc, int source_index)
4769 ost = new_output_stream(o, oc, AVMEDIA_TYPE_DATA, source_index);
4770 if (!ost->stream_copy) {
4771 av_log(NULL, AV_LOG_FATAL, "Data stream encoding not supported yet (only streamcopy)\n");
4778 static OutputStream *new_attachment_stream(OptionsContext *o, AVFormatContext *oc, int source_index)
4780 OutputStream *ost = new_output_stream(o, oc, AVMEDIA_TYPE_ATTACHMENT, source_index);
4781 ost->stream_copy = 1;
4785 static OutputStream *new_subtitle_stream(OptionsContext *o, AVFormatContext *oc, int source_index)
4789 AVCodecContext *subtitle_enc;
4791 ost = new_output_stream(o, oc, AVMEDIA_TYPE_SUBTITLE, source_index);
4793 subtitle_enc = st->codec;
4795 subtitle_enc->codec_type = AVMEDIA_TYPE_SUBTITLE;
4797 MATCH_PER_STREAM_OPT(copy_initial_nonkeyframes, i, ost->copy_initial_nonkeyframes, oc, st);
4802 /* arg format is "output-stream-index:streamid-value". */
4803 static int opt_streamid(OptionsContext *o, const char *opt, const char *arg)
4809 av_strlcpy(idx_str, arg, sizeof(idx_str));
4810 p = strchr(idx_str, ':');
4812 av_log(NULL, AV_LOG_FATAL,
4813 "Invalid value '%s' for option '%s', required syntax is 'index:value'\n",
4818 idx = parse_number_or_die(opt, idx_str, OPT_INT, 0, MAX_STREAMS-1);
4819 o->streamid_map = grow_array(o->streamid_map, sizeof(*o->streamid_map), &o->nb_streamid_map, idx+1);
4820 o->streamid_map[idx] = parse_number_or_die(opt, p, OPT_INT, 0, INT_MAX);
4824 static int copy_chapters(InputFile *ifile, OutputFile *ofile, int copy_metadata)
4826 AVFormatContext *is = ifile->ctx;
4827 AVFormatContext *os = ofile->ctx;
4830 for (i = 0; i < is->nb_chapters; i++) {
4831 AVChapter *in_ch = is->chapters[i], *out_ch;
4832 int64_t ts_off = av_rescale_q(ofile->start_time - ifile->ts_offset,
4833 AV_TIME_BASE_Q, in_ch->time_base);
4834 int64_t rt = (ofile->recording_time == INT64_MAX) ? INT64_MAX :
4835 av_rescale_q(ofile->recording_time, AV_TIME_BASE_Q, in_ch->time_base);
4838 if (in_ch->end < ts_off)
4840 if (rt != INT64_MAX && in_ch->start > rt + ts_off)
4843 out_ch = av_mallocz(sizeof(AVChapter));
4845 return AVERROR(ENOMEM);
4847 out_ch->id = in_ch->id;
4848 out_ch->time_base = in_ch->time_base;
4849 out_ch->start = FFMAX(0, in_ch->start - ts_off);
4850 out_ch->end = FFMIN(rt, in_ch->end - ts_off);
4853 av_dict_copy(&out_ch->metadata, in_ch->metadata, 0);
4856 os->chapters = av_realloc_f(os->chapters, os->nb_chapters, sizeof(AVChapter));
4858 return AVERROR(ENOMEM);
4859 os->chapters[os->nb_chapters - 1] = out_ch;
4864 static int read_ffserver_streams(OptionsContext *o, AVFormatContext *s, const char *filename)
4867 AVFormatContext *ic = avformat_alloc_context();
4869 ic->interrupt_callback = int_cb;
4870 err = avformat_open_input(&ic, filename, NULL, NULL);
4873 /* copy stream format */
4874 for(i=0;i<ic->nb_streams;i++) {
4878 AVCodecContext *avctx;
4880 codec = avcodec_find_encoder(ic->streams[i]->codec->codec_id);
4881 ost = new_output_stream(o, s, codec->type, -1);
4886 // FIXME: a more elegant solution is needed
4887 memcpy(st, ic->streams[i], sizeof(AVStream));
4889 st->info = av_malloc(sizeof(*st->info));
4890 memcpy(st->info, ic->streams[i]->info, sizeof(*st->info));
4892 avcodec_copy_context(st->codec, ic->streams[i]->codec);
4894 if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO && !ost->stream_copy)
4895 choose_sample_fmt(st, codec);
4896 else if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO && !ost->stream_copy)
4897 choose_pixel_fmt(st, codec, st->codec->pix_fmt);
4900 avformat_close_input(&ic);
4904 static void init_output_filter(OutputFilter *ofilter, OptionsContext *o,
4905 AVFormatContext *oc)
4909 if (ofilter->out_tmp->filter_ctx->output_pads[ofilter->out_tmp->pad_idx].type != AVMEDIA_TYPE_VIDEO) {
4910 av_log(NULL, AV_LOG_FATAL, "Only video filters are supported currently.\n");
4914 ost = new_video_stream(o, oc, -1);
4915 ost->source_index = -1;
4916 ost->filter = ofilter;
4920 if (ost->stream_copy) {
4921 av_log(NULL, AV_LOG_ERROR, "Streamcopy requested for output stream %d:%d, "
4922 "which is fed from a complex filtergraph. Filtering and streamcopy "
4923 "cannot be used together.\n", ost->file_index, ost->index);
4927 if (configure_output_filter(ofilter->graph, ofilter, ofilter->out_tmp) < 0) {
4928 av_log(NULL, AV_LOG_FATAL, "Error configuring filter.\n");
4931 avfilter_inout_free(&ofilter->out_tmp);
4934 static void opt_output_file(void *optctx, const char *filename)
4936 OptionsContext *o = optctx;
4937 AVFormatContext *oc;
4939 AVOutputFormat *file_oformat;
4943 if (configure_complex_filters() < 0) {
4944 av_log(NULL, AV_LOG_FATAL, "Error configuring filters.\n");
4948 if (!strcmp(filename, "-"))
4951 err = avformat_alloc_output_context2(&oc, NULL, o->format, filename);
4953 print_error(filename, err);
4956 file_oformat= oc->oformat;
4957 oc->interrupt_callback = int_cb;
4959 /* create streams for all unlabeled output pads */
4960 for (i = 0; i < nb_filtergraphs; i++) {
4961 FilterGraph *fg = filtergraphs[i];
4962 for (j = 0; j < fg->nb_outputs; j++) {
4963 OutputFilter *ofilter = fg->outputs[j];
4965 if (!ofilter->out_tmp || ofilter->out_tmp->name)
4968 switch (ofilter->out_tmp->filter_ctx->output_pads[ofilter->out_tmp->pad_idx].type) {
4969 case AVMEDIA_TYPE_VIDEO: o->video_disable = 1; break;
4970 case AVMEDIA_TYPE_AUDIO: o->audio_disable = 1; break;
4971 case AVMEDIA_TYPE_SUBTITLE: o->subtitle_disable = 1; break;
4973 init_output_filter(ofilter, o, oc);
4977 if (!strcmp(file_oformat->name, "ffm") &&
4978 av_strstart(filename, "http:", NULL)) {
4980 /* special case for files sent to ffserver: we get the stream
4981 parameters from ffserver */
4982 int err = read_ffserver_streams(o, oc, filename);
4984 print_error(filename, err);
4987 for(j = nb_output_streams - oc->nb_streams; j < nb_output_streams; j++) {
4988 ost = output_streams[j];
4989 for (i = 0; i < nb_input_streams; i++) {
4990 ist = input_streams[i];
4991 if(ist->st->codec->codec_type == ost->st->codec->codec_type){
4993 ost->source_index= i;
4995 ist->st->discard = AVDISCARD_NONE;
5000 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));
5004 } else if (!o->nb_stream_maps) {
5005 /* pick the "best" stream of each type */
5007 /* video: highest resolution */
5008 if (!o->video_disable && oc->oformat->video_codec != CODEC_ID_NONE) {
5009 int area = 0, idx = -1;
5010 for (i = 0; i < nb_input_streams; i++) {
5011 ist = input_streams[i];
5012 if (ist->st->codec->codec_type == AVMEDIA_TYPE_VIDEO &&
5013 ist->st->codec->width * ist->st->codec->height > area) {
5014 area = ist->st->codec->width * ist->st->codec->height;
5019 new_video_stream(o, oc, idx);
5022 /* audio: most channels */
5023 if (!o->audio_disable && oc->oformat->audio_codec != CODEC_ID_NONE) {
5024 int channels = 0, idx = -1;
5025 for (i = 0; i < nb_input_streams; i++) {
5026 ist = input_streams[i];
5027 if (ist->st->codec->codec_type == AVMEDIA_TYPE_AUDIO &&
5028 ist->st->codec->channels > channels) {
5029 channels = ist->st->codec->channels;
5034 new_audio_stream(o, oc, idx);
5037 /* subtitles: pick first */
5038 if (!o->subtitle_disable && (oc->oformat->subtitle_codec != CODEC_ID_NONE || subtitle_codec_name)) {
5039 for (i = 0; i < nb_input_streams; i++)
5040 if (input_streams[i]->st->codec->codec_type == AVMEDIA_TYPE_SUBTITLE) {
5041 new_subtitle_stream(o, oc, i);
5045 /* do something with data? */
5047 for (i = 0; i < o->nb_stream_maps; i++) {
5048 StreamMap *map = &o->stream_maps[i];
5049 int src_idx = input_files[map->file_index]->ist_index + map->stream_index;
5054 if (map->linklabel) {
5056 OutputFilter *ofilter = NULL;
5059 for (j = 0; j < nb_filtergraphs; j++) {
5060 fg = filtergraphs[j];
5061 for (k = 0; k < fg->nb_outputs; k++) {
5062 AVFilterInOut *out = fg->outputs[k]->out_tmp;
5063 if (out && !strcmp(out->name, map->linklabel)) {
5064 ofilter = fg->outputs[k];
5071 av_log(NULL, AV_LOG_FATAL, "Output with label '%s' does not exist "
5072 "in any defined filter graph.\n", map->linklabel);
5075 init_output_filter(ofilter, o, oc);
5077 ist = input_streams[input_files[map->file_index]->ist_index + map->stream_index];
5078 if(o->subtitle_disable && ist->st->codec->codec_type == AVMEDIA_TYPE_SUBTITLE)
5080 if(o-> audio_disable && ist->st->codec->codec_type == AVMEDIA_TYPE_AUDIO)
5082 if(o-> video_disable && ist->st->codec->codec_type == AVMEDIA_TYPE_VIDEO)
5084 if(o-> data_disable && ist->st->codec->codec_type == AVMEDIA_TYPE_DATA)
5087 switch (ist->st->codec->codec_type) {
5088 case AVMEDIA_TYPE_VIDEO: ost = new_video_stream (o, oc, src_idx); break;
5089 case AVMEDIA_TYPE_AUDIO: ost = new_audio_stream (o, oc, src_idx); break;
5090 case AVMEDIA_TYPE_SUBTITLE: ost = new_subtitle_stream (o, oc, src_idx); break;
5091 case AVMEDIA_TYPE_DATA: ost = new_data_stream (o, oc, src_idx); break;
5092 case AVMEDIA_TYPE_ATTACHMENT: ost = new_attachment_stream(o, oc, src_idx); break;
5094 av_log(NULL, AV_LOG_FATAL, "Cannot map stream #%d:%d - unsupported type.\n",
5095 map->file_index, map->stream_index);
5103 for (i = nb_output_streams - oc->nb_streams; i < nb_output_streams; i++) { //for all streams of this output file
5104 AVDictionaryEntry *e;
5105 ost = output_streams[i];
5107 if ( ost->stream_copy
5108 && (e = av_dict_get(codec_opts, "flags", NULL, AV_DICT_IGNORE_SUFFIX))
5109 && (!e->key[5] || check_stream_specifier(oc, ost->st, e->key+6)))
5110 if (av_opt_set(ost->st->codec, "flags", e->value, 0) < 0)
5114 /* handle attached files */
5115 for (i = 0; i < o->nb_attachments; i++) {
5117 uint8_t *attachment;
5121 if ((err = avio_open2(&pb, o->attachments[i], AVIO_FLAG_READ, &int_cb, NULL)) < 0) {
5122 av_log(NULL, AV_LOG_FATAL, "Could not open attachment file %s.\n",
5126 if ((len = avio_size(pb)) <= 0) {
5127 av_log(NULL, AV_LOG_FATAL, "Could not get size of the attachment %s.\n",
5131 if (!(attachment = av_malloc(len))) {
5132 av_log(NULL, AV_LOG_FATAL, "Attachment %s too large to fit into memory.\n",
5136 avio_read(pb, attachment, len);
5138 ost = new_attachment_stream(o, oc, -1);
5139 ost->stream_copy = 0;
5140 ost->attachment_filename = o->attachments[i];
5141 ost->st->codec->extradata = attachment;
5142 ost->st->codec->extradata_size = len;
5144 p = strrchr(o->attachments[i], '/');
5145 av_dict_set(&ost->st->metadata, "filename", (p && *p) ? p + 1 : o->attachments[i], AV_DICT_DONT_OVERWRITE);
5149 output_files = grow_array(output_files, sizeof(*output_files), &nb_output_files, nb_output_files + 1);
5150 if (!(output_files[nb_output_files - 1] = av_mallocz(sizeof(*output_files[0]))))
5153 output_files[nb_output_files - 1]->ctx = oc;
5154 output_files[nb_output_files - 1]->ost_index = nb_output_streams - oc->nb_streams;
5155 output_files[nb_output_files - 1]->recording_time = o->recording_time;
5156 if (o->recording_time != INT64_MAX)
5157 oc->duration = o->recording_time;
5158 output_files[nb_output_files - 1]->start_time = o->start_time;
5159 output_files[nb_output_files - 1]->limit_filesize = o->limit_filesize;
5160 av_dict_copy(&output_files[nb_output_files - 1]->opts, format_opts, 0);
5162 /* check filename in case of an image number is expected */
5163 if (oc->oformat->flags & AVFMT_NEEDNUMBER) {
5164 if (!av_filename_number_test(oc->filename)) {
5165 print_error(oc->filename, AVERROR(EINVAL));
5170 if (!(oc->oformat->flags & AVFMT_NOFILE)) {
5171 /* test if it already exists to avoid losing precious files */
5172 assert_file_overwrite(filename);
5175 if ((err = avio_open2(&oc->pb, filename, AVIO_FLAG_WRITE,
5176 &oc->interrupt_callback,
5177 &output_files[nb_output_files - 1]->opts)) < 0) {
5178 print_error(filename, err);
5183 if (o->mux_preload) {
5185 snprintf(buf, sizeof(buf), "%d", (int)(o->mux_preload*AV_TIME_BASE));
5186 av_dict_set(&output_files[nb_output_files - 1]->opts, "preload", buf, 0);
5188 oc->max_delay = (int)(o->mux_max_delay * AV_TIME_BASE);
5191 for (i = 0; i < o->nb_metadata_map; i++) {
5193 int in_file_index = strtol(o->metadata_map[i].u.str, &p, 0);
5195 if (in_file_index >= nb_input_files) {
5196 av_log(NULL, AV_LOG_FATAL, "Invalid input file index %d while processing metadata maps\n", in_file_index);
5199 copy_metadata(o->metadata_map[i].specifier, *p ? p + 1 : p, oc, in_file_index >= 0 ? input_files[in_file_index]->ctx : NULL, o);
5203 if (o->chapters_input_file >= nb_input_files) {
5204 if (o->chapters_input_file == INT_MAX) {
5205 /* copy chapters from the first input file that has them*/
5206 o->chapters_input_file = -1;
5207 for (i = 0; i < nb_input_files; i++)
5208 if (input_files[i]->ctx->nb_chapters) {
5209 o->chapters_input_file = i;
5213 av_log(NULL, AV_LOG_FATAL, "Invalid input file index %d in chapter mapping.\n",
5214 o->chapters_input_file);
5218 if (o->chapters_input_file >= 0)
5219 copy_chapters(input_files[o->chapters_input_file], output_files[nb_output_files - 1],
5220 !o->metadata_chapters_manual);
5222 /* copy global metadata by default */
5223 if (!o->metadata_global_manual && nb_input_files){
5224 av_dict_copy(&oc->metadata, input_files[0]->ctx->metadata,
5225 AV_DICT_DONT_OVERWRITE);
5226 if(o->recording_time != INT64_MAX)
5227 av_dict_set(&oc->metadata, "duration", NULL, 0);
5229 if (!o->metadata_streams_manual)
5230 for (i = output_files[nb_output_files - 1]->ost_index; i < nb_output_streams; i++) {
5232 if (output_streams[i]->source_index < 0) /* this is true e.g. for attached files */
5234 ist = input_streams[output_streams[i]->source_index];
5235 av_dict_copy(&output_streams[i]->st->metadata, ist->st->metadata, AV_DICT_DONT_OVERWRITE);
5238 /* process manually set metadata */
5239 for (i = 0; i < o->nb_metadata; i++) {
5242 const char *stream_spec;
5243 int index = 0, j, ret = 0;
5245 val = strchr(o->metadata[i].u.str, '=');
5247 av_log(NULL, AV_LOG_FATAL, "No '=' character in metadata string %s.\n",
5248 o->metadata[i].u.str);
5253 parse_meta_type(o->metadata[i].specifier, &type, &index, &stream_spec);
5255 for (j = 0; j < oc->nb_streams; j++) {
5256 if ((ret = check_stream_specifier(oc, oc->streams[j], stream_spec)) > 0) {
5257 av_dict_set(&oc->streams[j]->metadata, o->metadata[i].u.str, *val ? val : NULL, 0);
5261 printf("ret %d, stream_spec %s\n", ret, stream_spec);
5269 if (index < 0 || index >= oc->nb_chapters) {
5270 av_log(NULL, AV_LOG_FATAL, "Invalid chapter index %d in metadata specifier.\n", index);
5273 m = &oc->chapters[index]->metadata;
5276 av_log(NULL, AV_LOG_FATAL, "Invalid metadata specifier %s.\n", o->metadata[i].specifier);
5279 av_dict_set(m, o->metadata[i].u.str, *val ? val : NULL, 0);
5283 reset_options(o, 0);
5286 /* same option as mencoder */
5287 static int opt_pass(const char *opt, const char *arg)
5289 do_pass = parse_number_or_die(opt, arg, OPT_INT, 1, 3);
5293 static int64_t getmaxrss(void)
5295 #if HAVE_GETRUSAGE && HAVE_STRUCT_RUSAGE_RU_MAXRSS
5296 struct rusage rusage;
5297 getrusage(RUSAGE_SELF, &rusage);
5298 return (int64_t)rusage.ru_maxrss * 1024;
5299 #elif HAVE_GETPROCESSMEMORYINFO
5301 PROCESS_MEMORY_COUNTERS memcounters;
5302 proc = GetCurrentProcess();
5303 memcounters.cb = sizeof(memcounters);
5304 GetProcessMemoryInfo(proc, &memcounters, sizeof(memcounters));
5305 return memcounters.PeakPagefileUsage;
5311 static int opt_audio_qscale(OptionsContext *o, const char *opt, const char *arg)
5313 return parse_option(o, "q:a", arg, options);
5316 static void show_usage(void)
5318 av_log(NULL, AV_LOG_INFO, "Hyper fast Audio and Video encoder\n");
5319 av_log(NULL, AV_LOG_INFO, "usage: %s [options] [[infile options] -i infile]... {[outfile options] outfile}...\n", program_name);
5320 av_log(NULL, AV_LOG_INFO, "\n");
5323 static int opt_help(const char *opt, const char *arg)
5325 int flags = AV_OPT_FLAG_DECODING_PARAM | AV_OPT_FLAG_ENCODING_PARAM;
5326 av_log_set_callback(log_callback_help);
5328 show_help_options(options, "Main options:\n",
5329 OPT_EXPERT | OPT_AUDIO | OPT_VIDEO | OPT_SUBTITLE | OPT_GRAB, 0);
5330 show_help_options(options, "\nAdvanced options:\n",
5331 OPT_EXPERT | OPT_AUDIO | OPT_VIDEO | OPT_SUBTITLE | OPT_GRAB,
5333 show_help_options(options, "\nVideo options:\n",
5334 OPT_EXPERT | OPT_AUDIO | OPT_VIDEO | OPT_GRAB,
5336 show_help_options(options, "\nAdvanced Video options:\n",
5337 OPT_EXPERT | OPT_AUDIO | OPT_VIDEO | OPT_GRAB,
5338 OPT_VIDEO | OPT_EXPERT);
5339 show_help_options(options, "\nAudio options:\n",
5340 OPT_EXPERT | OPT_AUDIO | OPT_VIDEO | OPT_GRAB,
5342 show_help_options(options, "\nAdvanced Audio options:\n",
5343 OPT_EXPERT | OPT_AUDIO | OPT_VIDEO | OPT_GRAB,
5344 OPT_AUDIO | OPT_EXPERT);
5345 show_help_options(options, "\nSubtitle options:\n",
5346 OPT_SUBTITLE | OPT_GRAB,
5348 show_help_options(options, "\nAudio/Video grab options:\n",
5352 show_help_children(avcodec_get_class(), flags);
5353 show_help_children(avformat_get_class(), flags);
5354 show_help_children(sws_get_class(), flags);
5359 static int opt_target(OptionsContext *o, const char *opt, const char *arg)
5361 enum { PAL, NTSC, FILM, UNKNOWN } norm = UNKNOWN;
5362 static const char *const frame_rates[] = { "25", "30000/1001", "24000/1001" };
5364 if (!strncmp(arg, "pal-", 4)) {
5367 } else if (!strncmp(arg, "ntsc-", 5)) {
5370 } else if (!strncmp(arg, "film-", 5)) {
5374 /* Try to determine PAL/NTSC by peeking in the input files */
5375 if (nb_input_files) {
5377 for (j = 0; j < nb_input_files; j++) {
5378 for (i = 0; i < input_files[j]->nb_streams; i++) {
5379 AVCodecContext *c = input_files[j]->ctx->streams[i]->codec;
5380 if (c->codec_type != AVMEDIA_TYPE_VIDEO)
5382 fr = c->time_base.den * 1000 / c->time_base.num;
5386 } else if ((fr == 29970) || (fr == 23976)) {
5391 if (norm != UNKNOWN)
5395 if (norm != UNKNOWN)
5396 av_log(NULL, AV_LOG_INFO, "Assuming %s for target.\n", norm == PAL ? "PAL" : "NTSC");
5399 if (norm == UNKNOWN) {
5400 av_log(NULL, AV_LOG_FATAL, "Could not determine norm (PAL/NTSC/NTSC-Film) for target.\n");
5401 av_log(NULL, AV_LOG_FATAL, "Please prefix target with \"pal-\", \"ntsc-\" or \"film-\",\n");
5402 av_log(NULL, AV_LOG_FATAL, "or set a framerate with \"-r xxx\".\n");
5406 if (!strcmp(arg, "vcd")) {
5407 opt_video_codec(o, "c:v", "mpeg1video");
5408 opt_audio_codec(o, "c:a", "mp2");
5409 parse_option(o, "f", "vcd", options);
5411 parse_option(o, "s", norm == PAL ? "352x288" : "352x240", options);
5412 parse_option(o, "r", frame_rates[norm], options);
5413 opt_default("g", norm == PAL ? "15" : "18");
5415 opt_default("b:v", "1150000");
5416 opt_default("maxrate", "1150000");
5417 opt_default("minrate", "1150000");
5418 opt_default("bufsize", "327680"); // 40*1024*8;
5420 opt_default("b:a", "224000");
5421 parse_option(o, "ar", "44100", options);
5422 parse_option(o, "ac", "2", options);
5424 opt_default("packetsize", "2324");
5425 opt_default("muxrate", "1411200"); // 2352 * 75 * 8;
5427 /* We have to offset the PTS, so that it is consistent with the SCR.
5428 SCR starts at 36000, but the first two packs contain only padding
5429 and the first pack from the other stream, respectively, may also have
5430 been written before.
5431 So the real data starts at SCR 36000+3*1200. */
5432 o->mux_preload = (36000 + 3 * 1200) / 90000.0; // 0.44
5433 } else if (!strcmp(arg, "svcd")) {
5435 opt_video_codec(o, "c:v", "mpeg2video");
5436 opt_audio_codec(o, "c:a", "mp2");
5437 parse_option(o, "f", "svcd", options);
5439 parse_option(o, "s", norm == PAL ? "480x576" : "480x480", options);
5440 parse_option(o, "r", frame_rates[norm], options);
5441 parse_option(o, "pix_fmt", "yuv420p", options);
5442 opt_default("g", norm == PAL ? "15" : "18");
5444 opt_default("b:v", "2040000");
5445 opt_default("maxrate", "2516000");
5446 opt_default("minrate", "0"); // 1145000;
5447 opt_default("bufsize", "1835008"); // 224*1024*8;
5448 opt_default("scan_offset", "1");
5451 opt_default("b:a", "224000");
5452 parse_option(o, "ar", "44100", options);
5454 opt_default("packetsize", "2324");
5456 } else if (!strcmp(arg, "dvd")) {
5458 opt_video_codec(o, "c:v", "mpeg2video");
5459 opt_audio_codec(o, "c:a", "ac3");
5460 parse_option(o, "f", "dvd", options);
5462 parse_option(o, "s", norm == PAL ? "720x576" : "720x480", options);
5463 parse_option(o, "r", frame_rates[norm], options);
5464 parse_option(o, "pix_fmt", "yuv420p", options);
5465 opt_default("g", norm == PAL ? "15" : "18");
5467 opt_default("b:v", "6000000");
5468 opt_default("maxrate", "9000000");
5469 opt_default("minrate", "0"); // 1500000;
5470 opt_default("bufsize", "1835008"); // 224*1024*8;
5472 opt_default("packetsize", "2048"); // from www.mpucoder.com: DVD sectors contain 2048 bytes of data, this is also the size of one pack.
5473 opt_default("muxrate", "10080000"); // from mplex project: data_rate = 1260000. mux_rate = data_rate * 8
5475 opt_default("b:a", "448000");
5476 parse_option(o, "ar", "48000", options);
5478 } else if (!strncmp(arg, "dv", 2)) {
5480 parse_option(o, "f", "dv", options);
5482 parse_option(o, "s", norm == PAL ? "720x576" : "720x480", options);
5483 parse_option(o, "pix_fmt", !strncmp(arg, "dv50", 4) ? "yuv422p" :
5484 norm == PAL ? "yuv420p" : "yuv411p", options);
5485 parse_option(o, "r", frame_rates[norm], options);
5487 parse_option(o, "ar", "48000", options);
5488 parse_option(o, "ac", "2", options);
5491 av_log(NULL, AV_LOG_ERROR, "Unknown target: %s\n", arg);
5492 return AVERROR(EINVAL);
5497 static int opt_vstats_file(const char *opt, const char *arg)
5499 av_free (vstats_filename);
5500 vstats_filename = av_strdup (arg);
5504 static int opt_vstats(const char *opt, const char *arg)
5507 time_t today2 = time(NULL);
5508 struct tm *today = localtime(&today2);
5510 snprintf(filename, sizeof(filename), "vstats_%02d%02d%02d.log", today->tm_hour, today->tm_min,
5512 return opt_vstats_file(opt, filename);
5515 static int opt_video_frames(OptionsContext *o, const char *opt, const char *arg)
5517 return parse_option(o, "frames:v", arg, options);
5520 static int opt_audio_frames(OptionsContext *o, const char *opt, const char *arg)
5522 return parse_option(o, "frames:a", arg, options);
5525 static int opt_data_frames(OptionsContext *o, const char *opt, const char *arg)
5527 return parse_option(o, "frames:d", arg, options);
5530 static int opt_preset(OptionsContext *o, const char *opt, const char *arg)
5533 char filename[1000], line[1000], tmp_line[1000];
5534 const char *codec_name = *opt == 'v' ? video_codec_name :
5535 *opt == 'a' ? audio_codec_name :
5536 subtitle_codec_name;
5538 if (!(f = get_preset_file(filename, sizeof(filename), arg, *opt == 'f', codec_name))) {
5539 if(!strncmp(arg, "libx264-lossless", strlen("libx264-lossless"))){
5540 av_log(NULL, AV_LOG_FATAL, "Please use -preset <speed> -qp 0\n");
5542 av_log(NULL, AV_LOG_FATAL, "File for preset '%s' not found\n", arg);
5546 while (fgets(line, sizeof(line), f)) {
5547 char *key = tmp_line, *value, *endptr;
5549 if (strcspn(line, "#\n\r") == 0)
5551 strcpy(tmp_line, line);
5552 if (!av_strtok(key, "=", &value) ||
5553 !av_strtok(value, "\r\n", &endptr)) {
5554 av_log(NULL, AV_LOG_FATAL, "%s: Invalid syntax: '%s'\n", filename, line);
5557 av_log(NULL, AV_LOG_DEBUG, "ffpreset[%s]: set '%s' = '%s'\n", filename, key, value);
5559 if (!strcmp(key, "acodec")) opt_audio_codec (o, key, value);
5560 else if (!strcmp(key, "vcodec")) opt_video_codec (o, key, value);
5561 else if (!strcmp(key, "scodec")) opt_subtitle_codec(o, key, value);
5562 else if (!strcmp(key, "dcodec")) opt_data_codec (o, key, value);
5563 else if (opt_default(key, value) < 0) {
5564 av_log(NULL, AV_LOG_FATAL, "%s: Invalid option or argument: '%s', parsed as '%s' = '%s'\n",
5565 filename, line, key, value);
5575 static void log_callback_null(void *ptr, int level, const char *fmt, va_list vl)
5579 static int opt_passlogfile(const char *opt, const char *arg)
5581 pass_logfilename_prefix = arg;
5582 #if CONFIG_LIBX264_ENCODER
5583 return opt_default(opt, arg);
5589 static int opt_old2new(OptionsContext *o, const char *opt, const char *arg)
5591 char *s = av_asprintf("%s:%c", opt + 1, *opt);
5592 int ret = parse_option(o, s, arg, options);
5597 static int opt_bitrate(OptionsContext *o, const char *opt, const char *arg)
5599 if(!strcmp(opt, "b")){
5600 av_log(NULL, AV_LOG_WARNING, "Please use -b:a or -b:v, -b is ambiguous\n");
5601 return parse_option(o, "b:v", arg, options);
5603 return opt_default(opt, arg);
5606 static int opt_qscale(OptionsContext *o, const char *opt, const char *arg)
5610 if(!strcmp(opt, "qscale")){
5611 av_log(NULL, AV_LOG_WARNING, "Please use -q:a or -q:v, -qscale is ambiguous\n");
5612 return parse_option(o, "q:v", arg, options);
5614 s = av_asprintf("q%s", opt + 6);
5615 ret = parse_option(o, s, arg, options);
5620 static int opt_profile(OptionsContext *o, const char *opt, const char *arg)
5622 if(!strcmp(opt, "profile")){
5623 av_log(NULL, AV_LOG_WARNING, "Please use -profile:a or -profile:v, -profile is ambiguous\n");
5624 return parse_option(o, "profile:v", arg, options);
5626 return opt_default(opt, arg);
5629 static int opt_video_filters(OptionsContext *o, const char *opt, const char *arg)
5631 return parse_option(o, "filter:v", arg, options);
5634 static int opt_vsync(const char *opt, const char *arg)
5636 if (!av_strcasecmp(arg, "cfr")) video_sync_method = VSYNC_CFR;
5637 else if (!av_strcasecmp(arg, "vfr")) video_sync_method = VSYNC_VFR;
5638 else if (!av_strcasecmp(arg, "passthrough")) video_sync_method = VSYNC_PASSTHROUGH;
5639 else if (!av_strcasecmp(arg, "drop")) video_sync_method = VSYNC_DROP;
5641 if (video_sync_method == VSYNC_AUTO)
5642 video_sync_method = parse_number_or_die("vsync", arg, OPT_INT, VSYNC_AUTO, VSYNC_VFR);
5646 static int opt_deinterlace(const char *opt, const char *arg)
5648 av_log(NULL, AV_LOG_WARNING, "-%s is deprecated, use -filter:v yadif instead\n", opt);
5653 static void parse_cpuflags(int argc, char **argv, const OptionDef *options)
5655 int idx = locate_option(argc, argv, options, "cpuflags");
5656 if (idx && argv[idx + 1])
5657 opt_cpuflags("cpuflags", argv[idx + 1]);
5660 static int opt_channel_layout(OptionsContext *o, const char *opt, const char *arg)
5662 char layout_str[32];
5665 int ret, channels, ac_str_size;
5668 layout = av_get_channel_layout(arg);
5670 av_log(NULL, AV_LOG_ERROR, "Unknown channel layout: %s\n", arg);
5671 return AVERROR(EINVAL);
5673 snprintf(layout_str, sizeof(layout_str), "%"PRIu64, layout);
5674 ret = opt_default(opt, layout_str);
5678 /* set 'ac' option based on channel layout */
5679 channels = av_get_channel_layout_nb_channels(layout);
5680 snprintf(layout_str, sizeof(layout_str), "%d", channels);
5681 stream_str = strchr(opt, ':');
5682 ac_str_size = 3 + (stream_str ? strlen(stream_str) : 0);
5683 ac_str = av_mallocz(ac_str_size);
5685 return AVERROR(ENOMEM);
5686 av_strlcpy(ac_str, "ac", 3);
5688 av_strlcat(ac_str, stream_str, ac_str_size);
5689 ret = parse_option(o, ac_str, layout_str, options);
5695 static int opt_filter_complex(const char *opt, const char *arg)
5697 filtergraphs = grow_array(filtergraphs, sizeof(*filtergraphs),
5698 &nb_filtergraphs, nb_filtergraphs + 1);
5699 if (!(filtergraphs[nb_filtergraphs - 1] = av_mallocz(sizeof(*filtergraphs[0]))))
5700 return AVERROR(ENOMEM);
5701 filtergraphs[nb_filtergraphs - 1]->index = nb_filtergraphs - 1;
5702 filtergraphs[nb_filtergraphs - 1]->graph_desc = arg;
5706 #define OFFSET(x) offsetof(OptionsContext, x)
5707 static const OptionDef options[] = {
5709 #include "cmdutils_common_opts.h"
5710 { "f", HAS_ARG | OPT_STRING | OPT_OFFSET, {.off = OFFSET(format)}, "force format", "fmt" },
5711 { "i", HAS_ARG | OPT_FUNC2, {(void*)opt_input_file}, "input file name", "filename" },
5712 { "y", OPT_BOOL, {(void*)&file_overwrite}, "overwrite output files" },
5713 { "n", OPT_BOOL, {(void*)&no_file_overwrite}, "do not overwrite output files" },
5714 { "c", HAS_ARG | OPT_STRING | OPT_SPEC, {.off = OFFSET(codec_names)}, "codec name", "codec" },
5715 { "codec", HAS_ARG | OPT_STRING | OPT_SPEC, {.off = OFFSET(codec_names)}, "codec name", "codec" },
5716 { "pre", HAS_ARG | OPT_STRING | OPT_SPEC, {.off = OFFSET(presets)}, "preset name", "preset" },
5717 { "map", HAS_ARG | OPT_EXPERT | OPT_FUNC2, {(void*)opt_map}, "set input stream mapping", "[-]input_file_id[:stream_specifier][,sync_file_id[:stream_specifier]]" },
5718 { "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]" },
5719 { "map_metadata", HAS_ARG | OPT_STRING | OPT_SPEC, {.off = OFFSET(metadata_map)}, "set metadata information of outfile from infile",
5720 "outfile[,metadata]:infile[,metadata]" },
5721 { "map_chapters", OPT_INT | HAS_ARG | OPT_EXPERT | OPT_OFFSET, {.off = OFFSET(chapters_input_file)}, "set chapters mapping", "input_file_index" },
5722 { "t", HAS_ARG | OPT_TIME | OPT_OFFSET, {.off = OFFSET(recording_time)}, "record or transcode \"duration\" seconds of audio/video", "duration" },
5723 { "fs", HAS_ARG | OPT_INT64 | OPT_OFFSET, {.off = OFFSET(limit_filesize)}, "set the limit file size in bytes", "limit_size" }, //
5724 { "ss", HAS_ARG | OPT_TIME | OPT_OFFSET, {.off = OFFSET(start_time)}, "set the start time offset", "time_off" },
5725 { "itsoffset", HAS_ARG | OPT_TIME | OPT_OFFSET, {.off = OFFSET(input_ts_offset)}, "set the input ts offset", "time_off" },
5726 { "itsscale", HAS_ARG | OPT_DOUBLE | OPT_SPEC, {.off = OFFSET(ts_scale)}, "set the input ts scale", "scale" },
5727 { "timestamp", HAS_ARG | OPT_FUNC2, {(void*)opt_recording_timestamp}, "set the recording timestamp ('now' to set the current time)", "time" },
5728 { "metadata", HAS_ARG | OPT_STRING | OPT_SPEC, {.off = OFFSET(metadata)}, "add metadata", "string=string" },
5729 { "dframes", HAS_ARG | OPT_FUNC2, {(void*)opt_data_frames}, "set the number of data frames to record", "number" },
5730 { "benchmark", OPT_BOOL | OPT_EXPERT, {(void*)&do_benchmark},
5731 "add timings for benchmarking" },
5732 { "benchmark_all", OPT_BOOL | OPT_EXPERT, {(void*)&do_benchmark_all},
5733 "add timings for each task" },
5734 { "timelimit", HAS_ARG, {(void*)opt_timelimit}, "set max runtime in seconds", "limit" },
5735 { "dump", OPT_BOOL | OPT_EXPERT, {(void*)&do_pkt_dump},
5736 "dump each input packet" },
5737 { "hex", OPT_BOOL | OPT_EXPERT, {(void*)&do_hex_dump},
5738 "when dumping packets, also dump the payload" },
5739 { "re", OPT_BOOL | OPT_EXPERT | OPT_OFFSET, {.off = OFFSET(rate_emu)}, "read input at native frame rate", "" },
5740 { "target", HAS_ARG | OPT_FUNC2, {(void*)opt_target}, "specify target file type (\"vcd\", \"svcd\", \"dvd\", \"dv\", \"dv50\", \"pal-vcd\", \"ntsc-svcd\", ...)", "type" },
5741 { "vsync", HAS_ARG | OPT_EXPERT, {(void*)opt_vsync}, "video sync method", "" },
5742 { "async", HAS_ARG | OPT_INT | OPT_EXPERT, {(void*)&audio_sync_method}, "audio sync method", "" },
5743 { "adrift_threshold", HAS_ARG | OPT_FLOAT | OPT_EXPERT, {(void*)&audio_drift_threshold}, "audio drift threshold", "threshold" },
5744 { "copyts", OPT_BOOL | OPT_EXPERT, {(void*)©_ts}, "copy timestamps" },
5745 { "copytb", HAS_ARG | OPT_INT | OPT_EXPERT, {(void*)©_tb}, "copy input stream time base when stream copying", "mode" },
5746 { "shortest", OPT_BOOL | OPT_EXPERT, {(void*)&opt_shortest}, "finish encoding within shortest input" }, //
5747 { "dts_delta_threshold", HAS_ARG | OPT_FLOAT | OPT_EXPERT, {(void*)&dts_delta_threshold}, "timestamp discontinuity delta threshold", "threshold" },
5748 { "dts_error_threshold", HAS_ARG | OPT_FLOAT | OPT_EXPERT, {(void*)&dts_error_threshold}, "timestamp error delta threshold", "threshold" },
5749 { "xerror", OPT_BOOL, {(void*)&exit_on_error}, "exit on error", "error" },
5750 { "copyinkf", OPT_BOOL | OPT_EXPERT | OPT_SPEC, {.off = OFFSET(copy_initial_nonkeyframes)}, "copy initial non-keyframes" },
5751 { "frames", OPT_INT64 | HAS_ARG | OPT_SPEC, {.off = OFFSET(max_frames)}, "set the number of frames to record", "number" },
5752 { "tag", OPT_STRING | HAS_ARG | OPT_SPEC, {.off = OFFSET(codec_tags)}, "force codec tag/fourcc", "fourcc/tag" },
5753 { "q", HAS_ARG | OPT_EXPERT | OPT_DOUBLE | OPT_SPEC, {.off = OFFSET(qscale)}, "use fixed quality scale (VBR)", "q" },
5754 { "qscale", HAS_ARG | OPT_EXPERT | OPT_FUNC2, {(void*)opt_qscale}, "use fixed quality scale (VBR)", "q" },
5755 { "profile", HAS_ARG | OPT_EXPERT | OPT_FUNC2, {(void*)opt_profile}, "set profile", "profile" },
5756 { "filter", HAS_ARG | OPT_STRING | OPT_SPEC, {.off = OFFSET(filters)}, "set stream filterchain", "filter_list" },
5757 { "filter_complex", HAS_ARG | OPT_EXPERT, {(void*)opt_filter_complex}, "create a complex filtergraph", "graph_description" },
5758 { "stats", OPT_BOOL, {&print_stats}, "print progress report during encoding", },
5759 { "attach", HAS_ARG | OPT_FUNC2, {(void*)opt_attach}, "add an attachment to the output file", "filename" },
5760 { "dump_attachment", HAS_ARG | OPT_STRING | OPT_SPEC, {.off = OFFSET(dump_attachment)}, "extract an attachment into a file", "filename" },
5761 { "debug_ts", OPT_BOOL | OPT_EXPERT, {&debug_ts}, "print timestamp debugging info" },
5764 { "vframes", HAS_ARG | OPT_VIDEO | OPT_FUNC2, {(void*)opt_video_frames}, "set the number of video frames to record", "number" },
5765 { "r", HAS_ARG | OPT_VIDEO | OPT_STRING | OPT_SPEC, {.off = OFFSET(frame_rates)}, "set frame rate (Hz value, fraction or abbreviation)", "rate" },
5766 { "s", HAS_ARG | OPT_VIDEO | OPT_STRING | OPT_SPEC, {.off = OFFSET(frame_sizes)}, "set frame size (WxH or abbreviation)", "size" },
5767 { "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" },
5768 { "pix_fmt", HAS_ARG | OPT_EXPERT | OPT_VIDEO | OPT_STRING | OPT_SPEC, {.off = OFFSET(frame_pix_fmts)}, "set pixel format", "format" },
5769 { "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" },
5770 { "croptop", HAS_ARG | OPT_VIDEO, {(void*)opt_frame_crop}, "Removed, use the crop filter instead", "size" },
5771 { "cropbottom", HAS_ARG | OPT_VIDEO, {(void*)opt_frame_crop}, "Removed, use the crop filter instead", "size" },
5772 { "cropleft", HAS_ARG | OPT_VIDEO, {(void*)opt_frame_crop}, "Removed, use the crop filter instead", "size" },
5773 { "cropright", HAS_ARG | OPT_VIDEO, {(void*)opt_frame_crop}, "Removed, use the crop filter instead", "size" },
5774 { "padtop", HAS_ARG | OPT_VIDEO, {(void*)opt_pad}, "Removed, use the pad filter instead", "size" },
5775 { "padbottom", HAS_ARG | OPT_VIDEO, {(void*)opt_pad}, "Removed, use the pad filter instead", "size" },
5776 { "padleft", HAS_ARG | OPT_VIDEO, {(void*)opt_pad}, "Removed, use the pad filter instead", "size" },
5777 { "padright", HAS_ARG | OPT_VIDEO, {(void*)opt_pad}, "Removed, use the pad filter instead", "size" },
5778 { "padcolor", HAS_ARG | OPT_VIDEO, {(void*)opt_pad}, "Removed, use the pad filter instead", "color" },
5779 { "intra", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, {(void*)&intra_only}, "deprecated use -g 1"},
5780 { "vn", OPT_BOOL | OPT_VIDEO | OPT_OFFSET, {.off = OFFSET(video_disable)}, "disable video" },
5781 { "vdt", OPT_INT | HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)&video_discard}, "discard threshold", "n" },
5782 { "rc_override", HAS_ARG | OPT_EXPERT | OPT_VIDEO | OPT_STRING | OPT_SPEC, {.off = OFFSET(rc_overrides)}, "rate control override for specific intervals", "override" },
5783 { "vcodec", HAS_ARG | OPT_VIDEO | OPT_FUNC2, {(void*)opt_video_codec}, "force video codec ('copy' to copy stream)", "codec" },
5784 { "sameq", OPT_BOOL | OPT_VIDEO, {(void*)&same_quant}, "use same quantizer as source (implies VBR)" },
5785 { "same_quant", OPT_BOOL | OPT_VIDEO, {(void*)&same_quant},
5786 "use same quantizer as source (implies VBR)" },
5787 { "pass", HAS_ARG | OPT_VIDEO, {(void*)opt_pass}, "select the pass number (1 or 2)", "n" },
5788 { "passlogfile", HAS_ARG | OPT_VIDEO, {(void*)&opt_passlogfile}, "select two pass log file name prefix", "prefix" },
5789 { "deinterlace", OPT_EXPERT | OPT_VIDEO, {(void*)opt_deinterlace},
5790 "this option is deprecated, use the yadif filter instead" },
5791 { "psnr", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, {(void*)&do_psnr}, "calculate PSNR of compressed frames" },
5792 { "vstats", OPT_EXPERT | OPT_VIDEO, {(void*)&opt_vstats}, "dump video coding statistics to file" },
5793 { "vstats_file", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_vstats_file}, "dump video coding statistics to file", "file" },
5794 { "vf", HAS_ARG | OPT_VIDEO | OPT_FUNC2, {(void*)opt_video_filters}, "video filters", "filter list" },
5795 { "intra_matrix", HAS_ARG | OPT_EXPERT | OPT_VIDEO | OPT_STRING | OPT_SPEC, {.off = OFFSET(intra_matrices)}, "specify intra matrix coeffs", "matrix" },
5796 { "inter_matrix", HAS_ARG | OPT_EXPERT | OPT_VIDEO | OPT_STRING | OPT_SPEC, {.off = OFFSET(inter_matrices)}, "specify inter matrix coeffs", "matrix" },
5797 { "top", HAS_ARG | OPT_EXPERT | OPT_VIDEO | OPT_INT| OPT_SPEC, {.off = OFFSET(top_field_first)}, "top=1/bottom=0/auto=-1 field first", "" },
5798 { "dc", OPT_INT | HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)&intra_dc_precision}, "intra_dc_precision", "precision" },
5799 { "vtag", HAS_ARG | OPT_EXPERT | OPT_VIDEO | OPT_FUNC2, {(void*)opt_old2new}, "force video tag/fourcc", "fourcc/tag" },
5800 { "qphist", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, { (void *)&qp_hist }, "show QP histogram" },
5801 { "force_fps", OPT_BOOL | OPT_EXPERT | OPT_VIDEO | OPT_SPEC, {.off = OFFSET(force_fps)}, "force the selected framerate, disable the best supported framerate selection" },
5802 { "streamid", HAS_ARG | OPT_EXPERT | OPT_FUNC2, {(void*)opt_streamid}, "set the value of an outfile streamid", "streamIndex:value" },
5803 { "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" },
5804 { "b", HAS_ARG | OPT_VIDEO | OPT_FUNC2, {(void*)opt_bitrate}, "video bitrate (please use -b:v)", "bitrate" },
5807 { "aframes", HAS_ARG | OPT_AUDIO | OPT_FUNC2, {(void*)opt_audio_frames}, "set the number of audio frames to record", "number" },
5808 { "aq", HAS_ARG | OPT_AUDIO | OPT_FUNC2, {(void*)opt_audio_qscale}, "set audio quality (codec-specific)", "quality", },
5809 { "ar", HAS_ARG | OPT_AUDIO | OPT_INT | OPT_SPEC, {.off = OFFSET(audio_sample_rate)}, "set audio sampling rate (in Hz)", "rate" },
5810 { "ac", HAS_ARG | OPT_AUDIO | OPT_INT | OPT_SPEC, {.off = OFFSET(audio_channels)}, "set number of audio channels", "channels" },
5811 { "an", OPT_BOOL | OPT_AUDIO | OPT_OFFSET, {.off = OFFSET(audio_disable)}, "disable audio" },
5812 { "acodec", HAS_ARG | OPT_AUDIO | OPT_FUNC2, {(void*)opt_audio_codec}, "force audio codec ('copy' to copy stream)", "codec" },
5813 { "atag", HAS_ARG | OPT_EXPERT | OPT_AUDIO | OPT_FUNC2, {(void*)opt_old2new}, "force audio tag/fourcc", "fourcc/tag" },
5814 { "vol", OPT_INT | HAS_ARG | OPT_AUDIO, {(void*)&audio_volume}, "change audio volume (256=normal)" , "volume" }, //
5815 { "sample_fmt", HAS_ARG | OPT_EXPERT | OPT_AUDIO | OPT_SPEC | OPT_STRING, {.off = OFFSET(sample_fmts)}, "set sample format", "format" },
5816 { "rmvol", HAS_ARG | OPT_AUDIO | OPT_FLOAT | OPT_SPEC, {.off = OFFSET(rematrix_volume)}, "rematrix volume (as factor)", "volume" },
5817 { "channel_layout", HAS_ARG | OPT_EXPERT | OPT_AUDIO | OPT_FUNC2, {(void*)opt_channel_layout}, "set channel layout", "layout" },
5819 /* subtitle options */
5820 { "sn", OPT_BOOL | OPT_SUBTITLE | OPT_OFFSET, {.off = OFFSET(subtitle_disable)}, "disable subtitle" },
5821 { "scodec", HAS_ARG | OPT_SUBTITLE | OPT_FUNC2, {(void*)opt_subtitle_codec}, "force subtitle codec ('copy' to copy stream)", "codec" },
5822 { "stag", HAS_ARG | OPT_EXPERT | OPT_SUBTITLE | OPT_FUNC2, {(void*)opt_old2new}, "force subtitle tag/fourcc", "fourcc/tag" },
5825 { "vc", HAS_ARG | OPT_EXPERT | OPT_VIDEO | OPT_GRAB, {(void*)opt_video_channel}, "deprecated, use -channel", "channel" },
5826 { "tvstd", HAS_ARG | OPT_EXPERT | OPT_VIDEO | OPT_GRAB, {(void*)opt_video_standard}, "deprecated, use -standard", "standard" },
5827 { "isync", OPT_BOOL | OPT_EXPERT | OPT_GRAB, {(void*)&input_sync}, "sync read on input", "" },
5830 { "muxdelay", OPT_FLOAT | HAS_ARG | OPT_EXPERT | OPT_OFFSET, {.off = OFFSET(mux_max_delay)}, "set the maximum demux-decode delay", "seconds" },
5831 { "muxpreload", OPT_FLOAT | HAS_ARG | OPT_EXPERT | OPT_OFFSET, {.off = OFFSET(mux_preload)}, "set the initial demux-decode delay", "seconds" },
5833 { "bsf", HAS_ARG | OPT_STRING | OPT_SPEC, {.off = OFFSET(bitstream_filters)}, "A comma-separated list of bitstream filters", "bitstream_filters" },
5834 { "absf", HAS_ARG | OPT_AUDIO | OPT_EXPERT| OPT_FUNC2, {(void*)opt_old2new}, "deprecated", "audio bitstream_filters" },
5835 { "vbsf", HAS_ARG | OPT_VIDEO | OPT_EXPERT| OPT_FUNC2, {(void*)opt_old2new}, "deprecated", "video bitstream_filters" },
5837 { "apre", HAS_ARG | OPT_AUDIO | OPT_EXPERT| OPT_FUNC2, {(void*)opt_preset}, "set the audio options to the indicated preset", "preset" },
5838 { "vpre", HAS_ARG | OPT_VIDEO | OPT_EXPERT| OPT_FUNC2, {(void*)opt_preset}, "set the video options to the indicated preset", "preset" },
5839 { "spre", HAS_ARG | OPT_SUBTITLE | OPT_EXPERT| OPT_FUNC2, {(void*)opt_preset}, "set the subtitle options to the indicated preset", "preset" },
5840 { "fpre", HAS_ARG | OPT_EXPERT| OPT_FUNC2, {(void*)opt_preset}, "set options from indicated preset file", "filename" },
5841 /* data codec support */
5842 { "dcodec", HAS_ARG | OPT_DATA | OPT_FUNC2, {(void*)opt_data_codec}, "force data codec ('copy' to copy stream)", "codec" },
5843 { "dn", OPT_BOOL | OPT_VIDEO | OPT_OFFSET, {.off = OFFSET(data_disable)}, "disable data" },
5845 { "default", HAS_ARG | OPT_AUDIO | OPT_VIDEO | OPT_EXPERT, {(void*)opt_default}, "generic catch all option", "" },
5849 int main(int argc, char **argv)
5851 OptionsContext o = { 0 };
5854 reset_options(&o, 0);
5856 av_log_set_flags(AV_LOG_SKIP_REPEATED);
5857 parse_loglevel(argc, argv, options);
5859 if(argc>1 && !strcmp(argv[1], "-d")){
5861 av_log_set_callback(log_callback_null);
5866 avcodec_register_all();
5868 avdevice_register_all();
5870 avfilter_register_all();
5872 avformat_network_init();
5874 show_banner(argc, argv, options);
5878 parse_cpuflags(argc, argv, options);
5881 parse_options(&o, argc, argv, options, opt_output_file);
5883 if (nb_output_files <= 0 && nb_input_files == 0) {
5885 av_log(NULL, AV_LOG_WARNING, "Use -h to get full help or, even better, run 'man %s'\n", program_name);
5889 /* file converter / grab */
5890 if (nb_output_files <= 0) {
5891 av_log(NULL, AV_LOG_FATAL, "At least one output file must be specified\n");
5895 if (nb_input_files == 0) {
5896 av_log(NULL, AV_LOG_FATAL, "At least one input file must be specified\n");
5900 current_time = ti = getutime();
5901 if (transcode() < 0)
5903 ti = getutime() - ti;
5905 int maxrss = getmaxrss() / 1024;
5906 printf("bench: utime=%0.3fs maxrss=%ikB\n", ti / 1000000.0, maxrss);