2 * Copyright (c) 2000-2003 Fabrice Bellard
4 * This file is part of FFmpeg.
6 * FFmpeg is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License as published by the Free Software Foundation; either
9 * version 2.1 of the License, or (at your option) any later version.
11 * FFmpeg is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
16 * You should have received a copy of the GNU Lesser General Public
17 * License along with FFmpeg; if not, write to the Free Software
18 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
23 * multimedia converter based on the FFmpeg libraries
35 #include "libavformat/avformat.h"
36 #include "libavdevice/avdevice.h"
37 #include "libswscale/swscale.h"
38 #include "libavutil/opt.h"
39 #include "libavcodec/audioconvert.h"
40 #include "libavutil/audioconvert.h"
41 #include "libavutil/parseutils.h"
42 #include "libavutil/samplefmt.h"
43 #include "libavutil/colorspace.h"
44 #include "libavutil/fifo.h"
45 #include "libavutil/intreadwrite.h"
46 #include "libavutil/dict.h"
47 #include "libavutil/mathematics.h"
48 #include "libavutil/pixdesc.h"
49 #include "libavutil/avstring.h"
50 #include "libavutil/libm.h"
51 #include "libavutil/imgutils.h"
52 #include "libavutil/timestamp.h"
53 #include "libavformat/os_support.h"
54 #include "libswresample/swresample.h"
56 #include "libavformat/ffm.h" // not public API
58 # include "libavfilter/avcodec.h"
59 # include "libavfilter/avfilter.h"
60 # include "libavfilter/avfiltergraph.h"
61 # include "libavfilter/buffersink.h"
62 # include "libavfilter/buffersrc.h"
63 # include "libavfilter/vsrc_buffer.h"
65 #if HAVE_SYS_RESOURCE_H
66 #include <sys/types.h>
68 #include <sys/resource.h>
69 #elif HAVE_GETPROCESSTIMES
72 #if HAVE_GETPROCESSMEMORYINFO
78 #include <sys/select.h>
83 #include <sys/ioctl.h>
93 #include "libavutil/avassert.h"
96 #define VSYNC_PASSTHROUGH 0
99 #define VSYNC_DROP 0xff
101 const char program_name[] = "ffmpeg";
102 const int program_birth_year = 2000;
104 /* select an input stream for an output stream */
105 typedef struct StreamMap {
106 int disabled; /** 1 is this mapping is disabled by a negative map */
110 int sync_stream_index;
111 char *linklabel; /** name of an output link, for mapping lavfi outputs */
115 int file_idx, stream_idx, channel_idx; // input
116 int ofile_idx, ostream_idx; // output
119 static const OptionDef options[];
121 #define MAX_STREAMS 1024 /* arbitrary sanity check value */
123 static int frame_bits_per_raw_sample = 0;
124 static int video_discard = 0;
125 static int same_quant = 0;
126 static int do_deinterlace = 0;
127 static int intra_dc_precision = 8;
128 static int qp_hist = 0;
129 static int intra_only = 0;
130 static const char *video_codec_name = NULL;
131 static const char *audio_codec_name = NULL;
132 static const char *subtitle_codec_name = NULL;
134 static int file_overwrite = 0;
135 static int no_file_overwrite = 0;
136 static int do_benchmark = 0;
137 static int do_benchmark_all = 0;
138 static int do_hex_dump = 0;
139 static int do_pkt_dump = 0;
140 static int do_psnr = 0;
141 static int do_pass = 0;
142 static const char *pass_logfilename_prefix;
143 static int video_sync_method = VSYNC_AUTO;
144 static int audio_sync_method = 0;
145 static float audio_drift_threshold = 0.1;
146 static int copy_ts = 0;
147 static int copy_tb = -1;
148 static int opt_shortest = 0;
149 static char *vstats_filename;
150 static FILE *vstats_file;
152 static int audio_volume = 256;
154 static int exit_on_error = 0;
155 static int using_stdin = 0;
156 static int run_as_daemon = 0;
157 static volatile int received_nb_signals = 0;
158 static int64_t video_size = 0;
159 static int64_t audio_size = 0;
160 static int64_t extra_size = 0;
161 static int nb_frames_dup = 0;
162 static int nb_frames_drop = 0;
163 static int input_sync;
165 static float dts_delta_threshold = 10;
166 static float dts_error_threshold = 3600*30;
168 static int print_stats = 1;
169 static int debug_ts = 0;
170 static int current_time;
172 static uint8_t *audio_buf;
173 static unsigned int allocated_audio_buf_size;
174 static uint8_t *async_buf;
175 static unsigned int allocated_async_buf_size;
177 #define DEFAULT_PASS_LOGFILENAME_PREFIX "ffmpeg2pass"
179 typedef struct InputFilter {
180 AVFilterContext *filter;
181 struct InputStream *ist;
182 struct FilterGraph *graph;
185 typedef struct OutputFilter {
186 AVFilterContext *filter;
187 struct OutputStream *ost;
188 struct FilterGraph *graph;
190 /* temporary storage until stream maps are processed */
191 AVFilterInOut *out_tmp;
194 typedef struct FilterGraph {
196 const char *graph_desc;
198 AVFilterGraph *graph;
200 InputFilter **inputs;
202 OutputFilter **outputs;
206 typedef struct FrameBuffer {
212 enum PixelFormat pix_fmt;
215 struct InputStream *ist;
216 struct FrameBuffer *next;
219 typedef struct InputStream {
222 int discard; /* true if stream data should be discarded */
223 int decoding_needed; /* true if the packets must be decoded in 'raw_fifo' */
225 AVFrame *decoded_frame;
227 int64_t start; /* time when read started */
228 /* predicted dts of the next packet read for this stream or (when there are
229 * several frames in a packet) of the next frame in current packet */
231 /* dts of the last packet read for this stream */
234 int64_t next_pts; ///< synthetic pts for the next decode frame
235 int64_t pts; ///< current pts of the decoded frame
237 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 int resample_sample_rate;
303 float rematrix_volume;
304 AVFifoBuffer *fifo; /* for compression: one audio fifo per codec */
309 OutputFilter *filter;
313 int64_t swr_dither_method;
314 double swr_dither_scale;
316 int is_past_recording_time;
318 const char *attachment_filename;
319 int copy_initial_nonkeyframes;
321 enum PixelFormat pix_fmts[2];
327 /* init terminal so that we can grab keys */
328 static struct termios oldtty;
329 static int restore_tty;
332 typedef struct OutputFile {
333 AVFormatContext *ctx;
335 int ost_index; /* index of the first stream in output_streams */
336 int64_t recording_time; /* desired length of the resulting file in microseconds */
337 int64_t start_time; /* start time in microseconds */
338 uint64_t limit_filesize; /* filesize limit expressed in bytes */
341 static InputStream **input_streams = NULL;
342 static int nb_input_streams = 0;
343 static InputFile **input_files = NULL;
344 static int nb_input_files = 0;
346 static OutputStream **output_streams = NULL;
347 static int nb_output_streams = 0;
348 static OutputFile **output_files = NULL;
349 static int nb_output_files = 0;
351 static FilterGraph **filtergraphs;
354 typedef struct OptionsContext {
355 /* input/output options */
359 SpecifierOpt *codec_names;
361 SpecifierOpt *audio_channels;
362 int nb_audio_channels;
363 SpecifierOpt *audio_sample_rate;
364 int nb_audio_sample_rate;
365 SpecifierOpt *rematrix_volume;
366 int nb_rematrix_volume;
367 SpecifierOpt *frame_rates;
369 SpecifierOpt *frame_sizes;
371 SpecifierOpt *frame_pix_fmts;
372 int nb_frame_pix_fmts;
375 int64_t input_ts_offset;
378 SpecifierOpt *ts_scale;
380 SpecifierOpt *dump_attachment;
381 int nb_dump_attachment;
384 StreamMap *stream_maps;
386 AudioChannelMap *audio_channel_maps; ///< one info entry per -map_channel
387 int nb_audio_channel_maps; ///< number of (valid) -map_channel settings
388 int metadata_global_manual;
389 int metadata_streams_manual;
390 int metadata_chapters_manual;
391 const char **attachments;
394 int chapters_input_file;
396 int64_t recording_time;
397 uint64_t limit_filesize;
403 int subtitle_disable;
406 /* indexed by output file stream index */
410 SpecifierOpt *metadata;
412 SpecifierOpt *max_frames;
414 SpecifierOpt *bitstream_filters;
415 int nb_bitstream_filters;
416 SpecifierOpt *codec_tags;
418 SpecifierOpt *sample_fmts;
420 SpecifierOpt *qscale;
422 SpecifierOpt *forced_key_frames;
423 int nb_forced_key_frames;
424 SpecifierOpt *force_fps;
426 SpecifierOpt *frame_aspect_ratios;
427 int nb_frame_aspect_ratios;
428 SpecifierOpt *rc_overrides;
430 SpecifierOpt *intra_matrices;
431 int nb_intra_matrices;
432 SpecifierOpt *inter_matrices;
433 int nb_inter_matrices;
434 SpecifierOpt *top_field_first;
435 int nb_top_field_first;
436 SpecifierOpt *metadata_map;
438 SpecifierOpt *presets;
440 SpecifierOpt *copy_initial_nonkeyframes;
441 int nb_copy_initial_nonkeyframes;
442 SpecifierOpt *filters;
446 #define MATCH_PER_STREAM_OPT(name, type, outvar, fmtctx, st)\
449 for (i = 0; i < o->nb_ ## name; i++) {\
450 char *spec = o->name[i].specifier;\
451 if ((ret = check_stream_specifier(fmtctx, st, spec)) > 0)\
452 outvar = o->name[i].u.type;\
458 static int64_t getutime(void)
461 struct rusage rusage;
463 getrusage(RUSAGE_SELF, &rusage);
464 return (rusage.ru_utime.tv_sec * 1000000LL) + rusage.ru_utime.tv_usec;
465 #elif HAVE_GETPROCESSTIMES
468 proc = GetCurrentProcess();
469 GetProcessTimes(proc, &c, &e, &k, &u);
470 return ((int64_t) u.dwHighDateTime << 32 | u.dwLowDateTime) / 10;
476 static void update_benchmark(const char *fmt, ...)
478 if (do_benchmark_all) {
479 int64_t t = getutime();
485 vsnprintf(buf, sizeof(buf), fmt, va);
487 printf("bench: %8"PRIu64" %s \n", t - current_time, buf);
493 static void reset_options(OptionsContext *o, int is_input)
495 const OptionDef *po = options;
496 OptionsContext bak= *o;
499 /* all OPT_SPEC and OPT_STRING can be freed in generic way */
501 void *dst = (uint8_t*)o + po->u.off;
503 if (po->flags & OPT_SPEC) {
504 SpecifierOpt **so = dst;
505 int i, *count = (int*)(so + 1);
506 for (i = 0; i < *count; i++) {
507 av_freep(&(*so)[i].specifier);
508 if (po->flags & OPT_STRING)
509 av_freep(&(*so)[i].u.str);
513 } else if (po->flags & OPT_OFFSET && po->flags & OPT_STRING)
518 for (i = 0; i < o->nb_stream_maps; i++)
519 av_freep(&o->stream_maps[i].linklabel);
520 av_freep(&o->stream_maps);
521 av_freep(&o->audio_channel_maps);
522 av_freep(&o->streamid_map);
524 memset(o, 0, sizeof(*o));
526 if(is_input) o->recording_time = bak.recording_time;
527 else o->recording_time = INT64_MAX;
528 o->mux_max_delay = 0.7;
529 o->limit_filesize = UINT64_MAX;
530 o->chapters_input_file = INT_MAX;
536 static int alloc_buffer(InputStream *ist, AVCodecContext *s, FrameBuffer **pbuf)
538 FrameBuffer *buf = av_mallocz(sizeof(*buf));
540 const int pixel_size = av_pix_fmt_descriptors[s->pix_fmt].comp[0].step_minus1+1;
541 int h_chroma_shift, v_chroma_shift;
542 int edge = 32; // XXX should be avcodec_get_edge_width(), but that fails on svq1
543 int w = s->width, h = s->height;
546 return AVERROR(ENOMEM);
548 if (!(s->flags & CODEC_FLAG_EMU_EDGE)) {
553 avcodec_align_dimensions(s, &w, &h);
554 if ((ret = av_image_alloc(buf->base, buf->linesize, w, h,
555 s->pix_fmt, 32)) < 0) {
559 /* XXX this shouldn't be needed, but some tests break without this line
560 * those decoders are buggy and need to be fixed.
561 * the following tests fail:
562 * cdgraphics, ansi, aasc, fraps-v1, qtrle-1bit
564 memset(buf->base[0], 128, ret);
566 avcodec_get_chroma_sub_sample(s->pix_fmt, &h_chroma_shift, &v_chroma_shift);
567 for (i = 0; i < FF_ARRAY_ELEMS(buf->data); i++) {
568 const int h_shift = i==0 ? 0 : h_chroma_shift;
569 const int v_shift = i==0 ? 0 : v_chroma_shift;
570 if ((s->flags & CODEC_FLAG_EMU_EDGE) || !buf->linesize[1])
571 buf->data[i] = buf->base[i];
573 buf->data[i] = buf->base[i] +
574 FFALIGN((buf->linesize[i]*edge >> v_shift) +
575 (pixel_size*edge >> h_shift), 32);
579 buf->pix_fmt = s->pix_fmt;
586 static void free_buffer_pool(InputStream *ist)
588 FrameBuffer *buf = ist->buffer_pool;
590 ist->buffer_pool = buf->next;
591 av_freep(&buf->base[0]);
593 buf = ist->buffer_pool;
597 static void unref_buffer(InputStream *ist, FrameBuffer *buf)
599 av_assert0(buf->refcount > 0);
601 if (!buf->refcount) {
603 for(tmp= ist->buffer_pool; tmp; tmp= tmp->next)
604 av_assert1(tmp != buf);
605 buf->next = ist->buffer_pool;
606 ist->buffer_pool = buf;
610 static int codec_get_buffer(AVCodecContext *s, AVFrame *frame)
612 InputStream *ist = s->opaque;
616 if(av_image_check_size(s->width, s->height, 0, s) || s->pix_fmt<0)
619 if (!ist->buffer_pool && (ret = alloc_buffer(ist, s, &ist->buffer_pool)) < 0)
622 buf = ist->buffer_pool;
623 ist->buffer_pool = buf->next;
625 if (buf->w != s->width || buf->h != s->height || buf->pix_fmt != s->pix_fmt) {
626 av_freep(&buf->base[0]);
628 if ((ret = alloc_buffer(ist, s, &buf)) < 0)
631 av_assert0(!buf->refcount);
635 frame->type = FF_BUFFER_TYPE_USER;
636 frame->extended_data = frame->data;
637 frame->pkt_pts = s->pkt ? s->pkt->pts : AV_NOPTS_VALUE;
638 frame->width = buf->w;
639 frame->height = buf->h;
640 frame->format = buf->pix_fmt;
641 frame->sample_aspect_ratio = s->sample_aspect_ratio;
643 for (i = 0; i < FF_ARRAY_ELEMS(buf->data); i++) {
644 frame->base[i] = buf->base[i]; // XXX h264.c uses base though it shouldn't
645 frame->data[i] = buf->data[i];
646 frame->linesize[i] = buf->linesize[i];
652 static void codec_release_buffer(AVCodecContext *s, AVFrame *frame)
654 InputStream *ist = s->opaque;
655 FrameBuffer *buf = frame->opaque;
658 if(frame->type!=FF_BUFFER_TYPE_USER)
659 return avcodec_default_release_buffer(s, frame);
661 for (i = 0; i < FF_ARRAY_ELEMS(frame->data); i++)
662 frame->data[i] = NULL;
664 unref_buffer(ist, buf);
667 static void filter_release_buffer(AVFilterBuffer *fb)
669 FrameBuffer *buf = fb->priv;
671 unref_buffer(buf->ist, buf);
674 static enum PixelFormat choose_pixel_fmt(AVStream *st, AVCodec *codec, enum PixelFormat target)
676 if (codec && codec->pix_fmts) {
677 const enum PixelFormat *p = codec->pix_fmts;
678 int has_alpha= av_pix_fmt_descriptors[target].nb_components % 2 == 0;
679 enum PixelFormat best= PIX_FMT_NONE;
680 if (st->codec->strict_std_compliance <= FF_COMPLIANCE_UNOFFICIAL) {
681 if (st->codec->codec_id == CODEC_ID_MJPEG) {
682 p = (const enum PixelFormat[]) { PIX_FMT_YUVJ420P, PIX_FMT_YUVJ422P, PIX_FMT_YUV420P, PIX_FMT_YUV422P, PIX_FMT_NONE };
683 } else if (st->codec->codec_id == CODEC_ID_LJPEG) {
684 p = (const enum PixelFormat[]) { PIX_FMT_YUVJ420P, PIX_FMT_YUVJ422P, PIX_FMT_YUVJ444P, PIX_FMT_YUV420P,
685 PIX_FMT_YUV422P, PIX_FMT_YUV444P, PIX_FMT_BGRA, PIX_FMT_NONE };
688 for (; *p != PIX_FMT_NONE; p++) {
689 best= avcodec_find_best_pix_fmt2(best, *p, target, has_alpha, NULL);
693 if (*p == PIX_FMT_NONE) {
694 if (target != PIX_FMT_NONE)
695 av_log(NULL, AV_LOG_WARNING,
696 "Incompatible pixel format '%s' for codec '%s', auto-selecting format '%s'\n",
697 av_pix_fmt_descriptors[target].name,
699 av_pix_fmt_descriptors[best].name);
706 static const enum PixelFormat *choose_pixel_fmts(OutputStream *ost)
708 if (ost->st->codec->pix_fmt != PIX_FMT_NONE) {
709 ost->pix_fmts[0] = choose_pixel_fmt(ost->st, ost->enc, ost->st->codec->pix_fmt);
710 return ost->pix_fmts;
711 } else if (ost->enc->pix_fmts) {
712 if (ost->st->codec->strict_std_compliance <= FF_COMPLIANCE_UNOFFICIAL) {
713 if (ost->st->codec->codec_id == CODEC_ID_MJPEG) {
714 return (const enum PixelFormat[]) { PIX_FMT_YUVJ420P, PIX_FMT_YUVJ422P, PIX_FMT_YUV420P, PIX_FMT_YUV422P, PIX_FMT_NONE };
715 } else if (ost->st->codec->codec_id == CODEC_ID_LJPEG) {
716 return (const enum PixelFormat[]) { PIX_FMT_YUVJ420P, PIX_FMT_YUVJ422P, PIX_FMT_YUVJ444P, PIX_FMT_YUV420P,
717 PIX_FMT_YUV422P, PIX_FMT_YUV444P, PIX_FMT_BGRA, PIX_FMT_NONE };
720 return ost->enc->pix_fmts;
725 static int configure_video_filters(FilterGraph *fg)
727 InputStream *ist = fg->inputs[0]->ist;
728 OutputStream *ost = fg->outputs[0]->ost;
729 AVFilterContext *last_filter, *filter;
730 /** filter graph containing all filters including input & output */
731 AVCodecContext *codec = ost->st->codec;
732 enum PixelFormat *pix_fmts = choose_pixel_fmts(ost);
733 AVBufferSinkParams *buffersink_params = av_buffersink_params_alloc();
734 AVRational sample_aspect_ratio;
738 avfilter_graph_free(&fg->graph);
739 fg->graph = avfilter_graph_alloc();
741 return AVERROR(ENOMEM);
743 if (ist->st->sample_aspect_ratio.num) {
744 sample_aspect_ratio = ist->st->sample_aspect_ratio;
746 sample_aspect_ratio = ist->st->codec->sample_aspect_ratio;
748 snprintf(args, 255, "%d:%d:%d:%d:%d:%d:%d:flags=%d", ist->st->codec->width,
749 ist->st->codec->height, ist->st->codec->pix_fmt, 1, AV_TIME_BASE,
750 sample_aspect_ratio.num, sample_aspect_ratio.den, SWS_BILINEAR + ((ist->st->codec->flags&CODEC_FLAG_BITEXACT) ? SWS_BITEXACT:0));
752 ret = avfilter_graph_create_filter(&fg->inputs[0]->filter,
753 avfilter_get_by_name("buffer"),
754 "src", args, NULL, fg->graph);
758 #if FF_API_OLD_VSINK_API
759 ret = avfilter_graph_create_filter(&fg->outputs[0]->filter, avfilter_get_by_name("buffersink"),
760 "out", NULL, pix_fmts, fg->graph);
762 buffersink_params->pixel_fmts = pix_fmts;
763 ret = avfilter_graph_create_filter(&fg->outputs[0]->filter, avfilter_get_by_name("buffersink"),
764 "out", NULL, buffersink_params, fg->graph);
766 av_freep(&buffersink_params);
770 last_filter = fg->inputs[0]->filter;
772 if (codec->width || codec->height) {
773 snprintf(args, 255, "%d:%d:flags=0x%X",
776 (unsigned)ost->sws_flags);
777 if ((ret = avfilter_graph_create_filter(&filter, avfilter_get_by_name("scale"),
778 NULL, args, NULL, fg->graph)) < 0)
780 if ((ret = avfilter_link(last_filter, 0, filter, 0)) < 0)
782 last_filter = filter;
785 snprintf(args, sizeof(args), "flags=0x%X", (unsigned)ost->sws_flags);
786 fg->graph->scale_sws_opts = av_strdup(args);
789 AVFilterInOut *outputs = avfilter_inout_alloc();
790 AVFilterInOut *inputs = avfilter_inout_alloc();
792 outputs->name = av_strdup("in");
793 outputs->filter_ctx = last_filter;
794 outputs->pad_idx = 0;
795 outputs->next = NULL;
797 inputs->name = av_strdup("out");
798 inputs->filter_ctx = fg->outputs[0]->filter;
802 if ((ret = avfilter_graph_parse(fg->graph, ost->avfilter, &inputs, &outputs, NULL)) < 0)
804 av_freep(&ost->avfilter);
806 if ((ret = avfilter_link(last_filter, 0, fg->outputs[0]->filter, 0)) < 0)
810 if ((ret = avfilter_graph_config(fg->graph, NULL)) < 0)
813 ost->filter = fg->outputs[0];
818 static FilterGraph *init_simple_filtergraph(InputStream *ist, OutputStream *ost)
820 FilterGraph *fg = av_mallocz(sizeof(*fg));
824 fg->index = nb_filtergraphs;
826 fg->outputs = grow_array(fg->outputs, sizeof(*fg->outputs), &fg->nb_outputs,
828 if (!(fg->outputs[0] = av_mallocz(sizeof(*fg->outputs[0]))))
830 fg->outputs[0]->ost = ost;
831 fg->outputs[0]->graph = fg;
833 fg->inputs = grow_array(fg->inputs, sizeof(*fg->inputs), &fg->nb_inputs,
835 if (!(fg->inputs[0] = av_mallocz(sizeof(*fg->inputs[0]))))
837 fg->inputs[0]->ist = ist;
838 fg->inputs[0]->graph = fg;
840 ist->filters = grow_array(ist->filters, sizeof(*ist->filters),
841 &ist->nb_filters, ist->nb_filters + 1);
842 ist->filters[ist->nb_filters - 1] = fg->inputs[0];
844 filtergraphs = grow_array(filtergraphs, sizeof(*filtergraphs),
845 &nb_filtergraphs, nb_filtergraphs + 1);
846 filtergraphs[nb_filtergraphs - 1] = fg;
851 static void init_input_filter(FilterGraph *fg, AVFilterInOut *in)
854 enum AVMediaType type = in->filter_ctx->input_pads[in->pad_idx].type;
857 // TODO: support other filter types
858 if (type != AVMEDIA_TYPE_VIDEO) {
859 av_log(NULL, AV_LOG_FATAL, "Only video filters supported currently.\n");
867 int file_idx = strtol(in->name, &p, 0);
869 if (file_idx < 0 || file_idx >= nb_input_files) {
870 av_log(NULL, AV_LOG_FATAL, "Invalid file index %d in filtergraph description %s.\n",
871 file_idx, fg->graph_desc);
874 s = input_files[file_idx]->ctx;
876 for (i = 0; i < s->nb_streams; i++) {
877 if (s->streams[i]->codec->codec_type != type)
879 if (check_stream_specifier(s, s->streams[i], *p == ':' ? p + 1 : p) == 1) {
885 av_log(NULL, AV_LOG_FATAL, "Stream specifier '%s' in filtergraph description %s "
886 "matches no streams.\n", p, fg->graph_desc);
889 ist = input_streams[input_files[file_idx]->ist_index + st->index];
891 /* find the first unused stream of corresponding type */
892 for (i = 0; i < nb_input_streams; i++) {
893 ist = input_streams[i];
894 if (ist->st->codec->codec_type == type && ist->discard)
897 if (i == nb_input_streams) {
898 av_log(NULL, AV_LOG_FATAL, "Cannot find a matching stream for "
899 "unlabeled input pad %d on filter %s", in->pad_idx,
900 in->filter_ctx->name);
905 ist->decoding_needed = 1;
906 ist->st->discard = AVDISCARD_NONE;
908 fg->inputs = grow_array(fg->inputs, sizeof(*fg->inputs),
909 &fg->nb_inputs, fg->nb_inputs + 1);
910 if (!(fg->inputs[fg->nb_inputs - 1] = av_mallocz(sizeof(*fg->inputs[0]))))
912 fg->inputs[fg->nb_inputs - 1]->ist = ist;
913 fg->inputs[fg->nb_inputs - 1]->graph = fg;
915 ist->filters = grow_array(ist->filters, sizeof(*ist->filters),
916 &ist->nb_filters, ist->nb_filters + 1);
917 ist->filters[ist->nb_filters - 1] = fg->inputs[fg->nb_inputs - 1];
920 static int configure_output_filter(FilterGraph *fg, OutputFilter *ofilter, AVFilterInOut *out)
922 AVCodecContext *codec = ofilter->ost->st->codec;
923 AVFilterContext *last_filter = out->filter_ctx;
924 int pad_idx = out->pad_idx;
926 enum PixelFormat *pix_fmts = choose_pixel_fmts(ofilter->ost);
927 AVBufferSinkParams *buffersink_params = av_buffersink_params_alloc();
929 #if FF_API_OLD_VSINK_API
930 ret = avfilter_graph_create_filter(&ofilter->filter, avfilter_get_by_name("buffersink"),
931 "out", NULL, pix_fmts, fg->graph);
933 buffersink_params->pixel_fmts = pix_fmts;
934 ret = avfilter_graph_create_filter(&ofilter->filter, avfilter_get_by_name("buffersink"),
935 "out", NULL, buffersink_params, fg->graph);
937 av_freep(&buffersink_params);
942 if (codec->width || codec->height) {
944 snprintf(args, sizeof(args), "%d:%d:flags=0x%X",
947 (unsigned)ofilter->ost->sws_flags);
948 if ((ret = avfilter_graph_create_filter(&last_filter, avfilter_get_by_name("scale"),
949 NULL, args, NULL, fg->graph)) < 0)
951 if ((ret = avfilter_link(out->filter_ctx, out->pad_idx, last_filter, 0)) < 0)
956 if ((ret = avfilter_link(last_filter, pad_idx, ofilter->filter, 0)) < 0)
962 static int configure_complex_filter(FilterGraph *fg)
964 AVFilterInOut *inputs, *outputs, *cur;
965 int ret, i, init = !fg->graph;
967 avfilter_graph_free(&fg->graph);
968 if (!(fg->graph = avfilter_graph_alloc()))
969 return AVERROR(ENOMEM);
971 if ((ret = avfilter_graph_parse2(fg->graph, fg->graph_desc, &inputs, &outputs)) < 0)
974 for (cur = inputs; init && cur; cur = cur->next)
975 init_input_filter(fg, cur);
977 for (cur = inputs, i = 0; cur; cur = cur->next, i++) {
978 InputFilter *ifilter = fg->inputs[i];
979 InputStream *ist = ifilter->ist;
983 sar = ist->st->sample_aspect_ratio.num ? ist->st->sample_aspect_ratio :
984 ist->st->codec->sample_aspect_ratio;
985 snprintf(args, sizeof(args), "%d:%d:%d:%d:%d:%d:%d", ist->st->codec->width,
986 ist->st->codec->height, ist->st->codec->pix_fmt, 1, AV_TIME_BASE,
989 if ((ret = avfilter_graph_create_filter(&ifilter->filter,
990 avfilter_get_by_name("buffer"), cur->name,
991 args, NULL, fg->graph)) < 0)
993 if ((ret = avfilter_link(ifilter->filter, 0,
994 cur->filter_ctx, cur->pad_idx)) < 0)
997 avfilter_inout_free(&inputs);
1000 /* we already know the mappings between lavfi outputs and output streams,
1001 * so we can finish the setup */
1002 for (cur = outputs, i = 0; cur; cur = cur->next, i++)
1003 configure_output_filter(fg, fg->outputs[i], cur);
1004 avfilter_inout_free(&outputs);
1006 if ((ret = avfilter_graph_config(fg->graph, NULL)) < 0)
1009 /* wait until output mappings are processed */
1010 for (cur = outputs; cur;) {
1011 fg->outputs = grow_array(fg->outputs, sizeof(*fg->outputs),
1012 &fg->nb_outputs, fg->nb_outputs + 1);
1013 if (!(fg->outputs[fg->nb_outputs - 1] = av_mallocz(sizeof(*fg->outputs[0]))))
1015 fg->outputs[fg->nb_outputs - 1]->graph = fg;
1016 fg->outputs[fg->nb_outputs - 1]->out_tmp = cur;
1018 fg->outputs[fg->nb_outputs - 1]->out_tmp->next = NULL;
1025 static int configure_complex_filters(void)
1029 for (i = 0; i < nb_filtergraphs; i++)
1030 if (!filtergraphs[i]->graph &&
1031 (ret = configure_complex_filter(filtergraphs[i])) < 0)
1036 static int configure_filtergraph(FilterGraph *fg)
1038 return fg->graph_desc ? configure_complex_filter(fg) : configure_video_filters(fg);
1041 static int ist_in_filtergraph(FilterGraph *fg, InputStream *ist)
1044 for (i = 0; i < fg->nb_inputs; i++)
1045 if (fg->inputs[i]->ist == ist)
1050 static void term_exit(void)
1052 av_log(NULL, AV_LOG_QUIET, "%s", "");
1055 tcsetattr (0, TCSANOW, &oldtty);
1059 static volatile int received_sigterm = 0;
1061 static void sigterm_handler(int sig)
1063 received_sigterm = sig;
1064 received_nb_signals++;
1066 if(received_nb_signals > 3)
1070 static void term_init(void)
1076 if (tcgetattr (0, &tty) == 0) {
1081 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
1082 |INLCR|IGNCR|ICRNL|IXON);
1083 tty.c_oflag |= OPOST;
1084 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
1085 tty.c_cflag &= ~(CSIZE|PARENB);
1088 tty.c_cc[VTIME] = 0;
1090 tcsetattr (0, TCSANOW, &tty);
1092 signal(SIGQUIT, sigterm_handler); /* Quit (POSIX). */
1095 avformat_network_deinit();
1097 signal(SIGINT , sigterm_handler); /* Interrupt (ANSI). */
1098 signal(SIGTERM, sigterm_handler); /* Termination (ANSI). */
1100 signal(SIGXCPU, sigterm_handler);
1104 /* read a key without blocking */
1105 static int read_key(void)
1117 n = select(1, &rfds, NULL, NULL, &tv);
1119 n = read(0, &ch, 1);
1126 # if HAVE_PEEKNAMEDPIPE
1128 static HANDLE input_handle;
1131 input_handle = GetStdHandle(STD_INPUT_HANDLE);
1132 is_pipe = !GetConsoleMode(input_handle, &dw);
1135 if (stdin->_cnt > 0) {
1140 /* When running under a GUI, you will end here. */
1141 if (!PeekNamedPipe(input_handle, NULL, 0, NULL, &nchars, NULL))
1158 static int decode_interrupt_cb(void *ctx)
1160 return received_nb_signals > 1;
1163 static const AVIOInterruptCB int_cb = { decode_interrupt_cb, NULL };
1165 void av_noreturn exit_program(int ret)
1169 for (i = 0; i < nb_filtergraphs; i++) {
1170 avfilter_graph_free(&filtergraphs[i]->graph);
1171 for (j = 0; j < filtergraphs[i]->nb_inputs; j++)
1172 av_freep(&filtergraphs[i]->inputs[j]);
1173 av_freep(&filtergraphs[i]->inputs);
1174 for (j = 0; j < filtergraphs[i]->nb_outputs; j++)
1175 av_freep(&filtergraphs[i]->outputs[j]);
1176 av_freep(&filtergraphs[i]->outputs);
1177 av_freep(&filtergraphs[i]);
1179 av_freep(&filtergraphs);
1182 for (i = 0; i < nb_output_files; i++) {
1183 AVFormatContext *s = output_files[i]->ctx;
1184 if (!(s->oformat->flags & AVFMT_NOFILE) && s->pb)
1186 avformat_free_context(s);
1187 av_dict_free(&output_files[i]->opts);
1188 av_freep(&output_files[i]);
1190 for (i = 0; i < nb_output_streams; i++) {
1191 AVBitStreamFilterContext *bsfc = output_streams[i]->bitstream_filters;
1193 AVBitStreamFilterContext *next = bsfc->next;
1194 av_bitstream_filter_close(bsfc);
1197 output_streams[i]->bitstream_filters = NULL;
1199 if (output_streams[i]->output_frame) {
1200 AVFrame *frame = output_streams[i]->output_frame;
1201 if (frame->extended_data != frame->data)
1202 av_freep(&frame->extended_data);
1205 av_freep(&output_streams[i]->filtered_frame);
1206 av_freep(&output_streams[i]);
1208 for (i = 0; i < nb_input_files; i++) {
1209 avformat_close_input(&input_files[i]->ctx);
1210 av_freep(&input_files[i]);
1212 for (i = 0; i < nb_input_streams; i++) {
1213 av_freep(&input_streams[i]->decoded_frame);
1214 av_dict_free(&input_streams[i]->opts);
1215 free_buffer_pool(input_streams[i]);
1216 av_freep(&input_streams[i]->filters);
1217 av_freep(&input_streams[i]);
1221 fclose(vstats_file);
1222 av_free(vstats_filename);
1224 av_freep(&input_streams);
1225 av_freep(&input_files);
1226 av_freep(&output_streams);
1227 av_freep(&output_files);
1230 av_freep(&audio_buf);
1231 allocated_audio_buf_size = 0;
1232 av_freep(&async_buf);
1233 allocated_async_buf_size = 0;
1236 avformat_network_deinit();
1238 if (received_sigterm) {
1239 av_log(NULL, AV_LOG_INFO, "Received signal %d: terminating.\n",
1240 (int) received_sigterm);
1244 exit(ret); /* not all OS-es handle main() return value */
1247 static void assert_avoptions(AVDictionary *m)
1249 AVDictionaryEntry *t;
1250 if ((t = av_dict_get(m, "", NULL, AV_DICT_IGNORE_SUFFIX))) {
1251 av_log(NULL, AV_LOG_FATAL, "Option %s not found.\n", t->key);
1256 static void assert_codec_experimental(AVCodecContext *c, int encoder)
1258 const char *codec_string = encoder ? "encoder" : "decoder";
1260 if (c->codec->capabilities & CODEC_CAP_EXPERIMENTAL &&
1261 c->strict_std_compliance > FF_COMPLIANCE_EXPERIMENTAL) {
1262 av_log(NULL, AV_LOG_FATAL, "%s '%s' is experimental and might produce bad "
1263 "results.\nAdd '-strict experimental' if you want to use it.\n",
1264 codec_string, c->codec->name);
1265 codec = encoder ? avcodec_find_encoder(c->codec->id) : avcodec_find_decoder(c->codec->id);
1266 if (!(codec->capabilities & CODEC_CAP_EXPERIMENTAL))
1267 av_log(NULL, AV_LOG_FATAL, "Or use the non experimental %s '%s'.\n",
1268 codec_string, codec->name);
1273 static void choose_sample_fmt(AVStream *st, AVCodec *codec)
1275 if (codec && codec->sample_fmts) {
1276 const enum AVSampleFormat *p = codec->sample_fmts;
1277 for (; *p != -1; p++) {
1278 if (*p == st->codec->sample_fmt)
1282 if((codec->capabilities & CODEC_CAP_LOSSLESS) && av_get_sample_fmt_name(st->codec->sample_fmt) > av_get_sample_fmt_name(codec->sample_fmts[0]))
1283 av_log(NULL, AV_LOG_ERROR, "Conversion will not be lossless.\n");
1284 if(av_get_sample_fmt_name(st->codec->sample_fmt))
1285 av_log(NULL, AV_LOG_WARNING,
1286 "Incompatible sample format '%s' for codec '%s', auto-selecting format '%s'\n",
1287 av_get_sample_fmt_name(st->codec->sample_fmt),
1289 av_get_sample_fmt_name(codec->sample_fmts[0]));
1290 st->codec->sample_fmt = codec->sample_fmts[0];
1295 static void choose_sample_rate(AVStream *st, AVCodec *codec)
1297 if (codec && codec->supported_samplerates) {
1298 const int *p = codec->supported_samplerates;
1300 int best_dist = INT_MAX;
1302 int dist = abs(st->codec->sample_rate - *p);
1303 if (dist < best_dist) {
1310 const int *sample_rates = codec->supported_samplerates;
1311 av_log(st->codec, AV_LOG_WARNING,
1312 "Requested sampling rate (%dHz) unsupported, using %dHz instead\n"
1313 "Available sampling rates for %s:",
1314 st->codec->sample_rate, best, codec->name);
1315 for (i = 0; sample_rates[i]; i++) {
1316 if (!sample_rates[i + 1]) av_log(st->codec, AV_LOG_WARNING, " and");
1317 else if (i) av_log(st->codec, AV_LOG_WARNING, ",");
1318 av_log(st->codec, AV_LOG_WARNING, " %d", sample_rates[i]);
1320 av_log(st->codec, AV_LOG_WARNING, ".\n");
1322 st->codec->sample_rate = best;
1327 get_sync_ipts(const OutputStream *ost, int64_t pts)
1329 OutputFile *of = output_files[ost->file_index];
1330 return (double)(pts - of->start_time) / AV_TIME_BASE;
1333 static void write_frame(AVFormatContext *s, AVPacket *pkt, OutputStream *ost)
1335 AVBitStreamFilterContext *bsfc = ost->bitstream_filters;
1336 AVCodecContext *avctx = ost->st->codec;
1339 if ((avctx->codec_type == AVMEDIA_TYPE_VIDEO && video_sync_method == VSYNC_DROP) ||
1340 (avctx->codec_type == AVMEDIA_TYPE_AUDIO && audio_sync_method < 0))
1341 pkt->pts = pkt->dts = AV_NOPTS_VALUE;
1344 * Audio encoders may split the packets -- #frames in != #packets out.
1345 * But there is no reordering, so we can limit the number of output packets
1346 * by simply dropping them here.
1347 * Counting encoded video frames needs to be done separately because of
1348 * reordering, see do_video_out()
1350 if (!(avctx->codec_type == AVMEDIA_TYPE_VIDEO && avctx->codec)) {
1351 if (ost->frame_number >= ost->max_frames) {
1352 av_free_packet(pkt);
1355 ost->frame_number++;
1359 AVPacket new_pkt = *pkt;
1360 int a = av_bitstream_filter_filter(bsfc, avctx, NULL,
1361 &new_pkt.data, &new_pkt.size,
1362 pkt->data, pkt->size,
1363 pkt->flags & AV_PKT_FLAG_KEY);
1365 av_free_packet(pkt);
1366 new_pkt.destruct = av_destruct_packet;
1368 av_log(NULL, AV_LOG_ERROR, "Failed to open bitstream filter %s for stream %d with codec %s",
1369 bsfc->filter->name, pkt->stream_index,
1370 avctx->codec ? avctx->codec->name : "copy");
1380 pkt->stream_index = ost->index;
1381 ret = av_interleaved_write_frame(s, pkt);
1383 print_error("av_interleaved_write_frame()", ret);
1388 static void get_default_channel_layouts(OutputStream *ost, InputStream *ist)
1390 char layout_name[256];
1391 AVCodecContext *enc = ost->st->codec;
1392 AVCodecContext *dec = ist->st->codec;
1394 if (dec->channel_layout &&
1395 av_get_channel_layout_nb_channels(dec->channel_layout) != dec->channels) {
1396 av_get_channel_layout_string(layout_name, sizeof(layout_name),
1397 dec->channels, dec->channel_layout);
1398 av_log(NULL, AV_LOG_ERROR, "New channel layout (%s) is invalid\n",
1400 dec->channel_layout = 0;
1402 if (!dec->channel_layout) {
1403 if (enc->channel_layout && dec->channels == enc->channels) {
1404 dec->channel_layout = enc->channel_layout;
1406 dec->channel_layout = av_get_default_channel_layout(dec->channels);
1408 if (!dec->channel_layout) {
1409 av_log(NULL, AV_LOG_FATAL, "Unable to find default channel "
1410 "layout for Input Stream #%d.%d\n", ist->file_index,
1415 av_get_channel_layout_string(layout_name, sizeof(layout_name),
1416 dec->channels, dec->channel_layout);
1417 av_log(NULL, AV_LOG_WARNING, "Guessed Channel Layout for Input Stream "
1418 "#%d.%d : %s\n", ist->file_index, ist->st->index, layout_name);
1420 if (!enc->channel_layout) {
1421 if (dec->channels == enc->channels) {
1422 enc->channel_layout = dec->channel_layout;
1425 enc->channel_layout = av_get_default_channel_layout(enc->channels);
1427 if (!enc->channel_layout) {
1428 av_log(NULL, AV_LOG_FATAL, "Unable to find default channel layout "
1429 "for Output Stream #%d.%d\n", ost->file_index,
1433 av_get_channel_layout_string(layout_name, sizeof(layout_name),
1434 enc->channels, enc->channel_layout);
1435 av_log(NULL, AV_LOG_WARNING, "Guessed Channel Layout for Output Stream "
1436 "#%d.%d : %s\n", ost->file_index, ost->st->index, layout_name);
1440 static void generate_silence(uint8_t* buf, enum AVSampleFormat sample_fmt, size_t size)
1442 int fill_char = 0x00;
1443 if (sample_fmt == AV_SAMPLE_FMT_U8)
1445 memset(buf, fill_char, size);
1448 static int encode_audio_frame(AVFormatContext *s, OutputStream *ost,
1449 const uint8_t *buf, int buf_size)
1451 AVCodecContext *enc = ost->st->codec;
1452 AVFrame *frame = NULL;
1454 int ret, got_packet;
1456 av_init_packet(&pkt);
1460 if (buf && buf_size) {
1461 if (!ost->output_frame) {
1462 ost->output_frame = avcodec_alloc_frame();
1463 if (!ost->output_frame) {
1464 av_log(NULL, AV_LOG_FATAL, "out-of-memory in encode_audio_frame()\n");
1468 frame = ost->output_frame;
1469 if (frame->extended_data != frame->data)
1470 av_freep(&frame->extended_data);
1471 avcodec_get_frame_defaults(frame);
1473 frame->nb_samples = buf_size /
1474 (enc->channels * av_get_bytes_per_sample(enc->sample_fmt));
1475 if ((ret = avcodec_fill_audio_frame(frame, enc->channels, enc->sample_fmt,
1476 buf, buf_size, 1)) < 0) {
1477 av_log(NULL, AV_LOG_FATAL, "Audio encoding failed (avcodec_fill_audio_frame)\n");
1481 frame->pts = ost->sync_opts;
1482 ost->sync_opts += frame->nb_samples;
1486 update_benchmark(NULL);
1487 if (avcodec_encode_audio2(enc, &pkt, frame, &got_packet) < 0) {
1488 av_log(NULL, AV_LOG_FATAL, "Audio encoding failed (avcodec_encode_audio2)\n");
1491 update_benchmark("encode_audio %d.%d", ost->file_index, ost->index);
1496 if (pkt.pts != AV_NOPTS_VALUE)
1497 pkt.pts = av_rescale_q(pkt.pts, enc->time_base, ost->st->time_base);
1498 if (pkt.dts != AV_NOPTS_VALUE) {
1499 int64_t max = ost->st->cur_dts + !(s->oformat->flags & AVFMT_TS_NONSTRICT);
1500 pkt.dts = av_rescale_q(pkt.dts, enc->time_base, ost->st->time_base);
1501 if (ost->st->cur_dts && ost->st->cur_dts != AV_NOPTS_VALUE && max > pkt.dts) {
1502 av_log(s, max - pkt.dts > 2 ? AV_LOG_WARNING : AV_LOG_DEBUG, "Audio timestamp %"PRId64" < %"PRId64" invalid, cliping\n", pkt.dts, max);
1503 pkt.pts = pkt.dts = max;
1506 if (pkt.duration > 0)
1507 pkt.duration = av_rescale_q(pkt.duration, enc->time_base, ost->st->time_base);
1509 write_frame(s, &pkt, ost);
1511 audio_size += pkt.size;
1513 av_free_packet(&pkt);
1517 av_log(NULL, AV_LOG_INFO, "encoder -> type:audio "
1518 "pkt_pts:%s pkt_pts_time:%s pkt_dts:%s pkt_dts_time:%s\n",
1519 av_ts2str(pkt.pts), av_ts2timestr(pkt.pts, &ost->st->time_base),
1520 av_ts2str(pkt.dts), av_ts2timestr(pkt.dts, &ost->st->time_base));
1526 static int alloc_audio_output_buf(AVCodecContext *dec, AVCodecContext *enc,
1529 int64_t audio_buf_samples;
1532 /* calculate required number of samples to allocate */
1533 audio_buf_samples = ((int64_t)nb_samples * enc->sample_rate + dec->sample_rate) /
1535 audio_buf_samples = 4 * audio_buf_samples + 10000; // safety factors for resampling
1536 audio_buf_samples = FFMAX(audio_buf_samples, enc->frame_size);
1537 if (audio_buf_samples > INT_MAX)
1538 return AVERROR(EINVAL);
1540 audio_buf_size = av_samples_get_buffer_size(NULL, enc->channels,
1542 enc->sample_fmt, 0);
1543 if (audio_buf_size < 0)
1544 return audio_buf_size;
1546 av_fast_malloc(&audio_buf, &allocated_audio_buf_size, audio_buf_size);
1548 return AVERROR(ENOMEM);
1553 static void do_audio_out(AVFormatContext *s, OutputStream *ost,
1554 InputStream *ist, AVFrame *decoded_frame)
1559 int frame_bytes, resample_changed;
1560 AVCodecContext *enc = ost->st->codec;
1561 AVCodecContext *dec = ist->st->codec;
1562 int osize = av_get_bytes_per_sample(enc->sample_fmt);
1563 int isize = av_get_bytes_per_sample(dec->sample_fmt);
1564 uint8_t *buf[AV_NUM_DATA_POINTERS];
1565 int size = decoded_frame->nb_samples * dec->channels * isize;
1566 int planes = av_sample_fmt_is_planar(dec->sample_fmt) ? dec->channels : 1;
1569 av_assert0(planes <= AV_NUM_DATA_POINTERS);
1571 for(i=0; i<planes; i++)
1572 buf[i]= decoded_frame->data[i];
1574 get_default_channel_layouts(ost, ist);
1576 if (alloc_audio_output_buf(dec, enc, decoded_frame->nb_samples) < 0) {
1577 av_log(NULL, AV_LOG_FATAL, "Error allocating audio buffer\n");
1581 if (enc->channels != dec->channels
1582 || enc->sample_fmt != dec->sample_fmt
1583 || enc->sample_rate!= dec->sample_rate
1585 ost->audio_resample = 1;
1587 resample_changed = ost->resample_sample_fmt != dec->sample_fmt ||
1588 ost->resample_channels != dec->channels ||
1589 ost->resample_sample_rate != dec->sample_rate;
1591 if ((ost->audio_resample && !ost->swr) || resample_changed || ost->audio_channels_mapped) {
1592 if (resample_changed) {
1593 av_log(NULL, AV_LOG_INFO, "Input stream #%d:%d frame changed from rate:%d fmt:%s ch:%d to rate:%d fmt:%s ch:%d\n",
1594 ist->file_index, ist->st->index,
1595 ost->resample_sample_rate, av_get_sample_fmt_name(ost->resample_sample_fmt), ost->resample_channels,
1596 dec->sample_rate, av_get_sample_fmt_name(dec->sample_fmt), dec->channels);
1597 ost->resample_sample_fmt = dec->sample_fmt;
1598 ost->resample_channels = dec->channels;
1599 ost->resample_sample_rate = dec->sample_rate;
1600 swr_free(&ost->swr);
1602 /* if audio_sync_method is >1 the resampler is needed for audio drift compensation */
1603 if (audio_sync_method <= 1 && !ost->audio_channels_mapped &&
1604 ost->resample_sample_fmt == enc->sample_fmt &&
1605 ost->resample_channels == enc->channels &&
1606 ost->resample_sample_rate == enc->sample_rate) {
1608 ost->audio_resample = 0;
1610 ost->swr = swr_alloc_set_opts(ost->swr,
1611 enc->channel_layout, enc->sample_fmt, enc->sample_rate,
1612 dec->channel_layout, dec->sample_fmt, dec->sample_rate,
1614 av_opt_set_int(ost->swr, "dither_method", ost->swr_dither_method,0);
1615 av_opt_set_int(ost->swr, "dither_scale", ost->swr_dither_scale,0);
1616 if (ost->audio_channels_mapped)
1617 swr_set_channel_mapping(ost->swr, ost->audio_channels_map);
1618 av_opt_set_double(ost->swr, "rmvol", ost->rematrix_volume, 0);
1619 if (ost->audio_channels_mapped) {
1620 av_opt_set_int(ost->swr, "icl", av_get_default_channel_layout(ost->audio_channels_mapped), 0);
1621 av_opt_set_int(ost->swr, "uch", ost->audio_channels_mapped, 0);
1623 if (av_opt_set_int(ost->swr, "ich", dec->channels, 0) < 0) {
1624 av_log(NULL, AV_LOG_FATAL, "Unsupported number of input channels\n");
1627 if (av_opt_set_int(ost->swr, "och", enc->channels, 0) < 0) {
1628 av_log(NULL, AV_LOG_FATAL, "Unsupported number of output channels\n");
1631 if(audio_sync_method>1) av_opt_set_int(ost->swr, "flags", SWR_FLAG_RESAMPLE, 0);
1632 if(ost->swr && swr_init(ost->swr) < 0){
1633 av_log(NULL, AV_LOG_FATAL, "swr_init() failed\n");
1634 swr_free(&ost->swr);
1638 av_log(NULL, AV_LOG_FATAL, "Can not resample %d channels @ %d Hz to %d channels @ %d Hz\n",
1639 dec->channels, dec->sample_rate,
1640 enc->channels, enc->sample_rate);
1646 av_assert0(ost->audio_resample || dec->sample_fmt==enc->sample_fmt);
1648 if (audio_sync_method > 0) {
1649 double delta = get_sync_ipts(ost, ist->pts) * enc->sample_rate - ost->sync_opts -
1650 av_fifo_size(ost->fifo) / (enc->channels * osize);
1651 int idelta = delta * dec->sample_rate / enc->sample_rate;
1652 int byte_delta = idelta * isize * dec->channels;
1654 // FIXME resample delay
1655 if (fabs(delta) > 50) {
1656 if (ist->is_start || fabs(delta) > audio_drift_threshold*enc->sample_rate) {
1657 if (byte_delta < 0) {
1658 byte_delta = FFMAX(byte_delta, -size);
1660 for (i=0; i<planes; i++)
1661 buf[i] -= byte_delta/planes;
1662 av_log(NULL, AV_LOG_VERBOSE, "discarding %d audio samples\n",
1663 -byte_delta / (isize * dec->channels));
1668 av_fast_malloc(&async_buf, &allocated_async_buf_size,
1671 av_log(NULL, AV_LOG_FATAL, "Out of memory in do_audio_out\n");
1675 if (alloc_audio_output_buf(dec, enc, decoded_frame->nb_samples + idelta) < 0) {
1676 av_log(NULL, AV_LOG_FATAL, "Error allocating audio buffer\n");
1681 for (i=0; i<planes; i++) {
1682 uint8_t *t = async_buf + i*((byte_delta + size)/planes);
1683 generate_silence(t, dec->sample_fmt, byte_delta/planes);
1684 memcpy(t + byte_delta/planes, buf[i], size/planes);
1688 av_log(NULL, AV_LOG_VERBOSE, "adding %d audio samples of silence\n", idelta);
1690 } else if (audio_sync_method > 1) {
1691 int comp = av_clip(delta, -audio_sync_method, audio_sync_method);
1692 av_assert0(ost->audio_resample);
1693 av_log(NULL, AV_LOG_VERBOSE, "compensating audio timestamp drift:%f compensation:%d in:%d\n",
1694 delta, comp, enc->sample_rate);
1695 // 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));
1696 swr_set_compensation(ost->swr, comp, enc->sample_rate);
1699 } else if (audio_sync_method == 0)
1700 ost->sync_opts = lrintf(get_sync_ipts(ost, ist->pts) * enc->sample_rate) -
1701 av_fifo_size(ost->fifo) / (enc->channels * osize); // FIXME wrong
1703 if (ost->audio_resample || ost->audio_channels_mapped) {
1705 size_out = swr_convert(ost->swr, ( uint8_t*[]){buftmp}, allocated_audio_buf_size / (enc->channels * osize),
1706 buf, size / (dec->channels * isize));
1708 av_log(NULL, AV_LOG_FATAL, "swr_convert failed\n");
1711 size_out = size_out * enc->channels * osize;
1717 av_assert0(ost->audio_resample || dec->sample_fmt==enc->sample_fmt);
1719 /* now encode as many frames as possible */
1720 if (!(enc->codec->capabilities & CODEC_CAP_VARIABLE_FRAME_SIZE)) {
1721 /* output resampled raw samples */
1722 if (av_fifo_realloc2(ost->fifo, av_fifo_size(ost->fifo) + size_out) < 0) {
1723 av_log(NULL, AV_LOG_FATAL, "av_fifo_realloc2() failed\n");
1726 av_fifo_generic_write(ost->fifo, buftmp, size_out, NULL);
1728 frame_bytes = enc->frame_size * osize * enc->channels;
1730 while (av_fifo_size(ost->fifo) >= frame_bytes) {
1731 av_fifo_generic_read(ost->fifo, audio_buf, frame_bytes, NULL);
1732 encode_audio_frame(s, ost, audio_buf, frame_bytes);
1735 encode_audio_frame(s, ost, buftmp, size_out);
1739 static void pre_process_video_frame(InputStream *ist, AVPicture *picture, void **bufp)
1741 AVCodecContext *dec;
1742 AVPicture *picture2;
1743 AVPicture picture_tmp;
1746 dec = ist->st->codec;
1748 /* deinterlace : must be done before any resize */
1749 if (do_deinterlace) {
1752 /* create temporary picture */
1753 size = avpicture_get_size(dec->pix_fmt, dec->width, dec->height);
1754 buf = av_malloc(size);
1758 picture2 = &picture_tmp;
1759 avpicture_fill(picture2, buf, dec->pix_fmt, dec->width, dec->height);
1761 if (avpicture_deinterlace(picture2, picture,
1762 dec->pix_fmt, dec->width, dec->height) < 0) {
1763 /* if error, do not deinterlace */
1764 av_log(NULL, AV_LOG_WARNING, "Deinterlacing failed\n");
1773 if (picture != picture2)
1774 *picture = *picture2;
1778 static void do_subtitle_out(AVFormatContext *s,
1784 static uint8_t *subtitle_out = NULL;
1785 int subtitle_out_max_size = 1024 * 1024;
1786 int subtitle_out_size, nb, i;
1787 AVCodecContext *enc;
1790 if (pts == AV_NOPTS_VALUE) {
1791 av_log(NULL, AV_LOG_ERROR, "Subtitle packets must have a pts\n");
1797 enc = ost->st->codec;
1799 if (!subtitle_out) {
1800 subtitle_out = av_malloc(subtitle_out_max_size);
1803 /* Note: DVB subtitle need one packet to draw them and one other
1804 packet to clear them */
1805 /* XXX: signal it in the codec context ? */
1806 if (enc->codec_id == CODEC_ID_DVB_SUBTITLE)
1811 for (i = 0; i < nb; i++) {
1812 ost->sync_opts = av_rescale_q(pts, ist->st->time_base, enc->time_base);
1814 sub->pts = av_rescale_q(pts, ist->st->time_base, AV_TIME_BASE_Q);
1815 // start_display_time is required to be 0
1816 sub->pts += av_rescale_q(sub->start_display_time, (AVRational){ 1, 1000 }, AV_TIME_BASE_Q);
1817 sub->end_display_time -= sub->start_display_time;
1818 sub->start_display_time = 0;
1819 subtitle_out_size = avcodec_encode_subtitle(enc, subtitle_out,
1820 subtitle_out_max_size, sub);
1821 if (subtitle_out_size < 0) {
1822 av_log(NULL, AV_LOG_FATAL, "Subtitle encoding failed\n");
1826 av_init_packet(&pkt);
1827 pkt.data = subtitle_out;
1828 pkt.size = subtitle_out_size;
1829 pkt.pts = av_rescale_q(sub->pts, AV_TIME_BASE_Q, ost->st->time_base);
1830 if (enc->codec_id == CODEC_ID_DVB_SUBTITLE) {
1831 /* XXX: the pts correction is handled here. Maybe handling
1832 it in the codec would be better */
1834 pkt.pts += 90 * sub->start_display_time;
1836 pkt.pts += 90 * sub->end_display_time;
1838 write_frame(s, &pkt, ost);
1842 static double psnr(double d)
1844 return -10.0 * log(d) / log(10.0);
1847 static void do_video_stats(AVFormatContext *os, OutputStream *ost,
1850 AVCodecContext *enc;
1852 double ti1, bitrate, avg_bitrate;
1854 /* this is executed just the first time do_video_stats is called */
1856 vstats_file = fopen(vstats_filename, "w");
1863 enc = ost->st->codec;
1864 if (enc->codec_type == AVMEDIA_TYPE_VIDEO) {
1865 frame_number = ost->frame_number;
1866 fprintf(vstats_file, "frame= %5d q= %2.1f ", frame_number, enc->coded_frame->quality / (float)FF_QP2LAMBDA);
1867 if (enc->flags&CODEC_FLAG_PSNR)
1868 fprintf(vstats_file, "PSNR= %6.2f ", psnr(enc->coded_frame->error[0] / (enc->width * enc->height * 255.0 * 255.0)));
1870 fprintf(vstats_file,"f_size= %6d ", frame_size);
1871 /* compute pts value */
1872 ti1 = ost->sync_opts * av_q2d(enc->time_base);
1876 bitrate = (frame_size * 8) / av_q2d(enc->time_base) / 1000.0;
1877 avg_bitrate = (double)(video_size * 8) / ti1 / 1000.0;
1878 fprintf(vstats_file, "s_size= %8.0fkB time= %0.3f br= %7.1fkbits/s avg_br= %7.1fkbits/s ",
1879 (double)video_size / 1024, ti1, bitrate, avg_bitrate);
1880 fprintf(vstats_file, "type= %c\n", av_get_picture_type_char(enc->coded_frame->pict_type));
1885 static void do_video_out(AVFormatContext *s, OutputStream *ost,
1886 AVFrame *in_picture, float quality)
1888 int nb_frames, i, ret, format_video_sync;
1889 AVCodecContext *enc;
1890 double sync_ipts, delta;
1891 double duration = 0;
1893 InputStream *ist = NULL;
1895 if (ost->source_index >= 0)
1896 ist = input_streams[ost->source_index];
1898 enc = ost->st->codec;
1900 if (ist && ist->st->start_time != AV_NOPTS_VALUE && ist->st->first_dts != AV_NOPTS_VALUE) {
1901 duration = FFMAX(av_q2d(ist->st->time_base), av_q2d(ist->st->codec->time_base));
1902 if(ist->st->r_frame_rate.num)
1903 duration= FFMAX(duration, 1/av_q2d(ist->st->r_frame_rate));
1904 if(ist->st->avg_frame_rate.num && 0)
1905 duration= FFMAX(duration, 1/av_q2d(ist->st->avg_frame_rate));
1907 duration /= av_q2d(enc->time_base);
1910 sync_ipts = get_sync_ipts(ost, in_picture->pts) / av_q2d(enc->time_base);
1911 delta = sync_ipts - ost->sync_opts + duration;
1913 /* by default, we output a single frame */
1916 format_video_sync = video_sync_method;
1917 if (format_video_sync == VSYNC_AUTO)
1918 format_video_sync = (s->oformat->flags & AVFMT_VARIABLE_FPS) ? ((s->oformat->flags & AVFMT_NOTIMESTAMPS) ? VSYNC_PASSTHROUGH : VSYNC_VFR) : 1;
1920 switch (format_video_sync) {
1922 // FIXME set to 0.5 after we fix some dts/pts bugs like in avidec.c
1925 else if (delta > 1.1)
1926 nb_frames = lrintf(delta);
1931 else if (delta > 0.6)
1932 ost->sync_opts = lrintf(sync_ipts);
1935 case VSYNC_PASSTHROUGH:
1936 ost->sync_opts = lrintf(sync_ipts);
1942 nb_frames = FFMIN(nb_frames, ost->max_frames - ost->frame_number);
1943 if (nb_frames == 0) {
1945 av_log(NULL, AV_LOG_VERBOSE, "*** drop!\n");
1947 } else if (nb_frames > 1) {
1948 nb_frames_dup += nb_frames - 1;
1949 av_log(NULL, AV_LOG_VERBOSE, "*** %d dup!\n", nb_frames - 1);
1952 /* duplicates frame if needed */
1953 for (i = 0; i < nb_frames; i++) {
1955 av_init_packet(&pkt);
1959 if (s->oformat->flags & AVFMT_RAWPICTURE &&
1960 enc->codec->id == CODEC_ID_RAWVIDEO) {
1961 /* raw pictures are written as AVPicture structure to
1962 avoid any copies. We support temporarily the older
1964 enc->coded_frame->interlaced_frame = in_picture->interlaced_frame;
1965 enc->coded_frame->top_field_first = in_picture->top_field_first;
1966 pkt.data = (uint8_t *)in_picture;
1967 pkt.size = sizeof(AVPicture);
1968 pkt.pts = av_rescale_q(ost->sync_opts, enc->time_base, ost->st->time_base);
1969 pkt.flags |= AV_PKT_FLAG_KEY;
1971 write_frame(s, &pkt, ost);
1974 AVFrame big_picture;
1976 big_picture = *in_picture;
1977 /* better than nothing: use input picture interlaced
1979 big_picture.interlaced_frame = in_picture->interlaced_frame;
1980 if (ost->st->codec->flags & (CODEC_FLAG_INTERLACED_DCT|CODEC_FLAG_INTERLACED_ME)) {
1981 if (ost->top_field_first == -1)
1982 big_picture.top_field_first = in_picture->top_field_first;
1984 big_picture.top_field_first = !!ost->top_field_first;
1987 /* handles same_quant here. This is not correct because it may
1988 not be a global option */
1989 big_picture.quality = quality;
1990 if (!enc->me_threshold)
1991 big_picture.pict_type = 0;
1992 big_picture.pts = ost->sync_opts;
1993 if (ost->forced_kf_index < ost->forced_kf_count &&
1994 big_picture.pts >= ost->forced_kf_pts[ost->forced_kf_index]) {
1995 big_picture.pict_type = AV_PICTURE_TYPE_I;
1996 ost->forced_kf_index++;
1998 update_benchmark(NULL);
1999 ret = avcodec_encode_video2(enc, &pkt, &big_picture, &got_packet);
2000 update_benchmark("encode_video %d.%d", ost->file_index, ost->index);
2002 av_log(NULL, AV_LOG_FATAL, "Video encoding failed\n");
2007 if (pkt.pts == AV_NOPTS_VALUE && !(enc->codec->capabilities & CODEC_CAP_DELAY))
2008 pkt.pts = ost->sync_opts;
2010 if (pkt.pts != AV_NOPTS_VALUE)
2011 pkt.pts = av_rescale_q(pkt.pts, enc->time_base, ost->st->time_base);
2012 if (pkt.dts != AV_NOPTS_VALUE)
2013 pkt.dts = av_rescale_q(pkt.dts, enc->time_base, ost->st->time_base);
2016 av_log(NULL, AV_LOG_INFO, "encoder -> type:video "
2017 "pkt_pts:%s pkt_pts_time:%s pkt_dts:%s pkt_dts_time:%s\n",
2018 av_ts2str(pkt.pts), av_ts2timestr(pkt.pts, &ost->st->time_base),
2019 av_ts2str(pkt.dts), av_ts2timestr(pkt.dts, &ost->st->time_base));
2022 write_frame(s, &pkt, ost);
2023 frame_size = pkt.size;
2024 video_size += pkt.size;
2025 av_free_packet(&pkt);
2027 /* if two pass, output log */
2028 if (ost->logfile && enc->stats_out) {
2029 fprintf(ost->logfile, "%s", enc->stats_out);
2035 * For video, number of frames in == number of packets out.
2036 * But there may be reordering, so we can't throw away frames on encoder
2037 * flush, we need to limit them here, before they go into encoder.
2039 ost->frame_number++;
2041 if (vstats_filename && frame_size)
2042 do_video_stats(output_files[ost->file_index]->ctx, ost, frame_size);
2045 /* check for new output on any of the filtergraphs */
2046 static int poll_filters(void)
2048 AVFilterBufferRef *picref;
2049 AVFrame *filtered_frame = NULL;
2050 int i, ret, ret_all;
2051 unsigned nb_success, nb_eof;
2054 /* Reap all buffers present in the buffer sinks */
2056 for (i = 0; i < nb_output_streams; i++) {
2057 OutputStream *ost = output_streams[i];
2058 OutputFile *of = output_files[ost->file_index];
2060 if (!ost->filter || ost->is_past_recording_time)
2063 if (!ost->filtered_frame && !(ost->filtered_frame = avcodec_alloc_frame())) {
2064 return AVERROR(ENOMEM);
2066 avcodec_get_frame_defaults(ost->filtered_frame);
2067 filtered_frame = ost->filtered_frame;
2070 AVRational ist_pts_tb = ost->filter->filter->inputs[0]->time_base;
2071 ret = av_buffersink_get_buffer_ref(ost->filter->filter, &picref,
2072 AV_BUFFERSINK_FLAG_NO_REQUEST);
2074 if (ret != AVERROR(EAGAIN)) {
2076 av_strerror(ret, buf, sizeof(buf));
2077 av_log(NULL, AV_LOG_WARNING,
2078 "Error in av_buffersink_get_buffer_ref(): %s\n", buf);
2082 filtered_frame->pts = av_rescale_q(picref->pts, ist_pts_tb, AV_TIME_BASE_Q);
2083 // if (ost->source_index >= 0)
2084 // *filtered_frame= *input_streams[ost->source_index]->decoded_frame; //for me_threshold
2086 if (of->start_time && filtered_frame->pts < of->start_time)
2089 switch (ost->filter->filter->inputs[0]->type) {
2090 case AVMEDIA_TYPE_VIDEO:
2091 avfilter_fill_frame_from_video_buffer_ref(filtered_frame, picref);
2092 if (!ost->frame_aspect_ratio)
2093 ost->st->codec->sample_aspect_ratio = picref->video->sample_aspect_ratio;
2095 do_video_out(of->ctx, ost, filtered_frame,
2096 same_quant ? ost->last_quality :
2097 ost->st->codec->global_quality);
2100 // TODO support audio/subtitle filters
2104 avfilter_unref_buffer(picref);
2107 /* Request frames through all the graphs */
2108 ret_all = nb_success = nb_eof = 0;
2109 for (i = 0; i < nb_filtergraphs; i++) {
2110 ret = avfilter_graph_request_oldest(filtergraphs[i]->graph);
2113 } else if (ret == AVERROR_EOF) {
2115 } else if (ret != AVERROR(EAGAIN)) {
2117 av_strerror(ret, buf, sizeof(buf));
2118 av_log(NULL, AV_LOG_WARNING,
2119 "Error in request_frame(): %s\n", buf);
2125 /* Try again if anything succeeded */
2127 return nb_eof == nb_filtergraphs ? AVERROR_EOF : ret_all;
2130 static void print_report(int is_last_report, int64_t timer_start, int64_t cur_time)
2134 AVFormatContext *oc;
2136 AVCodecContext *enc;
2137 int frame_number, vid, i;
2139 int64_t pts = INT64_MAX;
2140 static int64_t last_time = -1;
2141 static int qp_histogram[52];
2142 int hours, mins, secs, us;
2144 if (!print_stats && !is_last_report)
2147 if (!is_last_report) {
2148 if (last_time == -1) {
2149 last_time = cur_time;
2152 if ((cur_time - last_time) < 500000)
2154 last_time = cur_time;
2158 oc = output_files[0]->ctx;
2160 total_size = avio_size(oc->pb);
2161 if (total_size < 0) { // FIXME improve avio_size() so it works with non seekable output too
2162 total_size = avio_tell(oc->pb);
2169 for (i = 0; i < nb_output_streams; i++) {
2171 ost = output_streams[i];
2172 enc = ost->st->codec;
2173 if (!ost->stream_copy && enc->coded_frame)
2174 q = enc->coded_frame->quality / (float)FF_QP2LAMBDA;
2175 if (vid && enc->codec_type == AVMEDIA_TYPE_VIDEO) {
2176 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "q=%2.1f ", q);
2178 if (!vid && enc->codec_type == AVMEDIA_TYPE_VIDEO) {
2179 float fps, t = (cur_time-timer_start) / 1000000.0;
2181 frame_number = ost->frame_number;
2182 fps = t > 1 ? frame_number / t : 0;
2183 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "frame=%5d fps=%3.*f q=%3.1f ",
2184 frame_number, fps < 9.95, fps, q);
2186 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "L");
2190 if (qp >= 0 && qp < FF_ARRAY_ELEMS(qp_histogram))
2192 for (j = 0; j < 32; j++)
2193 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "%X", (int)lrintf(log(qp_histogram[j] + 1) / log(2)));
2195 if (enc->flags&CODEC_FLAG_PSNR) {
2197 double error, error_sum = 0;
2198 double scale, scale_sum = 0;
2199 char type[3] = { 'Y','U','V' };
2200 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "PSNR=");
2201 for (j = 0; j < 3; j++) {
2202 if (is_last_report) {
2203 error = enc->error[j];
2204 scale = enc->width * enc->height * 255.0 * 255.0 * frame_number;
2206 error = enc->coded_frame->error[j];
2207 scale = enc->width * enc->height * 255.0 * 255.0;
2213 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "%c:%2.2f ", type[j], psnr(error / scale));
2215 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "*:%2.2f ", psnr(error_sum / scale_sum));
2219 /* compute min output value */
2220 pts = FFMIN(pts, av_rescale_q(ost->st->pts.val,
2221 ost->st->time_base, AV_TIME_BASE_Q));
2224 secs = pts / AV_TIME_BASE;
2225 us = pts % AV_TIME_BASE;
2231 bitrate = pts ? total_size * 8 / (pts / 1000.0) : 0;
2233 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
2234 "size=%8.0fkB time=", total_size / 1024.0);
2235 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
2236 "%02d:%02d:%02d.%02d ", hours, mins, secs,
2237 (100 * us) / AV_TIME_BASE);
2238 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
2239 "bitrate=%6.1fkbits/s", bitrate);
2241 if (nb_frames_dup || nb_frames_drop)
2242 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), " dup=%d drop=%d",
2243 nb_frames_dup, nb_frames_drop);
2245 av_log(NULL, AV_LOG_INFO, "%s \r", buf);
2249 if (is_last_report) {
2250 int64_t raw= audio_size + video_size + extra_size;
2251 av_log(NULL, AV_LOG_INFO, "\n");
2252 av_log(NULL, AV_LOG_INFO, "video:%1.0fkB audio:%1.0fkB global headers:%1.0fkB muxing overhead %f%%\n",
2253 video_size / 1024.0,
2254 audio_size / 1024.0,
2255 extra_size / 1024.0,
2256 100.0 * (total_size - raw) / raw
2258 if(video_size + audio_size + extra_size == 0){
2259 av_log(NULL, AV_LOG_WARNING, "Output file is empty, nothing was encoded (check -ss / -t / -frames parameters if used)\n");
2264 static void flush_encoders(void)
2268 for (i = 0; i < nb_output_streams; i++) {
2269 OutputStream *ost = output_streams[i];
2270 AVCodecContext *enc = ost->st->codec;
2271 AVFormatContext *os = output_files[ost->file_index]->ctx;
2272 int stop_encoding = 0;
2274 if (!ost->encoding_needed)
2277 if (ost->st->codec->codec_type == AVMEDIA_TYPE_AUDIO && enc->frame_size <= 1)
2279 if (ost->st->codec->codec_type == AVMEDIA_TYPE_VIDEO && (os->oformat->flags & AVFMT_RAWPICTURE) && enc->codec->id == CODEC_ID_RAWVIDEO)
2284 int fifo_bytes, got_packet;
2285 av_init_packet(&pkt);
2289 switch (ost->st->codec->codec_type) {
2290 case AVMEDIA_TYPE_AUDIO:
2291 fifo_bytes = av_fifo_size(ost->fifo);
2292 if (fifo_bytes > 0) {
2293 /* encode any samples remaining in fifo */
2294 int frame_bytes = fifo_bytes;
2296 av_fifo_generic_read(ost->fifo, audio_buf, fifo_bytes, NULL);
2298 /* pad last frame with silence if needed */
2299 if (!(enc->codec->capabilities & CODEC_CAP_SMALL_LAST_FRAME)) {
2300 frame_bytes = enc->frame_size * enc->channels *
2301 av_get_bytes_per_sample(enc->sample_fmt);
2302 if (allocated_audio_buf_size < frame_bytes)
2304 generate_silence(audio_buf+fifo_bytes, enc->sample_fmt, frame_bytes - fifo_bytes);
2306 encode_audio_frame(os, ost, audio_buf, frame_bytes);
2308 /* flush encoder with NULL frames until it is done
2309 returning packets */
2310 if (encode_audio_frame(os, ost, NULL, 0) == 0) {
2316 case AVMEDIA_TYPE_VIDEO:
2317 update_benchmark(NULL);
2318 ret = avcodec_encode_video2(enc, &pkt, NULL, &got_packet);
2319 update_benchmark("encode_video %d.%d", ost->file_index, ost->index);
2321 av_log(NULL, AV_LOG_FATAL, "Video encoding failed\n");
2324 video_size += pkt.size;
2325 if (ost->logfile && enc->stats_out) {
2326 fprintf(ost->logfile, "%s", enc->stats_out);
2332 if (pkt.pts != AV_NOPTS_VALUE)
2333 pkt.pts = av_rescale_q(pkt.pts, enc->time_base, ost->st->time_base);
2334 if (pkt.dts != AV_NOPTS_VALUE)
2335 pkt.dts = av_rescale_q(pkt.dts, enc->time_base, ost->st->time_base);
2336 write_frame(os, &pkt, ost);
2348 * Check whether a packet from ist should be written into ost at this time
2350 static int check_output_constraints(InputStream *ist, OutputStream *ost)
2352 OutputFile *of = output_files[ost->file_index];
2353 int ist_index = input_files[ist->file_index]->ist_index + ist->st->index;
2355 if (ost->source_index != ist_index)
2358 if (of->start_time && ist->pts < of->start_time)
2361 if (of->recording_time != INT64_MAX &&
2362 av_compare_ts(ist->pts, AV_TIME_BASE_Q, of->recording_time + of->start_time,
2363 (AVRational){ 1, 1000000 }) >= 0) {
2364 ost->is_past_recording_time = 1;
2371 static void do_streamcopy(InputStream *ist, OutputStream *ost, const AVPacket *pkt)
2373 OutputFile *of = output_files[ost->file_index];
2374 int64_t ost_tb_start_time = av_rescale_q(of->start_time, AV_TIME_BASE_Q, ost->st->time_base);
2378 av_init_packet(&opkt);
2380 if ((!ost->frame_number && !(pkt->flags & AV_PKT_FLAG_KEY)) &&
2381 !ost->copy_initial_nonkeyframes)
2384 /* force the input stream PTS */
2385 if (ost->st->codec->codec_type == AVMEDIA_TYPE_AUDIO)
2386 audio_size += pkt->size;
2387 else if (ost->st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
2388 video_size += pkt->size;
2392 if (pkt->pts != AV_NOPTS_VALUE)
2393 opkt.pts = av_rescale_q(pkt->pts, ist->st->time_base, ost->st->time_base) - ost_tb_start_time;
2395 opkt.pts = AV_NOPTS_VALUE;
2397 if (pkt->dts == AV_NOPTS_VALUE)
2398 opkt.dts = av_rescale_q(ist->dts, AV_TIME_BASE_Q, ost->st->time_base);
2400 opkt.dts = av_rescale_q(pkt->dts, ist->st->time_base, ost->st->time_base);
2401 opkt.dts -= ost_tb_start_time;
2403 opkt.duration = av_rescale_q(pkt->duration, ist->st->time_base, ost->st->time_base);
2404 opkt.flags = pkt->flags;
2406 // FIXME remove the following 2 lines they shall be replaced by the bitstream filters
2407 if ( ost->st->codec->codec_id != CODEC_ID_H264
2408 && ost->st->codec->codec_id != CODEC_ID_MPEG1VIDEO
2409 && ost->st->codec->codec_id != CODEC_ID_MPEG2VIDEO
2410 && ost->st->codec->codec_id != CODEC_ID_VC1
2412 if (av_parser_change(ist->st->parser, ost->st->codec, &opkt.data, &opkt.size, pkt->data, pkt->size, pkt->flags & AV_PKT_FLAG_KEY))
2413 opkt.destruct = av_destruct_packet;
2415 opkt.data = pkt->data;
2416 opkt.size = pkt->size;
2418 if (of->ctx->oformat->flags & AVFMT_RAWPICTURE) {
2419 /* store AVPicture in AVPacket, as expected by the output format */
2420 avpicture_fill(&pict, opkt.data, ost->st->codec->pix_fmt, ost->st->codec->width, ost->st->codec->height);
2421 opkt.data = (uint8_t *)&pict;
2422 opkt.size = sizeof(AVPicture);
2423 opkt.flags |= AV_PKT_FLAG_KEY;
2426 write_frame(of->ctx, &opkt, ost);
2427 ost->st->codec->frame_number++;
2428 av_free_packet(&opkt);
2431 static void rate_emu_sleep(InputStream *ist)
2433 if (input_files[ist->file_index]->rate_emu) {
2434 int64_t pts = av_rescale(ist->dts, 1000000, AV_TIME_BASE);
2435 int64_t now = av_gettime() - ist->start;
2441 static int transcode_audio(InputStream *ist, AVPacket *pkt, int *got_output)
2443 AVFrame *decoded_frame;
2444 AVCodecContext *avctx = ist->st->codec;
2445 int bps = av_get_bytes_per_sample(ist->st->codec->sample_fmt);
2448 if (!ist->decoded_frame && !(ist->decoded_frame = avcodec_alloc_frame()))
2449 return AVERROR(ENOMEM);
2451 avcodec_get_frame_defaults(ist->decoded_frame);
2452 decoded_frame = ist->decoded_frame;
2454 update_benchmark(NULL);
2455 ret = avcodec_decode_audio4(avctx, decoded_frame, got_output, pkt);
2456 update_benchmark("decode_audio %d.%d", ist->file_index, ist->st->index);
2460 if (avctx->sample_rate <= 0) {
2461 av_log(avctx, AV_LOG_ERROR, "Sample rate %d invalid\n", avctx->sample_rate);
2462 return AVERROR_INVALIDDATA;
2466 /* no audio frame */
2470 /* if the decoder provides a pts, use it instead of the last packet pts.
2471 the decoder could be delaying output by a packet or more. */
2472 if (decoded_frame->pts != AV_NOPTS_VALUE)
2473 ist->dts = ist->next_dts = ist->pts = ist->next_pts = decoded_frame->pts;
2475 /* increment next_dts to use for the case where the input stream does not
2476 have timestamps or there are multiple frames in the packet */
2477 ist->next_pts += ((int64_t)AV_TIME_BASE * decoded_frame->nb_samples) /
2479 ist->next_dts += ((int64_t)AV_TIME_BASE * decoded_frame->nb_samples) /
2483 // preprocess audio (volume)
2484 if (audio_volume != 256) {
2485 int decoded_data_size = decoded_frame->nb_samples * avctx->channels * bps;
2486 void *samples = decoded_frame->data[0];
2487 switch (avctx->sample_fmt) {
2488 case AV_SAMPLE_FMT_U8:
2490 uint8_t *volp = samples;
2491 for (i = 0; i < (decoded_data_size / sizeof(*volp)); i++) {
2492 int v = (((*volp - 128) * audio_volume + 128) >> 8) + 128;
2493 *volp++ = av_clip_uint8(v);
2497 case AV_SAMPLE_FMT_S16:
2499 int16_t *volp = samples;
2500 for (i = 0; i < (decoded_data_size / sizeof(*volp)); i++) {
2501 int v = ((*volp) * audio_volume + 128) >> 8;
2502 *volp++ = av_clip_int16(v);
2506 case AV_SAMPLE_FMT_S32:
2508 int32_t *volp = samples;
2509 for (i = 0; i < (decoded_data_size / sizeof(*volp)); i++) {
2510 int64_t v = (((int64_t)*volp * audio_volume + 128) >> 8);
2511 *volp++ = av_clipl_int32(v);
2515 case AV_SAMPLE_FMT_FLT:
2517 float *volp = samples;
2518 float scale = audio_volume / 256.f;
2519 for (i = 0; i < (decoded_data_size / sizeof(*volp)); i++) {
2524 case AV_SAMPLE_FMT_DBL:
2526 double *volp = samples;
2527 double scale = audio_volume / 256.;
2528 for (i = 0; i < (decoded_data_size / sizeof(*volp)); i++) {
2534 av_log(NULL, AV_LOG_FATAL,
2535 "Audio volume adjustment on sample format %s is not supported.\n",
2536 av_get_sample_fmt_name(ist->st->codec->sample_fmt));
2541 rate_emu_sleep(ist);
2543 for (i = 0; i < nb_output_streams; i++) {
2544 OutputStream *ost = output_streams[i];
2546 if (!check_output_constraints(ist, ost) || !ost->encoding_needed)
2548 do_audio_out(output_files[ost->file_index]->ctx, ost, ist, decoded_frame);
2554 static int transcode_video(InputStream *ist, AVPacket *pkt, int *got_output, int64_t *pkt_pts)
2556 AVFrame *decoded_frame;
2557 void *buffer_to_free = NULL;
2558 int i, ret = 0, resample_changed;
2559 int64_t *best_effort_timestamp;
2560 AVRational *frame_sample_aspect;
2563 if (!ist->decoded_frame && !(ist->decoded_frame = avcodec_alloc_frame()))
2564 return AVERROR(ENOMEM);
2566 avcodec_get_frame_defaults(ist->decoded_frame);
2567 decoded_frame = ist->decoded_frame;
2568 pkt->pts = *pkt_pts;
2569 pkt->dts = ist->dts;
2570 *pkt_pts = AV_NOPTS_VALUE;
2572 update_benchmark(NULL);
2573 ret = avcodec_decode_video2(ist->st->codec,
2574 decoded_frame, got_output, pkt);
2575 update_benchmark("decode_video %d.%d", ist->file_index, ist->st->index);
2579 quality = same_quant ? decoded_frame->quality : 0;
2581 /* no picture yet */
2583 for (i = 0; i < ist->nb_filters; i++)
2584 av_buffersrc_buffer(ist->filters[i]->filter, NULL);
2588 best_effort_timestamp= av_opt_ptr(avcodec_get_frame_class(), decoded_frame, "best_effort_timestamp");
2589 if(*best_effort_timestamp != AV_NOPTS_VALUE)
2590 ist->next_pts = ist->pts = decoded_frame->pts = *best_effort_timestamp;
2594 pre_process_video_frame(ist, (AVPicture *)decoded_frame, &buffer_to_free);
2596 rate_emu_sleep(ist);
2598 if (ist->st->sample_aspect_ratio.num)
2599 decoded_frame->sample_aspect_ratio = ist->st->sample_aspect_ratio;
2601 resample_changed = ist->resample_width != decoded_frame->width ||
2602 ist->resample_height != decoded_frame->height ||
2603 ist->resample_pix_fmt != decoded_frame->format;
2604 if (resample_changed) {
2605 av_log(NULL, AV_LOG_INFO,
2606 "Input stream #%d:%d frame changed from size:%dx%d fmt:%s to size:%dx%d fmt:%s\n",
2607 ist->file_index, ist->st->index,
2608 ist->resample_width, ist->resample_height, av_get_pix_fmt_name(ist->resample_pix_fmt),
2609 decoded_frame->width, decoded_frame->height, av_get_pix_fmt_name(decoded_frame->format));
2611 ist->resample_width = decoded_frame->width;
2612 ist->resample_height = decoded_frame->height;
2613 ist->resample_pix_fmt = decoded_frame->format;
2615 for (i = 0; i < nb_filtergraphs; i++)
2616 if (ist_in_filtergraph(filtergraphs[i], ist) &&
2617 configure_filtergraph(filtergraphs[i]) < 0) {
2618 av_log(NULL, AV_LOG_FATAL, "Error reinitializing filters!\n");
2623 frame_sample_aspect= av_opt_ptr(avcodec_get_frame_class(), decoded_frame, "sample_aspect_ratio");
2624 for (i = 0; i < ist->nb_filters; i++) {
2625 int changed = ist->st->codec->width != ist->filters[i]->filter->outputs[0]->w
2626 || ist->st->codec->height != ist->filters[i]->filter->outputs[0]->h
2627 || ist->st->codec->pix_fmt != ist->filters[i]->filter->outputs[0]->format;
2628 // XXX what an ugly hack
2629 if (ist->filters[i]->graph->nb_outputs == 1)
2630 ist->filters[i]->graph->outputs[0]->ost->last_quality = quality;
2632 if (!frame_sample_aspect->num)
2633 *frame_sample_aspect = ist->st->sample_aspect_ratio;
2634 if (ist->dr1 && decoded_frame->type==FF_BUFFER_TYPE_USER && !changed) {
2635 FrameBuffer *buf = decoded_frame->opaque;
2636 AVFilterBufferRef *fb = avfilter_get_video_buffer_ref_from_arrays(
2637 decoded_frame->data, decoded_frame->linesize,
2638 AV_PERM_READ | AV_PERM_PRESERVE,
2639 ist->st->codec->width, ist->st->codec->height,
2640 ist->st->codec->pix_fmt);
2642 avfilter_copy_frame_props(fb, decoded_frame);
2643 fb->buf->priv = buf;
2644 fb->buf->free = filter_release_buffer;
2646 av_assert0(buf->refcount>0);
2648 av_buffersrc_buffer(ist->filters[i]->filter, fb);
2650 if(av_vsrc_buffer_add_frame(ist->filters[i]->filter, decoded_frame,AV_VSRC_BUF_FLAG_OVERWRITE)<0) {
2651 av_log(NULL, AV_LOG_FATAL, "Failed to inject frame into filter network\n");
2657 av_free(buffer_to_free);
2661 static int transcode_subtitles(InputStream *ist, AVPacket *pkt, int *got_output)
2663 AVSubtitle subtitle;
2664 int i, ret = avcodec_decode_subtitle2(ist->st->codec,
2665 &subtitle, got_output, pkt);
2671 rate_emu_sleep(ist);
2673 for (i = 0; i < nb_output_streams; i++) {
2674 OutputStream *ost = output_streams[i];
2676 if (!check_output_constraints(ist, ost) || !ost->encoding_needed)
2679 do_subtitle_out(output_files[ost->file_index]->ctx, ost, ist, &subtitle, pkt->pts);
2682 avsubtitle_free(&subtitle);
2686 /* pkt = NULL means EOF (needed to flush decoder buffers) */
2687 static int output_packet(InputStream *ist, const AVPacket *pkt)
2691 int64_t pkt_pts = AV_NOPTS_VALUE;
2695 if (ist->next_dts == AV_NOPTS_VALUE)
2696 ist->next_dts = ist->dts;
2697 if (ist->next_pts == AV_NOPTS_VALUE)
2698 ist->next_pts = ist->pts;
2702 av_init_packet(&avpkt);
2710 if (pkt->dts != AV_NOPTS_VALUE) {
2711 ist->next_dts = ist->dts = av_rescale_q(pkt->dts, ist->st->time_base, AV_TIME_BASE_Q);
2712 if (ist->st->codec->codec_type != AVMEDIA_TYPE_VIDEO || !ist->decoding_needed)
2713 ist->next_pts = ist->pts = av_rescale_q(pkt->dts, ist->st->time_base, AV_TIME_BASE_Q);
2715 if(pkt->pts != AV_NOPTS_VALUE)
2716 pkt_pts = av_rescale_q(pkt->pts, ist->st->time_base, AV_TIME_BASE_Q);
2718 // while we have more to decode or while the decoder did output something on EOF
2719 while (ist->decoding_needed && (avpkt.size > 0 || (!pkt && got_output))) {
2723 ist->pts = ist->next_pts;
2724 ist->dts = ist->next_dts;
2726 if (avpkt.size && avpkt.size != pkt->size) {
2727 av_log(NULL, ist->showed_multi_packet_warning ? AV_LOG_VERBOSE : AV_LOG_WARNING,
2728 "Multiple frames in a packet from stream %d\n", pkt->stream_index);
2729 ist->showed_multi_packet_warning = 1;
2732 switch (ist->st->codec->codec_type) {
2733 case AVMEDIA_TYPE_AUDIO:
2734 ret = transcode_audio (ist, &avpkt, &got_output);
2736 case AVMEDIA_TYPE_VIDEO:
2737 ret = transcode_video (ist, &avpkt, &got_output, &pkt_pts);
2738 if (avpkt.duration) {
2739 duration = av_rescale_q(avpkt.duration, ist->st->time_base, AV_TIME_BASE_Q);
2740 } else if(ist->st->codec->time_base.num != 0 && ist->st->codec->time_base.den != 0) {
2741 int ticks= ist->st->parser ? ist->st->parser->repeat_pict+1 : ist->st->codec->ticks_per_frame;
2742 duration = ((int64_t)AV_TIME_BASE *
2743 ist->st->codec->time_base.num * ticks) /
2744 ist->st->codec->time_base.den;
2748 if(ist->dts != AV_NOPTS_VALUE && duration) {
2749 ist->next_dts += duration;
2751 ist->next_dts = AV_NOPTS_VALUE;
2754 ist->next_pts += duration; //FIXME the duration is not correct in some cases
2756 case AVMEDIA_TYPE_SUBTITLE:
2757 ret = transcode_subtitles(ist, &avpkt, &got_output);
2767 avpkt.pts= AV_NOPTS_VALUE;
2769 // touch data and size only if not EOF
2771 if(ist->st->codec->codec_type != AVMEDIA_TYPE_AUDIO)
2781 /* handle stream copy */
2782 if (!ist->decoding_needed) {
2783 rate_emu_sleep(ist);
2784 ist->dts = ist->next_dts;
2785 switch (ist->st->codec->codec_type) {
2786 case AVMEDIA_TYPE_AUDIO:
2787 ist->next_dts += ((int64_t)AV_TIME_BASE * ist->st->codec->frame_size) /
2788 ist->st->codec->sample_rate;
2790 case AVMEDIA_TYPE_VIDEO:
2791 if (pkt->duration) {
2792 ist->next_dts += av_rescale_q(pkt->duration, ist->st->time_base, AV_TIME_BASE_Q);
2793 } else if(ist->st->codec->time_base.num != 0) {
2794 int ticks= ist->st->parser ? ist->st->parser->repeat_pict + 1 : ist->st->codec->ticks_per_frame;
2795 ist->next_dts += ((int64_t)AV_TIME_BASE *
2796 ist->st->codec->time_base.num * ticks) /
2797 ist->st->codec->time_base.den;
2801 ist->pts = ist->dts;
2802 ist->next_pts = ist->next_dts;
2804 for (i = 0; pkt && i < nb_output_streams; i++) {
2805 OutputStream *ost = output_streams[i];
2807 if (!check_output_constraints(ist, ost) || ost->encoding_needed)
2810 do_streamcopy(ist, ost, pkt);
2816 static void print_sdp(void)
2820 AVFormatContext **avc = av_malloc(sizeof(*avc) * nb_output_files);
2824 for (i = 0; i < nb_output_files; i++)
2825 avc[i] = output_files[i]->ctx;
2827 av_sdp_create(avc, nb_output_files, sdp, sizeof(sdp));
2828 printf("SDP:\n%s\n", sdp);
2833 static int init_input_stream(int ist_index, char *error, int error_len)
2836 InputStream *ist = input_streams[ist_index];
2838 if (ist->decoding_needed) {
2839 AVCodec *codec = ist->dec;
2841 snprintf(error, error_len, "Decoder (codec %s) not found for input stream #%d:%d",
2842 avcodec_get_name(ist->st->codec->codec_id), ist->file_index, ist->st->index);
2843 return AVERROR(EINVAL);
2846 ist->dr1 = codec->capabilities & CODEC_CAP_DR1;
2847 if (codec->type == AVMEDIA_TYPE_VIDEO && ist->dr1) {
2848 ist->st->codec->get_buffer = codec_get_buffer;
2849 ist->st->codec->release_buffer = codec_release_buffer;
2850 ist->st->codec->opaque = ist;
2853 if (!av_dict_get(ist->opts, "threads", NULL, 0))
2854 av_dict_set(&ist->opts, "threads", "auto", 0);
2855 if (avcodec_open2(ist->st->codec, codec, &ist->opts) < 0) {
2856 snprintf(error, error_len, "Error while opening decoder for input stream #%d:%d",
2857 ist->file_index, ist->st->index);
2858 return AVERROR(EINVAL);
2860 assert_codec_experimental(ist->st->codec, 0);
2861 assert_avoptions(ist->opts);
2863 if (ist->st->codec->codec_type == AVMEDIA_TYPE_AUDIO) {
2864 for (i = 0; i < nb_output_streams; i++) {
2865 OutputStream *ost = output_streams[i];
2866 if (ost->source_index == ist_index) {
2867 if (!ist->st->codec->channel_layout || !ost->st->codec->channel_layout)
2868 get_default_channel_layouts(ost, ist);
2875 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;
2876 ist->next_pts = AV_NOPTS_VALUE;
2877 ist->next_dts = AV_NOPTS_VALUE;
2883 static InputStream *get_input_stream(OutputStream *ost)
2885 if (ost->source_index >= 0)
2886 return input_streams[ost->source_index];
2889 FilterGraph *fg = ost->filter->graph;
2892 for (i = 0; i < fg->nb_inputs; i++)
2893 if (fg->inputs[i]->ist->st->codec->codec_type == ost->st->codec->codec_type)
2894 return fg->inputs[i]->ist;
2900 static int transcode_init(void)
2902 int ret = 0, i, j, k;
2903 AVFormatContext *oc;
2904 AVCodecContext *codec, *icodec;
2910 /* init framerate emulation */
2911 for (i = 0; i < nb_input_files; i++) {
2912 InputFile *ifile = input_files[i];
2913 if (ifile->rate_emu)
2914 for (j = 0; j < ifile->nb_streams; j++)
2915 input_streams[j + ifile->ist_index]->start = av_gettime();
2918 /* output stream init */
2919 for (i = 0; i < nb_output_files; i++) {
2920 oc = output_files[i]->ctx;
2921 if (!oc->nb_streams && !(oc->oformat->flags & AVFMT_NOSTREAMS)) {
2922 av_dump_format(oc, i, oc->filename, 1);
2923 av_log(NULL, AV_LOG_ERROR, "Output file #%d does not contain any stream\n", i);
2924 return AVERROR(EINVAL);
2928 /* init complex filtergraphs */
2929 for (i = 0; i < nb_filtergraphs; i++)
2930 if ((ret = avfilter_graph_config(filtergraphs[i]->graph, NULL)) < 0)
2933 /* for each output stream, we compute the right encoding parameters */
2934 for (i = 0; i < nb_output_streams; i++) {
2935 ost = output_streams[i];
2936 oc = output_files[ost->file_index]->ctx;
2937 ist = get_input_stream(ost);
2939 if (ost->attachment_filename)
2942 codec = ost->st->codec;
2945 icodec = ist->st->codec;
2947 ost->st->disposition = ist->st->disposition;
2948 codec->bits_per_raw_sample = icodec->bits_per_raw_sample;
2949 codec->chroma_sample_location = icodec->chroma_sample_location;
2952 if (ost->stream_copy) {
2953 uint64_t extra_size = (uint64_t)icodec->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE;
2955 if (extra_size > INT_MAX) {
2956 return AVERROR(EINVAL);
2959 /* if stream_copy is selected, no need to decode or encode */
2960 codec->codec_id = icodec->codec_id;
2961 codec->codec_type = icodec->codec_type;
2963 if (!codec->codec_tag) {
2964 if (!oc->oformat->codec_tag ||
2965 av_codec_get_id (oc->oformat->codec_tag, icodec->codec_tag) == codec->codec_id ||
2966 av_codec_get_tag(oc->oformat->codec_tag, icodec->codec_id) <= 0)
2967 codec->codec_tag = icodec->codec_tag;
2970 codec->bit_rate = icodec->bit_rate;
2971 codec->rc_max_rate = icodec->rc_max_rate;
2972 codec->rc_buffer_size = icodec->rc_buffer_size;
2973 codec->field_order = icodec->field_order;
2974 codec->extradata = av_mallocz(extra_size);
2975 if (!codec->extradata) {
2976 return AVERROR(ENOMEM);
2978 memcpy(codec->extradata, icodec->extradata, icodec->extradata_size);
2979 codec->extradata_size= icodec->extradata_size;
2981 codec->time_base = ist->st->time_base;
2983 * Avi is a special case here because it supports variable fps but
2984 * having the fps and timebase differe significantly adds quite some
2987 if(!strcmp(oc->oformat->name, "avi")) {
2988 if ( copy_tb<0 && av_q2d(icodec->time_base)*icodec->ticks_per_frame > 2*av_q2d(ist->st->time_base)
2989 && av_q2d(ist->st->time_base) < 1.0/500
2991 codec->time_base = icodec->time_base;
2992 codec->time_base.num *= icodec->ticks_per_frame;
2993 codec->time_base.den *= 2;
2994 codec->ticks_per_frame = 2;
2996 } else if(!(oc->oformat->flags & AVFMT_VARIABLE_FPS)
2997 && strcmp(oc->oformat->name, "mov") && strcmp(oc->oformat->name, "mp4") && strcmp(oc->oformat->name, "3gp")
2998 && strcmp(oc->oformat->name, "3g2") && strcmp(oc->oformat->name, "psp") && strcmp(oc->oformat->name, "ipod")
3000 if( copy_tb<0 && av_q2d(icodec->time_base)*icodec->ticks_per_frame > av_q2d(ist->st->time_base)
3001 && av_q2d(ist->st->time_base) < 1.0/500
3003 codec->time_base = icodec->time_base;
3004 codec->time_base.num *= icodec->ticks_per_frame;
3007 av_reduce(&codec->time_base.num, &codec->time_base.den,
3008 codec->time_base.num, codec->time_base.den, INT_MAX);
3010 switch (codec->codec_type) {
3011 case AVMEDIA_TYPE_AUDIO:
3012 if (audio_volume != 256) {
3013 av_log(NULL, AV_LOG_FATAL, "-acodec copy and -vol are incompatible (frames are not decoded)\n");
3016 codec->channel_layout = icodec->channel_layout;
3017 codec->sample_rate = icodec->sample_rate;
3018 codec->channels = icodec->channels;
3019 codec->frame_size = icodec->frame_size;
3020 codec->audio_service_type = icodec->audio_service_type;
3021 codec->block_align = icodec->block_align;
3023 case AVMEDIA_TYPE_VIDEO:
3024 codec->pix_fmt = icodec->pix_fmt;
3025 codec->width = icodec->width;
3026 codec->height = icodec->height;
3027 codec->has_b_frames = icodec->has_b_frames;
3028 if (!codec->sample_aspect_ratio.num) {
3029 codec->sample_aspect_ratio =
3030 ost->st->sample_aspect_ratio =
3031 ist->st->sample_aspect_ratio.num ? ist->st->sample_aspect_ratio :
3032 ist->st->codec->sample_aspect_ratio.num ?
3033 ist->st->codec->sample_aspect_ratio : (AVRational){0, 1};
3035 ost->st->avg_frame_rate = ist->st->avg_frame_rate;
3037 case AVMEDIA_TYPE_SUBTITLE:
3038 codec->width = icodec->width;
3039 codec->height = icodec->height;
3041 case AVMEDIA_TYPE_DATA:
3042 case AVMEDIA_TYPE_ATTACHMENT:
3049 ost->enc = avcodec_find_encoder(codec->codec_id);
3051 /* should only happen when a default codec is not present. */
3052 snprintf(error, sizeof(error), "Encoder (codec %s) not found for output stream #%d:%d",
3053 avcodec_get_name(ost->st->codec->codec_id), ost->file_index, ost->index);
3054 ret = AVERROR(EINVAL);
3059 ist->decoding_needed = 1;
3060 ost->encoding_needed = 1;
3062 switch (codec->codec_type) {
3063 case AVMEDIA_TYPE_AUDIO:
3064 ost->fifo = av_fifo_alloc(1024);
3066 return AVERROR(ENOMEM);
3068 if (!codec->sample_rate)
3069 codec->sample_rate = icodec->sample_rate;
3070 choose_sample_rate(ost->st, ost->enc);
3071 codec->time_base = (AVRational){ 1, codec->sample_rate };
3073 if (codec->sample_fmt == AV_SAMPLE_FMT_NONE)
3074 codec->sample_fmt = icodec->sample_fmt;
3075 choose_sample_fmt(ost->st, ost->enc);
3077 if (ost->audio_channels_mapped) {
3078 /* the requested output channel is set to the number of
3079 * -map_channel only if no -ac are specified */
3080 if (!codec->channels) {
3081 codec->channels = ost->audio_channels_mapped;
3082 codec->channel_layout = av_get_default_channel_layout(codec->channels);
3083 if (!codec->channel_layout) {
3084 av_log(NULL, AV_LOG_FATAL, "Unable to find an appropriate channel layout for requested number of channel\n");
3088 /* fill unused channel mapping with -1 (which means a muted
3089 * channel in case the number of output channels is bigger
3090 * than the number of mapped channel) */
3091 for (j = ost->audio_channels_mapped; j < FF_ARRAY_ELEMS(ost->audio_channels_map); j++)
3092 ost->audio_channels_map[j] = -1;
3093 } else if (!codec->channels) {
3094 codec->channels = icodec->channels;
3095 codec->channel_layout = icodec->channel_layout;
3097 if (av_get_channel_layout_nb_channels(codec->channel_layout) != codec->channels)
3098 codec->channel_layout = 0;
3100 ost->audio_resample = codec->sample_rate != icodec->sample_rate || audio_sync_method > 1;
3101 ost->audio_resample |= codec->sample_fmt != icodec->sample_fmt
3102 || codec->channel_layout != icodec->channel_layout;
3103 icodec->request_channels = codec->channels;
3104 ost->resample_sample_fmt = icodec->sample_fmt;
3105 ost->resample_sample_rate = icodec->sample_rate;
3106 ost->resample_channels = icodec->channels;
3108 case AVMEDIA_TYPE_VIDEO:
3111 fg = init_simple_filtergraph(ist, ost);
3112 if (configure_video_filters(fg)) {
3113 av_log(NULL, AV_LOG_FATAL, "Error opening filters!\n");
3118 if (ist && !ost->frame_rate.num)
3119 ost->frame_rate = ist->st->r_frame_rate.num ? ist->st->r_frame_rate : (AVRational) { 25, 1 };
3120 if (ost->enc && ost->enc->supported_framerates && !ost->force_fps) {
3121 int idx = av_find_nearest_q_idx(ost->frame_rate, ost->enc->supported_framerates);
3122 ost->frame_rate = ost->enc->supported_framerates[idx];
3124 codec->time_base = (AVRational){ost->frame_rate.den, ost->frame_rate.num};
3125 if ( av_q2d(codec->time_base) < 0.001 && video_sync_method != VSYNC_PASSTHROUGH
3126 && (video_sync_method == VSYNC_CFR || (video_sync_method == VSYNC_AUTO && !(oc->oformat->flags & AVFMT_VARIABLE_FPS)))){
3127 av_log(oc, AV_LOG_WARNING, "Frame rate very high for a muxer not efficiently supporting it.\n"
3128 "Please consider specifying a lower framerate, a different muxer or -vsync 2\n");
3130 for (j = 0; j < ost->forced_kf_count; j++)
3131 ost->forced_kf_pts[j] = av_rescale_q(ost->forced_kf_pts[j],
3135 codec->width = ost->filter->filter->inputs[0]->w;
3136 codec->height = ost->filter->filter->inputs[0]->h;
3137 codec->sample_aspect_ratio = ost->st->sample_aspect_ratio =
3138 ost->frame_aspect_ratio ? // overridden by the -aspect cli option
3139 av_d2q(ost->frame_aspect_ratio * codec->height/codec->width, 255) :
3140 ost->filter->filter->inputs[0]->sample_aspect_ratio;
3141 codec->pix_fmt = ost->filter->filter->inputs[0]->format;
3143 if (codec->width != icodec->width ||
3144 codec->height != icodec->height ||
3145 codec->pix_fmt != icodec->pix_fmt) {
3146 codec->bits_per_raw_sample = frame_bits_per_raw_sample;
3150 case AVMEDIA_TYPE_SUBTITLE:
3151 codec->time_base = (AVRational){1, 1000};
3158 if (codec->flags & (CODEC_FLAG_PASS1 | CODEC_FLAG_PASS2)) {
3159 char logfilename[1024];
3162 snprintf(logfilename, sizeof(logfilename), "%s-%d.log",
3163 pass_logfilename_prefix ? pass_logfilename_prefix : DEFAULT_PASS_LOGFILENAME_PREFIX,
3165 if (!strcmp(ost->enc->name, "libx264")) {
3166 av_dict_set(&ost->opts, "stats", logfilename, AV_DICT_DONT_OVERWRITE);
3168 if (codec->flags & CODEC_FLAG_PASS2) {
3170 size_t logbuffer_size;
3171 if (cmdutils_read_file(logfilename, &logbuffer, &logbuffer_size) < 0) {
3172 av_log(NULL, AV_LOG_FATAL, "Error reading log file '%s' for pass-2 encoding\n",
3176 codec->stats_in = logbuffer;
3178 if (codec->flags & CODEC_FLAG_PASS1) {
3179 f = fopen(logfilename, "wb");
3181 av_log(NULL, AV_LOG_FATAL, "Cannot write log file '%s' for pass-1 encoding: %s\n",
3182 logfilename, strerror(errno));
3192 /* open each encoder */
3193 for (i = 0; i < nb_output_streams; i++) {
3194 ost = output_streams[i];
3195 if (ost->encoding_needed) {
3196 AVCodec *codec = ost->enc;
3197 AVCodecContext *dec = NULL;
3199 if ((ist = get_input_stream(ost)))
3200 dec = ist->st->codec;
3201 if (dec && dec->subtitle_header) {
3202 ost->st->codec->subtitle_header = av_malloc(dec->subtitle_header_size);
3203 if (!ost->st->codec->subtitle_header) {
3204 ret = AVERROR(ENOMEM);
3207 memcpy(ost->st->codec->subtitle_header, dec->subtitle_header, dec->subtitle_header_size);
3208 ost->st->codec->subtitle_header_size = dec->subtitle_header_size;
3210 if (!av_dict_get(ost->opts, "threads", NULL, 0))
3211 av_dict_set(&ost->opts, "threads", "auto", 0);
3212 if (avcodec_open2(ost->st->codec, codec, &ost->opts) < 0) {
3213 snprintf(error, sizeof(error), "Error while opening encoder for output stream #%d:%d - maybe incorrect parameters such as bit_rate, rate, width or height",
3214 ost->file_index, ost->index);
3215 ret = AVERROR(EINVAL);
3218 assert_codec_experimental(ost->st->codec, 1);
3219 assert_avoptions(ost->opts);
3220 if (ost->st->codec->bit_rate && ost->st->codec->bit_rate < 1000)
3221 av_log(NULL, AV_LOG_WARNING, "The bitrate parameter is set too low."
3222 " It takes bits/s as argument, not kbits/s\n");
3223 extra_size += ost->st->codec->extradata_size;
3225 if (ost->st->codec->me_threshold)
3226 input_streams[ost->source_index]->st->codec->debug |= FF_DEBUG_MV;
3230 /* init input streams */
3231 for (i = 0; i < nb_input_streams; i++)
3232 if ((ret = init_input_stream(i, error, sizeof(error))) < 0)
3235 /* discard unused programs */
3236 for (i = 0; i < nb_input_files; i++) {
3237 InputFile *ifile = input_files[i];
3238 for (j = 0; j < ifile->ctx->nb_programs; j++) {
3239 AVProgram *p = ifile->ctx->programs[j];
3240 int discard = AVDISCARD_ALL;
3242 for (k = 0; k < p->nb_stream_indexes; k++)
3243 if (!input_streams[ifile->ist_index + p->stream_index[k]]->discard) {
3244 discard = AVDISCARD_DEFAULT;
3247 p->discard = discard;
3251 /* open files and write file headers */
3252 for (i = 0; i < nb_output_files; i++) {
3253 oc = output_files[i]->ctx;
3254 oc->interrupt_callback = int_cb;
3255 if (avformat_write_header(oc, &output_files[i]->opts) < 0) {
3256 snprintf(error, sizeof(error), "Could not write header for output file #%d (incorrect codec parameters ?)", i);
3257 ret = AVERROR(EINVAL);
3260 // assert_avoptions(output_files[i]->opts);
3261 if (strcmp(oc->oformat->name, "rtp")) {
3267 /* dump the file output parameters - cannot be done before in case
3269 for (i = 0; i < nb_output_files; i++) {
3270 av_dump_format(output_files[i]->ctx, i, output_files[i]->ctx->filename, 1);
3273 /* dump the stream mapping */
3274 av_log(NULL, AV_LOG_INFO, "Stream mapping:\n");
3275 for (i = 0; i < nb_input_streams; i++) {
3276 ist = input_streams[i];
3278 for (j = 0; j < ist->nb_filters; j++) {
3279 AVFilterLink *link = ist->filters[j]->filter->outputs[0];
3280 if (ist->filters[j]->graph->graph_desc) {
3281 av_log(NULL, AV_LOG_INFO, " Stream #%d:%d (%s) -> %s",
3282 ist->file_index, ist->st->index, ist->dec ? ist->dec->name : "?",
3283 link->dst->filter->name);
3284 if (link->dst->input_count > 1)
3285 av_log(NULL, AV_LOG_INFO, ":%s", link->dstpad->name);
3286 if (nb_filtergraphs > 1)
3287 av_log(NULL, AV_LOG_INFO, " (graph %d)", ist->filters[j]->graph->index);
3288 av_log(NULL, AV_LOG_INFO, "\n");
3293 for (i = 0; i < nb_output_streams; i++) {
3294 ost = output_streams[i];
3296 if (ost->attachment_filename) {
3297 /* an attached file */
3298 av_log(NULL, AV_LOG_INFO, " File %s -> Stream #%d:%d\n",
3299 ost->attachment_filename, ost->file_index, ost->index);
3303 if (ost->filter && ost->filter->graph->graph_desc) {
3304 /* output from a complex graph */
3305 AVFilterLink *link = ost->filter->filter->inputs[0];
3306 av_log(NULL, AV_LOG_INFO, " %s", link->src->filter->name);
3307 if (link->src->output_count > 1)
3308 av_log(NULL, AV_LOG_INFO, ":%s", link->srcpad->name);
3309 if (nb_filtergraphs > 1)
3310 av_log(NULL, AV_LOG_INFO, " (graph %d)", ost->filter->graph->index);
3312 av_log(NULL, AV_LOG_INFO, " -> Stream #%d:%d (%s)\n", ost->file_index,
3313 ost->index, ost->enc ? ost->enc->name : "?");
3317 av_log(NULL, AV_LOG_INFO, " Stream #%d:%d -> #%d:%d",
3318 input_streams[ost->source_index]->file_index,
3319 input_streams[ost->source_index]->st->index,
3322 if (ost->audio_channels_mapped) {
3323 av_log(NULL, AV_LOG_INFO, " [ch:");
3324 for (j = 0; j < ost->audio_channels_mapped; j++)
3325 if (ost->audio_channels_map[j] == -1)
3326 av_log(NULL, AV_LOG_INFO, " M");
3328 av_log(NULL, AV_LOG_INFO, " %d", ost->audio_channels_map[j]);
3329 av_log(NULL, AV_LOG_INFO, "]");
3331 if (ost->sync_ist != input_streams[ost->source_index])
3332 av_log(NULL, AV_LOG_INFO, " [sync #%d:%d]",
3333 ost->sync_ist->file_index,
3334 ost->sync_ist->st->index);
3335 if (ost->stream_copy)
3336 av_log(NULL, AV_LOG_INFO, " (copy)");
3338 av_log(NULL, AV_LOG_INFO, " (%s -> %s)", input_streams[ost->source_index]->dec ?
3339 input_streams[ost->source_index]->dec->name : "?",
3340 ost->enc ? ost->enc->name : "?");
3341 av_log(NULL, AV_LOG_INFO, "\n");
3345 av_log(NULL, AV_LOG_ERROR, "%s\n", error);
3357 * The following code is the main loop of the file converter
3359 static int transcode(void)
3362 AVFormatContext *is, *os;
3366 int no_packet_count = 0;
3367 int64_t timer_start;
3370 if (!(no_packet = av_mallocz(nb_input_files)))
3373 ret = transcode_init();
3378 av_log(NULL, AV_LOG_INFO, "Press [q] to stop, [?] for help\n");
3381 timer_start = av_gettime();
3383 for (; received_sigterm == 0;) {
3384 int file_index, ist_index, past_recording_time = 1;
3387 int64_t cur_time= av_gettime();
3389 ipts_min = INT64_MAX;
3390 /* if 'q' pressed, exits */
3392 static int64_t last_time;
3393 if (received_nb_signals)
3395 /* read_key() returns 0 on EOF */
3396 if(cur_time - last_time >= 100000 && !run_as_daemon){
3398 last_time = cur_time;
3403 if (key == '+') av_log_set_level(av_log_get_level()+10);
3404 if (key == '-') av_log_set_level(av_log_get_level()-10);
3405 if (key == 's') qp_hist ^= 1;
3408 do_hex_dump = do_pkt_dump = 0;
3409 } else if(do_pkt_dump){
3413 av_log_set_level(AV_LOG_DEBUG);
3415 if (key == 'c' || key == 'C'){
3416 char buf[4096], target[64], command[256], arg[256] = {0};
3419 fprintf(stderr, "\nEnter command: <target> <time> <command>[ <argument>]\n");
3421 while ((k = read_key()) != '\n' && k != '\r' && i < sizeof(buf)-1)
3426 (n = sscanf(buf, "%63[^ ] %lf %255[^ ] %255[^\n]", target, &time, command, arg)) >= 3) {
3427 av_log(NULL, AV_LOG_DEBUG, "Processing command target:%s time:%f command:%s arg:%s",
3428 target, time, command, arg);
3429 for (i = 0; i < nb_filtergraphs; i++) {
3430 FilterGraph *fg = filtergraphs[i];
3433 ret = avfilter_graph_send_command(fg->graph, target, command, arg, buf, sizeof(buf),
3434 key == 'c' ? AVFILTER_CMD_FLAG_ONE : 0);
3435 fprintf(stderr, "Command reply for stream %d: ret:%d res:%s\n", i, ret, buf);
3437 ret = avfilter_graph_queue_command(fg->graph, target, command, arg, 0, time);
3442 av_log(NULL, AV_LOG_ERROR,
3443 "Parse error, at least 3 arguments were expected, "
3444 "only %d given in string '%s'\n", n, buf);
3447 if (key == 'd' || key == 'D'){
3450 debug = input_streams[0]->st->codec->debug<<1;
3451 if(!debug) debug = 1;
3452 while(debug & (FF_DEBUG_DCT_COEFF|FF_DEBUG_VIS_QP|FF_DEBUG_VIS_MB_TYPE)) //unsupported, would just crash
3455 if(scanf("%d", &debug)!=1)
3456 fprintf(stderr,"error parsing debug value\n");
3457 for(i=0;i<nb_input_streams;i++) {
3458 input_streams[i]->st->codec->debug = debug;
3460 for(i=0;i<nb_output_streams;i++) {
3461 ost = output_streams[i];
3462 ost->st->codec->debug = debug;
3464 if(debug) av_log_set_level(AV_LOG_DEBUG);
3465 fprintf(stderr,"debug=%d\n", debug);
3468 fprintf(stderr, "key function\n"
3469 "? show this help\n"
3470 "+ increase verbosity\n"
3471 "- decrease verbosity\n"
3472 "c Send command to filtergraph\n"
3473 "D cycle through available debug modes\n"
3474 "h dump packets/hex press to cycle through the 3 states\n"
3476 "s Show QP histogram\n"
3481 /* check if there's any stream where output is still needed */
3482 for (i = 0; i < nb_output_streams; i++) {
3484 ost = output_streams[i];
3485 of = output_files[ost->file_index];
3486 os = output_files[ost->file_index]->ctx;
3487 if (ost->is_past_recording_time ||
3488 (os->pb && avio_tell(os->pb) >= of->limit_filesize))
3490 if (ost->frame_number >= ost->max_frames) {
3492 for (j = 0; j < of->ctx->nb_streams; j++)
3493 output_streams[of->ost_index + j]->is_past_recording_time = 1;
3496 past_recording_time = 0;
3498 if (past_recording_time)
3501 /* select the stream that we must read now by looking at the
3502 smallest output pts */
3504 for (i = 0; i < nb_input_streams; i++) {
3506 ist = input_streams[i];
3508 if (ist->discard || no_packet[ist->file_index])
3510 if (!input_files[ist->file_index]->eof_reached) {
3511 if (ipts < ipts_min) {
3513 file_index = ist->file_index;
3517 /* if none, if is finished */
3518 if (file_index < 0) {
3519 if (no_packet_count) {
3520 no_packet_count = 0;
3521 memset(no_packet, 0, nb_input_files);
3528 /* read a frame from it and output it in the fifo */
3529 is = input_files[file_index]->ctx;
3530 ret = av_read_frame(is, &pkt);
3531 if (ret == AVERROR(EAGAIN)) {
3532 no_packet[file_index] = 1;
3537 input_files[file_index]->eof_reached = 1;
3539 for (i = 0; i < input_files[file_index]->nb_streams; i++) {
3540 ist = input_streams[input_files[file_index]->ist_index + i];
3541 if (ist->decoding_needed)
3542 output_packet(ist, NULL);
3551 no_packet_count = 0;
3552 memset(no_packet, 0, nb_input_files);
3555 av_pkt_dump_log2(NULL, AV_LOG_DEBUG, &pkt, do_hex_dump,
3556 is->streams[pkt.stream_index]);
3558 /* the following test is needed in case new streams appear
3559 dynamically in stream : we ignore them */
3560 if (pkt.stream_index >= input_files[file_index]->nb_streams)
3561 goto discard_packet;
3562 ist_index = input_files[file_index]->ist_index + pkt.stream_index;
3563 ist = input_streams[ist_index];
3565 goto discard_packet;
3567 if (pkt.dts != AV_NOPTS_VALUE)
3568 pkt.dts += av_rescale_q(input_files[ist->file_index]->ts_offset, AV_TIME_BASE_Q, ist->st->time_base);
3569 if (pkt.pts != AV_NOPTS_VALUE)
3570 pkt.pts += av_rescale_q(input_files[ist->file_index]->ts_offset, AV_TIME_BASE_Q, ist->st->time_base);
3572 if (pkt.pts != AV_NOPTS_VALUE)
3573 pkt.pts *= ist->ts_scale;
3574 if (pkt.dts != AV_NOPTS_VALUE)
3575 pkt.dts *= ist->ts_scale;
3578 av_log(NULL, AV_LOG_INFO, "demuxer -> ist_index:%d type:%s "
3579 "next_pts:%s next_pts_time:%s pkt_pts:%s pkt_pts_time:%s pkt_dts:%s pkt_dts_time:%s off:%"PRId64"\n",
3580 ist_index, av_get_media_type_string(ist->st->codec->codec_type),
3581 av_ts2str(ist->next_pts), av_ts2timestr(ist->next_pts, &ist->st->time_base),
3582 av_ts2str(pkt.pts), av_ts2timestr(pkt.pts, &ist->st->time_base),
3583 av_ts2str(pkt.dts), av_ts2timestr(pkt.dts, &ist->st->time_base),
3584 input_files[ist->file_index]->ts_offset);
3587 if (pkt.dts != AV_NOPTS_VALUE && ist->next_dts != AV_NOPTS_VALUE && !copy_ts) {
3588 int64_t pkt_dts = av_rescale_q(pkt.dts, ist->st->time_base, AV_TIME_BASE_Q);
3589 int64_t delta = pkt_dts - ist->next_dts;
3590 if (is->iformat->flags & AVFMT_TS_DISCONT) {
3591 if(delta < -1LL*dts_delta_threshold*AV_TIME_BASE ||
3592 (delta > 1LL*dts_delta_threshold*AV_TIME_BASE &&
3593 ist->st->codec->codec_type != AVMEDIA_TYPE_SUBTITLE) ||
3594 pkt_dts+1<ist->pts){
3595 input_files[ist->file_index]->ts_offset -= delta;
3596 av_log(NULL, AV_LOG_DEBUG,
3597 "timestamp discontinuity %"PRId64", new offset= %"PRId64"\n",
3598 delta, input_files[ist->file_index]->ts_offset);
3599 pkt.dts-= av_rescale_q(delta, AV_TIME_BASE_Q, ist->st->time_base);
3600 if (pkt.pts != AV_NOPTS_VALUE)
3601 pkt.pts-= av_rescale_q(delta, AV_TIME_BASE_Q, ist->st->time_base);
3604 if ( delta < -1LL*dts_error_threshold*AV_TIME_BASE ||
3605 (delta > 1LL*dts_error_threshold*AV_TIME_BASE && ist->st->codec->codec_type != AVMEDIA_TYPE_SUBTITLE) ||
3606 pkt_dts+1<ist->pts){
3607 av_log(NULL, AV_LOG_WARNING, "DTS %"PRId64", next:%"PRId64" st:%d invalid dropping\n", pkt.dts, ist->next_dts, pkt.stream_index);
3608 pkt.dts = AV_NOPTS_VALUE;
3610 if (pkt.pts != AV_NOPTS_VALUE){
3611 int64_t pkt_pts = av_rescale_q(pkt.pts, ist->st->time_base, AV_TIME_BASE_Q);
3612 delta = pkt_pts - ist->next_dts;
3613 if ( delta < -1LL*dts_error_threshold*AV_TIME_BASE ||
3614 (delta > 1LL*dts_error_threshold*AV_TIME_BASE && ist->st->codec->codec_type != AVMEDIA_TYPE_SUBTITLE) ||
3615 pkt_pts+1<ist->pts) {
3616 av_log(NULL, AV_LOG_WARNING, "PTS %"PRId64", next:%"PRId64" invalid dropping st:%d\n", pkt.pts, ist->next_dts, pkt.stream_index);
3617 pkt.pts = AV_NOPTS_VALUE;
3623 // fprintf(stderr,"read #%d.%d size=%d\n", ist->file_index, ist->st->index, pkt.size);
3624 if (output_packet(ist, &pkt) < 0 ||
3625 ((ret = poll_filters()) < 0 && ret != AVERROR_EOF)) {
3626 av_log(NULL, AV_LOG_ERROR, "Error while decoding stream #%d:%d\n",
3627 ist->file_index, ist->st->index);