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 */
2070 for (i = 0; i < nb_output_streams; i++) {
2071 OutputStream *ost = output_streams[i];
2072 OutputFile *of = output_files[ost->file_index];
2074 if (!ost->filter || ost->is_past_recording_time)
2077 if (!ost->filtered_frame && !(ost->filtered_frame = avcodec_alloc_frame())) {
2078 return AVERROR(ENOMEM);
2080 avcodec_get_frame_defaults(ost->filtered_frame);
2081 filtered_frame = ost->filtered_frame;
2084 AVRational ist_pts_tb = ost->filter->filter->inputs[0]->time_base;
2085 ret = av_buffersink_get_buffer_ref(ost->filter->filter, &picref,
2086 AV_BUFFERSINK_FLAG_NO_REQUEST);
2088 if (ret != AVERROR(EAGAIN)) {
2090 av_strerror(ret, buf, sizeof(buf));
2091 av_log(NULL, AV_LOG_WARNING,
2092 "Error in av_buffersink_get_buffer_ref(): %s\n", buf);
2096 filtered_frame->pts = av_rescale_q(picref->pts, ist_pts_tb, AV_TIME_BASE_Q);
2097 // if (ost->source_index >= 0)
2098 // *filtered_frame= *input_streams[ost->source_index]->decoded_frame; //for me_threshold
2100 if (of->start_time && filtered_frame->pts < of->start_time)
2103 switch (ost->filter->filter->inputs[0]->type) {
2104 case AVMEDIA_TYPE_VIDEO:
2105 avfilter_fill_frame_from_video_buffer_ref(filtered_frame, picref);
2106 if (!ost->frame_aspect_ratio)
2107 ost->st->codec->sample_aspect_ratio = picref->video->sample_aspect_ratio;
2109 do_video_out(of->ctx, ost, filtered_frame,
2110 same_quant ? ost->last_quality :
2111 ost->st->codec->global_quality);
2114 // TODO support audio/subtitle filters
2118 avfilter_unref_buffer(picref);
2121 /* Request frames through all the graphs */
2122 ret_all = nb_success = nb_eof = 0;
2123 for (i = 0; i < nb_filtergraphs; i++) {
2124 ret = avfilter_graph_request_oldest(filtergraphs[i]->graph);
2127 } else if (ret == AVERROR_EOF) {
2129 } else if (ret != AVERROR(EAGAIN)) {
2131 av_strerror(ret, buf, sizeof(buf));
2132 av_log(NULL, AV_LOG_WARNING,
2133 "Error in request_frame(): %s\n", buf);
2139 /* Try again if anything succeeded */
2141 return nb_eof == nb_filtergraphs ? AVERROR_EOF : ret_all;
2144 static void print_report(int is_last_report, int64_t timer_start, int64_t cur_time)
2148 AVFormatContext *oc;
2150 AVCodecContext *enc;
2151 int frame_number, vid, i;
2153 int64_t pts = INT64_MAX;
2154 static int64_t last_time = -1;
2155 static int qp_histogram[52];
2156 int hours, mins, secs, us;
2158 if (!print_stats && !is_last_report)
2161 if (!is_last_report) {
2162 if (last_time == -1) {
2163 last_time = cur_time;
2166 if ((cur_time - last_time) < 500000)
2168 last_time = cur_time;
2172 oc = output_files[0]->ctx;
2174 total_size = avio_size(oc->pb);
2175 if (total_size < 0) { // FIXME improve avio_size() so it works with non seekable output too
2176 total_size = avio_tell(oc->pb);
2183 for (i = 0; i < nb_output_streams; i++) {
2185 ost = output_streams[i];
2186 enc = ost->st->codec;
2187 if (!ost->stream_copy && enc->coded_frame)
2188 q = enc->coded_frame->quality / (float)FF_QP2LAMBDA;
2189 if (vid && enc->codec_type == AVMEDIA_TYPE_VIDEO) {
2190 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "q=%2.1f ", q);
2192 if (!vid && enc->codec_type == AVMEDIA_TYPE_VIDEO) {
2193 float fps, t = (cur_time-timer_start) / 1000000.0;
2195 frame_number = ost->frame_number;
2196 fps = t > 1 ? frame_number / t : 0;
2197 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "frame=%5d fps=%3.*f q=%3.1f ",
2198 frame_number, fps < 9.95, fps, q);
2200 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "L");
2204 if (qp >= 0 && qp < FF_ARRAY_ELEMS(qp_histogram))
2206 for (j = 0; j < 32; j++)
2207 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "%X", (int)lrintf(log(qp_histogram[j] + 1) / log(2)));
2209 if (enc->flags&CODEC_FLAG_PSNR) {
2211 double error, error_sum = 0;
2212 double scale, scale_sum = 0;
2213 char type[3] = { 'Y','U','V' };
2214 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "PSNR=");
2215 for (j = 0; j < 3; j++) {
2216 if (is_last_report) {
2217 error = enc->error[j];
2218 scale = enc->width * enc->height * 255.0 * 255.0 * frame_number;
2220 error = enc->coded_frame->error[j];
2221 scale = enc->width * enc->height * 255.0 * 255.0;
2227 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "%c:%2.2f ", type[j], psnr(error / scale));
2229 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "*:%2.2f ", psnr(error_sum / scale_sum));
2233 /* compute min output value */
2234 pts = FFMIN(pts, av_rescale_q(ost->st->pts.val,
2235 ost->st->time_base, AV_TIME_BASE_Q));
2238 secs = pts / AV_TIME_BASE;
2239 us = pts % AV_TIME_BASE;
2245 bitrate = pts ? total_size * 8 / (pts / 1000.0) : 0;
2247 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
2248 "size=%8.0fkB time=", total_size / 1024.0);
2249 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
2250 "%02d:%02d:%02d.%02d ", hours, mins, secs,
2251 (100 * us) / AV_TIME_BASE);
2252 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
2253 "bitrate=%6.1fkbits/s", bitrate);
2255 if (nb_frames_dup || nb_frames_drop)
2256 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), " dup=%d drop=%d",
2257 nb_frames_dup, nb_frames_drop);
2259 av_log(NULL, AV_LOG_INFO, "%s \r", buf);
2263 if (is_last_report) {
2264 int64_t raw= audio_size + video_size + extra_size;
2265 av_log(NULL, AV_LOG_INFO, "\n");
2266 av_log(NULL, AV_LOG_INFO, "video:%1.0fkB audio:%1.0fkB global headers:%1.0fkB muxing overhead %f%%\n",
2267 video_size / 1024.0,
2268 audio_size / 1024.0,
2269 extra_size / 1024.0,
2270 100.0 * (total_size - raw) / raw
2272 if(video_size + audio_size + extra_size == 0){
2273 av_log(NULL, AV_LOG_WARNING, "Output file is empty, nothing was encoded (check -ss / -t / -frames parameters if used)\n");
2278 static void flush_encoders(void)
2282 for (i = 0; i < nb_output_streams; i++) {
2283 OutputStream *ost = output_streams[i];
2284 AVCodecContext *enc = ost->st->codec;
2285 AVFormatContext *os = output_files[ost->file_index]->ctx;
2286 int stop_encoding = 0;
2288 if (!ost->encoding_needed)
2291 if (ost->st->codec->codec_type == AVMEDIA_TYPE_AUDIO && enc->frame_size <= 1)
2293 if (ost->st->codec->codec_type == AVMEDIA_TYPE_VIDEO && (os->oformat->flags & AVFMT_RAWPICTURE) && enc->codec->id == CODEC_ID_RAWVIDEO)
2298 int fifo_bytes, got_packet;
2299 av_init_packet(&pkt);
2303 switch (ost->st->codec->codec_type) {
2304 case AVMEDIA_TYPE_AUDIO:
2305 fifo_bytes = av_fifo_size(ost->fifo);
2306 if (fifo_bytes > 0) {
2307 /* encode any samples remaining in fifo */
2308 int frame_bytes = fifo_bytes;
2310 av_fifo_generic_read(ost->fifo, audio_buf, fifo_bytes, NULL);
2312 /* pad last frame with silence if needed */
2313 if (!(enc->codec->capabilities & CODEC_CAP_SMALL_LAST_FRAME)) {
2314 frame_bytes = enc->frame_size * enc->channels *
2315 av_get_bytes_per_sample(enc->sample_fmt);
2316 if (allocated_audio_buf_size < frame_bytes)
2318 generate_silence(audio_buf+fifo_bytes, enc->sample_fmt, frame_bytes - fifo_bytes);
2320 encode_audio_frame(os, ost, audio_buf, frame_bytes);
2322 /* flush encoder with NULL frames until it is done
2323 returning packets */
2324 if (encode_audio_frame(os, ost, NULL, 0) == 0) {
2330 case AVMEDIA_TYPE_VIDEO:
2331 update_benchmark(NULL);
2332 ret = avcodec_encode_video2(enc, &pkt, NULL, &got_packet);
2333 update_benchmark("encode_video %d.%d", ost->file_index, ost->index);
2335 av_log(NULL, AV_LOG_FATAL, "Video encoding failed\n");
2338 video_size += pkt.size;
2339 if (ost->logfile && enc->stats_out) {
2340 fprintf(ost->logfile, "%s", enc->stats_out);
2346 if (pkt.pts != AV_NOPTS_VALUE)
2347 pkt.pts = av_rescale_q(pkt.pts, enc->time_base, ost->st->time_base);
2348 if (pkt.dts != AV_NOPTS_VALUE)
2349 pkt.dts = av_rescale_q(pkt.dts, enc->time_base, ost->st->time_base);
2350 write_frame(os, &pkt, ost);
2362 * Check whether a packet from ist should be written into ost at this time
2364 static int check_output_constraints(InputStream *ist, OutputStream *ost)
2366 OutputFile *of = output_files[ost->file_index];
2367 int ist_index = input_files[ist->file_index]->ist_index + ist->st->index;
2369 if (ost->source_index != ist_index)
2372 if (of->start_time && ist->pts < of->start_time)
2375 if (of->recording_time != INT64_MAX &&
2376 av_compare_ts(ist->pts, AV_TIME_BASE_Q, of->recording_time + of->start_time,
2377 (AVRational){ 1, 1000000 }) >= 0) {
2378 ost->is_past_recording_time = 1;
2385 static void do_streamcopy(InputStream *ist, OutputStream *ost, const AVPacket *pkt)
2387 OutputFile *of = output_files[ost->file_index];
2388 int64_t ost_tb_start_time = av_rescale_q(of->start_time, AV_TIME_BASE_Q, ost->st->time_base);
2392 av_init_packet(&opkt);
2394 if ((!ost->frame_number && !(pkt->flags & AV_PKT_FLAG_KEY)) &&
2395 !ost->copy_initial_nonkeyframes)
2398 /* force the input stream PTS */
2399 if (ost->st->codec->codec_type == AVMEDIA_TYPE_AUDIO)
2400 audio_size += pkt->size;
2401 else if (ost->st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
2402 video_size += pkt->size;
2406 if (pkt->pts != AV_NOPTS_VALUE)
2407 opkt.pts = av_rescale_q(pkt->pts, ist->st->time_base, ost->st->time_base) - ost_tb_start_time;
2409 opkt.pts = AV_NOPTS_VALUE;
2411 if (pkt->dts == AV_NOPTS_VALUE)
2412 opkt.dts = av_rescale_q(ist->dts, AV_TIME_BASE_Q, ost->st->time_base);
2414 opkt.dts = av_rescale_q(pkt->dts, ist->st->time_base, ost->st->time_base);
2415 opkt.dts -= ost_tb_start_time;
2417 opkt.duration = av_rescale_q(pkt->duration, ist->st->time_base, ost->st->time_base);
2418 opkt.flags = pkt->flags;
2420 // FIXME remove the following 2 lines they shall be replaced by the bitstream filters
2421 if ( ost->st->codec->codec_id != CODEC_ID_H264
2422 && ost->st->codec->codec_id != CODEC_ID_MPEG1VIDEO
2423 && ost->st->codec->codec_id != CODEC_ID_MPEG2VIDEO
2424 && ost->st->codec->codec_id != CODEC_ID_VC1
2426 if (av_parser_change(ist->st->parser, ost->st->codec, &opkt.data, &opkt.size, pkt->data, pkt->size, pkt->flags & AV_PKT_FLAG_KEY))
2427 opkt.destruct = av_destruct_packet;
2429 opkt.data = pkt->data;
2430 opkt.size = pkt->size;
2432 if (of->ctx->oformat->flags & AVFMT_RAWPICTURE) {
2433 /* store AVPicture in AVPacket, as expected by the output format */
2434 avpicture_fill(&pict, opkt.data, ost->st->codec->pix_fmt, ost->st->codec->width, ost->st->codec->height);
2435 opkt.data = (uint8_t *)&pict;
2436 opkt.size = sizeof(AVPicture);
2437 opkt.flags |= AV_PKT_FLAG_KEY;
2440 write_frame(of->ctx, &opkt, ost);
2441 ost->st->codec->frame_number++;
2442 av_free_packet(&opkt);
2445 static void rate_emu_sleep(InputStream *ist)
2447 if (input_files[ist->file_index]->rate_emu) {
2448 int64_t pts = av_rescale(ist->dts, 1000000, AV_TIME_BASE);
2449 int64_t now = av_gettime() - ist->start;
2455 static int transcode_audio(InputStream *ist, AVPacket *pkt, int *got_output)
2457 AVFrame *decoded_frame;
2458 AVCodecContext *avctx = ist->st->codec;
2459 int bps = av_get_bytes_per_sample(ist->st->codec->sample_fmt);
2462 if (!ist->decoded_frame && !(ist->decoded_frame = avcodec_alloc_frame()))
2463 return AVERROR(ENOMEM);
2465 avcodec_get_frame_defaults(ist->decoded_frame);
2466 decoded_frame = ist->decoded_frame;
2468 update_benchmark(NULL);
2469 ret = avcodec_decode_audio4(avctx, decoded_frame, got_output, pkt);
2470 update_benchmark("decode_audio %d.%d", ist->file_index, ist->st->index);
2474 if (avctx->sample_rate <= 0) {
2475 av_log(avctx, AV_LOG_ERROR, "Sample rate %d invalid\n", avctx->sample_rate);
2476 return AVERROR_INVALIDDATA;
2480 /* no audio frame */
2484 /* if the decoder provides a pts, use it instead of the last packet pts.
2485 the decoder could be delaying output by a packet or more. */
2486 if (decoded_frame->pts != AV_NOPTS_VALUE)
2487 ist->dts = ist->next_dts = ist->pts = ist->next_pts = decoded_frame->pts;
2489 /* increment next_dts to use for the case where the input stream does not
2490 have timestamps or there are multiple frames in the packet */
2491 ist->next_pts += ((int64_t)AV_TIME_BASE * decoded_frame->nb_samples) /
2493 ist->next_dts += ((int64_t)AV_TIME_BASE * decoded_frame->nb_samples) /
2497 // preprocess audio (volume)
2498 if (audio_volume != 256) {
2499 int decoded_data_size = decoded_frame->nb_samples * avctx->channels * bps;
2500 void *samples = decoded_frame->data[0];
2501 switch (avctx->sample_fmt) {
2502 case AV_SAMPLE_FMT_U8:
2504 uint8_t *volp = samples;
2505 for (i = 0; i < (decoded_data_size / sizeof(*volp)); i++) {
2506 int v = (((*volp - 128) * audio_volume + 128) >> 8) + 128;
2507 *volp++ = av_clip_uint8(v);
2511 case AV_SAMPLE_FMT_S16:
2513 int16_t *volp = samples;
2514 for (i = 0; i < (decoded_data_size / sizeof(*volp)); i++) {
2515 int v = ((*volp) * audio_volume + 128) >> 8;
2516 *volp++ = av_clip_int16(v);
2520 case AV_SAMPLE_FMT_S32:
2522 int32_t *volp = samples;
2523 for (i = 0; i < (decoded_data_size / sizeof(*volp)); i++) {
2524 int64_t v = (((int64_t)*volp * audio_volume + 128) >> 8);
2525 *volp++ = av_clipl_int32(v);
2529 case AV_SAMPLE_FMT_FLT:
2531 float *volp = samples;
2532 float scale = audio_volume / 256.f;
2533 for (i = 0; i < (decoded_data_size / sizeof(*volp)); i++) {
2538 case AV_SAMPLE_FMT_DBL:
2540 double *volp = samples;
2541 double scale = audio_volume / 256.;
2542 for (i = 0; i < (decoded_data_size / sizeof(*volp)); i++) {
2548 av_log(NULL, AV_LOG_FATAL,
2549 "Audio volume adjustment on sample format %s is not supported.\n",
2550 av_get_sample_fmt_name(ist->st->codec->sample_fmt));
2555 rate_emu_sleep(ist);
2557 for (i = 0; i < nb_output_streams; i++) {
2558 OutputStream *ost = output_streams[i];
2560 if (!check_output_constraints(ist, ost) || !ost->encoding_needed)
2562 do_audio_out(output_files[ost->file_index]->ctx, ost, ist, decoded_frame);
2568 static int transcode_video(InputStream *ist, AVPacket *pkt, int *got_output, int64_t *pkt_pts)
2570 AVFrame *decoded_frame;
2571 void *buffer_to_free = NULL;
2572 int i, ret = 0, resample_changed;
2573 int64_t best_effort_timestamp;
2574 AVRational *frame_sample_aspect;
2577 if (!ist->decoded_frame && !(ist->decoded_frame = avcodec_alloc_frame()))
2578 return AVERROR(ENOMEM);
2580 avcodec_get_frame_defaults(ist->decoded_frame);
2581 decoded_frame = ist->decoded_frame;
2582 pkt->pts = *pkt_pts;
2583 pkt->dts = ist->dts;
2584 *pkt_pts = AV_NOPTS_VALUE;
2586 update_benchmark(NULL);
2587 ret = avcodec_decode_video2(ist->st->codec,
2588 decoded_frame, got_output, pkt);
2589 update_benchmark("decode_video %d.%d", ist->file_index, ist->st->index);
2593 quality = same_quant ? decoded_frame->quality : 0;
2595 /* no picture yet */
2597 for (i = 0; i < ist->nb_filters; i++)
2598 av_buffersrc_buffer(ist->filters[i]->filter, NULL);
2602 best_effort_timestamp= av_frame_get_best_effort_timestamp(decoded_frame);
2603 if(best_effort_timestamp != AV_NOPTS_VALUE)
2604 ist->next_pts = ist->pts = decoded_frame->pts = best_effort_timestamp;
2608 pre_process_video_frame(ist, (AVPicture *)decoded_frame, &buffer_to_free);
2610 rate_emu_sleep(ist);
2612 if (ist->st->sample_aspect_ratio.num)
2613 decoded_frame->sample_aspect_ratio = ist->st->sample_aspect_ratio;
2615 resample_changed = ist->resample_width != decoded_frame->width ||
2616 ist->resample_height != decoded_frame->height ||
2617 ist->resample_pix_fmt != decoded_frame->format;
2618 if (resample_changed) {
2619 av_log(NULL, AV_LOG_INFO,
2620 "Input stream #%d:%d frame changed from size:%dx%d fmt:%s to size:%dx%d fmt:%s\n",
2621 ist->file_index, ist->st->index,
2622 ist->resample_width, ist->resample_height, av_get_pix_fmt_name(ist->resample_pix_fmt),
2623 decoded_frame->width, decoded_frame->height, av_get_pix_fmt_name(decoded_frame->format));
2625 ist->resample_width = decoded_frame->width;
2626 ist->resample_height = decoded_frame->height;
2627 ist->resample_pix_fmt = decoded_frame->format;
2629 for (i = 0; i < nb_filtergraphs; i++)
2630 if (ist_in_filtergraph(filtergraphs[i], ist) &&
2631 configure_filtergraph(filtergraphs[i]) < 0) {
2632 av_log(NULL, AV_LOG_FATAL, "Error reinitializing filters!\n");
2637 frame_sample_aspect= av_opt_ptr(avcodec_get_frame_class(), decoded_frame, "sample_aspect_ratio");
2638 for (i = 0; i < ist->nb_filters; i++) {
2639 int changed = ist->st->codec->width != ist->filters[i]->filter->outputs[0]->w
2640 || ist->st->codec->height != ist->filters[i]->filter->outputs[0]->h
2641 || ist->st->codec->pix_fmt != ist->filters[i]->filter->outputs[0]->format;
2642 // XXX what an ugly hack
2643 if (ist->filters[i]->graph->nb_outputs == 1)
2644 ist->filters[i]->graph->outputs[0]->ost->last_quality = quality;
2646 if (!frame_sample_aspect->num)
2647 *frame_sample_aspect = ist->st->sample_aspect_ratio;
2648 if (ist->dr1 && decoded_frame->type==FF_BUFFER_TYPE_USER && !changed) {
2649 FrameBuffer *buf = decoded_frame->opaque;
2650 AVFilterBufferRef *fb = avfilter_get_video_buffer_ref_from_arrays(
2651 decoded_frame->data, decoded_frame->linesize,
2652 AV_PERM_READ | AV_PERM_PRESERVE,
2653 ist->st->codec->width, ist->st->codec->height,
2654 ist->st->codec->pix_fmt);
2656 avfilter_copy_frame_props(fb, decoded_frame);
2657 fb->buf->priv = buf;
2658 fb->buf->free = filter_release_buffer;
2660 av_assert0(buf->refcount>0);
2662 av_buffersrc_buffer(ist->filters[i]->filter, fb);
2664 if(av_vsrc_buffer_add_frame(ist->filters[i]->filter, decoded_frame,AV_VSRC_BUF_FLAG_OVERWRITE)<0) {
2665 av_log(NULL, AV_LOG_FATAL, "Failed to inject frame into filter network\n");
2671 av_free(buffer_to_free);
2675 static int transcode_subtitles(InputStream *ist, AVPacket *pkt, int *got_output)
2677 AVSubtitle subtitle;
2678 int i, ret = avcodec_decode_subtitle2(ist->st->codec,
2679 &subtitle, got_output, pkt);
2685 rate_emu_sleep(ist);
2687 for (i = 0; i < nb_output_streams; i++) {
2688 OutputStream *ost = output_streams[i];
2690 if (!check_output_constraints(ist, ost) || !ost->encoding_needed)
2693 do_subtitle_out(output_files[ost->file_index]->ctx, ost, ist, &subtitle, pkt->pts);
2696 avsubtitle_free(&subtitle);
2700 /* pkt = NULL means EOF (needed to flush decoder buffers) */
2701 static int output_packet(InputStream *ist, const AVPacket *pkt)
2705 int64_t pkt_pts = AV_NOPTS_VALUE;
2708 if (!ist->saw_first_ts) {
2709 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;
2711 if (pkt != NULL && pkt->pts != AV_NOPTS_VALUE && !ist->decoding_needed) {
2712 ist->dts += av_rescale_q(pkt->pts, ist->st->time_base, AV_TIME_BASE_Q);
2713 ist->pts = ist->dts; //unused but better to set it to a value thats not totally wrong
2715 ist->saw_first_ts = 1;
2718 if (ist->next_dts == AV_NOPTS_VALUE)
2719 ist->next_dts = ist->dts;
2720 if (ist->next_pts == AV_NOPTS_VALUE)
2721 ist->next_pts = ist->pts;
2725 av_init_packet(&avpkt);
2733 if (pkt->dts != AV_NOPTS_VALUE) {
2734 ist->next_dts = ist->dts = av_rescale_q(pkt->dts, ist->st->time_base, AV_TIME_BASE_Q);
2735 if (ist->st->codec->codec_type != AVMEDIA_TYPE_VIDEO || !ist->decoding_needed)
2736 ist->next_pts = ist->pts = av_rescale_q(pkt->dts, ist->st->time_base, AV_TIME_BASE_Q);
2738 if(pkt->pts != AV_NOPTS_VALUE)
2739 pkt_pts = av_rescale_q(pkt->pts, ist->st->time_base, AV_TIME_BASE_Q);
2741 // while we have more to decode or while the decoder did output something on EOF
2742 while (ist->decoding_needed && (avpkt.size > 0 || (!pkt && got_output))) {
2746 ist->pts = ist->next_pts;
2747 ist->dts = ist->next_dts;
2749 if (avpkt.size && avpkt.size != pkt->size) {
2750 av_log(NULL, ist->showed_multi_packet_warning ? AV_LOG_VERBOSE : AV_LOG_WARNING,
2751 "Multiple frames in a packet from stream %d\n", pkt->stream_index);
2752 ist->showed_multi_packet_warning = 1;
2755 switch (ist->st->codec->codec_type) {
2756 case AVMEDIA_TYPE_AUDIO:
2757 ret = transcode_audio (ist, &avpkt, &got_output);
2759 case AVMEDIA_TYPE_VIDEO:
2760 ret = transcode_video (ist, &avpkt, &got_output, &pkt_pts);
2761 if (avpkt.duration) {
2762 duration = av_rescale_q(avpkt.duration, ist->st->time_base, AV_TIME_BASE_Q);
2763 } else if(ist->st->codec->time_base.num != 0 && ist->st->codec->time_base.den != 0) {
2764 int ticks= ist->st->parser ? ist->st->parser->repeat_pict+1 : ist->st->codec->ticks_per_frame;
2765 duration = ((int64_t)AV_TIME_BASE *
2766 ist->st->codec->time_base.num * ticks) /
2767 ist->st->codec->time_base.den;
2771 if(ist->dts != AV_NOPTS_VALUE && duration) {
2772 ist->next_dts += duration;
2774 ist->next_dts = AV_NOPTS_VALUE;
2777 ist->next_pts += duration; //FIXME the duration is not correct in some cases
2779 case AVMEDIA_TYPE_SUBTITLE:
2780 ret = transcode_subtitles(ist, &avpkt, &got_output);
2790 avpkt.pts= AV_NOPTS_VALUE;
2792 // touch data and size only if not EOF
2794 if(ist->st->codec->codec_type != AVMEDIA_TYPE_AUDIO)
2804 /* handle stream copy */
2805 if (!ist->decoding_needed) {
2806 rate_emu_sleep(ist);
2807 ist->dts = ist->next_dts;
2808 switch (ist->st->codec->codec_type) {
2809 case AVMEDIA_TYPE_AUDIO:
2810 ist->next_dts += ((int64_t)AV_TIME_BASE * ist->st->codec->frame_size) /
2811 ist->st->codec->sample_rate;
2813 case AVMEDIA_TYPE_VIDEO:
2814 if (pkt->duration) {
2815 ist->next_dts += av_rescale_q(pkt->duration, ist->st->time_base, AV_TIME_BASE_Q);
2816 } else if(ist->st->codec->time_base.num != 0) {
2817 int ticks= ist->st->parser ? ist->st->parser->repeat_pict + 1 : ist->st->codec->ticks_per_frame;
2818 ist->next_dts += ((int64_t)AV_TIME_BASE *
2819 ist->st->codec->time_base.num * ticks) /
2820 ist->st->codec->time_base.den;
2824 ist->pts = ist->dts;
2825 ist->next_pts = ist->next_dts;
2827 for (i = 0; pkt && i < nb_output_streams; i++) {
2828 OutputStream *ost = output_streams[i];
2830 if (!check_output_constraints(ist, ost) || ost->encoding_needed)
2833 do_streamcopy(ist, ost, pkt);
2839 static void print_sdp(void)
2843 AVFormatContext **avc = av_malloc(sizeof(*avc) * nb_output_files);
2847 for (i = 0; i < nb_output_files; i++)
2848 avc[i] = output_files[i]->ctx;
2850 av_sdp_create(avc, nb_output_files, sdp, sizeof(sdp));
2851 printf("SDP:\n%s\n", sdp);
2856 static int init_input_stream(int ist_index, char *error, int error_len)
2859 InputStream *ist = input_streams[ist_index];
2861 if (ist->decoding_needed) {
2862 AVCodec *codec = ist->dec;
2864 snprintf(error, error_len, "Decoder (codec %s) not found for input stream #%d:%d",
2865 avcodec_get_name(ist->st->codec->codec_id), ist->file_index, ist->st->index);
2866 return AVERROR(EINVAL);
2869 ist->dr1 = codec->capabilities & CODEC_CAP_DR1;
2870 if (codec->type == AVMEDIA_TYPE_VIDEO && ist->dr1) {
2871 ist->st->codec->get_buffer = codec_get_buffer;
2872 ist->st->codec->release_buffer = codec_release_buffer;
2873 ist->st->codec->opaque = ist;
2876 if (!av_dict_get(ist->opts, "threads", NULL, 0))
2877 av_dict_set(&ist->opts, "threads", "auto", 0);
2878 if (avcodec_open2(ist->st->codec, codec, &ist->opts) < 0) {
2879 snprintf(error, error_len, "Error while opening decoder for input stream #%d:%d",
2880 ist->file_index, ist->st->index);
2881 return AVERROR(EINVAL);
2883 assert_codec_experimental(ist->st->codec, 0);
2884 assert_avoptions(ist->opts);
2886 if (ist->st->codec->codec_type == AVMEDIA_TYPE_AUDIO) {
2887 for (i = 0; i < nb_output_streams; i++) {
2888 OutputStream *ost = output_streams[i];
2889 if (ost->source_index == ist_index) {
2890 if (!ist->st->codec->channel_layout || !ost->st->codec->channel_layout)
2891 get_default_channel_layouts(ost, ist);
2898 ist->next_pts = AV_NOPTS_VALUE;
2899 ist->next_dts = AV_NOPTS_VALUE;
2905 static InputStream *get_input_stream(OutputStream *ost)
2907 if (ost->source_index >= 0)
2908 return input_streams[ost->source_index];
2911 FilterGraph *fg = ost->filter->graph;
2914 for (i = 0; i < fg->nb_inputs; i++)
2915 if (fg->inputs[i]->ist->st->codec->codec_type == ost->st->codec->codec_type)
2916 return fg->inputs[i]->ist;
2922 static int transcode_init(void)
2924 int ret = 0, i, j, k;
2925 AVFormatContext *oc;
2926 AVCodecContext *codec, *icodec;
2932 /* init framerate emulation */
2933 for (i = 0; i < nb_input_files; i++) {
2934 InputFile *ifile = input_files[i];
2935 if (ifile->rate_emu)
2936 for (j = 0; j < ifile->nb_streams; j++)
2937 input_streams[j + ifile->ist_index]->start = av_gettime();
2940 /* output stream init */
2941 for (i = 0; i < nb_output_files; i++) {
2942 oc = output_files[i]->ctx;
2943 if (!oc->nb_streams && !(oc->oformat->flags & AVFMT_NOSTREAMS)) {
2944 av_dump_format(oc, i, oc->filename, 1);
2945 av_log(NULL, AV_LOG_ERROR, "Output file #%d does not contain any stream\n", i);
2946 return AVERROR(EINVAL);
2950 /* init complex filtergraphs */
2951 for (i = 0; i < nb_filtergraphs; i++)
2952 if ((ret = avfilter_graph_config(filtergraphs[i]->graph, NULL)) < 0)
2955 /* for each output stream, we compute the right encoding parameters */
2956 for (i = 0; i < nb_output_streams; i++) {
2957 ost = output_streams[i];
2958 oc = output_files[ost->file_index]->ctx;
2959 ist = get_input_stream(ost);
2961 if (ost->attachment_filename)
2964 codec = ost->st->codec;
2967 icodec = ist->st->codec;
2969 ost->st->disposition = ist->st->disposition;
2970 codec->bits_per_raw_sample = icodec->bits_per_raw_sample;
2971 codec->chroma_sample_location = icodec->chroma_sample_location;
2974 if (ost->stream_copy) {
2975 uint64_t extra_size;
2977 av_assert0(ist && !ost->filter);
2979 extra_size = (uint64_t)icodec->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE;
2981 if (extra_size > INT_MAX) {
2982 return AVERROR(EINVAL);
2985 /* if stream_copy is selected, no need to decode or encode */
2986 codec->codec_id = icodec->codec_id;
2987 codec->codec_type = icodec->codec_type;
2989 if (!codec->codec_tag) {
2990 if (!oc->oformat->codec_tag ||
2991 av_codec_get_id (oc->oformat->codec_tag, icodec->codec_tag) == codec->codec_id ||
2992 av_codec_get_tag(oc->oformat->codec_tag, icodec->codec_id) <= 0)
2993 codec->codec_tag = icodec->codec_tag;
2996 codec->bit_rate = icodec->bit_rate;
2997 codec->rc_max_rate = icodec->rc_max_rate;
2998 codec->rc_buffer_size = icodec->rc_buffer_size;
2999 codec->field_order = icodec->field_order;
3000 codec->extradata = av_mallocz(extra_size);
3001 if (!codec->extradata) {
3002 return AVERROR(ENOMEM);
3004 memcpy(codec->extradata, icodec->extradata, icodec->extradata_size);
3005 codec->extradata_size= icodec->extradata_size;
3007 codec->time_base = ist->st->time_base;
3009 * Avi is a special case here because it supports variable fps but
3010 * having the fps and timebase differe significantly adds quite some
3013 if(!strcmp(oc->oformat->name, "avi")) {
3014 if ( copy_tb<0 && av_q2d(icodec->time_base)*icodec->ticks_per_frame > 2*av_q2d(ist->st->time_base)
3015 && av_q2d(ist->st->time_base) < 1.0/500
3017 codec->time_base = icodec->time_base;
3018 codec->time_base.num *= icodec->ticks_per_frame;
3019 codec->time_base.den *= 2;
3020 codec->ticks_per_frame = 2;
3022 } else if(!(oc->oformat->flags & AVFMT_VARIABLE_FPS)
3023 && strcmp(oc->oformat->name, "mov") && strcmp(oc->oformat->name, "mp4") && strcmp(oc->oformat->name, "3gp")
3024 && strcmp(oc->oformat->name, "3g2") && strcmp(oc->oformat->name, "psp") && strcmp(oc->oformat->name, "ipod")
3026 if( copy_tb<0 && av_q2d(icodec->time_base)*icodec->ticks_per_frame > av_q2d(ist->st->time_base)
3027 && av_q2d(ist->st->time_base) < 1.0/500
3029 codec->time_base = icodec->time_base;
3030 codec->time_base.num *= icodec->ticks_per_frame;
3033 av_reduce(&codec->time_base.num, &codec->time_base.den,
3034 codec->time_base.num, codec->time_base.den, INT_MAX);
3036 switch (codec->codec_type) {
3037 case AVMEDIA_TYPE_AUDIO:
3038 if (audio_volume != 256) {
3039 av_log(NULL, AV_LOG_FATAL, "-acodec copy and -vol are incompatible (frames are not decoded)\n");
3042 codec->channel_layout = icodec->channel_layout;
3043 codec->sample_rate = icodec->sample_rate;
3044 codec->channels = icodec->channels;
3045 codec->frame_size = icodec->frame_size;
3046 codec->audio_service_type = icodec->audio_service_type;
3047 codec->block_align = icodec->block_align;
3049 case AVMEDIA_TYPE_VIDEO:
3050 codec->pix_fmt = icodec->pix_fmt;
3051 codec->width = icodec->width;
3052 codec->height = icodec->height;
3053 codec->has_b_frames = icodec->has_b_frames;
3054 if (!codec->sample_aspect_ratio.num) {
3055 codec->sample_aspect_ratio =
3056 ost->st->sample_aspect_ratio =
3057 ist->st->sample_aspect_ratio.num ? ist->st->sample_aspect_ratio :
3058 ist->st->codec->sample_aspect_ratio.num ?
3059 ist->st->codec->sample_aspect_ratio : (AVRational){0, 1};
3061 ost->st->avg_frame_rate = ist->st->avg_frame_rate;
3063 case AVMEDIA_TYPE_SUBTITLE:
3064 codec->width = icodec->width;
3065 codec->height = icodec->height;
3067 case AVMEDIA_TYPE_DATA:
3068 case AVMEDIA_TYPE_ATTACHMENT:
3075 ost->enc = avcodec_find_encoder(codec->codec_id);
3077 /* should only happen when a default codec is not present. */
3078 snprintf(error, sizeof(error), "Encoder (codec %s) not found for output stream #%d:%d",
3079 avcodec_get_name(ost->st->codec->codec_id), ost->file_index, ost->index);
3080 ret = AVERROR(EINVAL);
3085 ist->decoding_needed = 1;
3086 ost->encoding_needed = 1;
3088 switch (codec->codec_type) {
3089 case AVMEDIA_TYPE_AUDIO:
3090 ost->fifo = av_fifo_alloc(1024);
3092 return AVERROR(ENOMEM);
3095 if (!codec->sample_rate)
3096 codec->sample_rate = icodec->sample_rate;
3097 choose_sample_rate(ost->st, ost->enc);
3098 codec->time_base = (AVRational){ 1, codec->sample_rate };
3100 if (codec->sample_fmt == AV_SAMPLE_FMT_NONE)
3101 codec->sample_fmt = icodec->sample_fmt;
3102 choose_sample_fmt(ost->st, ost->enc);
3104 if (ost->audio_channels_mapped) {
3105 /* the requested output channel is set to the number of
3106 * -map_channel only if no -ac are specified */
3107 if (!codec->channels) {
3108 codec->channels = ost->audio_channels_mapped;
3109 codec->channel_layout = av_get_default_channel_layout(codec->channels);
3110 if (!codec->channel_layout) {
3111 av_log(NULL, AV_LOG_FATAL, "Unable to find an appropriate channel layout for requested number of channel\n");
3115 /* fill unused channel mapping with -1 (which means a muted
3116 * channel in case the number of output channels is bigger
3117 * than the number of mapped channel) */
3118 for (j = ost->audio_channels_mapped; j < FF_ARRAY_ELEMS(ost->audio_channels_map); j++)
3119 ost->audio_channels_map[j] = -1;
3120 } else if (!codec->channels) {
3121 codec->channels = icodec->channels;
3122 codec->channel_layout = icodec->channel_layout;
3124 if (av_get_channel_layout_nb_channels(codec->channel_layout) != codec->channels)
3125 codec->channel_layout = 0;
3128 // ost->audio_resample = codec->sample_rate != icodec->sample_rate || audio_sync_method > 1;
3129 // ost->audio_resample |= codec->sample_fmt != icodec->sample_fmt
3130 // || codec->channel_layout != icodec->channel_layout;
3131 icodec->request_channels = codec-> channels;
3132 ost->resample_sample_fmt = icodec->sample_fmt;
3133 ost->resample_sample_rate = icodec->sample_rate;
3134 ost->resample_channels = icodec->channels;
3135 ost->resample_channel_layout = icodec->channel_layout;
3137 case AVMEDIA_TYPE_VIDEO:
3140 fg = init_simple_filtergraph(ist, ost);
3141 if (configure_video_filters(fg)) {
3142 av_log(NULL, AV_LOG_FATAL, "Error opening filters!\n");
3147 if (ist && !ost->frame_rate.num)
3148 ost->frame_rate = ist->st->r_frame_rate.num ? ist->st->r_frame_rate : (AVRational) { 25, 1 };
3149 if (ost->enc && ost->enc->supported_framerates && !ost->force_fps) {
3150 int idx = av_find_nearest_q_idx(ost->frame_rate, ost->enc->supported_framerates);
3151 ost->frame_rate = ost->enc->supported_framerates[idx];
3153 codec->time_base = (AVRational){ost->frame_rate.den, ost->frame_rate.num};
3154 if ( av_q2d(codec->time_base) < 0.001 && video_sync_method != VSYNC_PASSTHROUGH
3155 && (video_sync_method == VSYNC_CFR || (video_sync_method == VSYNC_AUTO && !(oc->oformat->flags & AVFMT_VARIABLE_FPS)))){
3156 av_log(oc, AV_LOG_WARNING, "Frame rate very high for a muxer not efficiently supporting it.\n"
3157 "Please consider specifying a lower framerate, a different muxer or -vsync 2\n");
3159 for (j = 0; j < ost->forced_kf_count; j++)
3160 ost->forced_kf_pts[j] = av_rescale_q(ost->forced_kf_pts[j],
3164 codec->width = ost->filter->filter->inputs[0]->w;
3165 codec->height = ost->filter->filter->inputs[0]->h;
3166 codec->sample_aspect_ratio = ost->st->sample_aspect_ratio =
3167 ost->frame_aspect_ratio ? // overridden by the -aspect cli option
3168 av_d2q(ost->frame_aspect_ratio * codec->height/codec->width, 255) :
3169 ost->filter->filter->inputs[0]->sample_aspect_ratio;
3170 codec->pix_fmt = ost->filter->filter->inputs[0]->format;
3172 if (codec->width != icodec->width ||
3173 codec->height != icodec->height ||
3174 codec->pix_fmt != icodec->pix_fmt) {
3175 codec->bits_per_raw_sample = frame_bits_per_raw_sample;
3179 case AVMEDIA_TYPE_SUBTITLE:
3180 codec->time_base = (AVRational){1, 1000};
3187 if (codec->flags & (CODEC_FLAG_PASS1 | CODEC_FLAG_PASS2)) {
3188 char logfilename[1024];
3191 snprintf(logfilename, sizeof(logfilename), "%s-%d.log",
3192 pass_logfilename_prefix ? pass_logfilename_prefix : DEFAULT_PASS_LOGFILENAME_PREFIX,
3194 if (!strcmp(ost->enc->name, "libx264")) {
3195 av_dict_set(&ost->opts, "stats", logfilename, AV_DICT_DONT_OVERWRITE);
3197 if (codec->flags & CODEC_FLAG_PASS2) {
3199 size_t logbuffer_size;
3200 if (cmdutils_read_file(logfilename, &logbuffer, &logbuffer_size) < 0) {
3201 av_log(NULL, AV_LOG_FATAL, "Error reading log file '%s' for pass-2 encoding\n",
3205 codec->stats_in = logbuffer;
3207 if (codec->flags & CODEC_FLAG_PASS1) {
3208 f = fopen(logfilename, "wb");
3210 av_log(NULL, AV_LOG_FATAL, "Cannot write log file '%s' for pass-1 encoding: %s\n",
3211 logfilename, strerror(errno));
3221 /* open each encoder */
3222 for (i = 0; i < nb_output_streams; i++) {
3223 ost = output_streams[i];
3224 if (ost->encoding_needed) {
3225 AVCodec *codec = ost->enc;
3226 AVCodecContext *dec = NULL;
3228 if ((ist = get_input_stream(ost)))
3229 dec = ist->st->codec;
3230 if (dec && dec->subtitle_header) {
3231 ost->st->codec->subtitle_header = av_malloc(dec->subtitle_header_size);
3232 if (!ost->st->codec->subtitle_header) {
3233 ret = AVERROR(ENOMEM);
3236 memcpy(ost->st->codec->subtitle_header, dec->subtitle_header, dec->subtitle_header_size);
3237 ost->st->codec->subtitle_header_size = dec->subtitle_header_size;
3239 if (!av_dict_get(ost->opts, "threads", NULL, 0))
3240 av_dict_set(&ost->opts, "threads", "auto", 0);
3241 if (avcodec_open2(ost->st->codec, codec, &ost->opts) < 0) {
3242 snprintf(error, sizeof(error), "Error while opening encoder for output stream #%d:%d - maybe incorrect parameters such as bit_rate, rate, width or height",
3243 ost->file_index, ost->index);
3244 ret = AVERROR(EINVAL);
3247 assert_codec_experimental(ost->st->codec, 1);
3248 assert_avoptions(ost->opts);
3249 if (ost->st->codec->bit_rate && ost->st->codec->bit_rate < 1000)
3250 av_log(NULL, AV_LOG_WARNING, "The bitrate parameter is set too low."
3251 " It takes bits/s as argument, not kbits/s\n");
3252 extra_size += ost->st->codec->extradata_size;
3254 if (ost->st->codec->me_threshold)
3255 input_streams[ost->source_index]->st->codec->debug |= FF_DEBUG_MV;
3259 /* init input streams */
3260 for (i = 0; i < nb_input_streams; i++)
3261 if ((ret = init_input_stream(i, error, sizeof(error))) < 0)
3264 /* discard unused programs */
3265 for (i = 0; i < nb_input_files; i++) {
3266 InputFile *ifile = input_files[i];
3267 for (j = 0; j < ifile->ctx->nb_programs; j++) {
3268 AVProgram *p = ifile->ctx->programs[j];
3269 int discard = AVDISCARD_ALL;
3271 for (k = 0; k < p->nb_stream_indexes; k++)
3272 if (!input_streams[ifile->ist_index + p->stream_index[k]]->discard) {
3273 discard = AVDISCARD_DEFAULT;
3276 p->discard = discard;
3280 /* open files and write file headers */
3281 for (i = 0; i < nb_output_files; i++) {
3282 oc = output_files[i]->ctx;
3283 oc->interrupt_callback = int_cb;
3284 if (avformat_write_header(oc, &output_files[i]->opts) < 0) {
3285 snprintf(error, sizeof(error), "Could not write header for output file #%d (incorrect codec parameters ?)", i);
3286 ret = AVERROR(EINVAL);
3289 // assert_avoptions(output_files[i]->opts);
3290 if (strcmp(oc->oformat->name, "rtp")) {
3296 /* dump the file output parameters - cannot be done before in case
3298 for (i = 0; i < nb_output_files; i++) {
3299 av_dump_format(output_files[i]->ctx, i, output_files[i]->ctx->filename, 1);
3302 /* dump the stream mapping */
3303 av_log(NULL, AV_LOG_INFO, "Stream mapping:\n");
3304 for (i = 0; i < nb_input_streams; i++) {
3305 ist = input_streams[i];
3307 for (j = 0; j < ist->nb_filters; j++) {
3308 AVFilterLink *link = ist->filters[j]->filter->outputs[0];
3309 if (ist->filters[j]->graph->graph_desc) {
3310 av_log(NULL, AV_LOG_INFO, " Stream #%d:%d (%s) -> %s",
3311 ist->file_index, ist->st->index, ist->dec ? ist->dec->name : "?",
3312 link->dst->filter->name);
3313 if (link->dst->input_count > 1)
3314 av_log(NULL, AV_LOG_INFO, ":%s", link->dstpad->name);
3315 if (nb_filtergraphs > 1)
3316 av_log(NULL, AV_LOG_INFO, " (graph %d)", ist->filters[j]->graph->index);
3317 av_log(NULL, AV_LOG_INFO, "\n");
3322 for (i = 0; i < nb_output_streams; i++) {
3323 ost = output_streams[i];
3325 if (ost->attachment_filename) {
3326 /* an attached file */
3327 av_log(NULL, AV_LOG_INFO, " File %s -> Stream #%d:%d\n",
3328 ost->attachment_filename, ost->file_index, ost->index);
3332 if (ost->filter && ost->filter->graph->graph_desc) {
3333 /* output from a complex graph */
3334 AVFilterLink *link = ost->filter->filter->inputs[0];
3335 av_log(NULL, AV_LOG_INFO, " %s", link->src->filter->name);
3336 if (link->src->output_count > 1)
3337 av_log(NULL, AV_LOG_INFO, ":%s", link->srcpad->name);
3338 if (nb_filtergraphs > 1)
3339 av_log(NULL, AV_LOG_INFO, " (graph %d)", ost->filter->graph->index);
3341 av_log(NULL, AV_LOG_INFO, " -> Stream #%d:%d (%s)\n", ost->file_index,
3342 ost->index, ost->enc ? ost->enc->name : "?");
3346 av_log(NULL, AV_LOG_INFO, " Stream #%d:%d -> #%d:%d",
3347 input_streams[ost->source_index]->file_index,
3348 input_streams[ost->source_index]->st->index,
3351 if (ost->audio_channels_mapped) {
3352 av_log(NULL, AV_LOG_INFO, " [ch:");
3353 for (j = 0; j < ost->audio_channels_mapped; j++)
3354 if (ost->audio_channels_map[j] == -1)
3355 av_log(NULL, AV_LOG_INFO, " M");
3357 av_log(NULL, AV_LOG_INFO, " %d", ost->audio_channels_map[j]);
3358 av_log(NULL, AV_LOG_INFO, "]");
3360 if (ost->sync_ist != input_streams[ost->source_index])
3361 av_log(NULL, AV_LOG_INFO, " [sync #%d:%d]",
3362 ost->sync_ist->file_index,
3363 ost->sync_ist->st->index);
3364 if (ost->stream_copy)
3365 av_log(NULL, AV_LOG_INFO, " (copy)");
3367 av_log(NULL, AV_LOG_INFO, " (%s -> %s)", input_streams[ost->source_index]->dec ?
3368 input_streams[ost->source_index]->dec->name : "?",
3369 ost->enc ? ost->enc->name : "?");
3370 av_log(NULL, AV_LOG_INFO, "\n");
3374 av_log(NULL, AV_LOG_ERROR, "%s\n", error);
3386 * The following code is the main loop of the file converter
3388 static int transcode(void)
3391 AVFormatContext *is, *os;
3395 int no_packet_count = 0;
3396 int64_t timer_start;
3399 if (!(no_packet = av_mallocz(nb_input_files)))
3402 ret = transcode_init();
3407 av_log(NULL, AV_LOG_INFO, "Press [q] to stop, [?] for help\n");
3410 timer_start = av_gettime();
3412 for (; received_sigterm == 0;) {
3413 int file_index, ist_index, past_recording_time = 1;
3416 int64_t cur_time= av_gettime();
3418 ipts_min = INT64_MAX;
3419 /* if 'q' pressed, exits */
3421 static int64_t last_time;
3422 if (received_nb_signals)
3424 /* read_key() returns 0 on EOF */
3425 if(cur_time - last_time >= 100000 && !run_as_daemon){
3427 last_time = cur_time;
3432 if (key == '+') av_log_set_level(av_log_get_level()+10);
3433 if (key == '-') av_log_set_level(av_log_get_level()-10);
3434 if (key == 's') qp_hist ^= 1;
3437 do_hex_dump = do_pkt_dump = 0;
3438 } else if(do_pkt_dump){
3442 av_log_set_level(AV_LOG_DEBUG);
3444 if (key == 'c' || key == 'C'){
3445 char buf[4096], target[64], command[256], arg[256] = {0};
3448 fprintf(stderr, "\nEnter command: <target> <time> <command>[ <argument>]\n");
3450 while ((k = read_key()) != '\n' && k != '\r' && i < sizeof(buf)-1)
3455 (n = sscanf(buf, "%63[^ ] %lf %255[^ ] %255[^\n]", target, &time, command, arg)) >= 3) {
3456 av_log(NULL, AV_LOG_DEBUG, "Processing command target:%s time:%f command:%s arg:%s",
3457 target, time, command, arg);
3458 for (i = 0; i < nb_filtergraphs; i++) {
3459 FilterGraph *fg = filtergraphs[i];
3462 ret = avfilter_graph_send_command(fg->graph, target, command, arg, buf, sizeof(buf),
3463 key == 'c' ? AVFILTER_CMD_FLAG_ONE : 0);
3464 fprintf(stderr, "Command reply for stream %d: ret:%d res:%s\n", i, ret, buf);
3466 ret = avfilter_graph_queue_command(fg->graph, target, command, arg, 0, time);
3471 av_log(NULL, AV_LOG_ERROR,
3472 "Parse error, at least 3 arguments were expected, "
3473 "only %d given in string '%s'\n", n, buf);
3476 if (key == 'd' || key == 'D'){
3479 debug = input_streams[0]->st->codec->debug<<1;
3480 if(!debug) debug = 1;
3481 while(debug & (FF_DEBUG_DCT_COEFF|FF_DEBUG_VIS_QP|FF_DEBUG_VIS_MB_TYPE)) //unsupported, would just crash
3484 if(scanf("%d", &debug)!=1)
3485 fprintf(stderr,"error parsing debug value\n");
3486 for(i=0;i<nb_input_streams;i++) {
3487 input_streams[i]->st->codec->debug = debug;
3489 for(i=0;i<nb_output_streams;i++) {
3490 ost = output_streams[i];
3491 ost->st->codec->debug = debug;
3493 if(debug) av_log_set_level(AV_LOG_DEBUG);
3494 fprintf(stderr,"debug=%d\n", debug);
3497 fprintf(stderr, "key function\n"
3498 "? show this help\n"
3499 "+ increase verbosity\n"
3500 "- decrease verbosity\n"
3501 "c Send command to filtergraph\n"
3502 "D cycle through available debug modes\n"
3503 "h dump packets/hex press to cycle through the 3 states\n"
3505 "s Show QP histogram\n"
3510 /* check if there's any stream where output is still needed */
3511 for (i = 0; i < nb_output_streams; i++) {
3513 ost = output_streams[i];
3514 of = output_files[ost->file_index];
3515 os = output_files[ost->file_index]->ctx;
3516 if (ost->is_past_recording_time ||
3517 (os->pb && avio_tell(os->pb) >= of->limit_filesize))
3519 if (ost->frame_number >= ost->max_frames) {
3521 for (j = 0; j < of->ctx->nb_streams; j++)
3522 output_streams[of->ost_index + j]->is_past_recording_time = 1;
3525 past_recording_time = 0;
3527 if (past_recording_time)
3530 /* select the stream that we must read now by looking at the
3531 smallest output pts */
3533 for (i = 0; i < nb_input_streams; i++) {
3535 ist = input_streams[i];
3537 if (ist->discard || no_packet[ist->file_index])
3539 if (!input_files[ist->file_index]->eof_reached) {
3540 if (ipts < ipts_min) {
3542 file_index = ist->file_index;
3546 /* if none, if is finished */
3547 if (file_index < 0) {
3548 if (no_packet_count) {
3549 no_packet_count = 0;
3550 memset(no_packet, 0, nb_input_files);
3557 /* read a frame from it and output it in the fifo */
3558 is = input_files[file_index]->ctx;
3559 ret = av_read_frame(is, &pkt);
3560 if (ret == AVERROR(EAGAIN)) {
3561 no_packet[file_index] = 1;
3566 input_files[file_index]->eof_reached = 1;
3568 for (i = 0; i < input_files[file_index]->nb_streams; i++) {
3569 ist = input_streams[input_files[file_index]->ist_index + i];
3570 if (ist->decoding_needed)
3571 output_packet(ist, NULL);
3580 no_packet_count = 0;
3581 memset(no_packet, 0, nb_input_files);
3584 av_pkt_dump_log2(NULL, AV_LOG_DEBUG, &pkt, do_hex_dump,
3585 is->streams[pkt.stream_index]);
3587 /* the following test is needed in case new streams appear
3588 dynamically in stream : we ignore them */
3589 if (pkt.stream_index >= input_files[file_index]->nb_streams)
3590 goto discard_packet;
3591 ist_index = input_files[file_index]->ist_index + pkt.stream_index;
3592 ist = input_streams[ist_index];
3594 goto discard_packet;
3596 if (pkt.dts != AV_NOPTS_VALUE)
3597 pkt.dts += av_rescale_q(input_files[ist->file_index]->ts_offset, AV_TIME_BASE_Q, ist->st->time_base);
3598 if (pkt.pts != AV_NOPTS_VALUE)
3599 pkt.pts += av_rescale_q(input_files[ist->file_index]->ts_offset, AV_TIME_BASE_Q, ist->st->time_base);
3601 if (pkt.pts != AV_NOPTS_VALUE)
3602 pkt.pts *= ist->ts_scale;
3603 if (pkt.dts != AV_NOPTS_VALUE)
3604 pkt.dts *= ist->ts_scale;
3607 av_log(NULL, AV_LOG_INFO, "demuxer -> ist_index:%d type:%s "
3608 "next_pts:%s next_pts_time:%s pkt_pts:%s pkt_pts_time:%s pkt_dts:%s pkt_dts_time:%s off:%"PRId64"\n",
3609 ist_index, av_get_media_type_string(ist->st->codec->codec_type),
3610 av_ts2str(ist->next_pts), av_ts2timestr(ist->next_pts, &ist->st->time_base),
3611 av_ts2str(pkt.pts), av_ts2timestr(pkt.pts, &ist->st->time_base),
3612 av_ts2str(pkt.dts), av_ts2timestr(pkt.dts, &ist->st->time_base),
3613 input_files[ist->file_index]->ts_offset);
3616 if (pkt.dts != AV_NOPTS_VALUE && ist->next_dts != AV_NOPTS_VALUE && !copy_ts) {
3617 int64_t pkt_dts = av_rescale_q(pkt.dts, ist->st->time_base, AV_TIME_BASE_Q);
3618 int64_t delta = pkt_dts - ist->next_dts;
3619 if (is->iformat->flags & AVFMT_TS_DISCONT) {
3620 if(delta < -1LL*dts_delta_threshold*AV_TIME_BASE ||
3621 (delta > 1LL*dts_delta_threshold*AV_TIME_BASE &&
3622 ist->st->codec->codec_type != AVMEDIA_TYPE_SUBTITLE) ||
3623 pkt_dts+1<ist->pts){
3624 input_files[ist->file_index]->ts_offset -= delta;
3625 av_log(NULL, AV_LOG_DEBUG,
3626 "timestamp discontinuity %"PRId64", new offset= %"PRId64"\n",
3627 delta, input_files[ist->file_index]->ts_offset);
3628 pkt.dts-= av_rescale_q(delta, AV_TIME_BASE_Q, ist->st->time_base);
3629 if (pkt.pts != AV_NOPTS_VALUE)
3630 pkt.pts-= av_rescale_q(delta, AV_TIME_BASE_Q, ist->st->time_base);
3633 if ( delta < -1LL*dts_error_threshold*AV_TIME_BASE ||
3634 (delta > 1LL*dts_error_threshold*AV_TIME_BASE && ist->st->codec->codec_type != AVMEDIA_TYPE_SUBTITLE) ||
3635 pkt_dts+1<ist->pts){
3636 av_log(NULL, AV_LOG_WARNING, "DTS %"PRId64", next:%"PRId64" st:%d invalid dropping\n", pkt.dts, ist->next_dts, pkt.stream_index);
3637 pkt.dts = AV_NOPTS_VALUE;
3639 if (pkt.pts != AV_NOPTS_VALUE){
3640 int64_t pkt_pts = av_rescale_q(pkt.pts, ist->st->time_base, AV_TIME_BASE_Q);
3641 delta = pkt_pts - ist->next_dts;
3642 if ( delta < -1LL*dts_error_threshold*AV_TIME_BASE ||
3643 (delta > 1LL*dts_error_threshold*AV_TIME_BASE && ist->st->codec->codec_type != AVMEDIA_TYPE_SUBTITLE) ||
3644 pkt_pts+1<ist->pts) {
3645 av_log(NULL, AV_LOG_WARNING, "PTS %"PRId64", next:%"PRId64" invalid dropping st:%d\n", pkt.pts, ist->next_dts, pkt.stream_index);
3646 pkt.pts = AV_NOPTS_VALUE;
3652 // fprintf(stderr,"read #%d.%d size=%d\n", ist->file_index, ist->st->index, pkt.size);
3653 if (output_packet(ist, &pkt) < 0 ||
3654 ((ret = poll_filters()) < 0 && ret != AVERROR_EOF)) {
3655 av_log(NULL, AV_LOG_ERROR, "Error while decoding stream #%d:%d\n",
3656 ist->file_index, ist->st->index);
3659 av_free_packet(&pkt);
3664 av_free_packet(&pkt);
3666 /* dump report by using the output first video and audio streams */
3667 print_report(0, timer_start, cur_time);
3670 /* at the end of stream, we must flush the decoder buffers */
3671 for (i = 0; i < nb_input_streams; i++) {
3672 ist = input_streams[i];
3673 if (!input_files[ist->file_index]->eof_reached && ist->decoding_needed) {
3674 output_packet(ist, NULL);
3682 /* write the trailer if needed and close file */
3683 for (i = 0; i < nb_output_files; i++) {
3684 os = output_files[i]->ctx;
3685 av_write_trailer(os);
3688 /* dump report by using the first video and audio streams */
3689 print_report(1, timer_start, av_gettime());
3691 /* close each encoder */
3692 for (i = 0; i < nb_output_streams; i++) {
3693 ost = output_streams[i];
3694 if (ost->encoding_needed) {
3695 av_freep(&ost->st->codec->stats_in);
3696 avcodec_close(ost->st->codec);
3700 /* close each decoder */
3701 for (i = 0; i < nb_input_streams; i++) {
3702 ist = input_streams[i];
3703 if (ist->decoding_needed) {
3704 avcodec_close(ist->st->codec);
3712 av_freep(&no_packet);
3714 if (output_streams) {
3715 for (i = 0; i < nb_output_streams; i++) {
3716 ost = output_streams[i];
3718 if (ost->stream_copy)
3719 av_freep(&ost->st->codec->extradata);
3721 fclose(ost->logfile);
3722 ost->logfile = NULL;
3724 av_fifo_free(ost->fifo); /* works even if fifo is not
3725 initialized but set to zero */
3726 av_freep(&ost->st->codec->subtitle_header);
3727 av_free(ost->forced_kf_pts);
3728 swr_free(&ost->swr);
3729 av_dict_free(&ost->opts);
3736 static int opt_frame_crop(const char *opt, const char *arg)
3738 av_log(NULL, AV_LOG_FATAL, "Option '%s' has been removed, use the crop filter instead\n", opt);
3739 return AVERROR(EINVAL);
3742 static int opt_pad(const char *opt, const char *arg)
3744 av_log(NULL, AV_LOG_FATAL, "Option '%s' has been removed, use the pad filter instead\n", opt);
3748 static int opt_video_channel(const char *opt, const char *arg)
3750 av_log(NULL, AV_LOG_WARNING, "This option is deprecated, use -channel.\n");
3751 return opt_default("channel", arg);
3754 static int opt_video_standard(const char *opt, const char *arg)
3756 av_log(NULL, AV_LOG_WARNING, "This option is deprecated, use -standard.\n");
3757 return opt_default("standard", arg);
3760 static int opt_audio_codec(OptionsContext *o, const char *opt, const char *arg)
3762 audio_codec_name = arg;
3763 return parse_option(o, "codec:a", arg, options);
3766 static int opt_video_codec(OptionsContext *o, const char *opt, const char *arg)
3768 video_codec_name = arg;
3769 return parse_option(o, "codec:v", arg, options);
3772 static int opt_subtitle_codec(OptionsContext *o, const char *opt, const char *arg)
3774 subtitle_codec_name = arg;
3775 return parse_option(o, "codec:s", arg, options);
3778 static int opt_data_codec(OptionsContext *o, const char *opt, const char *arg)
3780 return parse_option(o, "codec:d", arg, options);
3783 static int opt_map(OptionsContext *o, const char *opt, const char *arg)
3785 StreamMap *m = NULL;
3786 int i, negative = 0, file_idx;
3787 int sync_file_idx = -1, sync_stream_idx = 0;
3795 map = av_strdup(arg);
3797 /* parse sync stream first, just pick first matching stream */
3798 if (sync = strchr(map, ',')) {
3800 sync_file_idx = strtol(sync + 1, &sync, 0);
3801 if (sync_file_idx >= nb_input_files || sync_file_idx < 0) {
3802 av_log(NULL, AV_LOG_FATAL, "Invalid sync file index: %d.\n", sync_file_idx);
3807 for (i = 0; i < input_files[sync_file_idx]->nb_streams; i++)
3808 if (check_stream_specifier(input_files[sync_file_idx]->ctx,
3809 input_files[sync_file_idx]->ctx->streams[i], sync) == 1) {
3810 sync_stream_idx = i;
3813 if (i == input_files[sync_file_idx]->nb_streams) {
3814 av_log(NULL, AV_LOG_FATAL, "Sync stream specification in map %s does not "
3815 "match any streams.\n", arg);
3821 if (map[0] == '[') {
3822 /* this mapping refers to lavfi output */
3823 const char *c = map + 1;
3824 o->stream_maps = grow_array(o->stream_maps, sizeof(*o->stream_maps),
3825 &o->nb_stream_maps, o->nb_stream_maps + 1);
3826 m = &o->stream_maps[o->nb_stream_maps - 1];
3827 m->linklabel = av_get_token(&c, "]");
3828 if (!m->linklabel) {
3829 av_log(NULL, AV_LOG_ERROR, "Invalid output link label: %s.\n", map);
3833 file_idx = strtol(map, &p, 0);
3834 if (file_idx >= nb_input_files || file_idx < 0) {
3835 av_log(NULL, AV_LOG_FATAL, "Invalid input file index: %d.\n", file_idx);
3839 /* disable some already defined maps */
3840 for (i = 0; i < o->nb_stream_maps; i++) {
3841 m = &o->stream_maps[i];
3842 if (file_idx == m->file_index &&
3843 check_stream_specifier(input_files[m->file_index]->ctx,
3844 input_files[m->file_index]->ctx->streams[m->stream_index],
3845 *p == ':' ? p + 1 : p) > 0)
3849 for (i = 0; i < input_files[file_idx]->nb_streams; i++) {
3850 if (check_stream_specifier(input_files[file_idx]->ctx, input_files[file_idx]->ctx->streams[i],
3851 *p == ':' ? p + 1 : p) <= 0)
3853 o->stream_maps = grow_array(o->stream_maps, sizeof(*o->stream_maps),
3854 &o->nb_stream_maps, o->nb_stream_maps + 1);
3855 m = &o->stream_maps[o->nb_stream_maps - 1];
3857 m->file_index = file_idx;
3858 m->stream_index = i;
3860 if (sync_file_idx >= 0) {
3861 m->sync_file_index = sync_file_idx;
3862 m->sync_stream_index = sync_stream_idx;
3864 m->sync_file_index = file_idx;
3865 m->sync_stream_index = i;
3871 av_log(NULL, AV_LOG_FATAL, "Stream map '%s' matches no streams.\n", arg);
3879 static int opt_attach(OptionsContext *o, const char *opt, const char *arg)
3881 o->attachments = grow_array(o->attachments, sizeof(*o->attachments),
3882 &o->nb_attachments, o->nb_attachments + 1);
3883 o->attachments[o->nb_attachments - 1] = arg;
3887 static int opt_map_channel(OptionsContext *o, const char *opt, const char *arg)
3893 o->audio_channel_maps =
3894 grow_array(o->audio_channel_maps, sizeof(*o->audio_channel_maps),
3895 &o->nb_audio_channel_maps, o->nb_audio_channel_maps + 1);
3896 m = &o->audio_channel_maps[o->nb_audio_channel_maps - 1];
3898 /* muted channel syntax */
3899 n = sscanf(arg, "%d:%d.%d", &m->channel_idx, &m->ofile_idx, &m->ostream_idx);
3900 if ((n == 1 || n == 3) && m->channel_idx == -1) {
3901 m->file_idx = m->stream_idx = -1;
3903 m->ofile_idx = m->ostream_idx = -1;
3908 n = sscanf(arg, "%d.%d.%d:%d.%d",
3909 &m->file_idx, &m->stream_idx, &m->channel_idx,
3910 &m->ofile_idx, &m->ostream_idx);
3912 if (n != 3 && n != 5) {
3913 av_log(NULL, AV_LOG_FATAL, "Syntax error, mapchan usage: "
3914 "[file.stream.channel|-1][:syncfile:syncstream]\n");
3918 if (n != 5) // only file.stream.channel specified
3919 m->ofile_idx = m->ostream_idx = -1;