3 * Copyright (c) 2000-2011 The libav developers.
5 * This file is part of Libav.
7 * Libav is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU Lesser General Public
9 * License as published by the Free Software Foundation; either
10 * version 2.1 of the License, or (at your option) any later version.
12 * Libav is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * Lesser General Public License for more details.
17 * You should have received a copy of the GNU Lesser General Public
18 * License along with Libav; if not, write to the Free Software
19 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
31 #include "libavformat/avformat.h"
32 #include "libavdevice/avdevice.h"
33 #include "libswscale/swscale.h"
34 #include "libavutil/opt.h"
35 #include "libavcodec/audioconvert.h"
36 #include "libavutil/audioconvert.h"
37 #include "libavutil/parseutils.h"
38 #include "libavutil/samplefmt.h"
39 #include "libavutil/colorspace.h"
40 #include "libavutil/fifo.h"
41 #include "libavutil/intreadwrite.h"
42 #include "libavutil/dict.h"
43 #include "libavutil/mathematics.h"
44 #include "libavutil/pixdesc.h"
45 #include "libavutil/avstring.h"
46 #include "libavutil/libm.h"
47 #include "libavutil/imgutils.h"
48 #include "libavformat/os_support.h"
51 # include "libavfilter/avfilter.h"
52 # include "libavfilter/avfiltergraph.h"
53 # include "libavfilter/vsrc_buffer.h"
56 #if HAVE_SYS_RESOURCE_H
57 #include <sys/types.h>
59 #include <sys/resource.h>
60 #elif HAVE_GETPROCESSTIMES
63 #if HAVE_GETPROCESSMEMORYINFO
69 #include <sys/select.h>
76 #include "libavutil/avassert.h"
78 const char program_name
[] = "avconv";
79 const int program_birth_year
= 2000;
81 /* select an input stream for an output stream */
82 typedef struct StreamMap
{
83 int disabled
; /** 1 is this mapping is disabled by a negative map */
87 int sync_stream_index
;
91 * select an input file for an output file
93 typedef struct MetadataMap
{
94 int file
; ///< file index
95 char type
; ///< type of metadata to copy -- (g)lobal, (s)tream, (c)hapter or (p)rogram
96 int index
; ///< stream/chapter/program number
99 static const OptionDef options
[];
101 static int video_discard
= 0;
102 static int same_quant
= 0;
103 static int do_deinterlace
= 0;
104 static int intra_dc_precision
= 8;
105 static int qp_hist
= 0;
107 static int file_overwrite
= 0;
108 static int do_benchmark
= 0;
109 static int do_hex_dump
= 0;
110 static int do_pkt_dump
= 0;
111 static int do_pass
= 0;
112 static char *pass_logfilename_prefix
= NULL
;
113 static int video_sync_method
= -1;
114 static int audio_sync_method
= 0;
115 static float audio_drift_threshold
= 0.1;
116 static int copy_ts
= 0;
117 static int copy_tb
= 1;
118 static int opt_shortest
= 0;
119 static char *vstats_filename
;
120 static FILE *vstats_file
;
122 static int audio_volume
= 256;
124 static int exit_on_error
= 0;
125 static int using_stdin
= 0;
126 static int64_t video_size
= 0;
127 static int64_t audio_size
= 0;
128 static int64_t extra_size
= 0;
129 static int nb_frames_dup
= 0;
130 static int nb_frames_drop
= 0;
131 static int input_sync
;
133 static float dts_delta_threshold
= 10;
135 static int print_stats
= 1;
137 static uint8_t *audio_buf
;
138 static uint8_t *audio_out
;
139 static unsigned int allocated_audio_out_size
, allocated_audio_buf_size
;
141 #define DEFAULT_PASS_LOGFILENAME_PREFIX "av2pass"
143 typedef struct FrameBuffer
{
149 enum PixelFormat pix_fmt
;
152 struct InputStream
*ist
;
153 struct FrameBuffer
*next
;
156 typedef struct InputStream
{
159 int discard
; /* true if stream data should be discarded */
160 int decoding_needed
; /* true if the packets must be decoded in 'raw_fifo' */
162 AVFrame
*decoded_frame
;
163 AVFrame
*filtered_frame
;
165 int64_t start
; /* time when read started */
166 int64_t next_pts
; /* synthetic pts for cases where pkt.pts
168 int64_t pts
; /* current pts */
169 PtsCorrectionContext pts_ctx
;
171 int is_start
; /* is 1 at the start and after a discontinuity */
172 int showed_multi_packet_warning
;
175 /* a pool of free buffers for decoded data */
176 FrameBuffer
*buffer_pool
;
179 typedef struct InputFile
{
180 AVFormatContext
*ctx
;
181 int eof_reached
; /* true if eof reached */
182 int ist_index
; /* index of first stream in ist_table */
183 int buffer_size
; /* current total buffer size */
185 int nb_streams
; /* number of stream that avconv is aware of; may be different
186 from ctx.nb_streams if new streams appear during av_read_frame() */
190 typedef struct OutputStream
{
191 int file_index
; /* file index */
192 int index
; /* stream index in the output file */
193 int source_index
; /* InputStream index */
194 AVStream
*st
; /* stream in the output file */
195 int encoding_needed
; /* true if encoding needed for this stream */
197 /* input pts and corresponding output pts
199 //double sync_ipts; /* dts from the AVPacket of the demuxer in second units */
200 struct InputStream
*sync_ist
; /* input stream to sync against */
201 int64_t sync_opts
; /* output frame counter, could be changed to some true timestamp */ //FIXME look at frame_number
202 AVBitStreamFilterContext
*bitstream_filters
;
208 AVFrame pict_tmp
; /* temporary image for resampling */
209 struct SwsContext
*img_resample_ctx
; /* for image resampling */
212 int resample_pix_fmt
;
213 AVRational frame_rate
;
217 float frame_aspect_ratio
;
219 /* forced key frames */
220 int64_t *forced_kf_pts
;
226 ReSampleContext
*resample
; /* for audio resampling */
227 int resample_sample_fmt
;
228 int resample_channels
;
229 int resample_sample_rate
;
231 AVAudioConvert
*reformat_ctx
;
232 AVFifoBuffer
*fifo
; /* for compression: one audio fifo per codec */
236 AVFilterContext
*output_video_filter
;
237 AVFilterContext
*input_video_filter
;
238 AVFilterBufferRef
*picref
;
240 AVFilterGraph
*graph
;
245 int is_past_recording_time
;
247 const char *attachment_filename
;
248 int copy_initial_nonkeyframes
;
252 typedef struct OutputFile
{
253 AVFormatContext
*ctx
;
255 int ost_index
; /* index of the first stream in output_streams */
256 int64_t recording_time
; /* desired length of the resulting file in microseconds */
257 int64_t start_time
; /* start time in microseconds */
258 uint64_t limit_filesize
;
261 static InputStream
*input_streams
= NULL
;
262 static int nb_input_streams
= 0;
263 static InputFile
*input_files
= NULL
;
264 static int nb_input_files
= 0;
266 static OutputStream
*output_streams
= NULL
;
267 static int nb_output_streams
= 0;
268 static OutputFile
*output_files
= NULL
;
269 static int nb_output_files
= 0;
271 typedef struct OptionsContext
{
272 /* input/output options */
276 SpecifierOpt
*codec_names
;
278 SpecifierOpt
*audio_channels
;
279 int nb_audio_channels
;
280 SpecifierOpt
*audio_sample_rate
;
281 int nb_audio_sample_rate
;
282 SpecifierOpt
*frame_rates
;
284 SpecifierOpt
*frame_sizes
;
286 SpecifierOpt
*frame_pix_fmts
;
287 int nb_frame_pix_fmts
;
290 int64_t input_ts_offset
;
293 SpecifierOpt
*ts_scale
;
295 SpecifierOpt
*dump_attachment
;
296 int nb_dump_attachment
;
299 StreamMap
*stream_maps
;
301 /* first item specifies output metadata, second is input */
302 MetadataMap (*meta_data_maps
)[2];
303 int nb_meta_data_maps
;
304 int metadata_global_manual
;
305 int metadata_streams_manual
;
306 int metadata_chapters_manual
;
307 const char **attachments
;
310 int chapters_input_file
;
312 int64_t recording_time
;
313 uint64_t limit_filesize
;
319 int subtitle_disable
;
322 /* indexed by output file stream index */
326 SpecifierOpt
*metadata
;
328 SpecifierOpt
*max_frames
;
330 SpecifierOpt
*bitstream_filters
;
331 int nb_bitstream_filters
;
332 SpecifierOpt
*codec_tags
;
334 SpecifierOpt
*sample_fmts
;
336 SpecifierOpt
*qscale
;
338 SpecifierOpt
*forced_key_frames
;
339 int nb_forced_key_frames
;
340 SpecifierOpt
*force_fps
;
342 SpecifierOpt
*frame_aspect_ratios
;
343 int nb_frame_aspect_ratios
;
344 SpecifierOpt
*rc_overrides
;
346 SpecifierOpt
*intra_matrices
;
347 int nb_intra_matrices
;
348 SpecifierOpt
*inter_matrices
;
349 int nb_inter_matrices
;
350 SpecifierOpt
*top_field_first
;
351 int nb_top_field_first
;
352 SpecifierOpt
*metadata_map
;
354 SpecifierOpt
*presets
;
356 SpecifierOpt
*copy_initial_nonkeyframes
;
357 int nb_copy_initial_nonkeyframes
;
359 SpecifierOpt
*filters
;
364 #define MATCH_PER_STREAM_OPT(name, type, outvar, fmtctx, st)\
367 for (i = 0; i < o->nb_ ## name; i++) {\
368 char *spec = o->name[i].specifier;\
369 if ((ret = check_stream_specifier(fmtctx, st, spec)) > 0)\
370 outvar = o->name[i].u.type;\
376 static void reset_options(OptionsContext
*o
)
378 const OptionDef
*po
= options
;
380 /* all OPT_SPEC and OPT_STRING can be freed in generic way */
382 void *dst
= (uint8_t*)o
+ po
->u
.off
;
384 if (po
->flags
& OPT_SPEC
) {
385 SpecifierOpt
**so
= dst
;
386 int i
, *count
= (int*)(so
+ 1);
387 for (i
= 0; i
< *count
; i
++) {
388 av_freep(&(*so
)[i
].specifier
);
389 if (po
->flags
& OPT_STRING
)
390 av_freep(&(*so
)[i
].u
.str
);
394 } else if (po
->flags
& OPT_OFFSET
&& po
->flags
& OPT_STRING
)
399 av_freep(&o
->stream_maps
);
400 av_freep(&o
->meta_data_maps
);
401 av_freep(&o
->streamid_map
);
403 memset(o
, 0, sizeof(*o
));
405 o
->mux_max_delay
= 0.7;
406 o
->recording_time
= INT64_MAX
;
407 o
->limit_filesize
= UINT64_MAX
;
408 o
->chapters_input_file
= INT_MAX
;
414 static int alloc_buffer(InputStream
*ist
, FrameBuffer
**pbuf
)
416 AVCodecContext
*s
= ist
->st
->codec
;
417 FrameBuffer
*buf
= av_mallocz(sizeof(*buf
));
419 const int pixel_size
= av_pix_fmt_descriptors
[s
->pix_fmt
].comp
[0].step_minus1
+1;
420 int h_chroma_shift
, v_chroma_shift
;
421 int edge
= 32; // XXX should be avcodec_get_edge_width(), but that fails on svq1
422 int w
= s
->width
, h
= s
->height
;
425 return AVERROR(ENOMEM
);
427 if (!(s
->flags
& CODEC_FLAG_EMU_EDGE
)) {
432 avcodec_align_dimensions(s
, &w
, &h
);
433 if ((ret
= av_image_alloc(buf
->base
, buf
->linesize
, w
, h
,
434 s
->pix_fmt
, 32)) < 0) {
438 /* XXX this shouldn't be needed, but some tests break without this line
439 * those decoders are buggy and need to be fixed.
440 * the following tests fail:
441 * bethsoft-vid, cdgraphics, ansi, aasc, fraps-v1, qtrle-1bit
443 memset(buf
->base
[0], 128, ret
);
445 avcodec_get_chroma_sub_sample(s
->pix_fmt
, &h_chroma_shift
, &v_chroma_shift
);
446 for (int i
= 0; i
< FF_ARRAY_ELEMS(buf
->data
); i
++) {
447 const int h_shift
= i
==0 ?
0 : h_chroma_shift
;
448 const int v_shift
= i
==0 ?
0 : v_chroma_shift
;
449 if (s
->flags
& CODEC_FLAG_EMU_EDGE
)
450 buf
->data
[i
] = buf
->base
[i
];
452 buf
->data
[i
] = buf
->base
[i
] +
453 FFALIGN((buf
->linesize
[i
]*edge
>> v_shift
) +
454 (pixel_size
*edge
>> h_shift
), 32);
458 buf
->pix_fmt
= s
->pix_fmt
;
465 static void free_buffer_pool(InputStream
*ist
)
467 FrameBuffer
*buf
= ist
->buffer_pool
;
469 ist
->buffer_pool
= buf
->next
;
470 av_freep(&buf
->base
[0]);
472 buf
= ist
->buffer_pool
;
476 static void unref_buffer(InputStream
*ist
, FrameBuffer
*buf
)
478 av_assert0(buf
->refcount
);
480 if (!buf
->refcount
) {
481 buf
->next
= ist
->buffer_pool
;
482 ist
->buffer_pool
= buf
;
486 static int codec_get_buffer(AVCodecContext
*s
, AVFrame
*frame
)
488 InputStream
*ist
= s
->opaque
;
492 if (!ist
->buffer_pool
&& (ret
= alloc_buffer(ist
, &ist
->buffer_pool
)) < 0)
495 buf
= ist
->buffer_pool
;
496 ist
->buffer_pool
= buf
->next
;
498 if (buf
->w
!= s
->width
|| buf
->h
!= s
->height
|| buf
->pix_fmt
!= s
->pix_fmt
) {
499 av_freep(&buf
->base
[0]);
501 if ((ret
= alloc_buffer(ist
, &buf
)) < 0)
507 frame
->type
= FF_BUFFER_TYPE_USER
;
508 frame
->extended_data
= frame
->data
;
509 frame
->pkt_pts
= s
->pkt ? s
->pkt
->pts
: AV_NOPTS_VALUE
;
511 for (i
= 0; i
< FF_ARRAY_ELEMS(buf
->data
); i
++) {
512 frame
->base
[i
] = buf
->base
[i
]; // XXX h264.c uses base though it shouldn't
513 frame
->data
[i
] = buf
->data
[i
];
514 frame
->linesize
[i
] = buf
->linesize
[i
];
520 static void codec_release_buffer(AVCodecContext
*s
, AVFrame
*frame
)
522 InputStream
*ist
= s
->opaque
;
523 FrameBuffer
*buf
= frame
->opaque
;
526 for (i
= 0; i
< FF_ARRAY_ELEMS(frame
->data
); i
++)
527 frame
->data
[i
] = NULL
;
529 unref_buffer(ist
, buf
);
534 static int configure_video_filters(InputStream
*ist
, OutputStream
*ost
)
536 AVFilterContext
*last_filter
, *filter
;
537 /** filter graph containing all filters including input & output */
538 AVCodecContext
*codec
= ost
->st
->codec
;
539 AVCodecContext
*icodec
= ist
->st
->codec
;
540 FFSinkContext ffsink_ctx
= { .pix_fmt
= codec
->pix_fmt
};
541 AVRational sample_aspect_ratio
;
545 ost
->graph
= avfilter_graph_alloc();
547 if (ist
->st
->sample_aspect_ratio
.num
){
548 sample_aspect_ratio
= ist
->st
->sample_aspect_ratio
;
550 sample_aspect_ratio
= ist
->st
->codec
->sample_aspect_ratio
;
552 snprintf(args
, 255, "%d:%d:%d:%d:%d:%d:%d", ist
->st
->codec
->width
,
553 ist
->st
->codec
->height
, ist
->st
->codec
->pix_fmt
, 1, AV_TIME_BASE
,
554 sample_aspect_ratio
.num
, sample_aspect_ratio
.den
);
556 ret
= avfilter_graph_create_filter(&ost
->input_video_filter
, avfilter_get_by_name("buffer"),
557 "src", args
, NULL
, ost
->graph
);
560 ret
= avfilter_graph_create_filter(&ost
->output_video_filter
, &ffsink
,
561 "out", NULL
, &ffsink_ctx
, ost
->graph
);
564 last_filter
= ost
->input_video_filter
;
566 if (codec
->width
!= icodec
->width
|| codec
->height
!= icodec
->height
) {
567 snprintf(args
, 255, "%d:%d:flags=0x%X",
570 (unsigned)ost
->sws_flags
);
571 if ((ret
= avfilter_graph_create_filter(&filter
, avfilter_get_by_name("scale"),
572 NULL
, args
, NULL
, ost
->graph
)) < 0)
574 if ((ret
= avfilter_link(last_filter
, 0, filter
, 0)) < 0)
576 last_filter
= filter
;
579 snprintf(args
, sizeof(args
), "flags=0x%X", (unsigned)ost
->sws_flags
);
580 ost
->graph
->scale_sws_opts
= av_strdup(args
);
583 AVFilterInOut
*outputs
= av_malloc(sizeof(AVFilterInOut
));
584 AVFilterInOut
*inputs
= av_malloc(sizeof(AVFilterInOut
));
586 outputs
->name
= av_strdup("in");
587 outputs
->filter_ctx
= last_filter
;
588 outputs
->pad_idx
= 0;
589 outputs
->next
= NULL
;
591 inputs
->name
= av_strdup("out");
592 inputs
->filter_ctx
= ost
->output_video_filter
;
596 if ((ret
= avfilter_graph_parse(ost
->graph
, ost
->avfilter
, inputs
, outputs
, NULL
)) < 0)
598 av_freep(&ost
->avfilter
);
600 if ((ret
= avfilter_link(last_filter
, 0, ost
->output_video_filter
, 0)) < 0)
604 if ((ret
= avfilter_graph_config(ost
->graph
, NULL
)) < 0)
607 codec
->width
= ost
->output_video_filter
->inputs
[0]->w
;
608 codec
->height
= ost
->output_video_filter
->inputs
[0]->h
;
609 codec
->sample_aspect_ratio
= ost
->st
->sample_aspect_ratio
=
610 ost
->frame_aspect_ratio ?
// overridden by the -aspect cli option
611 av_d2q(ost
->frame_aspect_ratio
*codec
->height
/codec
->width
, 255) :
612 ost
->output_video_filter
->inputs
[0]->sample_aspect_ratio
;
616 #endif /* CONFIG_AVFILTER */
618 static void term_exit(void)
620 av_log(NULL
, AV_LOG_QUIET
, "");
623 static volatile int received_sigterm
= 0;
624 static volatile int received_nb_signals
= 0;
627 sigterm_handler(int sig
)
629 received_sigterm
= sig
;
630 received_nb_signals
++;
634 static void term_init(void)
636 signal(SIGINT
, sigterm_handler
); /* Interrupt (ANSI). */
637 signal(SIGTERM
, sigterm_handler
); /* Termination (ANSI). */
639 signal(SIGXCPU
, sigterm_handler
);
643 static int decode_interrupt_cb(void *ctx
)
645 return received_nb_signals
> 1;
648 static const AVIOInterruptCB int_cb
= { decode_interrupt_cb
, NULL
};
650 void exit_program(int ret
)
655 for(i
=0;i
<nb_output_files
;i
++) {
656 AVFormatContext
*s
= output_files
[i
].ctx
;
657 if (!(s
->oformat
->flags
& AVFMT_NOFILE
) && s
->pb
)
659 avformat_free_context(s
);
660 av_dict_free(&output_files
[i
].opts
);
662 for(i
=0;i
<nb_input_files
;i
++) {
663 avformat_close_input(&input_files
[i
].ctx
);
665 for (i
= 0; i
< nb_input_streams
; i
++) {
666 av_freep(&input_streams
[i
].decoded_frame
);
667 av_freep(&input_streams
[i
].filtered_frame
);
668 av_dict_free(&input_streams
[i
].opts
);
669 free_buffer_pool(&input_streams
[i
]);
674 av_free(vstats_filename
);
676 av_freep(&input_streams
);
677 av_freep(&input_files
);
678 av_freep(&output_streams
);
679 av_freep(&output_files
);
684 allocated_audio_buf_size
= allocated_audio_out_size
= 0;
689 avformat_network_deinit();
691 if (received_sigterm
) {
692 av_log(NULL
, AV_LOG_INFO
, "Received signal %d: terminating.\n",
693 (int) received_sigterm
);
700 static void assert_avoptions(AVDictionary
*m
)
702 AVDictionaryEntry
*t
;
703 if ((t
= av_dict_get(m
, "", NULL
, AV_DICT_IGNORE_SUFFIX
))) {
704 av_log(NULL
, AV_LOG_FATAL
, "Option %s not found.\n", t
->key
);
709 static void assert_codec_experimental(AVCodecContext
*c
, int encoder
)
711 const char *codec_string
= encoder ?
"encoder" : "decoder";
713 if (c
->codec
->capabilities
& CODEC_CAP_EXPERIMENTAL
&&
714 c
->strict_std_compliance
> FF_COMPLIANCE_EXPERIMENTAL
) {
715 av_log(NULL
, AV_LOG_FATAL
, "%s '%s' is experimental and might produce bad "
716 "results.\nAdd '-strict experimental' if you want to use it.\n",
717 codec_string
, c
->codec
->name
);
718 codec
= encoder ?
avcodec_find_encoder(c
->codec
->id
) : avcodec_find_decoder(c
->codec
->id
);
719 if (!(codec
->capabilities
& CODEC_CAP_EXPERIMENTAL
))
720 av_log(NULL
, AV_LOG_FATAL
, "Or use the non experimental %s '%s'.\n",
721 codec_string
, codec
->name
);
726 static void choose_sample_fmt(AVStream
*st
, AVCodec
*codec
)
728 if(codec
&& codec
->sample_fmts
){
729 const enum AVSampleFormat
*p
= codec
->sample_fmts
;
731 if(*p
== st
->codec
->sample_fmt
)
735 av_log(NULL
, AV_LOG_WARNING
,
736 "Incompatible sample format '%s' for codec '%s', auto-selecting format '%s'\n",
737 av_get_sample_fmt_name(st
->codec
->sample_fmt
),
739 av_get_sample_fmt_name(codec
->sample_fmts
[0]));
740 st
->codec
->sample_fmt
= codec
->sample_fmts
[0];
746 * Update the requested input sample format based on the output sample format.
747 * This is currently only used to request float output from decoders which
748 * support multiple sample formats, one of which is AV_SAMPLE_FMT_FLT.
749 * Ideally this will be removed in the future when decoders do not do format
750 * conversion and only output in their native format.
752 static void update_sample_fmt(AVCodecContext
*dec
, AVCodec
*dec_codec
,
755 /* if sample formats match or a decoder sample format has already been
756 requested, just return */
757 if (enc
->sample_fmt
== dec
->sample_fmt
||
758 dec
->request_sample_fmt
> AV_SAMPLE_FMT_NONE
)
761 /* if decoder supports more than one output format */
762 if (dec_codec
&& dec_codec
->sample_fmts
&&
763 dec_codec
->sample_fmts
[0] != AV_SAMPLE_FMT_NONE
&&
764 dec_codec
->sample_fmts
[1] != AV_SAMPLE_FMT_NONE
) {
765 const enum AVSampleFormat
*p
;
766 int min_dec
= -1, min_inc
= -1;
768 /* find a matching sample format in the encoder */
769 for (p
= dec_codec
->sample_fmts
; *p
!= AV_SAMPLE_FMT_NONE
; p
++) {
770 if (*p
== enc
->sample_fmt
) {
771 dec
->request_sample_fmt
= *p
;
773 } else if (*p
> enc
->sample_fmt
) {
774 min_inc
= FFMIN(min_inc
, *p
- enc
->sample_fmt
);
776 min_dec
= FFMIN(min_dec
, enc
->sample_fmt
- *p
);
779 /* if none match, provide the one that matches quality closest */
780 dec
->request_sample_fmt
= min_inc
> 0 ? enc
->sample_fmt
+ min_inc
:
781 enc
->sample_fmt
- min_dec
;
785 static void choose_sample_rate(AVStream
*st
, AVCodec
*codec
)
787 if(codec
&& codec
->supported_samplerates
){
788 const int *p
= codec
->supported_samplerates
;
790 int best_dist
=INT_MAX
;
792 int dist
= abs(st
->codec
->sample_rate
- *p
);
793 if(dist
< best_dist
){
799 av_log(st
->codec
, AV_LOG_WARNING
, "Requested sampling rate unsupported using closest supported (%d)\n", best
);
801 st
->codec
->sample_rate
= best
;
805 static void choose_pixel_fmt(AVStream
*st
, AVCodec
*codec
)
807 if(codec
&& codec
->pix_fmts
){
808 const enum PixelFormat
*p
= codec
->pix_fmts
;
809 if(st
->codec
->strict_std_compliance
<= FF_COMPLIANCE_UNOFFICIAL
){
810 if(st
->codec
->codec_id
==CODEC_ID_MJPEG
){
811 p
= (const enum PixelFormat
[]){PIX_FMT_YUVJ420P
, PIX_FMT_YUVJ422P
, PIX_FMT_YUV420P
, PIX_FMT_YUV422P
, PIX_FMT_NONE
};
812 }else if(st
->codec
->codec_id
==CODEC_ID_LJPEG
){
813 p
= (const enum PixelFormat
[]){PIX_FMT_YUVJ420P
, PIX_FMT_YUVJ422P
, PIX_FMT_YUVJ444P
, PIX_FMT_YUV420P
, PIX_FMT_YUV422P
, PIX_FMT_YUV444P
, PIX_FMT_BGRA
, PIX_FMT_NONE
};
816 for (; *p
!= PIX_FMT_NONE
; p
++) {
817 if(*p
== st
->codec
->pix_fmt
)
820 if (*p
== PIX_FMT_NONE
) {
821 if(st
->codec
->pix_fmt
!= PIX_FMT_NONE
)
822 av_log(NULL
, AV_LOG_WARNING
,
823 "Incompatible pixel format '%s' for codec '%s', auto-selecting format '%s'\n",
824 av_pix_fmt_descriptors
[st
->codec
->pix_fmt
].name
,
826 av_pix_fmt_descriptors
[codec
->pix_fmts
[0]].name
);
827 st
->codec
->pix_fmt
= codec
->pix_fmts
[0];
833 get_sync_ipts(const OutputStream
*ost
)
835 const InputStream
*ist
= ost
->sync_ist
;
836 OutputFile
*of
= &output_files
[ost
->file_index
];
837 return (double)(ist
->pts
- of
->start_time
)/AV_TIME_BASE
;
840 static void write_frame(AVFormatContext
*s
, AVPacket
*pkt
, AVCodecContext
*avctx
, AVBitStreamFilterContext
*bsfc
){
844 AVPacket new_pkt
= *pkt
;
845 int a
= av_bitstream_filter_filter(bsfc
, avctx
, NULL
,
846 &new_pkt
.data
, &new_pkt
.size
,
847 pkt
->data
, pkt
->size
,
848 pkt
->flags
& AV_PKT_FLAG_KEY
);
851 new_pkt
.destruct
= av_destruct_packet
;
853 av_log(NULL
, AV_LOG_ERROR
, "%s failed for stream %d, codec %s",
854 bsfc
->filter
->name
, pkt
->stream_index
,
855 avctx
->codec ? avctx
->codec
->name
: "copy");
865 ret
= av_interleaved_write_frame(s
, pkt
);
867 print_error("av_interleaved_write_frame()", ret
);
872 static void generate_silence(uint8_t* buf
, enum AVSampleFormat sample_fmt
, size_t size
)
874 int fill_char
= 0x00;
875 if (sample_fmt
== AV_SAMPLE_FMT_U8
)
877 memset(buf
, fill_char
, size
);
880 static void do_audio_out(AVFormatContext
*s
, OutputStream
*ost
,
881 InputStream
*ist
, AVFrame
*decoded_frame
)
884 int64_t audio_out_size
, audio_buf_size
;
886 int size_out
, frame_bytes
, ret
, resample_changed
;
887 AVCodecContext
*enc
= ost
->st
->codec
;
888 AVCodecContext
*dec
= ist
->st
->codec
;
889 int osize
= av_get_bytes_per_sample(enc
->sample_fmt
);
890 int isize
= av_get_bytes_per_sample(dec
->sample_fmt
);
891 const int coded_bps
= av_get_bits_per_sample(enc
->codec
->id
);
892 uint8_t *buf
= decoded_frame
->data
[0];
893 int size
= decoded_frame
->nb_samples
* dec
->channels
* isize
;
894 int64_t allocated_for_size
= size
;
897 audio_buf_size
= (allocated_for_size
+ isize
*dec
->channels
- 1) / (isize
*dec
->channels
);
898 audio_buf_size
= (audio_buf_size
*enc
->sample_rate
+ dec
->sample_rate
) / dec
->sample_rate
;
899 audio_buf_size
= audio_buf_size
*2 + 10000; //safety factors for the deprecated resampling API
900 audio_buf_size
= FFMAX(audio_buf_size
, enc
->frame_size
);
901 audio_buf_size
*= osize
*enc
->channels
;
903 audio_out_size
= FFMAX(audio_buf_size
, enc
->frame_size
* osize
* enc
->channels
);
904 if(coded_bps
> 8*osize
)
905 audio_out_size
= audio_out_size
* coded_bps
/ (8*osize
);
906 audio_out_size
+= FF_MIN_BUFFER_SIZE
;
908 if(audio_out_size
> INT_MAX
|| audio_buf_size
> INT_MAX
){
909 av_log(NULL
, AV_LOG_FATAL
, "Buffer sizes too large\n");
913 av_fast_malloc(&audio_buf
, &allocated_audio_buf_size
, audio_buf_size
);
914 av_fast_malloc(&audio_out
, &allocated_audio_out_size
, audio_out_size
);
915 if (!audio_buf
|| !audio_out
){
916 av_log(NULL
, AV_LOG_FATAL
, "Out of memory in do_audio_out\n");
920 if (enc
->channels
!= dec
->channels
|| enc
->sample_rate
!= dec
->sample_rate
)
921 ost
->audio_resample
= 1;
923 resample_changed
= ost
->resample_sample_fmt
!= dec
->sample_fmt
||
924 ost
->resample_channels
!= dec
->channels
||
925 ost
->resample_sample_rate
!= dec
->sample_rate
;
927 if ((ost
->audio_resample
&& !ost
->resample
) || resample_changed
) {
928 if (resample_changed
) {
929 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",
930 ist
->file_index
, ist
->st
->index
,
931 ost
->resample_sample_rate
, av_get_sample_fmt_name(ost
->resample_sample_fmt
), ost
->resample_channels
,
932 dec
->sample_rate
, av_get_sample_fmt_name(dec
->sample_fmt
), dec
->channels
);
933 ost
->resample_sample_fmt
= dec
->sample_fmt
;
934 ost
->resample_channels
= dec
->channels
;
935 ost
->resample_sample_rate
= dec
->sample_rate
;
937 audio_resample_close(ost
->resample
);
939 /* if audio_sync_method is >1 the resampler is needed for audio drift compensation */
940 if (audio_sync_method
<= 1 &&
941 ost
->resample_sample_fmt
== enc
->sample_fmt
&&
942 ost
->resample_channels
== enc
->channels
&&
943 ost
->resample_sample_rate
== enc
->sample_rate
) {
944 ost
->resample
= NULL
;
945 ost
->audio_resample
= 0;
946 } else if (ost
->audio_resample
) {
947 if (dec
->sample_fmt
!= AV_SAMPLE_FMT_S16
)
948 av_log(NULL
, AV_LOG_WARNING
, "Using s16 intermediate sample format for resampling\n");
949 ost
->resample
= av_audio_resample_init(enc
->channels
, dec
->channels
,
950 enc
->sample_rate
, dec
->sample_rate
,
951 enc
->sample_fmt
, dec
->sample_fmt
,
953 if (!ost
->resample
) {
954 av_log(NULL
, AV_LOG_FATAL
, "Can not resample %d channels @ %d Hz to %d channels @ %d Hz\n",
955 dec
->channels
, dec
->sample_rate
,
956 enc
->channels
, enc
->sample_rate
);
962 #define MAKE_SFMT_PAIR(a,b) ((a)+AV_SAMPLE_FMT_NB*(b))
963 if (!ost
->audio_resample
&& dec
->sample_fmt
!=enc
->sample_fmt
&&
964 MAKE_SFMT_PAIR(enc
->sample_fmt
,dec
->sample_fmt
)!=ost
->reformat_pair
) {
965 if (ost
->reformat_ctx
)
966 av_audio_convert_free(ost
->reformat_ctx
);
967 ost
->reformat_ctx
= av_audio_convert_alloc(enc
->sample_fmt
, 1,
968 dec
->sample_fmt
, 1, NULL
, 0);
969 if (!ost
->reformat_ctx
) {
970 av_log(NULL
, AV_LOG_FATAL
, "Cannot convert %s sample format to %s sample format\n",
971 av_get_sample_fmt_name(dec
->sample_fmt
),
972 av_get_sample_fmt_name(enc
->sample_fmt
));
975 ost
->reformat_pair
=MAKE_SFMT_PAIR(enc
->sample_fmt
,dec
->sample_fmt
);
978 if(audio_sync_method
){
979 double delta
= get_sync_ipts(ost
) * enc
->sample_rate
- ost
->sync_opts
980 - av_fifo_size(ost
->fifo
)/(enc
->channels
* osize
);
981 int idelta
= delta
* dec
->sample_rate
/ enc
->sample_rate
;
982 int byte_delta
= idelta
* isize
* dec
->channels
;
984 //FIXME resample delay
985 if(fabs(delta
) > 50){
986 if(ist
->is_start
|| fabs(delta
) > audio_drift_threshold
*enc
->sample_rate
){
988 byte_delta
= FFMAX(byte_delta
, -size
);
991 av_log(NULL
, AV_LOG_VERBOSE
, "discarding %d audio samples\n",
992 -byte_delta
/ (isize
* dec
->channels
));
997 static uint8_t *input_tmp
= NULL
;
998 input_tmp
= av_realloc(input_tmp
, byte_delta
+ size
);
1000 if(byte_delta
> allocated_for_size
- size
){
1001 allocated_for_size
= byte_delta
+ (int64_t)size
;
1006 generate_silence(input_tmp
, dec
->sample_fmt
, byte_delta
);
1007 memcpy(input_tmp
+ byte_delta
, buf
, size
);
1010 av_log(NULL
, AV_LOG_VERBOSE
, "adding %d audio samples of silence\n", idelta
);
1012 }else if(audio_sync_method
>1){
1013 int comp
= av_clip(delta
, -audio_sync_method
, audio_sync_method
);
1014 av_assert0(ost
->audio_resample
);
1015 av_log(NULL
, AV_LOG_VERBOSE
, "compensating audio timestamp drift:%f compensation:%d in:%d\n",
1016 delta
, comp
, enc
->sample_rate
);
1017 // 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));
1018 av_resample_compensate(*(struct AVResampleContext
**)ost
->resample
, comp
, enc
->sample_rate
);
1022 ost
->sync_opts
= lrintf(get_sync_ipts(ost
) * enc
->sample_rate
)
1023 - av_fifo_size(ost
->fifo
)/(enc
->channels
* osize
); //FIXME wrong
1025 if (ost
->audio_resample
) {
1027 size_out
= audio_resample(ost
->resample
,
1028 (short *)buftmp
, (short *)buf
,
1029 size
/ (dec
->channels
* isize
));
1030 size_out
= size_out
* enc
->channels
* osize
;
1036 if (!ost
->audio_resample
&& dec
->sample_fmt
!=enc
->sample_fmt
) {
1037 const void *ibuf
[6]= {buftmp
};
1038 void *obuf
[6]= {audio_buf
};
1039 int istride
[6]= {isize
};
1040 int ostride
[6]= {osize
};
1041 int len
= size_out
/istride
[0];
1042 if (av_audio_convert(ost
->reformat_ctx
, obuf
, ostride
, ibuf
, istride
, len
)<0) {
1043 printf("av_audio_convert() failed\n");
1049 size_out
= len
*osize
;
1052 /* now encode as many frames as possible */
1053 if (enc
->frame_size
> 1) {
1054 /* output resampled raw samples */
1055 if (av_fifo_realloc2(ost
->fifo
, av_fifo_size(ost
->fifo
) + size_out
) < 0) {
1056 av_log(NULL
, AV_LOG_FATAL
, "av_fifo_realloc2() failed\n");
1059 av_fifo_generic_write(ost
->fifo
, buftmp
, size_out
, NULL
);
1061 frame_bytes
= enc
->frame_size
* osize
* enc
->channels
;
1063 while (av_fifo_size(ost
->fifo
) >= frame_bytes
) {
1065 av_init_packet(&pkt
);
1067 av_fifo_generic_read(ost
->fifo
, audio_buf
, frame_bytes
, NULL
);
1069 //FIXME pass ost->sync_opts as AVFrame.pts in avcodec_encode_audio()
1071 ret
= avcodec_encode_audio(enc
, audio_out
, audio_out_size
,
1072 (short *)audio_buf
);
1074 av_log(NULL
, AV_LOG_FATAL
, "Audio encoding failed\n");
1078 pkt
.stream_index
= ost
->index
;
1079 pkt
.data
= audio_out
;
1081 if(enc
->coded_frame
&& enc
->coded_frame
->pts
!= AV_NOPTS_VALUE
)
1082 pkt
.pts
= av_rescale_q(enc
->coded_frame
->pts
, enc
->time_base
, ost
->st
->time_base
);
1083 pkt
.flags
|= AV_PKT_FLAG_KEY
;
1084 write_frame(s
, &pkt
, enc
, ost
->bitstream_filters
);
1086 ost
->sync_opts
+= enc
->frame_size
;
1090 av_init_packet(&pkt
);
1092 ost
->sync_opts
+= size_out
/ (osize
* enc
->channels
);
1094 /* output a pcm frame */
1095 /* determine the size of the coded buffer */
1098 size_out
= size_out
*coded_bps
/8;
1100 if(size_out
> audio_out_size
){
1101 av_log(NULL
, AV_LOG_FATAL
, "Internal error, buffer size too small\n");
1105 //FIXME pass ost->sync_opts as AVFrame.pts in avcodec_encode_audio()
1106 ret
= avcodec_encode_audio(enc
, audio_out
, size_out
,
1109 av_log(NULL
, AV_LOG_FATAL
, "Audio encoding failed\n");
1113 pkt
.stream_index
= ost
->index
;
1114 pkt
.data
= audio_out
;
1116 if(enc
->coded_frame
&& enc
->coded_frame
->pts
!= AV_NOPTS_VALUE
)
1117 pkt
.pts
= av_rescale_q(enc
->coded_frame
->pts
, enc
->time_base
, ost
->st
->time_base
);
1118 pkt
.flags
|= AV_PKT_FLAG_KEY
;
1119 write_frame(s
, &pkt
, enc
, ost
->bitstream_filters
);
1123 static void pre_process_video_frame(InputStream
*ist
, AVPicture
*picture
, void **bufp
)
1125 AVCodecContext
*dec
;
1126 AVPicture
*picture2
;
1127 AVPicture picture_tmp
;
1130 dec
= ist
->st
->codec
;
1132 /* deinterlace : must be done before any resize */
1133 if (do_deinterlace
) {
1136 /* create temporary picture */
1137 size
= avpicture_get_size(dec
->pix_fmt
, dec
->width
, dec
->height
);
1138 buf
= av_malloc(size
);
1142 picture2
= &picture_tmp
;
1143 avpicture_fill(picture2
, buf
, dec
->pix_fmt
, dec
->width
, dec
->height
);
1145 if(avpicture_deinterlace(picture2
, picture
,
1146 dec
->pix_fmt
, dec
->width
, dec
->height
) < 0) {
1147 /* if error, do not deinterlace */
1148 av_log(NULL
, AV_LOG_WARNING
, "Deinterlacing failed\n");
1157 if (picture
!= picture2
)
1158 *picture
= *picture2
;
1162 static void do_subtitle_out(AVFormatContext
*s
,
1168 static uint8_t *subtitle_out
= NULL
;
1169 int subtitle_out_max_size
= 1024 * 1024;
1170 int subtitle_out_size
, nb
, i
;
1171 AVCodecContext
*enc
;
1174 if (pts
== AV_NOPTS_VALUE
) {
1175 av_log(NULL
, AV_LOG_ERROR
, "Subtitle packets must have a pts\n");
1181 enc
= ost
->st
->codec
;
1183 if (!subtitle_out
) {
1184 subtitle_out
= av_malloc(subtitle_out_max_size
);
1187 /* Note: DVB subtitle need one packet to draw them and one other
1188 packet to clear them */
1189 /* XXX: signal it in the codec context ? */
1190 if (enc
->codec_id
== CODEC_ID_DVB_SUBTITLE
)
1195 for(i
= 0; i
< nb
; i
++) {
1196 sub
->pts
= av_rescale_q(pts
, ist
->st
->time_base
, AV_TIME_BASE_Q
);
1197 // start_display_time is required to be 0
1198 sub
->pts
+= av_rescale_q(sub
->start_display_time
, (AVRational
){1, 1000}, AV_TIME_BASE_Q
);
1199 sub
->end_display_time
-= sub
->start_display_time
;
1200 sub
->start_display_time
= 0;
1201 subtitle_out_size
= avcodec_encode_subtitle(enc
, subtitle_out
,
1202 subtitle_out_max_size
, sub
);
1203 if (subtitle_out_size
< 0) {
1204 av_log(NULL
, AV_LOG_FATAL
, "Subtitle encoding failed\n");
1208 av_init_packet(&pkt
);
1209 pkt
.stream_index
= ost
->index
;
1210 pkt
.data
= subtitle_out
;
1211 pkt
.size
= subtitle_out_size
;
1212 pkt
.pts
= av_rescale_q(sub
->pts
, AV_TIME_BASE_Q
, ost
->st
->time_base
);
1213 if (enc
->codec_id
== CODEC_ID_DVB_SUBTITLE
) {
1214 /* XXX: the pts correction is handled here. Maybe handling
1215 it in the codec would be better */
1217 pkt
.pts
+= 90 * sub
->start_display_time
;
1219 pkt
.pts
+= 90 * sub
->end_display_time
;
1221 write_frame(s
, &pkt
, ost
->st
->codec
, ost
->bitstream_filters
);
1225 static int bit_buffer_size
= 1024*256;
1226 static uint8_t *bit_buffer
= NULL
;
1228 static void do_video_resample(OutputStream
*ost
,
1230 AVFrame
*in_picture
,
1231 AVFrame
**out_picture
)
1233 int resample_changed
= 0;
1234 AVCodecContext
*dec
= ist
->st
->codec
;
1235 *out_picture
= in_picture
;
1237 resample_changed
= ost
->resample_width
!= dec
->width
||
1238 ost
->resample_height
!= dec
->height
||
1239 ost
->resample_pix_fmt
!= dec
->pix_fmt
;
1241 if (resample_changed
) {
1242 av_log(NULL
, AV_LOG_INFO
,
1243 "Input stream #%d:%d frame changed from size:%dx%d fmt:%s to size:%dx%d fmt:%s\n",
1244 ist
->file_index
, ist
->st
->index
,
1245 ost
->resample_width
, ost
->resample_height
, av_get_pix_fmt_name(ost
->resample_pix_fmt
),
1246 dec
->width
, dec
->height
, av_get_pix_fmt_name(dec
->pix_fmt
));
1247 if(!ost
->video_resample
)
1248 ost
->video_resample
= 1;
1251 #if !CONFIG_AVFILTER
1252 if (ost
->video_resample
) {
1253 *out_picture
= &ost
->pict_tmp
;
1254 if (resample_changed
) {
1255 /* initialize a new scaler context */
1256 sws_freeContext(ost
->img_resample_ctx
);
1257 ost
->img_resample_ctx
= sws_getContext(
1258 ist
->st
->codec
->width
,
1259 ist
->st
->codec
->height
,
1260 ist
->st
->codec
->pix_fmt
,
1261 ost
->st
->codec
->width
,
1262 ost
->st
->codec
->height
,
1263 ost
->st
->codec
->pix_fmt
,
1264 ost
->sws_flags
, NULL
, NULL
, NULL
);
1265 if (ost
->img_resample_ctx
== NULL
) {
1266 av_log(NULL
, AV_LOG_FATAL
, "Cannot get resampling context\n");
1270 sws_scale(ost
->img_resample_ctx
, in_picture
->data
, in_picture
->linesize
,
1271 0, ost
->resample_height
, (*out_picture
)->data
, (*out_picture
)->linesize
);
1274 if (resample_changed
) {
1275 avfilter_graph_free(&ost
->graph
);
1276 if (configure_video_filters(ist
, ost
)) {
1277 av_log(NULL
, AV_LOG_FATAL
, "Error reinitializing filters!\n");
1282 if (resample_changed
) {
1283 ost
->resample_width
= dec
->width
;
1284 ost
->resample_height
= dec
->height
;
1285 ost
->resample_pix_fmt
= dec
->pix_fmt
;
1290 static void do_video_out(AVFormatContext
*s
,
1293 AVFrame
*in_picture
,
1294 int *frame_size
, float quality
)
1296 int nb_frames
, i
, ret
, format_video_sync
;
1297 AVFrame
*final_picture
;
1298 AVCodecContext
*enc
;
1301 enc
= ost
->st
->codec
;
1303 sync_ipts
= get_sync_ipts(ost
) / av_q2d(enc
->time_base
);
1305 /* by default, we output a single frame */
1310 format_video_sync
= video_sync_method
;
1311 if (format_video_sync
< 0)
1312 format_video_sync
= (s
->oformat
->flags
& AVFMT_NOTIMESTAMPS
) ?
0 :
1313 (s
->oformat
->flags
& AVFMT_VARIABLE_FPS
) ?
2 : 1;
1315 if (format_video_sync
) {
1316 double vdelta
= sync_ipts
- ost
->sync_opts
;
1317 //FIXME set to 0.5 after we fix some dts/pts bugs like in avidec.c
1320 else if (format_video_sync
== 2) {
1323 }else if(vdelta
>0.6)
1324 ost
->sync_opts
= lrintf(sync_ipts
);
1325 }else if (vdelta
> 1.1)
1326 nb_frames
= lrintf(vdelta
);
1327 //fprintf(stderr, "vdelta:%f, ost->sync_opts:%"PRId64", ost->sync_ipts:%f nb_frames:%d\n", vdelta, ost->sync_opts, get_sync_ipts(ost), nb_frames);
1328 if (nb_frames
== 0){
1330 av_log(NULL
, AV_LOG_VERBOSE
, "*** drop!\n");
1331 }else if (nb_frames
> 1) {
1332 nb_frames_dup
+= nb_frames
- 1;
1333 av_log(NULL
, AV_LOG_VERBOSE
, "*** %d dup!\n", nb_frames
-1);
1336 ost
->sync_opts
= lrintf(sync_ipts
);
1338 nb_frames
= FFMIN(nb_frames
, ost
->max_frames
- ost
->frame_number
);
1342 do_video_resample(ost
, ist
, in_picture
, &final_picture
);
1344 /* duplicates frame if needed */
1345 for(i
=0;i
<nb_frames
;i
++) {
1347 av_init_packet(&pkt
);
1348 pkt
.stream_index
= ost
->index
;
1350 if (s
->oformat
->flags
& AVFMT_RAWPICTURE
&&
1351 enc
->codec
->id
== CODEC_ID_RAWVIDEO
) {
1352 /* raw pictures are written as AVPicture structure to
1353 avoid any copies. We support temporarily the older
1355 enc
->coded_frame
->interlaced_frame
= in_picture
->interlaced_frame
;
1356 enc
->coded_frame
->top_field_first
= in_picture
->top_field_first
;
1357 pkt
.data
= (uint8_t *)final_picture
;
1358 pkt
.size
= sizeof(AVPicture
);
1359 pkt
.pts
= av_rescale_q(ost
->sync_opts
, enc
->time_base
, ost
->st
->time_base
);
1360 pkt
.flags
|= AV_PKT_FLAG_KEY
;
1362 write_frame(s
, &pkt
, ost
->st
->codec
, ost
->bitstream_filters
);
1364 AVFrame big_picture
;
1366 big_picture
= *final_picture
;
1367 /* better than nothing: use input picture interlaced
1369 big_picture
.interlaced_frame
= in_picture
->interlaced_frame
;
1370 if (ost
->st
->codec
->flags
& (CODEC_FLAG_INTERLACED_DCT
|CODEC_FLAG_INTERLACED_ME
)) {
1371 if (ost
->top_field_first
== -1)
1372 big_picture
.top_field_first
= in_picture
->top_field_first
;
1374 big_picture
.top_field_first
= !!ost
->top_field_first
;
1377 /* handles same_quant here. This is not correct because it may
1378 not be a global option */
1379 big_picture
.quality
= quality
;
1380 if (!enc
->me_threshold
)
1381 big_picture
.pict_type
= 0;
1382 // big_picture.pts = AV_NOPTS_VALUE;
1383 big_picture
.pts
= ost
->sync_opts
;
1384 // big_picture.pts= av_rescale(ost->sync_opts, AV_TIME_BASE*(int64_t)enc->time_base.num, enc->time_base.den);
1385 //av_log(NULL, AV_LOG_DEBUG, "%"PRId64" -> encoder\n", ost->sync_opts);
1386 if (ost
->forced_kf_index
< ost
->forced_kf_count
&&
1387 big_picture
.pts
>= ost
->forced_kf_pts
[ost
->forced_kf_index
]) {
1388 big_picture
.pict_type
= AV_PICTURE_TYPE_I
;
1389 ost
->forced_kf_index
++;
1391 ret
= avcodec_encode_video(enc
,
1392 bit_buffer
, bit_buffer_size
,
1395 av_log(NULL
, AV_LOG_FATAL
, "Video encoding failed\n");
1400 pkt
.data
= bit_buffer
;
1402 if(enc
->coded_frame
->pts
!= AV_NOPTS_VALUE
)
1403 pkt
.pts
= av_rescale_q(enc
->coded_frame
->pts
, enc
->time_base
, ost
->st
->time_base
);
1404 /*av_log(NULL, AV_LOG_DEBUG, "encoder -> %"PRId64"/%"PRId64"\n",
1405 pkt.pts != AV_NOPTS_VALUE ? av_rescale(pkt.pts, enc->time_base.den, AV_TIME_BASE*(int64_t)enc->time_base.num) : -1,
1406 pkt.dts != AV_NOPTS_VALUE ? av_rescale(pkt.dts, enc->time_base.den, AV_TIME_BASE*(int64_t)enc->time_base.num) : -1);*/
1408 if(enc
->coded_frame
->key_frame
)
1409 pkt
.flags
|= AV_PKT_FLAG_KEY
;
1410 write_frame(s
, &pkt
, ost
->st
->codec
, ost
->bitstream_filters
);
1413 //fprintf(stderr,"\nFrame: %3d size: %5d type: %d",
1414 // enc->frame_number-1, ret, enc->pict_type);
1415 /* if two pass, output log */
1416 if (ost
->logfile
&& enc
->stats_out
) {
1417 fprintf(ost
->logfile
, "%s", enc
->stats_out
);
1422 ost
->frame_number
++;
1426 static double psnr(double d
){
1427 return -10.0*log(d
)/log(10.0);
1430 static void do_video_stats(AVFormatContext
*os
, OutputStream
*ost
,
1433 AVCodecContext
*enc
;
1435 double ti1
, bitrate
, avg_bitrate
;
1437 /* this is executed just the first time do_video_stats is called */
1439 vstats_file
= fopen(vstats_filename
, "w");
1446 enc
= ost
->st
->codec
;
1447 if (enc
->codec_type
== AVMEDIA_TYPE_VIDEO
) {
1448 frame_number
= ost
->frame_number
;
1449 fprintf(vstats_file
, "frame= %5d q= %2.1f ", frame_number
, enc
->coded_frame
->quality
/(float)FF_QP2LAMBDA
);
1450 if (enc
->flags
&CODEC_FLAG_PSNR
)
1451 fprintf(vstats_file
, "PSNR= %6.2f ", psnr(enc
->coded_frame
->error
[0]/(enc
->width
*enc
->height
*255.0*255.0)));
1453 fprintf(vstats_file
,"f_size= %6d ", frame_size
);
1454 /* compute pts value */
1455 ti1
= ost
->sync_opts
* av_q2d(enc
->time_base
);
1459 bitrate
= (frame_size
* 8) / av_q2d(enc
->time_base
) / 1000.0;
1460 avg_bitrate
= (double)(video_size
* 8) / ti1
/ 1000.0;
1461 fprintf(vstats_file
, "s_size= %8.0fkB time= %0.3f br= %7.1fkbits/s avg_br= %7.1fkbits/s ",
1462 (double)video_size
/ 1024, ti1
, bitrate
, avg_bitrate
);
1463 fprintf(vstats_file
, "type= %c\n", av_get_picture_type_char(enc
->coded_frame
->pict_type
));
1467 static void print_report(OutputFile
*output_files
,
1468 OutputStream
*ost_table
, int nb_ostreams
,
1469 int is_last_report
, int64_t timer_start
)
1473 AVFormatContext
*oc
;
1475 AVCodecContext
*enc
;
1476 int frame_number
, vid
, i
;
1477 double bitrate
, ti1
, pts
;
1478 static int64_t last_time
= -1;
1479 static int qp_histogram
[52];
1481 if (!print_stats
&& !is_last_report
)
1484 if (!is_last_report
) {
1486 /* display the report every 0.5 seconds */
1487 cur_time
= av_gettime();
1488 if (last_time
== -1) {
1489 last_time
= cur_time
;
1492 if ((cur_time
- last_time
) < 500000)
1494 last_time
= cur_time
;
1498 oc
= output_files
[0].ctx
;
1500 total_size
= avio_size(oc
->pb
);
1501 if(total_size
<0) // FIXME improve avio_size() so it works with non seekable output too
1502 total_size
= avio_tell(oc
->pb
);
1507 for(i
=0;i
<nb_ostreams
;i
++) {
1509 ost
= &ost_table
[i
];
1510 enc
= ost
->st
->codec
;
1511 if (!ost
->stream_copy
&& enc
->coded_frame
)
1512 q
= enc
->coded_frame
->quality
/(float)FF_QP2LAMBDA
;
1513 if (vid
&& enc
->codec_type
== AVMEDIA_TYPE_VIDEO
) {
1514 snprintf(buf
+ strlen(buf
), sizeof(buf
) - strlen(buf
), "q=%2.1f ", q
);
1516 if (!vid
&& enc
->codec_type
== AVMEDIA_TYPE_VIDEO
) {
1517 float t
= (av_gettime()-timer_start
) / 1000000.0;
1519 frame_number
= ost
->frame_number
;
1520 snprintf(buf
+ strlen(buf
), sizeof(buf
) - strlen(buf
), "frame=%5d fps=%3d q=%3.1f ",
1521 frame_number
, (t
>1)?
(int)(frame_number
/t
+0.5) : 0, q
);
1523 snprintf(buf
+ strlen(buf
), sizeof(buf
) - strlen(buf
), "L");
1527 if(qp
>=0 && qp
<FF_ARRAY_ELEMS(qp_histogram
))
1530 snprintf(buf
+ strlen(buf
), sizeof(buf
) - strlen(buf
), "%X", (int)lrintf(log(qp_histogram
[j
]+1)/log(2)));
1532 if (enc
->flags
&CODEC_FLAG_PSNR
){
1534 double error
, error_sum
=0;
1535 double scale
, scale_sum
=0;
1536 char type
[3]= {'Y','U','V'};
1537 snprintf(buf
+ strlen(buf
), sizeof(buf
) - strlen(buf
), "PSNR=");
1540 error
= enc
->error
[j
];
1541 scale
= enc
->width
*enc
->height
*255.0*255.0*frame_number
;
1543 error
= enc
->coded_frame
->error
[j
];
1544 scale
= enc
->width
*enc
->height
*255.0*255.0;
1549 snprintf(buf
+ strlen(buf
), sizeof(buf
) - strlen(buf
), "%c:%2.2f ", type
[j
], psnr(error
/scale
));
1551 snprintf(buf
+ strlen(buf
), sizeof(buf
) - strlen(buf
), "*:%2.2f ", psnr(error_sum
/scale_sum
));
1555 /* compute min output value */
1556 pts
= (double)ost
->st
->pts
.val
* av_q2d(ost
->st
->time_base
);
1557 if ((pts
< ti1
) && (pts
> 0))
1563 bitrate
= (double)(total_size
* 8) / ti1
/ 1000.0;
1565 snprintf(buf
+ strlen(buf
), sizeof(buf
) - strlen(buf
),
1566 "size=%8.0fkB time=%0.2f bitrate=%6.1fkbits/s",
1567 (double)total_size
/ 1024, ti1
, bitrate
);
1569 if (nb_frames_dup
|| nb_frames_drop
)
1570 snprintf(buf
+ strlen(buf
), sizeof(buf
) - strlen(buf
), " dup=%d drop=%d",
1571 nb_frames_dup
, nb_frames_drop
);
1573 av_log(NULL
, AV_LOG_INFO
, "%s \r", buf
);
1577 if (is_last_report
) {
1578 int64_t raw
= audio_size
+ video_size
+ extra_size
;
1579 av_log(NULL
, AV_LOG_INFO
, "\n");
1580 av_log(NULL
, AV_LOG_INFO
, "video:%1.0fkB audio:%1.0fkB global headers:%1.0fkB muxing overhead %f%%\n",
1584 100.0*(total_size
- raw
)/raw
1589 static void flush_encoders(OutputStream
*ost_table
, int nb_ostreams
)
1593 for (i
= 0; i
< nb_ostreams
; i
++) {
1594 OutputStream
*ost
= &ost_table
[i
];
1595 AVCodecContext
*enc
= ost
->st
->codec
;
1596 AVFormatContext
*os
= output_files
[ost
->file_index
].ctx
;
1598 if (!ost
->encoding_needed
)
1601 if (ost
->st
->codec
->codec_type
== AVMEDIA_TYPE_AUDIO
&& enc
->frame_size
<=1)
1603 if (ost
->st
->codec
->codec_type
== AVMEDIA_TYPE_VIDEO
&& (os
->oformat
->flags
& AVFMT_RAWPICTURE
) && enc
->codec
->id
== CODEC_ID_RAWVIDEO
)
1609 av_init_packet(&pkt
);
1610 pkt
.stream_index
= ost
->index
;
1612 switch (ost
->st
->codec
->codec_type
) {
1613 case AVMEDIA_TYPE_AUDIO
:
1614 fifo_bytes
= av_fifo_size(ost
->fifo
);
1616 /* encode any samples remaining in fifo */
1617 if (fifo_bytes
> 0) {
1618 int osize
= av_get_bytes_per_sample(enc
->sample_fmt
);
1619 int fs_tmp
= enc
->frame_size
;
1621 av_fifo_generic_read(ost
->fifo
, audio_buf
, fifo_bytes
, NULL
);
1622 if (enc
->codec
->capabilities
& CODEC_CAP_SMALL_LAST_FRAME
) {
1623 enc
->frame_size
= fifo_bytes
/ (osize
* enc
->channels
);
1625 int frame_bytes
= enc
->frame_size
*osize
*enc
->channels
;
1626 if (allocated_audio_buf_size
< frame_bytes
)
1628 generate_silence(audio_buf
+fifo_bytes
, enc
->sample_fmt
, frame_bytes
- fifo_bytes
);
1631 ret
= avcodec_encode_audio(enc
, bit_buffer
, bit_buffer_size
, (short *)audio_buf
);
1632 pkt
.duration
= av_rescale((int64_t)enc
->frame_size
*ost
->st
->time_base
.den
,
1633 ost
->st
->time_base
.num
, enc
->sample_rate
);
1634 enc
->frame_size
= fs_tmp
;
1637 ret
= avcodec_encode_audio(enc
, bit_buffer
, bit_buffer_size
, NULL
);
1640 av_log(NULL
, AV_LOG_FATAL
, "Audio encoding failed\n");
1644 pkt
.flags
|= AV_PKT_FLAG_KEY
;
1646 case AVMEDIA_TYPE_VIDEO
:
1647 ret
= avcodec_encode_video(enc
, bit_buffer
, bit_buffer_size
, NULL
);
1649 av_log(NULL
, AV_LOG_FATAL
, "Video encoding failed\n");
1653 if(enc
->coded_frame
&& enc
->coded_frame
->key_frame
)
1654 pkt
.flags
|= AV_PKT_FLAG_KEY
;
1655 if (ost
->logfile
&& enc
->stats_out
) {
1656 fprintf(ost
->logfile
, "%s", enc
->stats_out
);
1665 pkt
.data
= bit_buffer
;
1667 if (enc
->coded_frame
&& enc
->coded_frame
->pts
!= AV_NOPTS_VALUE
)
1668 pkt
.pts
= av_rescale_q(enc
->coded_frame
->pts
, enc
->time_base
, ost
->st
->time_base
);
1669 write_frame(os
, &pkt
, ost
->st
->codec
, ost
->bitstream_filters
);
1675 * Check whether a packet from ist should be written into ost at this time
1677 static int check_output_constraints(InputStream
*ist
, OutputStream
*ost
)
1679 OutputFile
*of
= &output_files
[ost
->file_index
];
1680 int ist_index
= ist
- input_streams
;
1682 if (ost
->source_index
!= ist_index
)
1685 if (of
->start_time
&& ist
->pts
< of
->start_time
)
1688 if (of
->recording_time
!= INT64_MAX
&&
1689 av_compare_ts(ist
->pts
, AV_TIME_BASE_Q
, of
->recording_time
+ of
->start_time
,
1690 (AVRational
){1, 1000000}) >= 0) {
1691 ost
->is_past_recording_time
= 1;
1698 static void do_streamcopy(InputStream
*ist
, OutputStream
*ost
, const AVPacket
*pkt
)
1700 OutputFile
*of
= &output_files
[ost
->file_index
];
1701 int64_t ost_tb_start_time
= av_rescale_q(of
->start_time
, AV_TIME_BASE_Q
, ost
->st
->time_base
);
1704 av_init_packet(&opkt
);
1706 if ((!ost
->frame_number
&& !(pkt
->flags
& AV_PKT_FLAG_KEY
)) &&
1707 !ost
->copy_initial_nonkeyframes
)
1710 /* force the input stream PTS */
1711 if (ost
->st
->codec
->codec_type
== AVMEDIA_TYPE_AUDIO
)
1712 audio_size
+= pkt
->size
;
1713 else if (ost
->st
->codec
->codec_type
== AVMEDIA_TYPE_VIDEO
) {
1714 video_size
+= pkt
->size
;
1718 opkt
.stream_index
= ost
->index
;
1719 if (pkt
->pts
!= AV_NOPTS_VALUE
)
1720 opkt
.pts
= av_rescale_q(pkt
->pts
, ist
->st
->time_base
, ost
->st
->time_base
) - ost_tb_start_time
;
1722 opkt
.pts
= AV_NOPTS_VALUE
;
1724 if (pkt
->dts
== AV_NOPTS_VALUE
)
1725 opkt
.dts
= av_rescale_q(ist
->pts
, AV_TIME_BASE_Q
, ost
->st
->time_base
);
1727 opkt
.dts
= av_rescale_q(pkt
->dts
, ist
->st
->time_base
, ost
->st
->time_base
);
1728 opkt
.dts
-= ost_tb_start_time
;
1730 opkt
.duration
= av_rescale_q(pkt
->duration
, ist
->st
->time_base
, ost
->st
->time_base
);
1731 opkt
.flags
= pkt
->flags
;
1733 //FIXME remove the following 2 lines they shall be replaced by the bitstream filters
1734 if( ost
->st
->codec
->codec_id
!= CODEC_ID_H264
1735 && ost
->st
->codec
->codec_id
!= CODEC_ID_MPEG1VIDEO
1736 && ost
->st
->codec
->codec_id
!= CODEC_ID_MPEG2VIDEO
1738 if (av_parser_change(ist
->st
->parser
, ost
->st
->codec
, &opkt
.data
, &opkt
.size
, pkt
->data
, pkt
->size
, pkt
->flags
& AV_PKT_FLAG_KEY
))
1739 opkt
.destruct
= av_destruct_packet
;
1741 opkt
.data
= pkt
->data
;
1742 opkt
.size
= pkt
->size
;
1745 write_frame(of
->ctx
, &opkt
, ost
->st
->codec
, ost
->bitstream_filters
);
1746 ost
->st
->codec
->frame_number
++;
1747 ost
->frame_number
++;
1748 av_free_packet(&opkt
);
1751 static void rate_emu_sleep(InputStream
*ist
)
1753 if (input_files
[ist
->file_index
].rate_emu
) {
1754 int64_t pts
= av_rescale(ist
->pts
, 1000000, AV_TIME_BASE
);
1755 int64_t now
= av_gettime() - ist
->start
;
1761 static int transcode_audio(InputStream
*ist
, AVPacket
*pkt
, int *got_output
)
1763 AVFrame
*decoded_frame
;
1764 AVCodecContext
*avctx
= ist
->st
->codec
;
1765 int bps
= av_get_bytes_per_sample(ist
->st
->codec
->sample_fmt
);
1768 if (!ist
->decoded_frame
&& !(ist
->decoded_frame
= avcodec_alloc_frame()))
1769 return AVERROR(ENOMEM
);
1771 avcodec_get_frame_defaults(ist
->decoded_frame
);
1772 decoded_frame
= ist
->decoded_frame
;
1774 ret
= avcodec_decode_audio4(avctx
, decoded_frame
, got_output
, pkt
);
1780 /* no audio frame */
1784 /* if the decoder provides a pts, use it instead of the last packet pts.
1785 the decoder could be delaying output by a packet or more. */
1786 if (decoded_frame
->pts
!= AV_NOPTS_VALUE
)
1787 ist
->next_pts
= decoded_frame
->pts
;
1789 /* increment next_pts to use for the case where the input stream does not
1790 have timestamps or there are multiple frames in the packet */
1791 ist
->next_pts
+= ((int64_t)AV_TIME_BASE
* decoded_frame
->nb_samples
) /
1794 // preprocess audio (volume)
1795 if (audio_volume
!= 256) {
1796 int decoded_data_size
= decoded_frame
->nb_samples
* avctx
->channels
* bps
;
1797 void *samples
= decoded_frame
->data
[0];
1798 switch (avctx
->sample_fmt
) {
1799 case AV_SAMPLE_FMT_U8
:
1801 uint8_t *volp
= samples
;
1802 for (i
= 0; i
< (decoded_data_size
/ sizeof(*volp
)); i
++) {
1803 int v
= (((*volp
- 128) * audio_volume
+ 128) >> 8) + 128;
1804 *volp
++ = av_clip_uint8(v
);
1808 case AV_SAMPLE_FMT_S16
:
1810 int16_t *volp
= samples
;
1811 for (i
= 0; i
< (decoded_data_size
/ sizeof(*volp
)); i
++) {
1812 int v
= ((*volp
) * audio_volume
+ 128) >> 8;
1813 *volp
++ = av_clip_int16(v
);
1817 case AV_SAMPLE_FMT_S32
:
1819 int32_t *volp
= samples
;
1820 for (i
= 0; i
< (decoded_data_size
/ sizeof(*volp
)); i
++) {
1821 int64_t v
= (((int64_t)*volp
* audio_volume
+ 128) >> 8);
1822 *volp
++ = av_clipl_int32(v
);
1826 case AV_SAMPLE_FMT_FLT
:
1828 float *volp
= samples
;
1829 float scale
= audio_volume
/ 256.f
;
1830 for (i
= 0; i
< (decoded_data_size
/ sizeof(*volp
)); i
++) {
1835 case AV_SAMPLE_FMT_DBL
:
1837 double *volp
= samples
;
1838 double scale
= audio_volume
/ 256.;
1839 for (i
= 0; i
< (decoded_data_size
/ sizeof(*volp
)); i
++) {
1845 av_log(NULL
, AV_LOG_FATAL
,
1846 "Audio volume adjustment on sample format %s is not supported.\n",
1847 av_get_sample_fmt_name(ist
->st
->codec
->sample_fmt
));
1852 rate_emu_sleep(ist
);
1854 for (i
= 0; i
< nb_output_streams
; i
++) {
1855 OutputStream
*ost
= &output_streams
[i
];
1857 if (!check_output_constraints(ist
, ost
) || !ost
->encoding_needed
)
1859 do_audio_out(output_files
[ost
->file_index
].ctx
, ost
, ist
, decoded_frame
);
1865 static int transcode_video(InputStream
*ist
, AVPacket
*pkt
, int *got_output
, int64_t *pkt_pts
)
1867 AVFrame
*decoded_frame
, *filtered_frame
= NULL
;
1868 void *buffer_to_free
= NULL
;
1872 int frame_available
= 1;
1875 if (!ist
->decoded_frame
&& !(ist
->decoded_frame
= avcodec_alloc_frame()))
1876 return AVERROR(ENOMEM
);
1878 avcodec_get_frame_defaults(ist
->decoded_frame
);
1879 decoded_frame
= ist
->decoded_frame
;
1880 pkt
->pts
= *pkt_pts
;
1881 pkt
->dts
= ist
->pts
;
1882 *pkt_pts
= AV_NOPTS_VALUE
;
1884 ret
= avcodec_decode_video2(ist
->st
->codec
,
1885 decoded_frame
, got_output
, pkt
);
1889 quality
= same_quant ? decoded_frame
->quality
: 0;
1891 /* no picture yet */
1894 ist
->next_pts
= ist
->pts
= guess_correct_pts(&ist
->pts_ctx
, decoded_frame
->pkt_pts
,
1895 decoded_frame
->pkt_dts
);
1897 ist
->next_pts
+= av_rescale_q(pkt
->duration
, ist
->st
->time_base
, AV_TIME_BASE_Q
);
1898 else if (ist
->st
->codec
->time_base
.num
!= 0) {
1899 int ticks
= ist
->st
->parser ? ist
->st
->parser
->repeat_pict
+ 1 :
1900 ist
->st
->codec
->ticks_per_frame
;
1901 ist
->next_pts
+= ((int64_t)AV_TIME_BASE
*
1902 ist
->st
->codec
->time_base
.num
* ticks
) /
1903 ist
->st
->codec
->time_base
.den
;
1906 pre_process_video_frame(ist
, (AVPicture
*)decoded_frame
, &buffer_to_free
);
1908 rate_emu_sleep(ist
);
1910 for (i
= 0; i
< nb_output_streams
; i
++) {
1911 OutputStream
*ost
= &output_streams
[i
];
1914 if (!check_output_constraints(ist
, ost
) || !ost
->encoding_needed
)
1918 if (ost
->input_video_filter
) {
1920 if (ist
->st
->sample_aspect_ratio
.num
)
1921 sar
= ist
->st
->sample_aspect_ratio
;
1923 sar
= ist
->st
->codec
->sample_aspect_ratio
;
1924 av_vsrc_buffer_add_frame(ost
->input_video_filter
, decoded_frame
, ist
->pts
, sar
);
1925 if (!ist
->filtered_frame
&& !(ist
->filtered_frame
= avcodec_alloc_frame())) {
1926 av_free(buffer_to_free
);
1927 return AVERROR(ENOMEM
);
1929 avcodec_get_frame_defaults(ist
->filtered_frame
);
1930 filtered_frame
= ist
->filtered_frame
;
1931 frame_available
= avfilter_poll_frame(ost
->output_video_filter
->inputs
[0]);
1933 while (frame_available
) {
1934 AVRational ist_pts_tb
;
1935 if (ost
->output_video_filter
)
1936 get_filtered_video_frame(ost
->output_video_filter
, filtered_frame
, &ost
->picref
, &ist_pts_tb
);
1938 ist
->pts
= av_rescale_q(ost
->picref
->pts
, ist_pts_tb
, AV_TIME_BASE_Q
);
1939 if (ost
->picref
->video
&& !ost
->frame_aspect_ratio
)
1940 ost
->st
->codec
->sample_aspect_ratio
= ost
->picref
->video
->pixel_aspect
;
1942 filtered_frame
= decoded_frame
;
1945 do_video_out(output_files
[ost
->file_index
].ctx
, ost
, ist
, filtered_frame
, &frame_size
,
1946 same_quant ? quality
: ost
->st
->codec
->global_quality
);
1947 if (vstats_filename
&& frame_size
)
1948 do_video_stats(output_files
[ost
->file_index
].ctx
, ost
, frame_size
);
1950 frame_available
= ost
->output_video_filter
&& avfilter_poll_frame(ost
->output_video_filter
->inputs
[0]);
1952 avfilter_unref_buffer(ost
->picref
);
1957 av_free(buffer_to_free
);
1961 static int transcode_subtitles(InputStream
*ist
, AVPacket
*pkt
, int *got_output
)
1963 AVSubtitle subtitle
;
1964 int i
, ret
= avcodec_decode_subtitle2(ist
->st
->codec
,
1965 &subtitle
, got_output
, pkt
);
1971 rate_emu_sleep(ist
);
1973 for (i
= 0; i
< nb_output_streams
; i
++) {
1974 OutputStream
*ost
= &output_streams
[i
];
1976 if (!check_output_constraints(ist
, ost
) || !ost
->encoding_needed
)
1979 do_subtitle_out(output_files
[ost
->file_index
].ctx
, ost
, ist
, &subtitle
, pkt
->pts
);
1982 avsubtitle_free(&subtitle
);
1986 /* pkt = NULL means EOF (needed to flush decoder buffers) */
1987 static int output_packet(InputStream
*ist
,
1988 OutputStream
*ost_table
, int nb_ostreams
,
1989 const AVPacket
*pkt
)
1993 int64_t pkt_pts
= AV_NOPTS_VALUE
;
1996 if (ist
->next_pts
== AV_NOPTS_VALUE
)
1997 ist
->next_pts
= ist
->pts
;
2001 av_init_packet(&avpkt
);
2009 if(pkt
->dts
!= AV_NOPTS_VALUE
)
2010 ist
->next_pts
= ist
->pts
= av_rescale_q(pkt
->dts
, ist
->st
->time_base
, AV_TIME_BASE_Q
);
2011 if(pkt
->pts
!= AV_NOPTS_VALUE
)
2012 pkt_pts
= av_rescale_q(pkt
->pts
, ist
->st
->time_base
, AV_TIME_BASE_Q
);
2014 //while we have more to decode or while the decoder did output something on EOF
2015 while (ist
->decoding_needed
&& (avpkt
.size
> 0 || (!pkt
&& got_output
))) {
2019 ist
->pts
= ist
->next_pts
;
2021 if (avpkt
.size
&& avpkt
.size
!= pkt
->size
) {
2022 av_log(NULL
, ist
->showed_multi_packet_warning ? AV_LOG_VERBOSE
: AV_LOG_WARNING
,
2023 "Multiple frames in a packet from stream %d\n", pkt
->stream_index
);
2024 ist
->showed_multi_packet_warning
= 1;
2027 switch(ist
->st
->codec
->codec_type
) {
2028 case AVMEDIA_TYPE_AUDIO
:
2029 ret
= transcode_audio (ist
, &avpkt
, &got_output
);
2031 case AVMEDIA_TYPE_VIDEO
:
2032 ret
= transcode_video (ist
, &avpkt
, &got_output
, &pkt_pts
);
2034 case AVMEDIA_TYPE_SUBTITLE
:
2035 ret
= transcode_subtitles(ist
, &avpkt
, &got_output
);
2043 // touch data and size only if not EOF
2053 /* handle stream copy */
2054 if (!ist
->decoding_needed
) {
2055 rate_emu_sleep(ist
);
2056 ist
->pts
= ist
->next_pts
;
2057 switch (ist
->st
->codec
->codec_type
) {
2058 case AVMEDIA_TYPE_AUDIO
:
2059 ist
->next_pts
+= ((int64_t)AV_TIME_BASE
* ist
->st
->codec
->frame_size
) /
2060 ist
->st
->codec
->sample_rate
;
2062 case AVMEDIA_TYPE_VIDEO
:
2063 if (ist
->st
->codec
->time_base
.num
!= 0) {
2064 int ticks
= ist
->st
->parser ? ist
->st
->parser
->repeat_pict
+1 : ist
->st
->codec
->ticks_per_frame
;
2065 ist
->next_pts
+= ((int64_t)AV_TIME_BASE
*
2066 ist
->st
->codec
->time_base
.num
* ticks
) /
2067 ist
->st
->codec
->time_base
.den
;
2072 for (i
= 0; pkt
&& i
< nb_ostreams
; i
++) {
2073 OutputStream
*ost
= &ost_table
[i
];
2075 if (!check_output_constraints(ist
, ost
) || ost
->encoding_needed
)
2078 do_streamcopy(ist
, ost
, pkt
);
2084 static void print_sdp(OutputFile
*output_files
, int n
)
2088 AVFormatContext
**avc
= av_malloc(sizeof(*avc
)*n
);
2092 for (i
= 0; i
< n
; i
++)
2093 avc
[i
] = output_files
[i
].ctx
;
2095 av_sdp_create(avc
, n
, sdp
, sizeof(sdp
));
2096 printf("SDP:\n%s\n", sdp
);
2101 static int init_input_stream(int ist_index
, OutputStream
*output_streams
, int nb_output_streams
,
2102 char *error
, int error_len
)
2105 InputStream
*ist
= &input_streams
[ist_index
];
2106 if (ist
->decoding_needed
) {
2107 AVCodec
*codec
= ist
->dec
;
2109 snprintf(error
, error_len
, "Decoder (codec id %d) not found for input stream #%d:%d",
2110 ist
->st
->codec
->codec_id
, ist
->file_index
, ist
->st
->index
);
2111 return AVERROR(EINVAL
);
2114 /* update requested sample format for the decoder based on the
2115 corresponding encoder sample format */
2116 for (i
= 0; i
< nb_output_streams
; i
++) {
2117 OutputStream
*ost
= &output_streams
[i
];
2118 if (ost
->source_index
== ist_index
) {
2119 update_sample_fmt(ist
->st
->codec
, codec
, ost
->st
->codec
);
2124 if (codec
->type
== AVMEDIA_TYPE_VIDEO
&& codec
->capabilities
& CODEC_CAP_DR1
) {
2125 ist
->st
->codec
->get_buffer
= codec_get_buffer
;
2126 ist
->st
->codec
->release_buffer
= codec_release_buffer
;
2127 ist
->st
->codec
->opaque
= ist
;
2130 if (avcodec_open2(ist
->st
->codec
, codec
, &ist
->opts
) < 0) {
2131 snprintf(error
, error_len
, "Error while opening decoder for input stream #%d:%d",
2132 ist
->file_index
, ist
->st
->index
);
2133 return AVERROR(EINVAL
);
2135 assert_codec_experimental(ist
->st
->codec
, 0);
2136 assert_avoptions(ist
->opts
);
2139 ist
->pts
= ist
->st
->avg_frame_rate
.num ?
- ist
->st
->codec
->has_b_frames
*AV_TIME_BASE
/ av_q2d(ist
->st
->avg_frame_rate
) : 0;
2140 ist
->next_pts
= AV_NOPTS_VALUE
;
2141 init_pts_correction(&ist
->pts_ctx
);
2147 static int transcode_init(OutputFile
*output_files
,
2148 int nb_output_files
,
2149 InputFile
*input_files
,
2152 int ret
= 0, i
, j
, k
;
2153 AVFormatContext
*oc
;
2154 AVCodecContext
*codec
, *icodec
;
2160 /* init framerate emulation */
2161 for (i
= 0; i
< nb_input_files
; i
++) {
2162 InputFile
*ifile
= &input_files
[i
];
2163 if (ifile
->rate_emu
)
2164 for (j
= 0; j
< ifile
->nb_streams
; j
++)
2165 input_streams
[j
+ ifile
->ist_index
].start
= av_gettime();
2168 /* output stream init */
2169 for (i
= 0; i
< nb_output_files
; i
++) {
2170 oc
= output_files
[i
].ctx
;
2171 if (!oc
->nb_streams
&& !(oc
->oformat
->flags
& AVFMT_NOSTREAMS
)) {
2172 av_dump_format(oc
, i
, oc
->filename
, 1);
2173 av_log(NULL
, AV_LOG_ERROR
, "Output file #%d does not contain any stream\n", i
);
2174 return AVERROR(EINVAL
);
2178 /* for each output stream, we compute the right encoding parameters */
2179 for (i
= 0; i
< nb_output_streams
; i
++) {
2180 ost
= &output_streams
[i
];
2181 oc
= output_files
[ost
->file_index
].ctx
;
2182 ist
= &input_streams
[ost
->source_index
];
2184 if (ost
->attachment_filename
)
2187 codec
= ost
->st
->codec
;
2188 icodec
= ist
->st
->codec
;
2190 ost
->st
->disposition
= ist
->st
->disposition
;
2191 codec
->bits_per_raw_sample
= icodec
->bits_per_raw_sample
;
2192 codec
->chroma_sample_location
= icodec
->chroma_sample_location
;
2194 if (ost
->stream_copy
) {
2195 uint64_t extra_size
= (uint64_t)icodec
->extradata_size
+ FF_INPUT_BUFFER_PADDING_SIZE
;
2197 if (extra_size
> INT_MAX
) {
2198 return AVERROR(EINVAL
);
2201 /* if stream_copy is selected, no need to decode or encode */
2202 codec
->codec_id
= icodec
->codec_id
;
2203 codec
->codec_type
= icodec
->codec_type
;
2205 if (!codec
->codec_tag
) {
2206 if (!oc
->oformat
->codec_tag
||
2207 av_codec_get_id (oc
->oformat
->codec_tag
, icodec
->codec_tag
) == codec
->codec_id
||
2208 av_codec_get_tag(oc
->oformat
->codec_tag
, icodec
->codec_id
) <= 0)
2209 codec
->codec_tag
= icodec
->codec_tag
;
2212 codec
->bit_rate
= icodec
->bit_rate
;
2213 codec
->rc_max_rate
= icodec
->rc_max_rate
;
2214 codec
->rc_buffer_size
= icodec
->rc_buffer_size
;
2215 codec
->field_order
= icodec
->field_order
;
2216 codec
->extradata
= av_mallocz(extra_size
);
2217 if (!codec
->extradata
) {
2218 return AVERROR(ENOMEM
);
2220 memcpy(codec
->extradata
, icodec
->extradata
, icodec
->extradata_size
);
2221 codec
->extradata_size
= icodec
->extradata_size
;
2223 codec
->time_base
= icodec
->time_base
;
2224 codec
->time_base
.num
*= icodec
->ticks_per_frame
;
2225 av_reduce(&codec
->time_base
.num
, &codec
->time_base
.den
,
2226 codec
->time_base
.num
, codec
->time_base
.den
, INT_MAX
);
2228 codec
->time_base
= ist
->st
->time_base
;
2230 switch(codec
->codec_type
) {
2231 case AVMEDIA_TYPE_AUDIO
:
2232 if(audio_volume
!= 256) {
2233 av_log(NULL
, AV_LOG_FATAL
, "-acodec copy and -vol are incompatible (frames are not decoded)\n");
2236 codec
->channel_layout
= icodec
->channel_layout
;
2237 codec
->sample_rate
= icodec
->sample_rate
;
2238 codec
->channels
= icodec
->channels
;
2239 codec
->frame_size
= icodec
->frame_size
;
2240 codec
->audio_service_type
= icodec
->audio_service_type
;
2241 codec
->block_align
= icodec
->block_align
;
2243 case AVMEDIA_TYPE_VIDEO
:
2244 codec
->pix_fmt
= icodec
->pix_fmt
;
2245 codec
->width
= icodec
->width
;
2246 codec
->height
= icodec
->height
;
2247 codec
->has_b_frames
= icodec
->has_b_frames
;
2248 if (!codec
->sample_aspect_ratio
.num
) {
2249 codec
->sample_aspect_ratio
=
2250 ost
->st
->sample_aspect_ratio
=
2251 ist
->st
->sample_aspect_ratio
.num ? ist
->st
->sample_aspect_ratio
:
2252 ist
->st
->codec
->sample_aspect_ratio
.num ?
2253 ist
->st
->codec
->sample_aspect_ratio
: (AVRational
){0, 1};
2256 case AVMEDIA_TYPE_SUBTITLE
:
2257 codec
->width
= icodec
->width
;
2258 codec
->height
= icodec
->height
;
2260 case AVMEDIA_TYPE_DATA
:
2261 case AVMEDIA_TYPE_ATTACHMENT
:
2268 ost
->enc
= avcodec_find_encoder(ost
->st
->codec
->codec_id
);
2270 ist
->decoding_needed
= 1;
2271 ost
->encoding_needed
= 1;
2273 switch(codec
->codec_type
) {
2274 case AVMEDIA_TYPE_AUDIO
:
2275 ost
->fifo
= av_fifo_alloc(1024);
2277 return AVERROR(ENOMEM
);
2279 ost
->reformat_pair
= MAKE_SFMT_PAIR(AV_SAMPLE_FMT_NONE
,AV_SAMPLE_FMT_NONE
);
2281 if (!codec
->sample_rate
)
2282 codec
->sample_rate
= icodec
->sample_rate
;
2283 choose_sample_rate(ost
->st
, ost
->enc
);
2284 codec
->time_base
= (AVRational
){1, codec
->sample_rate
};
2286 if (codec
->sample_fmt
== AV_SAMPLE_FMT_NONE
)
2287 codec
->sample_fmt
= icodec
->sample_fmt
;
2288 choose_sample_fmt(ost
->st
, ost
->enc
);
2290 if (!codec
->channels
)
2291 codec
->channels
= icodec
->channels
;
2292 codec
->channel_layout
= icodec
->channel_layout
;
2293 if (av_get_channel_layout_nb_channels(codec
->channel_layout
) != codec
->channels
)
2294 codec
->channel_layout
= 0;
2296 ost
->audio_resample
= codec
-> sample_rate
!= icodec
->sample_rate
|| audio_sync_method
> 1;
2297 icodec
->request_channels
= codec
-> channels
;
2298 ost
->resample_sample_fmt
= icodec
->sample_fmt
;
2299 ost
->resample_sample_rate
= icodec
->sample_rate
;
2300 ost
->resample_channels
= icodec
->channels
;
2302 case AVMEDIA_TYPE_VIDEO
:
2303 if (codec
->pix_fmt
== PIX_FMT_NONE
)
2304 codec
->pix_fmt
= icodec
->pix_fmt
;
2305 choose_pixel_fmt(ost
->st
, ost
->enc
);
2307 if (ost
->st
->codec
->pix_fmt
== PIX_FMT_NONE
) {
2308 av_log(NULL
, AV_LOG_FATAL
, "Video pixel format is unknown, stream cannot be encoded\n");
2312 if (!codec
->width
|| !codec
->height
) {
2313 codec
->width
= icodec
->width
;
2314 codec
->height
= icodec
->height
;
2317 ost
->video_resample
= codec
->width
!= icodec
->width
||
2318 codec
->height
!= icodec
->height
||
2319 codec
->pix_fmt
!= icodec
->pix_fmt
;
2320 if (ost
->video_resample
) {
2321 #if !CONFIG_AVFILTER
2322 avcodec_get_frame_defaults(&ost
->pict_tmp
);
2323 if(avpicture_alloc((AVPicture
*)&ost
->pict_tmp
, codec
->pix_fmt
,
2324 codec
->width
, codec
->height
)) {
2325 av_log(NULL
, AV_LOG_FATAL
, "Cannot allocate temp picture, check pix fmt\n");
2328 ost
->img_resample_ctx
= sws_getContext(
2335 ost
->sws_flags
, NULL
, NULL
, NULL
);
2336 if (ost
->img_resample_ctx
== NULL
) {
2337 av_log(NULL
, AV_LOG_FATAL
, "Cannot get resampling context\n");
2341 codec
->bits_per_raw_sample
= 0;
2344 ost
->resample_height
= icodec
->height
;
2345 ost
->resample_width
= icodec
->width
;
2346 ost
->resample_pix_fmt
= icodec
->pix_fmt
;
2348 if (!ost
->frame_rate
.num
)
2349 ost
->frame_rate
= ist
->st
->r_frame_rate
.num ? ist
->st
->r_frame_rate
: (AVRational
){25,1};
2350 if (ost
->enc
&& ost
->enc
->supported_framerates
&& !ost
->force_fps
) {
2351 int idx
= av_find_nearest_q_idx(ost
->frame_rate
, ost
->enc
->supported_framerates
);
2352 ost
->frame_rate
= ost
->enc
->supported_framerates
[idx
];
2354 codec
->time_base
= (AVRational
){ost
->frame_rate
.den
, ost
->frame_rate
.num
};
2357 if (configure_video_filters(ist
, ost
)) {
2358 av_log(NULL
, AV_LOG_FATAL
, "Error opening filters!\n");
2363 case AVMEDIA_TYPE_SUBTITLE
:
2370 if ((codec
->flags
& (CODEC_FLAG_PASS1
| CODEC_FLAG_PASS2
))) {
2371 char logfilename
[1024];
2374 snprintf(logfilename
, sizeof(logfilename
), "%s-%d.log",
2375 pass_logfilename_prefix ? pass_logfilename_prefix
: DEFAULT_PASS_LOGFILENAME_PREFIX
,
2377 if (codec
->flags
& CODEC_FLAG_PASS1
) {
2378 f
= fopen(logfilename
, "wb");
2380 av_log(NULL
, AV_LOG_FATAL
, "Cannot write log file '%s' for pass-1 encoding: %s\n",
2381 logfilename
, strerror(errno
));
2387 size_t logbuffer_size
;
2388 if (cmdutils_read_file(logfilename
, &logbuffer
, &logbuffer_size
) < 0) {
2389 av_log(NULL
, AV_LOG_FATAL
, "Error reading log file '%s' for pass-2 encoding\n",
2393 codec
->stats_in
= logbuffer
;
2397 if(codec
->codec_type
== AVMEDIA_TYPE_VIDEO
){
2398 int size
= codec
->width
* codec
->height
;
2399 bit_buffer_size
= FFMAX(bit_buffer_size
, 6*size
+ 200);
2404 bit_buffer
= av_malloc(bit_buffer_size
);
2406 av_log(NULL
, AV_LOG_ERROR
, "Cannot allocate %d bytes output buffer\n",
2408 return AVERROR(ENOMEM
);
2411 /* open each encoder */
2412 for (i
= 0; i
< nb_output_streams
; i
++) {
2413 ost
= &output_streams
[i
];
2414 if (ost
->encoding_needed
) {
2415 AVCodec
*codec
= ost
->enc
;
2416 AVCodecContext
*dec
= input_streams
[ost
->source_index
].st
->codec
;
2418 snprintf(error
, sizeof(error
), "Encoder (codec id %d) not found for output stream #%d:%d",
2419 ost
->st
->codec
->codec_id
, ost
->file_index
, ost
->index
);
2420 ret
= AVERROR(EINVAL
);
2423 if (dec
->subtitle_header
) {
2424 ost
->st
->codec
->subtitle_header
= av_malloc(dec
->subtitle_header_size
);
2425 if (!ost
->st
->codec
->subtitle_header
) {
2426 ret
= AVERROR(ENOMEM
);
2429 memcpy(ost
->st
->codec
->subtitle_header
, dec
->subtitle_header
, dec
->subtitle_header_size
);
2430 ost
->st
->codec
->subtitle_header_size
= dec
->subtitle_header_size
;
2432 if (avcodec_open2(ost
->st
->codec
, codec
, &ost
->opts
) < 0) {
2433 snprintf(error
, sizeof(error
), "Error while opening encoder for output stream #%d:%d - maybe incorrect parameters such as bit_rate, rate, width or height",
2434 ost
->file_index
, ost
->index
);
2435 ret
= AVERROR(EINVAL
);
2438 assert_codec_experimental(ost
->st
->codec
, 1);
2439 assert_avoptions(ost
->opts
);
2440 if (ost
->st
->codec
->bit_rate
&& ost
->st
->codec
->bit_rate
< 1000)
2441 av_log(NULL
, AV_LOG_WARNING
, "The bitrate parameter is set too low."
2442 "It takes bits/s as argument, not kbits/s\n");
2443 extra_size
+= ost
->st
->codec
->extradata_size
;
2445 if (ost
->st
->codec
->me_threshold
)
2446 input_streams
[ost
->source_index
].st
->codec
->debug
|= FF_DEBUG_MV
;
2450 /* init input streams */
2451 for (i
= 0; i
< nb_input_streams
; i
++)
2452 if ((ret
= init_input_stream(i
, output_streams
, nb_output_streams
, error
, sizeof(error
))) < 0)
2455 /* discard unused programs */
2456 for (i
= 0; i
< nb_input_files
; i
++) {
2457 InputFile
*ifile
= &input_files
[i
];
2458 for (j
= 0; j
< ifile
->ctx
->nb_programs
; j
++) {
2459 AVProgram
*p
= ifile
->ctx
->programs
[j
];
2460 int discard
= AVDISCARD_ALL
;
2462 for (k
= 0; k
< p
->nb_stream_indexes
; k
++)
2463 if (!input_streams
[ifile
->ist_index
+ p
->stream_index
[k
]].discard
) {
2464 discard
= AVDISCARD_DEFAULT
;
2467 p
->discard
= discard
;
2471 /* open files and write file headers */
2472 for (i
= 0; i
< nb_output_files
; i
++) {
2473 oc
= output_files
[i
].ctx
;
2474 oc
->interrupt_callback
= int_cb
;
2475 if (avformat_write_header(oc
, &output_files
[i
].opts
) < 0) {
2476 snprintf(error
, sizeof(error
), "Could not write header for output file #%d (incorrect codec parameters ?)", i
);
2477 ret
= AVERROR(EINVAL
);
2480 assert_avoptions(output_files
[i
].opts
);
2481 if (strcmp(oc
->oformat
->name
, "rtp")) {
2487 /* dump the file output parameters - cannot be done before in case
2489 for (i
= 0; i
< nb_output_files
; i
++) {
2490 av_dump_format(output_files
[i
].ctx
, i
, output_files
[i
].ctx
->filename
, 1);
2493 /* dump the stream mapping */
2494 av_log(NULL
, AV_LOG_INFO
, "Stream mapping:\n");
2495 for (i
= 0; i
< nb_output_streams
; i
++) {
2496 ost
= &output_streams
[i
];
2498 if (ost
->attachment_filename
) {
2499 /* an attached file */
2500 av_log(NULL
, AV_LOG_INFO
, " File %s -> Stream #%d:%d\n",
2501 ost
->attachment_filename
, ost
->file_index
, ost
->index
);
2504 av_log(NULL
, AV_LOG_INFO
, " Stream #%d:%d -> #%d:%d",
2505 input_streams
[ost
->source_index
].file_index
,
2506 input_streams
[ost
->source_index
].st
->index
,
2509 if (ost
->sync_ist
!= &input_streams
[ost
->source_index
])
2510 av_log(NULL
, AV_LOG_INFO
, " [sync #%d:%d]",
2511 ost
->sync_ist
->file_index
,
2512 ost
->sync_ist
->st
->index
);
2513 if (ost
->stream_copy
)
2514 av_log(NULL
, AV_LOG_INFO
, " (copy)");
2516 av_log(NULL
, AV_LOG_INFO
, " (%s -> %s)", input_streams
[ost
->source_index
].dec ?
2517 input_streams
[ost
->source_index
].dec
->name
: "?",
2518 ost
->enc ? ost
->enc
->name
: "?");
2519 av_log(NULL
, AV_LOG_INFO
, "\n");
2523 av_log(NULL
, AV_LOG_ERROR
, "%s\n", error
);
2528 print_sdp(output_files
, nb_output_files
);
2535 * The following code is the main loop of the file converter
2537 static int transcode(OutputFile
*output_files
,
2538 int nb_output_files
,
2539 InputFile
*input_files
,
2543 AVFormatContext
*is
, *os
;
2547 int no_packet_count
=0;
2548 int64_t timer_start
;
2550 if (!(no_packet
= av_mallocz(nb_input_files
)))
2553 ret
= transcode_init(output_files
, nb_output_files
, input_files
, nb_input_files
);
2557 av_log(NULL
, AV_LOG_INFO
, "Press ctrl-c to stop encoding\n");
2560 timer_start
= av_gettime();
2562 for(; received_sigterm
== 0;) {
2563 int file_index
, ist_index
;
2568 ipts_min
= INT64_MAX
;
2571 /* select the stream that we must read now by looking at the
2572 smallest output pts */
2574 for (i
= 0; i
< nb_output_streams
; i
++) {
2578 ost
= &output_streams
[i
];
2579 of
= &output_files
[ost
->file_index
];
2580 os
= output_files
[ost
->file_index
].ctx
;
2581 ist
= &input_streams
[ost
->source_index
];
2582 if (ost
->is_past_recording_time
|| no_packet
[ist
->file_index
] ||
2583 (os
->pb
&& avio_tell(os
->pb
) >= of
->limit_filesize
))
2585 opts
= ost
->st
->pts
.val
* av_q2d(ost
->st
->time_base
);
2587 if (!input_files
[ist
->file_index
].eof_reached
){
2588 if(ipts
< ipts_min
) {
2590 if(input_sync
) file_index
= ist
->file_index
;
2592 if(opts
< opts_min
) {
2594 if(!input_sync
) file_index
= ist
->file_index
;
2597 if (ost
->frame_number
>= ost
->max_frames
) {
2599 for (j
= 0; j
< of
->ctx
->nb_streams
; j
++)
2600 output_streams
[of
->ost_index
+ j
].is_past_recording_time
= 1;
2604 /* if none, if is finished */
2605 if (file_index
< 0) {
2606 if(no_packet_count
){
2608 memset(no_packet
, 0, nb_input_files
);
2615 /* read a frame from it and output it in the fifo */
2616 is
= input_files
[file_index
].ctx
;
2617 ret
= av_read_frame(is
, &pkt
);
2618 if(ret
== AVERROR(EAGAIN
)){
2619 no_packet
[file_index
]=1;
2624 input_files
[file_index
].eof_reached
= 1;
2632 memset(no_packet
, 0, nb_input_files
);
2635 av_pkt_dump_log2(NULL
, AV_LOG_DEBUG
, &pkt
, do_hex_dump
,
2636 is
->streams
[pkt
.stream_index
]);
2638 /* the following test is needed in case new streams appear
2639 dynamically in stream : we ignore them */
2640 if (pkt
.stream_index
>= input_files
[file_index
].nb_streams
)
2641 goto discard_packet
;
2642 ist_index
= input_files
[file_index
].ist_index
+ pkt
.stream_index
;
2643 ist
= &input_streams
[ist_index
];
2645 goto discard_packet
;
2647 if (pkt
.dts
!= AV_NOPTS_VALUE
)
2648 pkt
.dts
+= av_rescale_q(input_files
[ist
->file_index
].ts_offset
, AV_TIME_BASE_Q
, ist
->st
->time_base
);
2649 if (pkt
.pts
!= AV_NOPTS_VALUE
)
2650 pkt
.pts
+= av_rescale_q(input_files
[ist
->file_index
].ts_offset
, AV_TIME_BASE_Q
, ist
->st
->time_base
);
2652 if(pkt
.pts
!= AV_NOPTS_VALUE
)
2653 pkt
.pts
*= ist
->ts_scale
;
2654 if(pkt
.dts
!= AV_NOPTS_VALUE
)
2655 pkt
.dts
*= ist
->ts_scale
;
2657 // fprintf(stderr, "next:%"PRId64" dts:%"PRId64" off:%"PRId64" %d\n", ist->next_pts, pkt.dts, input_files[ist->file_index].ts_offset, ist->st->codec->codec_type);
2658 if (pkt
.dts
!= AV_NOPTS_VALUE
&& ist
->next_pts
!= AV_NOPTS_VALUE
2659 && (is
->iformat
->flags
& AVFMT_TS_DISCONT
)) {
2660 int64_t pkt_dts
= av_rescale_q(pkt
.dts
, ist
->st
->time_base
, AV_TIME_BASE_Q
);
2661 int64_t delta
= pkt_dts
- ist
->next_pts
;
2662 if((FFABS(delta
) > 1LL*dts_delta_threshold
*AV_TIME_BASE
|| pkt_dts
+1<ist
->pts
)&& !copy_ts
){
2663 input_files
[ist
->file_index
].ts_offset
-= delta
;
2664 av_log(NULL
, AV_LOG_DEBUG
, "timestamp discontinuity %"PRId64
", new offset= %"PRId64
"\n",
2665 delta
, input_files
[ist
->file_index
].ts_offset
);
2666 pkt
.dts
-= av_rescale_q(delta
, AV_TIME_BASE_Q
, ist
->st
->time_base
);
2667 if(pkt
.pts
!= AV_NOPTS_VALUE
)
2668 pkt
.pts
-= av_rescale_q(delta
, AV_TIME_BASE_Q
, ist
->st
->time_base
);
2672 //fprintf(stderr,"read #%d.%d size=%d\n", ist->file_index, ist->st->index, pkt.size);
2673 if (output_packet(ist
, output_streams
, nb_output_streams
, &pkt
) < 0) {
2675 av_log(NULL
, AV_LOG_ERROR
, "Error while decoding stream #%d:%d\n",
2676 ist
->file_index
, ist
->st
->index
);
2679 av_free_packet(&pkt
);
2684 av_free_packet(&pkt
);
2686 /* dump report by using the output first video and audio streams */
2687 print_report(output_files
, output_streams
, nb_output_streams
, 0, timer_start
);
2690 /* at the end of stream, we must flush the decoder buffers */
2691 for (i
= 0; i
< nb_input_streams
; i
++) {
2692 ist
= &input_streams
[i
];
2693 if (ist
->decoding_needed
) {
2694 output_packet(ist
, output_streams
, nb_output_streams
, NULL
);
2697 flush_encoders(output_streams
, nb_output_streams
);
2701 /* write the trailer if needed and close file */
2702 for(i
=0;i
<nb_output_files
;i
++) {
2703 os
= output_files
[i
].ctx
;
2704 av_write_trailer(os
);
2707 /* dump report by using the first video and audio streams */
2708 print_report(output_files
, output_streams
, nb_output_streams
, 1, timer_start
);
2710 /* close each encoder */
2711 for (i
= 0; i
< nb_output_streams
; i
++) {
2712 ost
= &output_streams
[i
];
2713 if (ost
->encoding_needed
) {
2714 av_freep(&ost
->st
->codec
->stats_in
);
2715 avcodec_close(ost
->st
->codec
);
2718 avfilter_graph_free(&ost
->graph
);
2722 /* close each decoder */
2723 for (i
= 0; i
< nb_input_streams
; i
++) {
2724 ist
= &input_streams
[i
];
2725 if (ist
->decoding_needed
) {
2726 avcodec_close(ist
->st
->codec
);
2734 av_freep(&bit_buffer
);
2735 av_freep(&no_packet
);
2737 if (output_streams
) {
2738 for (i
= 0; i
< nb_output_streams
; i
++) {
2739 ost
= &output_streams
[i
];
2741 if (ost
->stream_copy
)
2742 av_freep(&ost
->st
->codec
->extradata
);
2744 fclose(ost
->logfile
);
2745 ost
->logfile
= NULL
;
2747 av_fifo_free(ost
->fifo
); /* works even if fifo is not
2748 initialized but set to zero */
2749 av_freep(&ost
->st
->codec
->subtitle_header
);
2750 av_free(ost
->pict_tmp
.data
[0]);
2751 av_free(ost
->forced_kf_pts
);
2752 if (ost
->video_resample
)
2753 sws_freeContext(ost
->img_resample_ctx
);
2755 audio_resample_close(ost
->resample
);
2756 if (ost
->reformat_ctx
)
2757 av_audio_convert_free(ost
->reformat_ctx
);
2758 av_dict_free(&ost
->opts
);
2765 static double parse_frame_aspect_ratio(const char *arg
)
2772 p
= strchr(arg
, ':');
2774 x
= strtol(arg
, &end
, 10);
2776 y
= strtol(end
+1, &end
, 10);
2778 ar
= (double)x
/ (double)y
;
2780 ar
= strtod(arg
, NULL
);
2783 av_log(NULL
, AV_LOG_FATAL
, "Incorrect aspect ratio specification.\n");
2789 static int opt_audio_codec(OptionsContext
*o
, const char *opt
, const char *arg
)
2791 return parse_option(o
, "codec:a", arg
, options
);
2794 static int opt_video_codec(OptionsContext
*o
, const char *opt
, const char *arg
)
2796 return parse_option(o
, "codec:v", arg
, options
);
2799 static int opt_subtitle_codec(OptionsContext
*o
, const char *opt
, const char *arg
)
2801 return parse_option(o
, "codec:s", arg
, options
);
2804 static int opt_data_codec(OptionsContext
*o
, const char *opt
, const char *arg
)
2806 return parse_option(o
, "codec:d", arg
, options
);
2809 static int opt_map(OptionsContext
*o
, const char *opt
, const char *arg
)
2811 StreamMap
*m
= NULL
;
2812 int i
, negative
= 0, file_idx
;
2813 int sync_file_idx
= -1, sync_stream_idx
;
2821 map
= av_strdup(arg
);
2823 /* parse sync stream first, just pick first matching stream */
2824 if (sync
= strchr(map
, ',')) {
2826 sync_file_idx
= strtol(sync
+ 1, &sync
, 0);
2827 if (sync_file_idx
>= nb_input_files
|| sync_file_idx
< 0) {
2828 av_log(NULL
, AV_LOG_FATAL
, "Invalid sync file index: %d.\n", sync_file_idx
);
2833 for (i
= 0; i
< input_files
[sync_file_idx
].nb_streams
; i
++)
2834 if (check_stream_specifier(input_files
[sync_file_idx
].ctx
,
2835 input_files
[sync_file_idx
].ctx
->streams
[i
], sync
) == 1) {
2836 sync_stream_idx
= i
;
2839 if (i
== input_files
[sync_file_idx
].nb_streams
) {
2840 av_log(NULL
, AV_LOG_FATAL
, "Sync stream specification in map %s does not "
2841 "match any streams.\n", arg
);
2847 file_idx
= strtol(map
, &p
, 0);
2848 if (file_idx
>= nb_input_files
|| file_idx
< 0) {
2849 av_log(NULL
, AV_LOG_FATAL
, "Invalid input file index: %d.\n", file_idx
);
2853 /* disable some already defined maps */
2854 for (i
= 0; i
< o
->nb_stream_maps
; i
++) {
2855 m
= &o
->stream_maps
[i
];
2856 if (file_idx
== m
->file_index
&&
2857 check_stream_specifier(input_files
[m
->file_index
].ctx
,
2858 input_files
[m
->file_index
].ctx
->streams
[m
->stream_index
],
2859 *p
== ':' ? p
+ 1 : p
) > 0)
2863 for (i
= 0; i
< input_files
[file_idx
].nb_streams
; i
++) {
2864 if (check_stream_specifier(input_files
[file_idx
].ctx
, input_files
[file_idx
].ctx
->streams
[i
],
2865 *p
== ':' ? p
+ 1 : p
) <= 0)
2867 o
->stream_maps
= grow_array(o
->stream_maps
, sizeof(*o
->stream_maps
),
2868 &o
->nb_stream_maps
, o
->nb_stream_maps
+ 1);
2869 m
= &o
->stream_maps
[o
->nb_stream_maps
- 1];
2871 m
->file_index
= file_idx
;
2872 m
->stream_index
= i
;
2874 if (sync_file_idx
>= 0) {
2875 m
->sync_file_index
= sync_file_idx
;
2876 m
->sync_stream_index
= sync_stream_idx
;
2878 m
->sync_file_index
= file_idx
;
2879 m
->sync_stream_index
= i
;
2884 av_log(NULL
, AV_LOG_FATAL
, "Stream map '%s' matches no streams.\n", arg
);
2892 static int opt_attach(OptionsContext
*o
, const char *opt
, const char *arg
)
2894 o
->attachments
= grow_array(o
->attachments
, sizeof(*o
->attachments
),
2895 &o
->nb_attachments
, o
->nb_attachments
+ 1);
2896 o
->attachments
[o
->nb_attachments
- 1] = arg
;
2901 * Parse a metadata specifier in arg.
2902 * @param type metadata type is written here -- g(lobal)/s(tream)/c(hapter)/p(rogram)
2903 * @param index for type c/p, chapter/program index is written here
2904 * @param stream_spec for type s, the stream specifier is written here
2906 static void parse_meta_type(char *arg
, char *type
, int *index
, const char **stream_spec
)
2914 if (*(++arg
) && *arg
!= ':') {
2915 av_log(NULL
, AV_LOG_FATAL
, "Invalid metadata specifier %s.\n", arg
);
2918 *stream_spec
= *arg
== ':' ? arg
+ 1 : "";
2922 if (*(++arg
) == ':')
2923 *index
= strtol(++arg
, NULL
, 0);
2926 av_log(NULL
, AV_LOG_FATAL
, "Invalid metadata type %c.\n", *arg
);
2933 static int copy_metadata(char *outspec
, char *inspec
, AVFormatContext
*oc
, AVFormatContext
*ic
, OptionsContext
*o
)
2935 AVDictionary
**meta_in
= NULL
;
2936 AVDictionary
**meta_out
;
2938 char type_in
, type_out
;
2939 const char *istream_spec
= NULL
, *ostream_spec
= NULL
;
2940 int idx_in
= 0, idx_out
= 0;
2942 parse_meta_type(inspec
, &type_in
, &idx_in
, &istream_spec
);
2943 parse_meta_type(outspec
, &type_out
, &idx_out
, &ostream_spec
);
2945 if (type_in
== 'g' || type_out
== 'g')
2946 o
->metadata_global_manual
= 1;
2947 if (type_in
== 's' || type_out
== 's')
2948 o
->metadata_streams_manual
= 1;
2949 if (type_in
== 'c' || type_out
== 'c')
2950 o
->metadata_chapters_manual
= 1;
2952 #define METADATA_CHECK_INDEX(index, nb_elems, desc)\
2953 if ((index) < 0 || (index) >= (nb_elems)) {\
2954 av_log(NULL, AV_LOG_FATAL, "Invalid %s index %d while processing metadata maps.\n",\
2959 #define SET_DICT(type, meta, context, index)\
2962 meta = &context->metadata;\
2965 METADATA_CHECK_INDEX(index, context->nb_chapters, "chapter")\
2966 meta = &context->chapters[index]->metadata;\
2969 METADATA_CHECK_INDEX(index, context->nb_programs, "program")\
2970 meta = &context->programs[index]->metadata;\
2974 SET_DICT(type_in, meta_in, ic, idx_in);
2975 SET_DICT(type_out
, meta_out
, oc
, idx_out
);
2977 /* for input streams choose first matching stream */
2978 if (type_in
== 's') {
2979 for (i
= 0; i
< ic
->nb_streams
; i
++) {
2980 if ((ret
= check_stream_specifier(ic
, ic
->streams
[i
], istream_spec
)) > 0) {
2981 meta_in
= &ic
->streams
[i
]->metadata
;
2987 av_log(NULL
, AV_LOG_FATAL
, "Stream specifier %s does not match any streams.\n", istream_spec
);
2992 if (type_out
== 's') {
2993 for (i
= 0; i
< oc
->nb_streams
; i
++) {
2994 if ((ret
= check_stream_specifier(oc
, oc
->streams
[i
], ostream_spec
)) > 0) {
2995 meta_out
= &oc
->streams
[i
]->metadata
;
2996 av_dict_copy(meta_out
, *meta_in
, AV_DICT_DONT_OVERWRITE
);
3001 av_dict_copy(meta_out
, *meta_in
, AV_DICT_DONT_OVERWRITE
);
3006 static AVCodec
*find_codec_or_die(const char *name
, enum AVMediaType type
, int encoder
)
3008 const char *codec_string
= encoder ?
"encoder" : "decoder";
3012 avcodec_find_encoder_by_name(name
) :
3013 avcodec_find_decoder_by_name(name
);
3015 av_log(NULL
, AV_LOG_FATAL
, "Unknown %s '%s'\n", codec_string
, name
);
3018 if(codec
->type
!= type
) {
3019 av_log(NULL
, AV_LOG_FATAL
, "Invalid %s type '%s'\n", codec_string
, name
);
3025 static AVCodec
*choose_decoder(OptionsContext
*o
, AVFormatContext
*s
, AVStream
*st
)
3027 char *codec_name
= NULL
;
3029 MATCH_PER_STREAM_OPT(codec_names
, str
, codec_name
, s
, st
);
3031 AVCodec
*codec
= find_codec_or_die(codec_name
, st
->codec
->codec_type
, 0);
3032 st
->codec
->codec_id
= codec
->id
;
3035 return avcodec_find_decoder(st
->codec
->codec_id
);
3039 * Add all the streams from the given input file to the global
3040 * list of input streams.
3042 static void add_input_streams(OptionsContext
*o
, AVFormatContext
*ic
)
3044 int i
, rfps
, rfps_base
;
3046 for (i
= 0; i
< ic
->nb_streams
; i
++) {
3047 AVStream
*st
= ic
->streams
[i
];
3048 AVCodecContext
*dec
= st
->codec
;
3051 input_streams
= grow_array(input_streams
, sizeof(*input_streams
), &nb_input_streams
, nb_input_streams
+ 1);
3052 ist
= &input_streams
[nb_input_streams
- 1];
3054 ist
->file_index
= nb_input_files
;
3056 ist
->opts
= filter_codec_opts(codec_opts
, ist
->st
->codec
->codec_id
, ic
, st
);
3058 ist
->ts_scale
= 1.0;
3059 MATCH_PER_STREAM_OPT(ts_scale
, dbl
, ist
->ts_scale
, ic
, st
);
3061 ist
->dec
= choose_decoder(o
, ic
, st
);
3063 switch (dec
->codec_type
) {
3064 case AVMEDIA_TYPE_AUDIO
:
3065 if (o
->audio_disable
)
3066 st
->discard
= AVDISCARD_ALL
;
3068 case AVMEDIA_TYPE_VIDEO
:
3069 rfps
= ic
->streams
[i
]->r_frame_rate
.num
;
3070 rfps_base
= ic
->streams
[i
]->r_frame_rate
.den
;
3072 dec
->flags
|= CODEC_FLAG_EMU_EDGE
;
3073 dec
->height
>>= dec
->lowres
;
3074 dec
->width
>>= dec
->lowres
;
3077 if (dec
->time_base
.den
!= rfps
*dec
->ticks_per_frame
|| dec
->time_base
.num
!= rfps_base
) {
3079 av_log(NULL
, AV_LOG_INFO
,"\nSeems stream %d codec frame rate differs from container frame rate: %2.2f (%d/%d) -> %2.2f (%d/%d)\n",
3080 i
, (float)dec
->time_base
.den
/ dec
->time_base
.num
, dec
->time_base
.den
, dec
->time_base
.num
,
3081 (float)rfps
/ rfps_base
, rfps
, rfps_base
);
3084 if (o
->video_disable
)
3085 st
->discard
= AVDISCARD_ALL
;
3086 else if(video_discard
)
3087 st
->discard
= video_discard
;
3089 case AVMEDIA_TYPE_DATA
:
3091 case AVMEDIA_TYPE_SUBTITLE
:
3092 if (o
->subtitle_disable
)
3093 st
->discard
= AVDISCARD_ALL
;
3095 case AVMEDIA_TYPE_ATTACHMENT
:
3096 case AVMEDIA_TYPE_UNKNOWN
:
3104 static void assert_file_overwrite(const char *filename
)
3106 if (!file_overwrite
&&
3107 (strchr(filename
, ':') == NULL
|| filename
[1] == ':' ||
3108 av_strstart(filename
, "file:", NULL
))) {
3109 if (avio_check(filename
, 0) == 0) {
3111 fprintf(stderr
,"File '%s' already exists. Overwrite ? [y/N] ", filename
);
3113 if (!read_yesno()) {
3114 fprintf(stderr
, "Not overwriting - exiting\n");
3119 fprintf(stderr
,"File '%s' already exists. Exiting.\n", filename
);
3126 static void dump_attachment(AVStream
*st
, const char *filename
)
3129 AVIOContext
*out
= NULL
;
3130 AVDictionaryEntry
*e
;
3132 if (!st
->codec
->extradata_size
) {
3133 av_log(NULL
, AV_LOG_WARNING
, "No extradata to dump in stream #%d:%d.\n",
3134 nb_input_files
- 1, st
->index
);
3137 if (!*filename
&& (e
= av_dict_get(st
->metadata
, "filename", NULL
, 0)))
3138 filename
= e
->value
;
3140 av_log(NULL
, AV_LOG_FATAL
, "No filename specified and no 'filename' tag"
3141 "in stream #%d:%d.\n", nb_input_files
- 1, st
->index
);
3145 assert_file_overwrite(filename
);
3147 if ((ret
= avio_open2(&out
, filename
, AVIO_FLAG_WRITE
, &int_cb
, NULL
)) < 0) {
3148 av_log(NULL
, AV_LOG_FATAL
, "Could not open file %s for writing.\n",
3153 avio_write(out
, st
->codec
->extradata
, st
->codec
->extradata_size
);
3158 static int opt_input_file(OptionsContext
*o
, const char *opt
, const char *filename
)
3160 AVFormatContext
*ic
;
3161 AVInputFormat
*file_iformat
= NULL
;
3165 AVDictionary
**opts
;
3166 int orig_nb_streams
; // number of streams before avformat_find_stream_info
3169 if (!(file_iformat
= av_find_input_format(o
->format
))) {
3170 av_log(NULL
, AV_LOG_FATAL
, "Unknown input format: '%s'\n", o
->format
);
3175 if (!strcmp(filename
, "-"))
3178 using_stdin
|= !strncmp(filename
, "pipe:", 5) ||
3179 !strcmp(filename
, "/dev/stdin");
3181 /* get default parameters from command line */
3182 ic
= avformat_alloc_context();
3184 print_error(filename
, AVERROR(ENOMEM
));
3187 if (o
->nb_audio_sample_rate
) {
3188 snprintf(buf
, sizeof(buf
), "%d", o
->audio_sample_rate
[o
->nb_audio_sample_rate
- 1].u
.i
);
3189 av_dict_set(&format_opts
, "sample_rate", buf
, 0);
3191 if (o
->nb_audio_channels
) {
3192 snprintf(buf
, sizeof(buf
), "%d", o
->audio_channels
[o
->nb_audio_channels
- 1].u
.i
);
3193 av_dict_set(&format_opts
, "channels", buf
, 0