8ad6fcd412add7a40ac51c5cbb56b940547074bb
[libav.git] / avconv.c
1 /*
2 * avconv main
3 * Copyright (c) 2000-2011 The libav developers.
4 *
5 * This file is part of Libav.
6 *
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.
11 *
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.
16 *
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
20 */
21
22 #include "config.h"
23 #include <ctype.h>
24 #include <string.h>
25 #include <math.h>
26 #include <stdlib.h>
27 #include <errno.h>
28 #include <signal.h>
29 #include <limits.h>
30 #include <unistd.h>
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"
49
50 #if CONFIG_AVFILTER
51 # include "libavfilter/avfilter.h"
52 # include "libavfilter/avfiltergraph.h"
53 # include "libavfilter/buffersrc.h"
54 # include "libavfilter/vsrc_buffer.h"
55 #endif
56
57 #if HAVE_SYS_RESOURCE_H
58 #include <sys/types.h>
59 #include <sys/time.h>
60 #include <sys/resource.h>
61 #elif HAVE_GETPROCESSTIMES
62 #include <windows.h>
63 #endif
64 #if HAVE_GETPROCESSMEMORYINFO
65 #include <windows.h>
66 #include <psapi.h>
67 #endif
68
69 #if HAVE_SYS_SELECT_H
70 #include <sys/select.h>
71 #endif
72
73 #include <time.h>
74
75 #include "cmdutils.h"
76
77 #include "libavutil/avassert.h"
78
79 #define VSYNC_AUTO -1
80 #define VSYNC_PASSTHROUGH 0
81 #define VSYNC_CFR 1
82 #define VSYNC_VFR 2
83
84 const char program_name[] = "avconv";
85 const int program_birth_year = 2000;
86
87 /* select an input stream for an output stream */
88 typedef struct StreamMap {
89 int disabled; /** 1 is this mapping is disabled by a negative map */
90 int file_index;
91 int stream_index;
92 int sync_file_index;
93 int sync_stream_index;
94 } StreamMap;
95
96 /**
97 * select an input file for an output file
98 */
99 typedef struct MetadataMap {
100 int file; ///< file index
101 char type; ///< type of metadata to copy -- (g)lobal, (s)tream, (c)hapter or (p)rogram
102 int index; ///< stream/chapter/program number
103 } MetadataMap;
104
105 static const OptionDef options[];
106
107 static int video_discard = 0;
108 static int same_quant = 0;
109 static int do_deinterlace = 0;
110 static int intra_dc_precision = 8;
111 static int qp_hist = 0;
112
113 static int file_overwrite = 0;
114 static int do_benchmark = 0;
115 static int do_hex_dump = 0;
116 static int do_pkt_dump = 0;
117 static int do_pass = 0;
118 static char *pass_logfilename_prefix = NULL;
119 static int video_sync_method = VSYNC_AUTO;
120 static int audio_sync_method = 0;
121 static float audio_drift_threshold = 0.1;
122 static int copy_ts = 0;
123 static int copy_tb = 1;
124 static int opt_shortest = 0;
125 static char *vstats_filename;
126 static FILE *vstats_file;
127
128 static int audio_volume = 256;
129
130 static int exit_on_error = 0;
131 static int using_stdin = 0;
132 static int64_t video_size = 0;
133 static int64_t audio_size = 0;
134 static int64_t extra_size = 0;
135 static int nb_frames_dup = 0;
136 static int nb_frames_drop = 0;
137 static int input_sync;
138
139 static float dts_delta_threshold = 10;
140
141 static int print_stats = 1;
142
143 static uint8_t *audio_buf;
144 static unsigned int allocated_audio_buf_size;
145
146 #define DEFAULT_PASS_LOGFILENAME_PREFIX "av2pass"
147
148 typedef struct FrameBuffer {
149 uint8_t *base[4];
150 uint8_t *data[4];
151 int linesize[4];
152
153 int h, w;
154 enum PixelFormat pix_fmt;
155
156 int refcount;
157 struct InputStream *ist;
158 struct FrameBuffer *next;
159 } FrameBuffer;
160
161 typedef struct InputStream {
162 int file_index;
163 AVStream *st;
164 int discard; /* true if stream data should be discarded */
165 int decoding_needed; /* true if the packets must be decoded in 'raw_fifo' */
166 AVCodec *dec;
167 AVFrame *decoded_frame;
168 AVFrame *filtered_frame;
169
170 int64_t start; /* time when read started */
171 /* predicted dts of the next packet read for this stream or (when there are
172 * several frames in a packet) of the next frame in current packet */
173 int64_t next_dts;
174 int64_t pts; /* current pts */
175 PtsCorrectionContext pts_ctx;
176 double ts_scale;
177 int is_start; /* is 1 at the start and after a discontinuity */
178 int showed_multi_packet_warning;
179 AVDictionary *opts;
180
181 /* a pool of free buffers for decoded data */
182 FrameBuffer *buffer_pool;
183 } InputStream;
184
185 typedef struct InputFile {
186 AVFormatContext *ctx;
187 int eof_reached; /* true if eof reached */
188 int ist_index; /* index of first stream in ist_table */
189 int buffer_size; /* current total buffer size */
190 int64_t ts_offset;
191 int nb_streams; /* number of stream that avconv is aware of; may be different
192 from ctx.nb_streams if new streams appear during av_read_frame() */
193 int rate_emu;
194 } InputFile;
195
196 typedef struct OutputStream {
197 int file_index; /* file index */
198 int index; /* stream index in the output file */
199 int source_index; /* InputStream index */
200 AVStream *st; /* stream in the output file */
201 int encoding_needed; /* true if encoding needed for this stream */
202 int frame_number;
203 /* input pts and corresponding output pts
204 for A/V sync */
205 // double sync_ipts; /* dts from the AVPacket of the demuxer in second units */
206 struct InputStream *sync_ist; /* input stream to sync against */
207 int64_t sync_opts; /* output frame counter, could be changed to some true timestamp */ // FIXME look at frame_number
208 /* pts of the first frame encoded for this stream, used for limiting
209 * recording time */
210 int64_t first_pts;
211 AVBitStreamFilterContext *bitstream_filters;
212 AVCodec *enc;
213 int64_t max_frames;
214 AVFrame *output_frame;
215
216 /* video only */
217 int video_resample;
218 AVFrame pict_tmp; /* temporary image for resampling */
219 struct SwsContext *img_resample_ctx; /* for image resampling */
220 int resample_height;
221 int resample_width;
222 int resample_pix_fmt;
223 AVRational frame_rate;
224 int force_fps;
225 int top_field_first;
226
227 float frame_aspect_ratio;
228
229 /* forced key frames */
230 int64_t *forced_kf_pts;
231 int forced_kf_count;
232 int forced_kf_index;
233
234 /* audio only */
235 int audio_resample;
236 ReSampleContext *resample; /* for audio resampling */
237 int resample_sample_fmt;
238 int resample_channels;
239 int resample_sample_rate;
240 int reformat_pair;
241 AVAudioConvert *reformat_ctx;
242 AVFifoBuffer *fifo; /* for compression: one audio fifo per codec */
243 FILE *logfile;
244
245 #if CONFIG_AVFILTER
246 AVFilterContext *output_video_filter;
247 AVFilterContext *input_video_filter;
248 AVFilterBufferRef *picref;
249 char *avfilter;
250 AVFilterGraph *graph;
251 #endif
252
253 int64_t sws_flags;
254 AVDictionary *opts;
255 int is_past_recording_time;
256 int stream_copy;
257 const char *attachment_filename;
258 int copy_initial_nonkeyframes;
259 } OutputStream;
260
261
262 typedef struct OutputFile {
263 AVFormatContext *ctx;
264 AVDictionary *opts;
265 int ost_index; /* index of the first stream in output_streams */
266 int64_t recording_time; /* desired length of the resulting file in microseconds */
267 int64_t start_time; /* start time in microseconds */
268 uint64_t limit_filesize;
269 } OutputFile;
270
271 static InputStream *input_streams = NULL;
272 static int nb_input_streams = 0;
273 static InputFile *input_files = NULL;
274 static int nb_input_files = 0;
275
276 static OutputStream *output_streams = NULL;
277 static int nb_output_streams = 0;
278 static OutputFile *output_files = NULL;
279 static int nb_output_files = 0;
280
281 typedef struct OptionsContext {
282 /* input/output options */
283 int64_t start_time;
284 const char *format;
285
286 SpecifierOpt *codec_names;
287 int nb_codec_names;
288 SpecifierOpt *audio_channels;
289 int nb_audio_channels;
290 SpecifierOpt *audio_sample_rate;
291 int nb_audio_sample_rate;
292 SpecifierOpt *frame_rates;
293 int nb_frame_rates;
294 SpecifierOpt *frame_sizes;
295 int nb_frame_sizes;
296 SpecifierOpt *frame_pix_fmts;
297 int nb_frame_pix_fmts;
298
299 /* input options */
300 int64_t input_ts_offset;
301 int rate_emu;
302
303 SpecifierOpt *ts_scale;
304 int nb_ts_scale;
305 SpecifierOpt *dump_attachment;
306 int nb_dump_attachment;
307
308 /* output options */
309 StreamMap *stream_maps;
310 int nb_stream_maps;
311 /* first item specifies output metadata, second is input */
312 MetadataMap (*meta_data_maps)[2];
313 int nb_meta_data_maps;
314 int metadata_global_manual;
315 int metadata_streams_manual;
316 int metadata_chapters_manual;
317 const char **attachments;
318 int nb_attachments;
319
320 int chapters_input_file;
321
322 int64_t recording_time;
323 uint64_t limit_filesize;
324 float mux_preload;
325 float mux_max_delay;
326
327 int video_disable;
328 int audio_disable;
329 int subtitle_disable;
330 int data_disable;
331
332 /* indexed by output file stream index */
333 int *streamid_map;
334 int nb_streamid_map;
335
336 SpecifierOpt *metadata;
337 int nb_metadata;
338 SpecifierOpt *max_frames;
339 int nb_max_frames;
340 SpecifierOpt *bitstream_filters;
341 int nb_bitstream_filters;
342 SpecifierOpt *codec_tags;
343 int nb_codec_tags;
344 SpecifierOpt *sample_fmts;
345 int nb_sample_fmts;
346 SpecifierOpt *qscale;
347 int nb_qscale;
348 SpecifierOpt *forced_key_frames;
349 int nb_forced_key_frames;
350 SpecifierOpt *force_fps;
351 int nb_force_fps;
352 SpecifierOpt *frame_aspect_ratios;
353 int nb_frame_aspect_ratios;
354 SpecifierOpt *rc_overrides;
355 int nb_rc_overrides;
356 SpecifierOpt *intra_matrices;
357 int nb_intra_matrices;
358 SpecifierOpt *inter_matrices;
359 int nb_inter_matrices;
360 SpecifierOpt *top_field_first;
361 int nb_top_field_first;
362 SpecifierOpt *metadata_map;
363 int nb_metadata_map;
364 SpecifierOpt *presets;
365 int nb_presets;
366 SpecifierOpt *copy_initial_nonkeyframes;
367 int nb_copy_initial_nonkeyframes;
368 #if CONFIG_AVFILTER
369 SpecifierOpt *filters;
370 int nb_filters;
371 #endif
372 } OptionsContext;
373
374 #define MATCH_PER_STREAM_OPT(name, type, outvar, fmtctx, st)\
375 {\
376 int i, ret;\
377 for (i = 0; i < o->nb_ ## name; i++) {\
378 char *spec = o->name[i].specifier;\
379 if ((ret = check_stream_specifier(fmtctx, st, spec)) > 0)\
380 outvar = o->name[i].u.type;\
381 else if (ret < 0)\
382 exit_program(1);\
383 }\
384 }
385
386 static void reset_options(OptionsContext *o)
387 {
388 const OptionDef *po = options;
389
390 /* all OPT_SPEC and OPT_STRING can be freed in generic way */
391 while (po->name) {
392 void *dst = (uint8_t*)o + po->u.off;
393
394 if (po->flags & OPT_SPEC) {
395 SpecifierOpt **so = dst;
396 int i, *count = (int*)(so + 1);
397 for (i = 0; i < *count; i++) {
398 av_freep(&(*so)[i].specifier);
399 if (po->flags & OPT_STRING)
400 av_freep(&(*so)[i].u.str);
401 }
402 av_freep(so);
403 *count = 0;
404 } else if (po->flags & OPT_OFFSET && po->flags & OPT_STRING)
405 av_freep(dst);
406 po++;
407 }
408
409 av_freep(&o->stream_maps);
410 av_freep(&o->meta_data_maps);
411 av_freep(&o->streamid_map);
412
413 memset(o, 0, sizeof(*o));
414
415 o->mux_max_delay = 0.7;
416 o->recording_time = INT64_MAX;
417 o->limit_filesize = UINT64_MAX;
418 o->chapters_input_file = INT_MAX;
419
420 uninit_opts();
421 init_opts();
422 }
423
424 static int alloc_buffer(InputStream *ist, FrameBuffer **pbuf)
425 {
426 AVCodecContext *s = ist->st->codec;
427 FrameBuffer *buf = av_mallocz(sizeof(*buf));
428 int i, ret;
429 const int pixel_size = av_pix_fmt_descriptors[s->pix_fmt].comp[0].step_minus1+1;
430 int h_chroma_shift, v_chroma_shift;
431 int edge = 32; // XXX should be avcodec_get_edge_width(), but that fails on svq1
432 int w = s->width, h = s->height;
433
434 if (!buf)
435 return AVERROR(ENOMEM);
436
437 if (!(s->flags & CODEC_FLAG_EMU_EDGE)) {
438 w += 2*edge;
439 h += 2*edge;
440 }
441
442 avcodec_align_dimensions(s, &w, &h);
443 if ((ret = av_image_alloc(buf->base, buf->linesize, w, h,
444 s->pix_fmt, 32)) < 0) {
445 av_freep(&buf);
446 return ret;
447 }
448 /* XXX this shouldn't be needed, but some tests break without this line
449 * those decoders are buggy and need to be fixed.
450 * the following tests fail:
451 * bethsoft-vid, cdgraphics, ansi, aasc, fraps-v1, qtrle-1bit
452 */
453 memset(buf->base[0], 128, ret);
454
455 avcodec_get_chroma_sub_sample(s->pix_fmt, &h_chroma_shift, &v_chroma_shift);
456 for (i = 0; i < FF_ARRAY_ELEMS(buf->data); i++) {
457 const int h_shift = i==0 ? 0 : h_chroma_shift;
458 const int v_shift = i==0 ? 0 : v_chroma_shift;
459 if (s->flags & CODEC_FLAG_EMU_EDGE)
460 buf->data[i] = buf->base[i];
461 else
462 buf->data[i] = buf->base[i] +
463 FFALIGN((buf->linesize[i]*edge >> v_shift) +
464 (pixel_size*edge >> h_shift), 32);
465 }
466 buf->w = s->width;
467 buf->h = s->height;
468 buf->pix_fmt = s->pix_fmt;
469 buf->ist = ist;
470
471 *pbuf = buf;
472 return 0;
473 }
474
475 static void free_buffer_pool(InputStream *ist)
476 {
477 FrameBuffer *buf = ist->buffer_pool;
478 while (buf) {
479 ist->buffer_pool = buf->next;
480 av_freep(&buf->base[0]);
481 av_free(buf);
482 buf = ist->buffer_pool;
483 }
484 }
485
486 static void unref_buffer(InputStream *ist, FrameBuffer *buf)
487 {
488 av_assert0(buf->refcount);
489 buf->refcount--;
490 if (!buf->refcount) {
491 buf->next = ist->buffer_pool;
492 ist->buffer_pool = buf;
493 }
494 }
495
496 static int codec_get_buffer(AVCodecContext *s, AVFrame *frame)
497 {
498 InputStream *ist = s->opaque;
499 FrameBuffer *buf;
500 int ret, i;
501
502 if (!ist->buffer_pool && (ret = alloc_buffer(ist, &ist->buffer_pool)) < 0)
503 return ret;
504
505 buf = ist->buffer_pool;
506 ist->buffer_pool = buf->next;
507 buf->next = NULL;
508 if (buf->w != s->width || buf->h != s->height || buf->pix_fmt != s->pix_fmt) {
509 av_freep(&buf->base[0]);
510 av_free(buf);
511 if ((ret = alloc_buffer(ist, &buf)) < 0)
512 return ret;
513 }
514 buf->refcount++;
515
516 frame->opaque = buf;
517 frame->type = FF_BUFFER_TYPE_USER;
518 frame->extended_data = frame->data;
519 frame->pkt_pts = s->pkt ? s->pkt->pts : AV_NOPTS_VALUE;
520
521 for (i = 0; i < FF_ARRAY_ELEMS(buf->data); i++) {
522 frame->base[i] = buf->base[i]; // XXX h264.c uses base though it shouldn't
523 frame->data[i] = buf->data[i];
524 frame->linesize[i] = buf->linesize[i];
525 }
526
527 return 0;
528 }
529
530 static void codec_release_buffer(AVCodecContext *s, AVFrame *frame)
531 {
532 InputStream *ist = s->opaque;
533 FrameBuffer *buf = frame->opaque;
534 int i;
535
536 for (i = 0; i < FF_ARRAY_ELEMS(frame->data); i++)
537 frame->data[i] = NULL;
538
539 unref_buffer(ist, buf);
540 }
541
542 static void filter_release_buffer(AVFilterBuffer *fb)
543 {
544 FrameBuffer *buf = fb->priv;
545 av_free(fb);
546 unref_buffer(buf->ist, buf);
547 }
548
549 #if CONFIG_AVFILTER
550
551 static int configure_video_filters(InputStream *ist, OutputStream *ost)
552 {
553 AVFilterContext *last_filter, *filter;
554 /** filter graph containing all filters including input & output */
555 AVCodecContext *codec = ost->st->codec;
556 AVCodecContext *icodec = ist->st->codec;
557 SinkContext sink_ctx = { .pix_fmt = codec->pix_fmt };
558 AVRational sample_aspect_ratio;
559 char args[255];
560 int ret;
561
562 ost->graph = avfilter_graph_alloc();
563
564 if (ist->st->sample_aspect_ratio.num) {
565 sample_aspect_ratio = ist->st->sample_aspect_ratio;
566 } else
567 sample_aspect_ratio = ist->st->codec->sample_aspect_ratio;
568
569 snprintf(args, 255, "%d:%d:%d:%d:%d:%d:%d", ist->st->codec->width,
570 ist->st->codec->height, ist->st->codec->pix_fmt, 1, AV_TIME_BASE,
571 sample_aspect_ratio.num, sample_aspect_ratio.den);
572
573 ret = avfilter_graph_create_filter(&ost->input_video_filter, avfilter_get_by_name("buffer"),
574 "src", args, NULL, ost->graph);
575 if (ret < 0)
576 return ret;
577 ret = avfilter_graph_create_filter(&ost->output_video_filter, &sink,
578 "out", NULL, &sink_ctx, ost->graph);
579 if (ret < 0)
580 return ret;
581 last_filter = ost->input_video_filter;
582
583 if (codec->width != icodec->width || codec->height != icodec->height) {
584 snprintf(args, 255, "%d:%d:flags=0x%X",
585 codec->width,
586 codec->height,
587 (unsigned)ost->sws_flags);
588 if ((ret = avfilter_graph_create_filter(&filter, avfilter_get_by_name("scale"),
589 NULL, args, NULL, ost->graph)) < 0)
590 return ret;
591 if ((ret = avfilter_link(last_filter, 0, filter, 0)) < 0)
592 return ret;
593 last_filter = filter;
594 }
595
596 snprintf(args, sizeof(args), "flags=0x%X", (unsigned)ost->sws_flags);
597 ost->graph->scale_sws_opts = av_strdup(args);
598
599 if (ost->avfilter) {
600 AVFilterInOut *outputs = av_malloc(sizeof(AVFilterInOut));
601 AVFilterInOut *inputs = av_malloc(sizeof(AVFilterInOut));
602
603 outputs->name = av_strdup("in");
604 outputs->filter_ctx = last_filter;
605 outputs->pad_idx = 0;
606 outputs->next = NULL;
607
608 inputs->name = av_strdup("out");
609 inputs->filter_ctx = ost->output_video_filter;
610 inputs->pad_idx = 0;
611 inputs->next = NULL;
612
613 if ((ret = avfilter_graph_parse(ost->graph, ost->avfilter, inputs, outputs, NULL)) < 0)
614 return ret;
615 } else {
616 if ((ret = avfilter_link(last_filter, 0, ost->output_video_filter, 0)) < 0)
617 return ret;
618 }
619
620 if ((ret = avfilter_graph_config(ost->graph, NULL)) < 0)
621 return ret;
622
623 codec->width = ost->output_video_filter->inputs[0]->w;
624 codec->height = ost->output_video_filter->inputs[0]->h;
625 codec->sample_aspect_ratio = ost->st->sample_aspect_ratio =
626 ost->frame_aspect_ratio ? // overridden by the -aspect cli option
627 av_d2q(ost->frame_aspect_ratio * codec->height/codec->width, 255) :
628 ost->output_video_filter->inputs[0]->sample_aspect_ratio;
629
630 return 0;
631 }
632 #endif /* CONFIG_AVFILTER */
633
634 static void term_exit(void)
635 {
636 av_log(NULL, AV_LOG_QUIET, "");
637 }
638
639 static volatile int received_sigterm = 0;
640 static volatile int received_nb_signals = 0;
641
642 static void
643 sigterm_handler(int sig)
644 {
645 received_sigterm = sig;
646 received_nb_signals++;
647 term_exit();
648 }
649
650 static void term_init(void)
651 {
652 signal(SIGINT , sigterm_handler); /* Interrupt (ANSI). */
653 signal(SIGTERM, sigterm_handler); /* Termination (ANSI). */
654 #ifdef SIGXCPU
655 signal(SIGXCPU, sigterm_handler);
656 #endif
657 }
658
659 static int decode_interrupt_cb(void *ctx)
660 {
661 return received_nb_signals > 1;
662 }
663
664 static const AVIOInterruptCB int_cb = { decode_interrupt_cb, NULL };
665
666 void exit_program(int ret)
667 {
668 int i;
669
670 /* close files */
671 for (i = 0; i < nb_output_files; i++) {
672 AVFormatContext *s = output_files[i].ctx;
673 if (!(s->oformat->flags & AVFMT_NOFILE) && s->pb)
674 avio_close(s->pb);
675 avformat_free_context(s);
676 av_dict_free(&output_files[i].opts);
677 }
678 for (i = 0; i < nb_output_streams; i++) {
679 AVBitStreamFilterContext *bsfc = output_streams[i].bitstream_filters;
680 while (bsfc) {
681 AVBitStreamFilterContext *next = bsfc->next;
682 av_bitstream_filter_close(bsfc);
683 bsfc = next;
684 }
685 output_streams[i].bitstream_filters = NULL;
686
687 if (output_streams[i].output_frame) {
688 AVFrame *frame = output_streams[i].output_frame;
689 if (frame->extended_data != frame->data)
690 av_freep(&frame->extended_data);
691 av_freep(&frame);
692 }
693
694 #if CONFIG_AVFILTER
695 av_freep(&output_streams[i].avfilter);
696 #endif
697 }
698 for (i = 0; i < nb_input_files; i++) {
699 avformat_close_input(&input_files[i].ctx);
700 }
701 for (i = 0; i < nb_input_streams; i++) {
702 av_freep(&input_streams[i].decoded_frame);
703 av_freep(&input_streams[i].filtered_frame);
704 av_dict_free(&input_streams[i].opts);
705 free_buffer_pool(&input_streams[i]);
706 }
707
708 if (vstats_file)
709 fclose(vstats_file);
710 av_free(vstats_filename);
711
712 av_freep(&input_streams);
713 av_freep(&input_files);
714 av_freep(&output_streams);
715 av_freep(&output_files);
716
717 uninit_opts();
718 av_free(audio_buf);
719 allocated_audio_buf_size = 0;
720
721 #if CONFIG_AVFILTER
722 avfilter_uninit();
723 #endif
724 avformat_network_deinit();
725
726 if (received_sigterm) {
727 av_log(NULL, AV_LOG_INFO, "Received signal %d: terminating.\n",
728 (int) received_sigterm);
729 exit (255);
730 }
731
732 exit(ret);
733 }
734
735 static void assert_avoptions(AVDictionary *m)
736 {
737 AVDictionaryEntry *t;
738 if ((t = av_dict_get(m, "", NULL, AV_DICT_IGNORE_SUFFIX))) {
739 av_log(NULL, AV_LOG_FATAL, "Option %s not found.\n", t->key);
740 exit_program(1);
741 }
742 }
743
744 static void assert_codec_experimental(AVCodecContext *c, int encoder)
745 {
746 const char *codec_string = encoder ? "encoder" : "decoder";
747 AVCodec *codec;
748 if (c->codec->capabilities & CODEC_CAP_EXPERIMENTAL &&
749 c->strict_std_compliance > FF_COMPLIANCE_EXPERIMENTAL) {
750 av_log(NULL, AV_LOG_FATAL, "%s '%s' is experimental and might produce bad "
751 "results.\nAdd '-strict experimental' if you want to use it.\n",
752 codec_string, c->codec->name);
753 codec = encoder ? avcodec_find_encoder(c->codec->id) : avcodec_find_decoder(c->codec->id);
754 if (!(codec->capabilities & CODEC_CAP_EXPERIMENTAL))
755 av_log(NULL, AV_LOG_FATAL, "Or use the non experimental %s '%s'.\n",
756 codec_string, codec->name);
757 exit_program(1);
758 }
759 }
760
761 static void choose_sample_fmt(AVStream *st, AVCodec *codec)
762 {
763 if (codec && codec->sample_fmts) {
764 const enum AVSampleFormat *p = codec->sample_fmts;
765 for (; *p != -1; p++) {
766 if (*p == st->codec->sample_fmt)
767 break;
768 }
769 if (*p == -1) {
770 av_log(NULL, AV_LOG_WARNING,
771 "Incompatible sample format '%s' for codec '%s', auto-selecting format '%s'\n",
772 av_get_sample_fmt_name(st->codec->sample_fmt),
773 codec->name,
774 av_get_sample_fmt_name(codec->sample_fmts[0]));
775 st->codec->sample_fmt = codec->sample_fmts[0];
776 }
777 }
778 }
779
780 /**
781 * Update the requested input sample format based on the output sample format.
782 * This is currently only used to request float output from decoders which
783 * support multiple sample formats, one of which is AV_SAMPLE_FMT_FLT.
784 * Ideally this will be removed in the future when decoders do not do format
785 * conversion and only output in their native format.
786 */
787 static void update_sample_fmt(AVCodecContext *dec, AVCodec *dec_codec,
788 AVCodecContext *enc)
789 {
790 /* if sample formats match or a decoder sample format has already been
791 requested, just return */
792 if (enc->sample_fmt == dec->sample_fmt ||
793 dec->request_sample_fmt > AV_SAMPLE_FMT_NONE)
794 return;
795
796 /* if decoder supports more than one output format */
797 if (dec_codec && dec_codec->sample_fmts &&
798 dec_codec->sample_fmts[0] != AV_SAMPLE_FMT_NONE &&
799 dec_codec->sample_fmts[1] != AV_SAMPLE_FMT_NONE) {
800 const enum AVSampleFormat *p;
801 int min_dec = -1, min_inc = -1;
802
803 /* find a matching sample format in the encoder */
804 for (p = dec_codec->sample_fmts; *p != AV_SAMPLE_FMT_NONE; p++) {
805 if (*p == enc->sample_fmt) {
806 dec->request_sample_fmt = *p;
807 return;
808 } else if (*p > enc->sample_fmt) {
809 min_inc = FFMIN(min_inc, *p - enc->sample_fmt);
810 } else
811 min_dec = FFMIN(min_dec, enc->sample_fmt - *p);
812 }
813
814 /* if none match, provide the one that matches quality closest */
815 dec->request_sample_fmt = min_inc > 0 ? enc->sample_fmt + min_inc :
816 enc->sample_fmt - min_dec;
817 }
818 }
819
820 static void choose_sample_rate(AVStream *st, AVCodec *codec)
821 {
822 if (codec && codec->supported_samplerates) {
823 const int *p = codec->supported_samplerates;
824 int best = 0;
825 int best_dist = INT_MAX;
826 for (; *p; p++) {
827 int dist = abs(st->codec->sample_rate - *p);
828 if (dist < best_dist) {
829 best_dist = dist;
830 best = *p;
831 }
832 }
833 if (best_dist) {
834 av_log(st->codec, AV_LOG_WARNING, "Requested sampling rate unsupported using closest supported (%d)\n", best);
835 }
836 st->codec->sample_rate = best;
837 }
838 }
839
840 static void choose_pixel_fmt(AVStream *st, AVCodec *codec)
841 {
842 if (codec && codec->pix_fmts) {
843 const enum PixelFormat *p = codec->pix_fmts;
844 if (st->codec->strict_std_compliance <= FF_COMPLIANCE_UNOFFICIAL) {
845 if (st->codec->codec_id == CODEC_ID_MJPEG) {
846 p = (const enum PixelFormat[]) { PIX_FMT_YUVJ420P, PIX_FMT_YUVJ422P, PIX_FMT_YUV420P, PIX_FMT_YUV422P, PIX_FMT_NONE };
847 } else if (st->codec->codec_id == CODEC_ID_LJPEG) {
848 p = (const enum PixelFormat[]) { PIX_FMT_YUVJ420P, PIX_FMT_YUVJ422P, PIX_FMT_YUVJ444P, PIX_FMT_YUV420P,
849 PIX_FMT_YUV422P, PIX_FMT_YUV444P, PIX_FMT_BGRA, PIX_FMT_NONE };
850 }
851 }
852 for (; *p != PIX_FMT_NONE; p++) {
853 if (*p == st->codec->pix_fmt)
854 break;
855 }
856 if (*p == PIX_FMT_NONE) {
857 if (st->codec->pix_fmt != PIX_FMT_NONE)
858 av_log(NULL, AV_LOG_WARNING,
859 "Incompatible pixel format '%s' for codec '%s', auto-selecting format '%s'\n",
860 av_pix_fmt_descriptors[st->codec->pix_fmt].name,
861 codec->name,
862 av_pix_fmt_descriptors[codec->pix_fmts[0]].name);
863 st->codec->pix_fmt = codec->pix_fmts[0];
864 }
865 }
866 }
867
868 static double
869 get_sync_ipts(const OutputStream *ost)
870 {
871 const InputStream *ist = ost->sync_ist;
872 OutputFile *of = &output_files[ost->file_index];
873 return (double)(ist->pts - of->start_time) / AV_TIME_BASE;
874 }
875
876 static void write_frame(AVFormatContext *s, AVPacket *pkt, OutputStream *ost)
877 {
878 AVBitStreamFilterContext *bsfc = ost->bitstream_filters;
879 AVCodecContext *avctx = ost->st->codec;
880 int ret;
881
882 /*
883 * Audio encoders may split the packets -- #frames in != #packets out.
884 * But there is no reordering, so we can limit the number of output packets
885 * by simply dropping them here.
886 * Counting encoded video frames needs to be done separately because of
887 * reordering, see do_video_out()
888 */
889 if (!(avctx->codec_type == AVMEDIA_TYPE_VIDEO && avctx->codec)) {
890 if (ost->frame_number >= ost->max_frames)
891 return;
892 ost->frame_number++;
893 }
894
895 while (bsfc) {
896 AVPacket new_pkt = *pkt;
897 int a = av_bitstream_filter_filter(bsfc, avctx, NULL,
898 &new_pkt.data, &new_pkt.size,
899 pkt->data, pkt->size,
900 pkt->flags & AV_PKT_FLAG_KEY);
901 if (a > 0) {
902 av_free_packet(pkt);
903 new_pkt.destruct = av_destruct_packet;
904 } else if (a < 0) {
905 av_log(NULL, AV_LOG_ERROR, "%s failed for stream %d, codec %s",
906 bsfc->filter->name, pkt->stream_index,
907 avctx->codec ? avctx->codec->name : "copy");
908 print_error("", a);
909 if (exit_on_error)
910 exit_program(1);
911 }
912 *pkt = new_pkt;
913
914 bsfc = bsfc->next;
915 }
916
917 pkt->stream_index = ost->index;
918 ret = av_interleaved_write_frame(s, pkt);
919 if (ret < 0) {
920 print_error("av_interleaved_write_frame()", ret);
921 exit_program(1);
922 }
923 }
924
925 static int check_recording_time(OutputStream *ost)
926 {
927 OutputFile *of = &output_files[ost->file_index];
928
929 if (of->recording_time != INT64_MAX &&
930 av_compare_ts(ost->sync_opts - ost->first_pts, ost->st->codec->time_base, of->recording_time,
931 AV_TIME_BASE_Q) >= 0) {
932 ost->is_past_recording_time = 1;
933 return 0;
934 }
935 return 1;
936 }
937
938 static void generate_silence(uint8_t* buf, enum AVSampleFormat sample_fmt, size_t size)
939 {
940 int fill_char = 0x00;
941 if (sample_fmt == AV_SAMPLE_FMT_U8)
942 fill_char = 0x80;
943 memset(buf, fill_char, size);
944 }
945
946 static int encode_audio_frame(AVFormatContext *s, OutputStream *ost,
947 const uint8_t *buf, int buf_size)
948 {
949 AVCodecContext *enc = ost->st->codec;
950 AVFrame *frame = NULL;
951 AVPacket pkt;
952 int ret, got_packet;
953
954 av_init_packet(&pkt);
955 pkt.data = NULL;
956 pkt.size = 0;
957
958 if (buf) {
959 if (!ost->output_frame) {
960 ost->output_frame = avcodec_alloc_frame();
961 if (!ost->output_frame) {
962 av_log(NULL, AV_LOG_FATAL, "out-of-memory in encode_audio_frame()\n");
963 exit_program(1);
964 }
965 }
966 frame = ost->output_frame;
967 if (frame->extended_data != frame->data)
968 av_freep(&frame->extended_data);
969 avcodec_get_frame_defaults(frame);
970
971 frame->nb_samples = buf_size /
972 (enc->channels * av_get_bytes_per_sample(enc->sample_fmt));
973 if ((ret = avcodec_fill_audio_frame(frame, enc->channels, enc->sample_fmt,
974 buf, buf_size, 1)) < 0) {
975 av_log(NULL, AV_LOG_FATAL, "Audio encoding failed\n");
976 exit_program(1);
977 }
978
979 if (!check_recording_time(ost))
980 return 0;
981
982 ost->sync_opts += frame->nb_samples;
983 }
984
985 got_packet = 0;
986 if (avcodec_encode_audio2(enc, &pkt, frame, &got_packet) < 0) {
987 av_log(NULL, AV_LOG_FATAL, "Audio encoding failed\n");
988 exit_program(1);
989 }
990
991 if (got_packet) {
992 if (pkt.pts != AV_NOPTS_VALUE)
993 pkt.pts = av_rescale_q(pkt.pts, enc->time_base, ost->st->time_base);
994 if (pkt.duration > 0)
995 pkt.duration = av_rescale_q(pkt.duration, enc->time_base, ost->st->time_base);
996
997 write_frame(s, &pkt, ost);
998
999 audio_size += pkt.size;
1000 }
1001
1002 return pkt.size;
1003 }
1004
1005 static void do_audio_out(AVFormatContext *s, OutputStream *ost,
1006 InputStream *ist, AVFrame *decoded_frame)
1007 {
1008 uint8_t *buftmp;
1009 int64_t audio_buf_size;
1010
1011 int size_out, frame_bytes, resample_changed;
1012 AVCodecContext *enc = ost->st->codec;
1013 AVCodecContext *dec = ist->st->codec;
1014 int osize = av_get_bytes_per_sample(enc->sample_fmt);
1015 int isize = av_get_bytes_per_sample(dec->sample_fmt);
1016 uint8_t *buf = decoded_frame->data[0];
1017 int size = decoded_frame->nb_samples * dec->channels * isize;
1018 int64_t allocated_for_size = size;
1019
1020 need_realloc:
1021 audio_buf_size = (allocated_for_size + isize * dec->channels - 1) / (isize * dec->channels);
1022 audio_buf_size = (audio_buf_size * enc->sample_rate + dec->sample_rate) / dec->sample_rate;
1023 audio_buf_size = audio_buf_size * 2 + 10000; // safety factors for the deprecated resampling API
1024 audio_buf_size = FFMAX(audio_buf_size, enc->frame_size);
1025 audio_buf_size *= osize * enc->channels;
1026
1027 if (audio_buf_size > INT_MAX) {
1028 av_log(NULL, AV_LOG_FATAL, "Buffer sizes too large\n");
1029 exit_program(1);
1030 }
1031
1032 av_fast_malloc(&audio_buf, &allocated_audio_buf_size, audio_buf_size);
1033 if (!audio_buf) {
1034 av_log(NULL, AV_LOG_FATAL, "Out of memory in do_audio_out\n");
1035 exit_program(1);
1036 }
1037
1038 if (enc->channels != dec->channels || enc->sample_rate != dec->sample_rate)
1039 ost->audio_resample = 1;
1040
1041 resample_changed = ost->resample_sample_fmt != dec->sample_fmt ||
1042 ost->resample_channels != dec->channels ||
1043 ost->resample_sample_rate != dec->sample_rate;
1044
1045 if ((ost->audio_resample && !ost->resample) || resample_changed) {
1046 if (resample_changed) {
1047 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",
1048 ist->file_index, ist->st->index,
1049 ost->resample_sample_rate, av_get_sample_fmt_name(ost->resample_sample_fmt), ost->resample_channels,
1050 dec->sample_rate, av_get_sample_fmt_name(dec->sample_fmt), dec->channels);
1051 ost->resample_sample_fmt = dec->sample_fmt;
1052 ost->resample_channels = dec->channels;
1053 ost->resample_sample_rate = dec->sample_rate;
1054 if (ost->resample)
1055 audio_resample_close(ost->resample);
1056 }
1057 /* if audio_sync_method is >1 the resampler is needed for audio drift compensation */
1058 if (audio_sync_method <= 1 &&
1059 ost->resample_sample_fmt == enc->sample_fmt &&
1060 ost->resample_channels == enc->channels &&
1061 ost->resample_sample_rate == enc->sample_rate) {
1062 ost->resample = NULL;
1063 ost->audio_resample = 0;
1064 } else if (ost->audio_resample) {
1065 if (dec->sample_fmt != AV_SAMPLE_FMT_S16)
1066 av_log(NULL, AV_LOG_WARNING, "Using s16 intermediate sample format for resampling\n");
1067 ost->resample = av_audio_resample_init(enc->channels, dec->channels,
1068 enc->sample_rate, dec->sample_rate,
1069 enc->sample_fmt, dec->sample_fmt,
1070 16, 10, 0, 0.8);
1071 if (!ost->resample) {
1072 av_log(NULL, AV_LOG_FATAL, "Can not resample %d channels @ %d Hz to %d channels @ %d Hz\n",
1073 dec->channels, dec->sample_rate,
1074 enc->channels, enc->sample_rate);
1075 exit_program(1);
1076 }
1077 }
1078 }
1079
1080 #define MAKE_SFMT_PAIR(a,b) ((a)+AV_SAMPLE_FMT_NB*(b))
1081 if (!ost->audio_resample && dec->sample_fmt != enc->sample_fmt &&
1082 MAKE_SFMT_PAIR(enc->sample_fmt,dec->sample_fmt) != ost->reformat_pair) {
1083 if (ost->reformat_ctx)
1084 av_audio_convert_free(ost->reformat_ctx);
1085 ost->reformat_ctx = av_audio_convert_alloc(enc->sample_fmt, 1,
1086 dec->sample_fmt, 1, NULL, 0);
1087 if (!ost->reformat_ctx) {
1088 av_log(NULL, AV_LOG_FATAL, "Cannot convert %s sample format to %s sample format\n",
1089 av_get_sample_fmt_name(dec->sample_fmt),
1090 av_get_sample_fmt_name(enc->sample_fmt));
1091 exit_program(1);
1092 }
1093 ost->reformat_pair = MAKE_SFMT_PAIR(enc->sample_fmt,dec->sample_fmt);
1094 }
1095
1096 if (audio_sync_method) {
1097 double delta = get_sync_ipts(ost) * enc->sample_rate - ost->sync_opts -
1098 av_fifo_size(ost->fifo) / (enc->channels * osize);
1099 int idelta = delta * dec->sample_rate / enc->sample_rate;
1100 int byte_delta = idelta * isize * dec->channels;
1101
1102 // FIXME resample delay
1103 if (fabs(delta) > 50) {
1104 if (ist->is_start || fabs(delta) > audio_drift_threshold*enc->sample_rate) {
1105 if (byte_delta < 0) {
1106 byte_delta = FFMAX(byte_delta, -size);
1107 size += byte_delta;
1108 buf -= byte_delta;
1109 av_log(NULL, AV_LOG_VERBOSE, "discarding %d audio samples\n",
1110 -byte_delta / (isize * dec->channels));
1111 if (!size)
1112 return;
1113 ist->is_start = 0;
1114 } else {
1115 static uint8_t *input_tmp = NULL;
1116 input_tmp = av_realloc(input_tmp, byte_delta + size);
1117
1118 if (byte_delta > allocated_for_size - size) {
1119 allocated_for_size = byte_delta + (int64_t)size;
1120 goto need_realloc;
1121 }
1122 ist->is_start = 0;
1123
1124 generate_silence(input_tmp, dec->sample_fmt, byte_delta);
1125 memcpy(input_tmp + byte_delta, buf, size);
1126 buf = input_tmp;
1127 size += byte_delta;
1128 av_log(NULL, AV_LOG_VERBOSE, "adding %d audio samples of silence\n", idelta);
1129 }
1130 } else if (audio_sync_method > 1) {
1131 int comp = av_clip(delta, -audio_sync_method, audio_sync_method);
1132 av_assert0(ost->audio_resample);
1133 av_log(NULL, AV_LOG_VERBOSE, "compensating audio timestamp drift:%f compensation:%d in:%d\n",
1134 delta, comp, enc->sample_rate);
1135 // 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));
1136 av_resample_compensate(*(struct AVResampleContext**)ost->resample, comp, enc->sample_rate);
1137 }
1138 }
1139 } else
1140 ost->sync_opts = lrintf(get_sync_ipts(ost) * enc->sample_rate) -
1141 av_fifo_size(ost->fifo) / (enc->channels * osize); // FIXME wrong
1142
1143 if (ost->audio_resample) {
1144 buftmp = audio_buf;
1145 size_out = audio_resample(ost->resample,
1146 (short *)buftmp, (short *)buf,
1147 size / (dec->channels * isize));
1148 size_out = size_out * enc->channels * osize;
1149 } else {
1150 buftmp = buf;
1151 size_out = size;
1152 }
1153
1154 if (!ost->audio_resample && dec->sample_fmt != enc->sample_fmt) {
1155 const void *ibuf[6] = { buftmp };
1156 void *obuf[6] = { audio_buf };
1157 int istride[6] = { isize };
1158 int ostride[6] = { osize };
1159 int len = size_out / istride[0];
1160 if (av_audio_convert(ost->reformat_ctx, obuf, ostride, ibuf, istride, len) < 0) {
1161 printf("av_audio_convert() failed\n");
1162 if (exit_on_error)
1163 exit_program(1);
1164 return;
1165 }
1166 buftmp = audio_buf;
1167 size_out = len * osize;
1168 }
1169
1170 /* now encode as many frames as possible */
1171 if (!(enc->codec->capabilities & CODEC_CAP_VARIABLE_FRAME_SIZE)) {
1172 /* output resampled raw samples */
1173 if (av_fifo_realloc2(ost->fifo, av_fifo_size(ost->fifo) + size_out) < 0) {
1174 av_log(NULL, AV_LOG_FATAL, "av_fifo_realloc2() failed\n");
1175 exit_program(1);
1176 }
1177 av_fifo_generic_write(ost->fifo, buftmp, size_out, NULL);
1178
1179 frame_bytes = enc->frame_size * osize * enc->channels;
1180
1181 while (av_fifo_size(ost->fifo) >= frame_bytes) {
1182 av_fifo_generic_read(ost->fifo, audio_buf, frame_bytes, NULL);
1183 encode_audio_frame(s, ost, audio_buf, frame_bytes);
1184 }
1185 } else {
1186 encode_audio_frame(s, ost, buftmp, size_out);
1187 }
1188 }
1189
1190 static void pre_process_video_frame(InputStream *ist, AVPicture *picture, void **bufp)
1191 {
1192 AVCodecContext *dec;
1193 AVPicture *picture2;
1194 AVPicture picture_tmp;
1195 uint8_t *buf = 0;
1196
1197 dec = ist->st->codec;
1198
1199 /* deinterlace : must be done before any resize */
1200 if (do_deinterlace) {
1201 int size;
1202
1203 /* create temporary picture */
1204 size = avpicture_get_size(dec->pix_fmt, dec->width, dec->height);
1205 buf = av_malloc(size);
1206 if (!buf)
1207 return;
1208
1209 picture2 = &picture_tmp;
1210 avpicture_fill(picture2, buf, dec->pix_fmt, dec->width, dec->height);
1211
1212 if (avpicture_deinterlace(picture2, picture,
1213 dec->pix_fmt, dec->width, dec->height) < 0) {
1214 /* if error, do not deinterlace */
1215 av_log(NULL, AV_LOG_WARNING, "Deinterlacing failed\n");
1216 av_free(buf);
1217 buf = NULL;
1218 picture2 = picture;
1219 }
1220 } else {
1221 picture2 = picture;
1222 }
1223
1224 if (picture != picture2)
1225 *picture = *picture2;
1226 *bufp = buf;
1227 }
1228
1229 static void do_subtitle_out(AVFormatContext *s,
1230 OutputStream *ost,
1231 InputStream *ist,
1232 AVSubtitle *sub,
1233 int64_t pts)
1234 {
1235 static uint8_t *subtitle_out = NULL;
1236 int subtitle_out_max_size = 1024 * 1024;
1237 int subtitle_out_size, nb, i;
1238 AVCodecContext *enc;
1239 AVPacket pkt;
1240
1241 if (pts == AV_NOPTS_VALUE) {
1242 av_log(NULL, AV_LOG_ERROR, "Subtitle packets must have a pts\n");
1243 if (exit_on_error)
1244 exit_program(1);
1245 return;
1246 }
1247
1248 enc = ost->st->codec;
1249
1250 if (!subtitle_out) {
1251 subtitle_out = av_malloc(subtitle_out_max_size);
1252 }
1253
1254 /* Note: DVB subtitle need one packet to draw them and one other
1255 packet to clear them */
1256 /* XXX: signal it in the codec context ? */
1257 if (enc->codec_id == CODEC_ID_DVB_SUBTITLE)
1258 nb = 2;
1259 else
1260 nb = 1;
1261
1262 for (i = 0; i < nb; i++) {
1263 ost->sync_opts = av_rescale_q(pts, ist->st->time_base, enc->time_base);
1264 if (!check_recording_time(ost))
1265 return;
1266
1267 sub->pts = av_rescale_q(pts, ist->st->time_base, AV_TIME_BASE_Q);
1268 // start_display_time is required to be 0
1269 sub->pts += av_rescale_q(sub->start_display_time, (AVRational){ 1, 1000 }, AV_TIME_BASE_Q);
1270 sub->end_display_time -= sub->start_display_time;
1271 sub->start_display_time = 0;
1272 subtitle_out_size = avcodec_encode_subtitle(enc, subtitle_out,
1273 subtitle_out_max_size, sub);
1274 if (subtitle_out_size < 0) {
1275 av_log(NULL, AV_LOG_FATAL, "Subtitle encoding failed\n");
1276 exit_program(1);
1277 }
1278
1279 av_init_packet(&pkt);
1280 pkt.data = subtitle_out;
1281 pkt.size = subtitle_out_size;
1282 pkt.pts = av_rescale_q(sub->pts, AV_TIME_BASE_Q, ost->st->time_base);
1283 if (enc->codec_id == CODEC_ID_DVB_SUBTITLE) {
1284 /* XXX: the pts correction is handled here. Maybe handling
1285 it in the codec would be better */
1286 if (i == 0)
1287 pkt.pts += 90 * sub->start_display_time;
1288 else
1289 pkt.pts += 90 * sub->end_display_time;
1290 }
1291 write_frame(s, &pkt, ost);
1292 }
1293 }
1294
1295 static int bit_buffer_size = 1024 * 256;
1296 static uint8_t *bit_buffer = NULL;
1297
1298 #if !CONFIG_AVFILTER
1299 static void do_video_resample(OutputStream *ost,
1300 InputStream *ist,
1301 AVFrame *in_picture,
1302 AVFrame **out_picture)
1303 {
1304 int resample_changed = 0;
1305 *out_picture = in_picture;
1306
1307 resample_changed = ost->resample_width != in_picture->width ||
1308 ost->resample_height != in_picture->height ||
1309 ost->resample_pix_fmt != in_picture->format;
1310
1311 if (resample_changed) {
1312 av_log(NULL, AV_LOG_INFO,
1313 "Input stream #%d:%d frame changed from size:%dx%d fmt:%s to size:%dx%d fmt:%s\n",
1314 ist->file_index, ist->st->index,
1315 ost->resample_width, ost->resample_height, av_get_pix_fmt_name(ost->resample_pix_fmt),
1316 in_picture->width, in_picture->height, av_get_pix_fmt_name(in_picture->format));
1317 if (!ost->video_resample)
1318 ost->video_resample = 1;
1319 }
1320
1321 if (ost->video_resample) {
1322 *out_picture = &ost->pict_tmp;
1323 if (resample_changed) {
1324 /* initialize a new scaler context */
1325 sws_freeContext(ost->img_resample_ctx);
1326 ost->img_resample_ctx = sws_getContext(
1327 ist->st->codec->width,
1328 ist->st->codec->height,
1329 ist->st->codec->pix_fmt,
1330 ost->st->codec->width,
1331 ost->st->codec->height,
1332 ost->st->codec->pix_fmt,
1333 ost->sws_flags, NULL, NULL, NULL);
1334 if (ost->img_resample_ctx == NULL) {
1335 av_log(NULL, AV_LOG_FATAL, "Cannot get resampling context\n");
1336 exit_program(1);
1337 }
1338 }
1339 sws_scale(ost->img_resample_ctx, in_picture->data, in_picture->linesize,
1340 0, ost->resample_height, (*out_picture)->data, (*out_picture)->linesize);
1341 }
1342 if (resample_changed) {
1343 ost->resample_width = in_picture->width;
1344 ost->resample_height = in_picture->height;
1345 ost->resample_pix_fmt = in_picture->format;
1346 }
1347 }
1348 #endif
1349
1350
1351 static void do_video_out(AVFormatContext *s,
1352 OutputStream *ost,
1353 InputStream *ist,
1354 AVFrame *in_picture,
1355 int *frame_size, float quality)
1356 {
1357 int nb_frames, i, ret, format_video_sync;
1358 AVFrame *final_picture;
1359 AVCodecContext *enc;
1360 double sync_ipts;
1361
1362 enc = ost->st->codec;
1363
1364 sync_ipts = get_sync_ipts(ost) / av_q2d(enc->time_base);
1365
1366 /* by default, we output a single frame */
1367 nb_frames = 1;
1368
1369 *frame_size = 0;
1370
1371 format_video_sync = video_sync_method;
1372 if (format_video_sync == VSYNC_AUTO)
1373 format_video_sync = (s->oformat->flags & AVFMT_NOTIMESTAMPS) ? VSYNC_PASSTHROUGH :
1374 (s->oformat->flags & AVFMT_VARIABLE_FPS) ? VSYNC_VFR : VSYNC_CFR;
1375
1376 if (format_video_sync != VSYNC_PASSTHROUGH) {
1377 double vdelta = sync_ipts - ost->sync_opts;
1378 // FIXME set to 0.5 after we fix some dts/pts bugs like in avidec.c
1379 if (vdelta < -1.1)
1380 nb_frames = 0;
1381 else if (format_video_sync == VSYNC_VFR) {
1382 if (vdelta <= -0.6) {
1383 nb_frames = 0;
1384 } else if (vdelta > 0.6)
1385 ost->sync_opts = lrintf(sync_ipts);
1386 } else if (vdelta > 1.1)
1387 nb_frames = lrintf(vdelta);
1388 if (nb_frames == 0) {
1389 ++nb_frames_drop;
1390 av_log(NULL, AV_LOG_VERBOSE, "*** drop!\n");
1391 } else if (nb_frames > 1) {
1392 nb_frames_dup += nb_frames - 1;
1393 av_log(NULL, AV_LOG_VERBOSE, "*** %d dup!\n", nb_frames - 1);
1394 }
1395 } else
1396 ost->sync_opts = lrintf(sync_ipts);
1397
1398 nb_frames = FFMIN(nb_frames, ost->max_frames - ost->frame_number);
1399 if (nb_frames <= 0)
1400 return;
1401
1402 #if !CONFIG_AVFILTER
1403 do_video_resample(ost, ist, in_picture, &final_picture);
1404 #else
1405 final_picture = in_picture;
1406 #endif
1407
1408 if (!ost->frame_number)
1409 ost->first_pts = ost->sync_opts;
1410
1411 /* duplicates frame if needed */
1412 for (i = 0; i < nb_frames; i++) {
1413 AVPacket pkt;
1414 av_init_packet(&pkt);
1415
1416 if (!check_recording_time(ost))
1417 return;
1418
1419 if (s->oformat->flags & AVFMT_RAWPICTURE &&
1420 enc->codec->id == CODEC_ID_RAWVIDEO) {
1421 /* raw pictures are written as AVPicture structure to
1422 avoid any copies. We support temporarily the older
1423 method. */
1424 enc->coded_frame->interlaced_frame = in_picture->interlaced_frame;
1425 enc->coded_frame->top_field_first = in_picture->top_field_first;
1426 pkt.data = (uint8_t *)final_picture;
1427 pkt.size = sizeof(AVPicture);
1428 pkt.pts = av_rescale_q(ost->sync_opts, enc->time_base, ost->st->time_base);
1429 pkt.flags |= AV_PKT_FLAG_KEY;
1430
1431 write_frame(s, &pkt, ost);
1432 } else {
1433 AVFrame big_picture;
1434
1435 big_picture = *final_picture;
1436 /* better than nothing: use input picture interlaced
1437 settings */
1438 big_picture.interlaced_frame = in_picture->interlaced_frame;
1439 if (ost->st->codec->flags & (CODEC_FLAG_INTERLACED_DCT|CODEC_FLAG_INTERLACED_ME)) {
1440 if (ost->top_field_first == -1)
1441 big_picture.top_field_first = in_picture->top_field_first;
1442 else
1443 big_picture.top_field_first = !!ost->top_field_first;
1444 }
1445
1446 /* handles same_quant here. This is not correct because it may
1447 not be a global option */
1448 big_picture.quality = quality;
1449 if (!enc->me_threshold)
1450 big_picture.pict_type = 0;
1451 big_picture.pts = ost->sync_opts;
1452 if (ost->forced_kf_index < ost->forced_kf_count &&
1453 big_picture.pts >= ost->forced_kf_pts[ost->forced_kf_index]) {
1454 big_picture.pict_type = AV_PICTURE_TYPE_I;
1455 ost->forced_kf_index++;
1456 }
1457 ret = avcodec_encode_video(enc,
1458 bit_buffer, bit_buffer_size,
1459 &big_picture);
1460 if (ret < 0) {
1461 av_log(NULL, AV_LOG_FATAL, "Video encoding failed\n");
1462 exit_program(1);
1463 }
1464
1465 if (ret > 0) {
1466 pkt.data = bit_buffer;
1467 pkt.size = ret;
1468 if (enc->coded_frame->pts != AV_NOPTS_VALUE)
1469 pkt.pts = av_rescale_q(enc->coded_frame->pts, enc->time_base, ost->st->time_base);
1470
1471 if (enc->coded_frame->key_frame)
1472 pkt.flags |= AV_PKT_FLAG_KEY;
1473 write_frame(s, &pkt, ost);
1474 *frame_size = ret;
1475 video_size += ret;
1476
1477 /* if two pass, output log */
1478 if (ost->logfile && enc->stats_out) {
1479 fprintf(ost->logfile, "%s", enc->stats_out);
1480 }
1481 }
1482 }
1483 ost->sync_opts++;
1484 /*
1485 * For video, number of frames in == number of packets out.
1486 * But there may be reordering, so we can't throw away frames on encoder
1487 * flush, we need to limit them here, before they go into encoder.
1488 */
1489 ost->frame_number++;
1490 }
1491 }
1492
1493 static double psnr(double d)
1494 {
1495 return -10.0 * log(d) / log(10.0);
1496 }
1497
1498 static void do_video_stats(AVFormatContext *os, OutputStream *ost,
1499 int frame_size)
1500 {
1501 AVCodecContext *enc;
1502 int frame_number;
1503 double ti1, bitrate, avg_bitrate;
1504
1505 /* this is executed just the first time do_video_stats is called */
1506 if (!vstats_file) {
1507 vstats_file = fopen(vstats_filename, "w");
1508 if (!vstats_file) {
1509 perror("fopen");
1510 exit_program(1);
1511 }
1512 }
1513
1514 enc = ost->st->codec;
1515 if (enc->codec_type == AVMEDIA_TYPE_VIDEO) {
1516 frame_number = ost->frame_number;
1517 fprintf(vstats_file, "frame= %5d q= %2.1f ", frame_number, enc->coded_frame->quality / (float)FF_QP2LAMBDA);
1518 if (enc->flags&CODEC_FLAG_PSNR)
1519 fprintf(vstats_file, "PSNR= %6.2f ", psnr(enc->coded_frame->error[0] / (enc->width * enc->height * 255.0 * 255.0)));
1520
1521 fprintf(vstats_file,"f_size= %6d ", frame_size);
1522 /* compute pts value */
1523 ti1 = ost->sync_opts * av_q2d(enc->time_base);
1524 if (ti1 < 0.01)
1525 ti1 = 0.01;
1526
1527 bitrate = (frame_size * 8) / av_q2d(enc->time_base) / 1000.0;
1528 avg_bitrate = (double)(video_size * 8) / ti1 / 1000.0;
1529 fprintf(vstats_file, "s_size= %8.0fkB time= %0.3f br= %7.1fkbits/s avg_br= %7.1fkbits/s ",
1530 (double)video_size / 1024, ti1, bitrate, avg_bitrate);
1531 fprintf(vstats_file, "type= %c\n", av_get_picture_type_char(enc->coded_frame->pict_type));
1532 }
1533 }
1534
1535 static void print_report(OutputFile *output_files,
1536 OutputStream *ost_table, int nb_ostreams,
1537 int is_last_report, int64_t timer_start)
1538 {
1539 char buf[1024];
1540 OutputStream *ost;
1541 AVFormatContext *oc;
1542 int64_t total_size;
1543 AVCodecContext *enc;
1544 int frame_number, vid, i;
1545 double bitrate, ti1, pts;
1546 static int64_t last_time = -1;
1547 static int qp_histogram[52];
1548
1549 if (!print_stats && !is_last_report)
1550 return;
1551
1552 if (!is_last_report) {
1553 int64_t cur_time;
1554 /* display the report every 0.5 seconds */
1555 cur_time = av_gettime();
1556 if (last_time == -1) {
1557 last_time = cur_time;
1558 return;
1559 }
1560 if ((cur_time - last_time) < 500000)
1561 return;
1562 last_time = cur_time;
1563 }
1564
1565
1566 oc = output_files[0].ctx;
1567
1568 total_size = avio_size(oc->pb);
1569 if (total_size < 0) // FIXME improve avio_size() so it works with non seekable output too
1570 total_size = avio_tell(oc->pb);
1571
1572 buf[0] = '\0';
1573 ti1 = 1e10;
1574 vid = 0;
1575 for (i = 0; i < nb_ostreams; i++) {
1576 float q = -1;
1577 ost = &ost_table[i];
1578 enc = ost->st->codec;
1579 if (!ost->stream_copy && enc->coded_frame)
1580 q = enc->coded_frame->quality / (float)FF_QP2LAMBDA;
1581 if (vid && enc->codec_type == AVMEDIA_TYPE_VIDEO) {
1582 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "q=%2.1f ", q);
1583 }
1584 if (!vid && enc->codec_type == AVMEDIA_TYPE_VIDEO) {
1585 float t = (av_gettime() - timer_start) / 1000000.0;
1586
1587 frame_number = ost->frame_number;
1588 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "frame=%5d fps=%3d q=%3.1f ",
1589 frame_number, (t > 1) ? (int)(frame_number / t + 0.5) : 0, q);
1590 if (is_last_report)
1591 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "L");
1592 if (qp_hist) {
1593 int j;
1594 int qp = lrintf(q);
1595 if (qp >= 0 && qp < FF_ARRAY_ELEMS(qp_histogram))
1596 qp_histogram[qp]++;
1597 for (j = 0; j < 32; j++)
1598 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "%X", (int)lrintf(log(qp_histogram[j] + 1) / log(2)));
1599 }
1600 if (enc->flags&CODEC_FLAG_PSNR) {
1601 int j;
1602 double error, error_sum = 0;
1603 double scale, scale_sum = 0;
1604 char type[3] = { 'Y','U','V' };
1605 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "PSNR=");
1606 for (j = 0; j < 3; j++) {
1607 if (is_last_report) {
1608 error = enc->error[j];
1609 scale = enc->width * enc->height * 255.0 * 255.0 * frame_number;
1610 } else {
1611 error = enc->coded_frame->error[j];
1612 scale = enc->width * enc->height * 255.0 * 255.0;
1613 }
1614 if (j)
1615 scale /= 4;
1616 error_sum += error;
1617 scale_sum += scale;
1618 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "%c:%2.2f ", type[j], psnr(error / scale));
1619 }
1620 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "*:%2.2f ", psnr(error_sum / scale_sum));
1621 }
1622 vid = 1;
1623 }
1624 /* compute min output value */
1625 pts = (double)ost->st->pts.val * av_q2d(ost->st->time_base);
1626 if ((pts < ti1) && (pts > 0))
1627 ti1 = pts;
1628 }
1629 if (ti1 < 0.01)
1630 ti1 = 0.01;
1631
1632 bitrate = (double)(total_size * 8) / ti1 / 1000.0;
1633
1634 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
1635 "size=%8.0fkB time=%0.2f bitrate=%6.1fkbits/s",
1636 (double)total_size / 1024, ti1, bitrate);
1637
1638 if (nb_frames_dup || nb_frames_drop)
1639 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), " dup=%d drop=%d",
1640 nb_frames_dup, nb_frames_drop);
1641
1642 av_log(NULL, AV_LOG_INFO, "%s \r", buf);
1643
1644 fflush(stderr);
1645
1646 if (is_last_report) {
1647 int64_t raw= audio_size + video_size + extra_size;
1648 av_log(NULL, AV_LOG_INFO, "\n");
1649 av_log(NULL, AV_LOG_INFO, "video:%1.0fkB audio:%1.0fkB global headers:%1.0fkB muxing overhead %f%%\n",
1650 video_size / 1024.0,
1651 audio_size / 1024.0,
1652 extra_size / 1024.0,
1653 100.0 * (total_size - raw) / raw
1654 );
1655 }
1656 }
1657
1658 static void flush_encoders(OutputStream *ost_table, int nb_ostreams)
1659 {
1660 int i, ret;
1661
1662 for (i = 0; i < nb_ostreams; i++) {
1663 OutputStream *ost = &ost_table[i];
1664 AVCodecContext *enc = ost->st->codec;
1665 AVFormatContext *os = output_files[ost->file_index].ctx;
1666 int stop_encoding = 0;
1667
1668 if (!ost->encoding_needed)
1669 continue;
1670
1671 if (ost->st->codec->codec_type == AVMEDIA_TYPE_AUDIO && enc->frame_size <= 1)
1672 continue;
1673 if (ost->st->codec->codec_type == AVMEDIA_TYPE_VIDEO && (os->oformat->flags & AVFMT_RAWPICTURE) && enc->codec->id == CODEC_ID_RAWVIDEO)
1674 continue;
1675
1676 for (;;) {
1677 AVPacket pkt;
1678 int fifo_bytes;
1679 av_init_packet(&pkt);
1680 pkt.data = NULL;
1681 pkt.size = 0;
1682
1683 switch (ost->st->codec->codec_type) {
1684 case AVMEDIA_TYPE_AUDIO:
1685 fifo_bytes = av_fifo_size(ost->fifo);
1686 if (fifo_bytes > 0) {
1687 /* encode any samples remaining in fifo */
1688 int frame_bytes = fifo_bytes;
1689
1690 av_fifo_generic_read(ost->fifo, audio_buf, fifo_bytes, NULL);
1691
1692 /* pad last frame with silence if needed */
1693 if (!(enc->codec->capabilities & CODEC_CAP_SMALL_LAST_FRAME)) {
1694 frame_bytes = enc->frame_size * enc->channels *
1695 av_get_bytes_per_sample(enc->sample_fmt);
1696 if (allocated_audio_buf_size < frame_bytes)
1697 exit_program(1);
1698 generate_silence(audio_buf+fifo_bytes, enc->sample_fmt, frame_bytes - fifo_bytes);
1699 }
1700 encode_audio_frame(os, ost, audio_buf, frame_bytes);
1701 } else {
1702 /* flush encoder with NULL frames until it is done
1703 returning packets */
1704 if (encode_audio_frame(os, ost, NULL, 0) == 0) {
1705 stop_encoding = 1;
1706 break;
1707 }
1708 }
1709 break;
1710 case AVMEDIA_TYPE_VIDEO:
1711 ret = avcodec_encode_video(enc, bit_buffer, bit_buffer_size, NULL);
1712 if (ret < 0) {
1713 av_log(NULL, AV_LOG_FATAL, "Video encoding failed\n");
1714 exit_program(1);
1715 }
1716 video_size += ret;
1717 if (enc->coded_frame && enc->coded_frame->key_frame)
1718 pkt.flags |= AV_PKT_FLAG_KEY;
1719 if (ost->logfile && enc->stats_out) {
1720 fprintf(ost->logfile, "%s", enc->stats_out);
1721 }
1722 if (ret <= 0) {
1723 stop_encoding = 1;
1724 break;
1725 }
1726 pkt.data = bit_buffer;
1727 pkt.size = ret;
1728 if (enc->coded_frame && enc->coded_frame->pts != AV_NOPTS_VALUE)
1729 pkt.pts = av_rescale_q(enc->coded_frame->pts, enc->time_base, ost->st->time_base);
1730 write_frame(os, &pkt, ost);
1731 break;
1732 default:
1733 stop_encoding = 1;
1734 }
1735 if (stop_encoding)
1736 break;
1737 }
1738 }
1739 }
1740
1741 /*
1742 * Check whether a packet from ist should be written into ost at this time
1743 */
1744 static int check_output_constraints(InputStream *ist, OutputStream *ost)
1745 {
1746 OutputFile *of = &output_files[ost->file_index];
1747 int ist_index = ist - input_streams;
1748
1749 if (ost->source_index != ist_index)
1750 return 0;
1751
1752 if (of->start_time && ist->pts < of->start_time)
1753 return 0;
1754
1755 return 1;
1756 }
1757
1758 static void do_streamcopy(InputStream *ist, OutputStream *ost, const AVPacket *pkt)
1759 {
1760 OutputFile *of = &output_files[ost->file_index];
1761 int64_t ost_tb_start_time = av_rescale_q(of->start_time, AV_TIME_BASE_Q, ost->st->time_base);
1762 AVPacket opkt;
1763
1764 av_init_packet(&opkt);
1765
1766 if ((!ost->frame_number && !(pkt->flags & AV_PKT_FLAG_KEY)) &&
1767 !ost->copy_initial_nonkeyframes)
1768 return;
1769
1770 if (of->recording_time != INT64_MAX &&
1771 ist->pts >= of->recording_time + of->start_time) {
1772 ost->is_past_recording_time = 1;
1773 return;
1774 }
1775
1776 /* force the input stream PTS */
1777 if (ost->st->codec->codec_type == AVMEDIA_TYPE_AUDIO)
1778 audio_size += pkt->size;
1779 else if (ost->st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
1780 video_size += pkt->size;
1781 ost->sync_opts++;
1782 }
1783
1784 if (pkt->pts != AV_NOPTS_VALUE)
1785 opkt.pts = av_rescale_q(pkt->pts, ist->st->time_base, ost->st->time_base) - ost_tb_start_time;
1786 else
1787 opkt.pts = AV_NOPTS_VALUE;
1788
1789 if (pkt->dts == AV_NOPTS_VALUE)
1790 opkt.dts = av_rescale_q(ist->pts, AV_TIME_BASE_Q, ost->st->time_base);
1791 else
1792 opkt.dts = av_rescale_q(pkt->dts, ist->st->time_base, ost->st->time_base);
1793 opkt.dts -= ost_tb_start_time;
1794
1795 opkt.duration = av_rescale_q(pkt->duration, ist->st->time_base, ost->st->time_base);
1796 opkt.flags = pkt->flags;
1797
1798 // FIXME remove the following 2 lines they shall be replaced by the bitstream filters
1799 if ( ost->st->codec->codec_id != CODEC_ID_H264
1800 && ost->st->codec->codec_id != CODEC_ID_MPEG1VIDEO
1801 && ost->st->codec->codec_id != CODEC_ID_MPEG2VIDEO
1802 ) {
1803 if (av_parser_change(ist->st->parser, ost->st->codec, &opkt.data, &opkt.size, pkt->data, pkt->size, pkt->flags & AV_PKT_FLAG_KEY))
1804 opkt.destruct = av_destruct_packet;
1805 } else {
1806 opkt.data = pkt->data;
1807 opkt.size = pkt->size;
1808 }
1809
1810 write_frame(of->ctx, &opkt, ost);
1811 ost->st->codec->frame_number++;
1812 av_free_packet(&opkt);
1813 }
1814
1815 static void rate_emu_sleep(InputStream *ist)
1816 {
1817 if (input_files[ist->file_index].rate_emu) {
1818 int64_t pts = av_rescale(ist->pts, 1000000, AV_TIME_BASE);
1819 int64_t now = av_gettime() - ist->start;
1820 if (pts > now)
1821 usleep(pts - now);
1822 }
1823 }
1824
1825 static int transcode_audio(InputStream *ist, AVPacket *pkt, int *got_output)
1826 {
1827 AVFrame *decoded_frame;
1828 AVCodecContext *avctx = ist->st->codec;
1829 int bps = av_get_bytes_per_sample(ist->st->codec->sample_fmt);
1830 int i, ret;
1831
1832 if (!ist->decoded_frame && !(ist->decoded_frame = avcodec_alloc_frame()))
1833 return AVERROR(ENOMEM);
1834 else
1835 avcodec_get_frame_defaults(ist->decoded_frame);
1836 decoded_frame = ist->decoded_frame;
1837
1838 ret = avcodec_decode_audio4(avctx, decoded_frame, got_output, pkt);
1839 if (ret < 0) {
1840 return ret;
1841 }
1842
1843 if (!*got_output) {
1844 /* no audio frame */
1845 return ret;
1846 }
1847
1848 /* if the decoder provides a pts, use it instead of the last packet pts.
1849 the decoder could be delaying output by a packet or more. */
1850 if (decoded_frame->pts != AV_NOPTS_VALUE)
1851 ist->next_dts = decoded_frame->pts;
1852
1853 /* increment next_dts to use for the case where the input stream does not
1854 have timestamps or there are multiple frames in the packet */
1855 ist->next_dts += ((int64_t)AV_TIME_BASE * decoded_frame->nb_samples) /
1856 avctx->sample_rate;
1857
1858 // preprocess audio (volume)
1859 if (audio_volume != 256) {
1860 int decoded_data_size = decoded_frame->nb_samples * avctx->channels * bps;
1861 void *samples = decoded_frame->data[0];
1862 switch (avctx->sample_fmt) {
1863 case AV_SAMPLE_FMT_U8:
1864 {
1865 uint8_t *volp = samples;
1866 for (i = 0; i < (decoded_data_size / sizeof(*volp)); i++) {
1867 int v = (((*volp - 128) * audio_volume + 128) >> 8) + 128;
1868 *volp++ = av_clip_uint8(v);
1869 }
1870 break;
1871 }
1872 case AV_SAMPLE_FMT_S16:
1873 {
1874 int16_t *volp = samples;
1875 for (i = 0; i < (decoded_data_size / sizeof(*volp)); i++) {
1876 int v = ((*volp) * audio_volume + 128) >> 8;
1877 *volp++ = av_clip_int16(v);
1878 }
1879 break;
1880 }
1881 case AV_SAMPLE_FMT_S32:
1882 {
1883 int32_t *volp = samples;
1884 for (i = 0; i < (decoded_data_size / sizeof(*volp)); i++) {
1885 int64_t v = (((int64_t)*volp * audio_volume + 128) >> 8);
1886 *volp++ = av_clipl_int32(v);
1887 }
1888 break;
1889 }
1890 case AV_SAMPLE_FMT_FLT:
1891 {
1892 float *volp = samples;
1893 float scale = audio_volume / 256.f;
1894 for (i = 0; i < (decoded_data_size / sizeof(*volp)); i++) {
1895 *volp++ *= scale;
1896 }
1897 break;
1898 }
1899 case AV_SAMPLE_FMT_DBL:
1900 {
1901 double *volp = samples;
1902 double scale = audio_volume / 256.;
1903 for (i = 0; i < (decoded_data_size / sizeof(*volp)); i++) {
1904 *volp++ *= scale;
1905 }
1906 break;
1907 }
1908 default:
1909 av_log(NULL, AV_LOG_FATAL,
1910 "Audio volume adjustment on sample format %s is not supported.\n",
1911 av_get_sample_fmt_name(ist->st->codec->sample_fmt));
1912 exit_program(1);
1913 }
1914 }
1915
1916 rate_emu_sleep(ist);
1917
1918 for (i = 0; i < nb_output_streams; i++) {
1919 OutputStream *ost = &output_streams[i];
1920
1921 if (!check_output_constraints(ist, ost) || !ost->encoding_needed)
1922 continue;
1923 do_audio_out(output_files[ost->file_index].ctx, ost, ist, decoded_frame);
1924 }
1925
1926 return ret;
1927 }
1928
1929 static int transcode_video(InputStream *ist, AVPacket *pkt, int *got_output, int64_t *pkt_pts)
1930 {
1931 AVFrame *decoded_frame, *filtered_frame = NULL;
1932 void *buffer_to_free = NULL;
1933 int i, ret = 0;
1934 float quality;
1935 #if CONFIG_AVFILTER
1936 int frame_available = 1;
1937 #endif
1938
1939 if (!ist->decoded_frame && !(ist->decoded_frame = avcodec_alloc_frame()))
1940 return AVERROR(ENOMEM);
1941 else
1942 avcodec_get_frame_defaults(ist->decoded_frame);
1943 decoded_frame = ist->decoded_frame;
1944 pkt->pts = *pkt_pts;
1945 pkt->dts = ist->pts;
1946 *pkt_pts = AV_NOPTS_VALUE;
1947
1948 ret = avcodec_decode_video2(ist->st->codec,
1949 decoded_frame, got_output, pkt);
1950 if (ret < 0)
1951 return ret;
1952
1953 quality = same_quant ? decoded_frame->quality : 0;
1954 if (!*got_output) {
1955 /* no picture yet */
1956 return ret;
1957 }
1958 ist->next_dts = ist->pts = guess_correct_pts(&ist->pts_ctx, decoded_frame->pkt_pts,
1959 decoded_frame->pkt_dts);
1960 if (pkt->duration)
1961 ist->next_dts += av_rescale_q(pkt->duration, ist->st->time_base, AV_TIME_BASE_Q);
1962 else if (ist->st->codec->time_base.num != 0) {
1963 int ticks = ist->st->parser ? ist->st->parser->repeat_pict + 1 :
1964 ist->st->codec->ticks_per_frame;
1965 ist->next_dts += ((int64_t)AV_TIME_BASE *
1966 ist->st->codec->time_base.num * ticks) /
1967 ist->st->codec->time_base.den;
1968 }
1969 pkt->size = 0;
1970 pre_process_video_frame(ist, (AVPicture *)decoded_frame, &buffer_to_free);
1971
1972 rate_emu_sleep(ist);
1973
1974 for (i = 0; i < nb_output_streams; i++) {
1975 OutputStream *ost = &output_streams[i];
1976 int frame_size, resample_changed;
1977
1978 if (!check_output_constraints(ist, ost) || !ost->encoding_needed)
1979 continue;
1980
1981 #if CONFIG_AVFILTER
1982 resample_changed = ost->resample_width != decoded_frame->width ||
1983 ost->resample_height != decoded_frame->height ||
1984 ost->resample_pix_fmt != decoded_frame->format;
1985 if (resample_changed) {
1986 av_log(NULL, AV_LOG_INFO,
1987 "Input stream #%d:%d frame changed from size:%dx%d fmt:%s to size:%dx%d fmt:%s\n",
1988 ist->file_index, ist->st->index,
1989 ost->resample_width, ost->resample_height, av_get_pix_fmt_name(ost->resample_pix_fmt),
1990 decoded_frame->width, decoded_frame->height, av_get_pix_fmt_name(decoded_frame->format));
1991
1992 avfilter_graph_free(&ost->graph);
1993 if (configure_video_filters(ist, ost)) {
1994 av_log(NULL, AV_LOG_FATAL, "Error reinitializing filters!\n");
1995 exit_program(1);
1996 }
1997
1998 ost->resample_width = decoded_frame->width;
1999 ost->resample_height = decoded_frame->height;
2000 ost->resample_pix_fmt = decoded_frame->format;
2001 }
2002
2003 if (ist->st->sample_aspect_ratio.num)
2004 decoded_frame->sample_aspect_ratio = ist->st->sample_aspect_ratio;
2005 if (ist->st->codec->codec->capabilities & CODEC_CAP_DR1) {
2006 FrameBuffer *buf = decoded_frame->opaque;
2007 AVFilterBufferRef *fb = avfilter_get_video_buffer_ref_from_arrays(
2008 decoded_frame->data, decoded_frame->linesize,
2009 AV_PERM_READ | AV_PERM_PRESERVE,
2010 ist->st->codec->width, ist->st->codec->height,
2011 ist->st->codec->pix_fmt);
2012
2013 avfilter_copy_frame_props(fb, decoded_frame);
2014 fb->pts = ist->pts;
2015 fb->buf->priv = buf;
2016 fb->buf->free = filter_release_buffer;
2017
2018 buf->refcount++;
2019 av_buffersrc_buffer(ost->input_video_filter, fb);
2020 } else
2021 av_vsrc_buffer_add_frame(ost->input_video_filter, decoded_frame,
2022 ist->pts, decoded_frame->sample_aspect_ratio);
2023
2024 if (!ist->filtered_frame && !(ist->filtered_frame = avcodec_alloc_frame())) {
2025 av_free(buffer_to_free);
2026 return AVERROR(ENOMEM);
2027 } else
2028 avcodec_get_frame_defaults(ist->filtered_frame);
2029 filtered_frame = ist->filtered_frame;
2030
2031 frame_available = avfilter_poll_frame(ost->output_video_filter->inputs[0]);
2032 while (frame_available) {
2033 AVRational ist_pts_tb;
2034 if (ost->output_video_filter)
2035 get_filtered_video_frame(ost->output_video_filter, filtered_frame, &ost->picref, &ist_pts_tb);
2036 if (ost->picref)
2037 ist->pts = av_rescale_q(ost->picref->pts, ist_pts_tb, AV_TIME_BASE_Q);
2038 if (ost->picref->video && !ost->frame_aspect_ratio)
2039 ost->st->codec->sample_aspect_ratio = ost->picref->video->pixel_aspect;
2040 #else
2041 filtered_frame = decoded_frame;
2042 #endif
2043
2044 do_video_out(output_files[ost->file_index].ctx, ost, ist, filtered_frame, &frame_size,
2045 same_quant ? quality : ost->st->codec->global_quality);
2046 if (vstats_filename && frame_size)
2047 do_video_stats(output_files[ost->file_index].ctx, ost, frame_size);
2048 #if CONFIG_AVFILTER
2049 frame_available = ost->output_video_filter && avfilter_poll_frame(ost->output_video_filter->inputs[0]);
2050 if (ost->picref)
2051 avfilter_unref_buffer(ost->picref);
2052 }
2053 #endif
2054 }
2055
2056 av_free(buffer_to_free);
2057 return ret;
2058 }
2059
2060 static int transcode_subtitles(InputStream *ist, AVPacket *pkt, int *got_output)
2061 {
2062 AVSubtitle subtitle;
2063 int i, ret = avcodec_decode_subtitle2(ist->st->codec,
2064 &subtitle, got_output, pkt);
2065 if (ret < 0)
2066 return ret;
2067 if (!*got_output)
2068 return ret;
2069
2070 rate_emu_sleep(ist);
2071
2072 for (i = 0; i < nb_output_streams; i++) {
2073 OutputStream *ost = &output_streams[i];
2074
2075 if (!check_output_constraints(ist, ost) || !ost->encoding_needed)
2076 continue;
2077
2078 do_subtitle_out(output_files[ost->file_index].ctx, ost, ist, &subtitle, pkt->pts);
2079 }
2080
2081 avsubtitle_free(&subtitle);
2082 return ret;
2083 }
2084
2085 /* pkt = NULL means EOF (needed to flush decoder buffers) */
2086 static int output_packet(InputStream *ist,
2087 OutputStream *ost_table, int nb_ostreams,
2088 const AVPacket *pkt)
2089 {
2090 int i;
2091 int got_output;
2092 int64_t pkt_pts = AV_NOPTS_VALUE;
2093 AVPacket avpkt;
2094
2095 if (ist->next_dts == AV_NOPTS_VALUE)
2096 ist->next_dts = ist->pts;
2097
2098 if (pkt == NULL) {
2099 /* EOF handling */
2100 av_init_packet(&avpkt);
2101 avpkt.data = NULL;
2102 avpkt.size = 0;
2103 goto handle_eof;
2104 } else {
2105 avpkt = *pkt;
2106 }
2107
2108 if (pkt->dts != AV_NOPTS_VALUE)
2109 ist->next_dts = ist->pts = av_rescale_q(pkt->dts, ist->st->time_base, AV_TIME_BASE_Q);
2110 if (pkt->pts != AV_NOPTS_VALUE)
2111 pkt_pts = av_rescale_q(pkt->pts, ist->st->time_base, AV_TIME_BASE_Q);
2112
2113 // while we have more to decode or while the decoder did output something on EOF
2114 while (ist->decoding_needed && (avpkt.size > 0 || (!pkt && got_output))) {
2115 int ret = 0;
2116 handle_eof:
2117
2118 ist->pts = ist->next_dts;
2119
2120 if (avpkt.size && avpkt.size != pkt->size) {
2121 av_log(NULL, ist->showed_multi_packet_warning ? AV_LOG_VERBOSE : AV_LOG_WARNING,
2122 "Multiple frames in a packet from stream %d\n", pkt->stream_index);
2123 ist->showed_multi_packet_warning = 1;
2124 }
2125
2126 switch (ist->st->codec->codec_type) {
2127 case AVMEDIA_TYPE_AUDIO:
2128 ret = transcode_audio (ist, &avpkt, &got_output);
2129 break;
2130 case AVMEDIA_TYPE_VIDEO:
2131 ret = transcode_video (ist, &avpkt, &got_output, &pkt_pts);
2132 break;
2133 case AVMEDIA_TYPE_SUBTITLE:
2134 ret = transcode_subtitles(ist, &avpkt, &got_output);
2135 break;
2136 default:
2137 return -1;
2138 }
2139
2140 if (ret < 0)
2141 return ret;
2142 // touch data and size only if not EOF
2143 if (pkt) {
2144 avpkt.data += ret;
2145 avpkt.size -= ret;
2146 }
2147 if (!got_output) {
2148 continue;
2149 }
2150 }
2151
2152 /* handle stream copy */
2153 if (!ist->decoding_needed) {
2154 rate_emu_sleep(ist);
2155 ist->pts = ist->next_dts;
2156 switch (ist->st->codec->codec_type) {
2157 case AVMEDIA_TYPE_AUDIO:
2158 ist->next_dts += ((int64_t)AV_TIME_BASE * ist->st->codec->frame_size) /
2159 ist->st->codec->sample_rate;
2160 break;
2161 case AVMEDIA_TYPE_VIDEO:
2162 if (ist->st->codec->time_base.num != 0) {
2163 int ticks = ist->st->parser ? ist->st->parser->repeat_pict + 1 : ist->st->codec->ticks_per_frame;
2164 ist->next_dts += ((int64_t)AV_TIME_BASE *
2165 ist->st->codec->time_base.num * ticks) /
2166 ist->st->codec->time_base.den;
2167 }
2168 break;
2169 }
2170 }
2171 for (i = 0; pkt && i < nb_ostreams; i++) {
2172 OutputStream *ost = &ost_table[i];
2173
2174 if (!check_output_constraints(ist, ost) || ost->encoding_needed)
2175 continue;
2176
2177 do_streamcopy(ist, ost, pkt);
2178 }
2179
2180 return 0;
2181 }
2182
2183 static void print_sdp(OutputFile *output_files, int n)
2184 {
2185 char sdp[2048];
2186 int i;
2187 AVFormatContext **avc = av_malloc(sizeof(*avc) * n);
2188
2189 if (!avc)
2190 exit_program(1);
2191 for (i = 0; i < n; i++)
2192 avc[i] = output_files[i].ctx;
2193
2194 av_sdp_create(avc, n, sdp, sizeof(sdp));
2195 printf("SDP:\n%s\n", sdp);
2196 fflush(stdout);
2197 av_freep(&avc);
2198 }
2199
2200 static int init_input_stream(int ist_index, OutputStream *output_streams, int nb_output_streams,
2201 char *error, int error_len)
2202 {
2203 int i;
2204 InputStream *ist = &input_streams[ist_index];
2205 if (ist->decoding_needed) {
2206 AVCodec *codec = ist->dec;
2207 if (!codec) {
2208 snprintf(error, error_len, "Decoder (codec id %d) not found for input stream #%d:%d",
2209 ist->st->codec->codec_id, ist->file_index, ist->st->index);
2210 return AVERROR(EINVAL);
2211 }
2212
2213 /* update requested sample format for the decoder based on the
2214 corresponding encoder sample format */
2215 for (i = 0; i < nb_output_streams; i++) {
2216 OutputStream *ost = &output_streams[i];
2217 if (ost->source_index == ist_index) {
2218 update_sample_fmt(ist->st->codec, codec, ost->st->codec);
2219 break;
2220 }
2221 }
2222
2223 if (codec->type == AVMEDIA_TYPE_VIDEO && codec->capabilities & CODEC_CAP_DR1) {
2224 ist->st->codec->get_buffer = codec_get_buffer;
2225 ist->st->codec->release_buffer = codec_release_buffer;
2226 ist->st->codec->opaque = ist;
2227 }
2228
2229 if (!av_dict_get(ist->opts, "threads", NULL, 0))
2230 av_dict_set(&ist->opts, "threads", "auto", 0);
2231 if (avcodec_open2(ist->st->codec, codec, &ist->opts) < 0) {
2232 snprintf(error, error_len, "Error while opening decoder for input stream #%d:%d",
2233 ist->file_index, ist->st->index);
2234 return AVERROR(EINVAL);
2235 }
2236 assert_codec_experimental(ist->st->codec, 0);
2237 assert_avoptions(ist->opts);
2238 }
2239
2240 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;
2241 ist->next_dts = AV_NOPTS_VALUE;
2242 init_pts_correction(&ist->pts_ctx);
2243 ist->is_start = 1;
2244
2245 return 0;
2246 }
2247
2248 static int transcode_init(OutputFile *output_files,
2249 int nb_output_files,
2250 InputFile *input_files,
2251 int nb_input_files)
2252 {
2253 int ret = 0, i, j, k;
2254 AVFormatContext *oc;
2255 AVCodecContext *codec, *icodec;
2256 OutputStream *ost;
2257 InputStream *ist;
2258 char error[1024];
2259 int want_sdp = 1;
2260
2261 /* init framerate emulation */
2262 for (i = 0; i < nb_input_files; i++) {
2263 InputFile *ifile = &input_files[i];
2264 if (ifile->rate_emu)
2265 for (j = 0; j < ifile->nb_streams; j++)
2266 input_streams[j + ifile->ist_index].start = av_gettime();
2267 }
2268
2269 /* output stream init */
2270 for (i = 0; i < nb_output_files; i++) {
2271 oc = output_files[i].ctx;
2272 if (!oc->nb_streams && !(oc->oformat->flags & AVFMT_NOSTREAMS)) {
2273 av_dump_format(oc, i, oc->filename, 1);
2274 av_log(NULL, AV_LOG_ERROR, "Output file #%d does not contain any stream\n", i);
2275 return AVERROR(EINVAL);
2276 }
2277 }
2278
2279 /* for each output stream, we compute the right encoding parameters */
2280 for (i = 0; i < nb_output_streams; i++) {
2281 ost = &output_streams[i];
2282 oc = output_files[ost->file_index].ctx;
2283 ist = &input_streams[ost->source_index];
2284
2285 if (ost->attachment_filename)
2286 continue;
2287
2288 codec = ost->st->codec;
2289 icodec = ist->st->codec;
2290
2291 ost->st->disposition = ist->st->disposition;
2292 codec->bits_per_raw_sample = icodec->bits_per_raw_sample;
2293 codec->chroma_sample_location = icodec->chroma_sample_location;
2294
2295 if (ost->stream_copy) {
2296 uint64_t extra_size = (uint64_t)icodec->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE;
2297
2298 if (extra_size > INT_MAX) {
2299 return AVERROR(EINVAL);
2300 }
2301
2302 /* if stream_copy is selected, no need to decode or encode */
2303 codec->codec_id = icodec->codec_id;
2304 codec->codec_type = icodec->codec_type;
2305
2306 if (!codec->codec_tag) {
2307 if (!oc->oformat->codec_tag ||
2308 av_codec_get_id (oc->oformat->codec_tag, icodec->codec_tag) == codec->codec_id ||
2309 av_codec_get_tag(oc->oformat->codec_tag, icodec->codec_id) <= 0)
2310 codec->codec_tag = icodec->codec_tag;
2311 }
2312
2313 codec->bit_rate = icodec->bit_rate;
2314 codec->rc_max_rate = icodec->rc_max_rate;
2315 codec->rc_buffer_size = icodec->rc_buffer_size;
2316 codec->field_order = icodec->field_order;
2317 codec->extradata = av_mallocz(extra_size);
2318 if (!codec->extradata) {
2319 return AVERROR(ENOMEM);
2320 }
2321 memcpy(codec->extradata, icodec->extradata, icodec->extradata_size);
2322 codec->extradata_size = icodec->extradata_size;
2323 if (!copy_tb) {
2324 codec->time_base = icodec->time_base;
2325 codec->time_base.num *= icodec->ticks_per_frame;
2326 av_reduce(&codec->time_base.num, &codec->time_base.den,
2327 codec->time_base.num, codec->time_base.den, INT_MAX);
2328 } else
2329 codec->time_base = ist->st->time_base;
2330
2331 switch (codec->codec_type) {
2332 case AVMEDIA_TYPE_AUDIO:
2333 if (audio_volume != 256) {
2334 av_log(NULL, AV_LOG_FATAL, "-acodec copy and -vol are incompatible (frames are not decoded)\n");
2335 exit_program(1);
2336 }
2337 codec->channel_layout = icodec->channel_layout;
2338 codec->sample_rate = icodec->sample_rate;
2339 codec->channels = icodec->channels;
2340 codec->frame_size = icodec->frame_size;
2341 codec->audio_service_type = icodec->audio_service_type;
2342 codec->block_align = icodec->block_align;
2343 break;
2344 case AVMEDIA_TYPE_VIDEO:
2345 codec->pix_fmt = icodec->pix_fmt;
2346 codec->width = icodec->width;
2347 codec->height = icodec->height;
2348 codec->has_b_frames = icodec->has_b_frames;
2349 if (!codec->sample_aspect_ratio.num) {
2350 codec->sample_aspect_ratio =
2351 ost->st->sample_aspect_ratio =
2352 ist->st->sample_aspect_ratio.num ? ist->st->sample_aspect_ratio :
2353 ist->st->codec->sample_aspect_ratio.num ?
2354 ist->st->codec->sample_aspect_ratio : (AVRational){0, 1};
2355 }
2356 break;
2357 case AVMEDIA_TYPE_SUBTITLE:
2358 codec->width = icodec->width;
2359 codec->height = icodec->height;
2360 break;
2361 case AVMEDIA_TYPE_DATA:
2362 case AVMEDIA_TYPE_ATTACHMENT:
2363 break;
2364 default:
2365 abort();
2366 }
2367 } else {
2368 if (!ost->enc)
2369 ost->enc = avcodec_find_encoder(ost->st->codec->codec_id);
2370
2371 ist->decoding_needed = 1;
2372 ost->encoding_needed = 1;
2373
2374 switch (codec->codec_type) {
2375 case AVMEDIA_TYPE_AUDIO:
2376 ost->fifo = av_fifo_alloc(1024);
2377 if (!ost->fifo) {
2378 return AVERROR(ENOMEM);
2379 }
2380 ost->reformat_pair = MAKE_SFMT_PAIR(AV_SAMPLE_FMT_NONE,AV_SAMPLE_FMT_NONE);
2381
2382 if (!codec->sample_rate)
2383 codec->sample_rate = icodec->sample_rate;
2384 choose_sample_rate(ost->st, ost->enc);
2385 codec->time_base = (AVRational){ 1, codec->sample_rate };
2386
2387 if (codec->sample_fmt == AV_SAMPLE_FMT_NONE)
2388 codec->sample_fmt = icodec->sample_fmt;
2389 choose_sample_fmt(ost->st, ost->enc);
2390
2391 if (!codec->channels)
2392 codec->channels = icodec->channels;
2393 codec->channel_layout = icodec->channel_layout;
2394 if (av_get_channel_layout_nb_channels(codec->channel_layout) != codec->channels)
2395 codec->channel_layout = 0;
2396
2397 ost->audio_resample = codec-> sample_rate != icodec->sample_rate || audio_sync_method > 1;
2398 icodec->request_channels = codec-> channels;
2399 ost->resample_sample_fmt = icodec->sample_fmt;
2400 ost->resample_sample_rate = icodec->sample_rate;
2401 ost->resample_channels = icodec->channels;
2402 break;
2403 case AVMEDIA_TYPE_VIDEO:
2404 if (codec->pix_fmt == PIX_FMT_NONE)
2405 codec->pix_fmt = icodec->pix_fmt;
2406 choose_pixel_fmt(ost->st, ost->enc);
2407
2408 if (ost->st->codec->pix_fmt == PIX_FMT_NONE) {
2409 av_log(NULL, AV_LOG_FATAL, "Video pixel format is unknown, stream cannot be encoded\n");
2410 exit_program(1);
2411 }
2412
2413 if (!codec->width || !codec->height) {
2414 codec->width = icodec->width;
2415 codec->height = icodec->height;
2416 }
2417
2418 ost->video_resample = codec->width != icodec->width ||
2419 codec->height != icodec->height ||
2420 codec->pix_fmt != icodec->pix_fmt;
2421 if (ost->video_resample) {
2422 #if !CONFIG_AVFILTER
2423 avcodec_get_frame_defaults(&ost->pict_tmp);
2424 if (avpicture_alloc((AVPicture*)&ost->pict_tmp, codec->pix_fmt,
2425 codec->width, codec->height)) {
2426 av_log(NULL, AV_LOG_FATAL, "Cannot allocate temp picture, check pix fmt\n");
2427 exit_program(1);
2428 }
2429 ost->img_resample_ctx = sws_getContext(
2430 icodec->width,
2431 icodec->height,
2432 icodec->pix_fmt,
2433 codec->width,
2434 codec->height,
2435 codec->pix_fmt,
2436 ost->sws_flags, NULL, NULL, NULL);
2437 if (ost->img_resample_ctx == NULL) {
2438 av_log(NULL, AV_LOG_FATAL, "Cannot get resampling context\n");
2439 exit_program(1);
2440 }
2441 #endif
2442 codec->bits_per_raw_sample = 0;
2443 }
2444
2445 ost->resample_height = icodec->height;
2446 ost->resample_width = icodec->width;
2447 ost->resample_pix_fmt = icodec->pix_fmt;
2448
2449 if (!ost->frame_rate.num)
2450 ost->frame_rate = ist->st->r_frame_rate.num ? ist->st->r_frame_rate : (AVRational) { 25, 1 };
2451 if (ost->enc && ost->enc->supported_framerates && !ost->force_fps) {
2452 int idx = av_find_nearest_q_idx(ost->frame_rate, ost->enc->supported_framerates);
2453 ost->frame_rate = ost->enc->supported_framerates[idx];
2454 }
2455 codec->time_base = (AVRational){ost->frame_rate.den, ost->frame_rate.num};
2456
2457 #if CONFIG_AVFILTER
2458 if (configure_video_filters(ist, ost)) {
2459 av_log(NULL, AV_LOG_FATAL, "Error opening filters!\n");
2460 exit(1);
2461 }
2462 #endif
2463 break;
2464 case AVMEDIA_TYPE_SUBTITLE:
2465 codec->time_base = (AVRational){1, 1000};
2466 break;
2467 default:
2468 abort();
2469 break;
2470 }
2471 /* two pass mode */
2472 if ((codec->flags & (CODEC_FLAG_PASS1 | CODEC_FLAG_PASS2))) {
2473 char logfilename[1024];
2474 FILE *f;
2475
2476 snprintf(logfilename, sizeof(logfilename), "%s-%d.log",
2477 pass_logfilename_prefix ? pass_logfilename_prefix : DEFAULT_PASS_LOGFILENAME_PREFIX,
2478 i);
2479 if (codec->flags & CODEC_FLAG_PASS1) {
2480 f = fopen(logfilename, "wb");
2481 if (!f) {
2482 av_log(NULL, AV_LOG_FATAL, "Cannot write log file '%s' for pass-1 encoding: %s\n",
2483 logfilename, strerror(errno));
2484 exit_program(1);
2485 }
2486 ost->logfile = f;
2487 } else {
2488 char *logbuffer;
2489 size_t logbuffer_size;
2490 if (cmdutils_read_file(logfilename, &logbuffer, &logbuffer_size) < 0) {
2491 av_log(NULL, AV_LOG_FATAL, "Error reading log file '%s' for pass-2 encoding\n",
2492 logfilename);
2493 exit_program(1);
2494 }
2495 codec->stats_in = logbuffer;
2496 }
2497 }
2498 }
2499 if (codec->codec_type == AVMEDIA_TYPE_VIDEO) {
2500 int size = codec->width * codec->height;
2501 bit_buffer_size = FFMAX(bit_buffer_size, 6 * size + 200);
2502 }
2503 }
2504
2505 if (!bit_buffer)
2506 bit_buffer = av_malloc(bit_buffer_size);
2507 if (!bit_buffer) {
2508 av_log(NULL, AV_LOG_ERROR, "Cannot allocate %d bytes output buffer\n",
2509 bit_buffer_size);
2510 return AVERROR(ENOMEM);
2511 }
2512
2513 /* open each encoder */
2514 for (i = 0; i < nb_output_streams; i++) {
2515 ost = &output_streams[i];
2516 if (ost->encoding_needed) {
2517 AVCodec *codec = ost->enc;
2518 AVCodecContext *dec = input_streams[ost->source_index].st->codec;
2519 if (!codec) {
2520 snprintf(error, sizeof(error), "Encoder (codec id %d) not found for output stream #%d:%d",
2521 ost->st->codec->codec_id, ost->file_index, ost->index);
2522 ret = AVERROR(EINVAL);
2523 goto dump_format;
2524 }
2525 if (dec->subtitle_header) {
2526 ost->st->codec->subtitle_header = av_malloc(dec->subtitle_header_size);
2527 if (!ost->st->codec->subtitle_header) {
2528 ret = AVERROR(ENOMEM);
2529 goto dump_format;
2530 }
2531 memcpy(ost->st->codec->subtitle_header, dec->subtitle_header, dec->subtitle_header_size);
2532 ost->st->codec->subtitle_header_size = dec->subtitle_header_size;
2533 }
2534 if (!av_dict_get(ost->opts, "threads", NULL, 0))
2535 av_dict_set(&ost->opts, "threads", "auto", 0);
2536 if (avcodec_open2(ost->st->codec, codec, &ost->opts) < 0) {
2537 snprintf(error, sizeof(error), "Error while opening encoder for output stream #%d:%d - maybe incorrect parameters such as bit_rate, rate, width or height",
2538 ost->file_index, ost->index);
2539 ret = AVERROR(EINVAL);
2540 goto dump_format;
2541 }
2542 assert_codec_experimental(ost->st->codec, 1);
2543 assert_avoptions(ost->opts);
2544 if (ost->st->codec->bit_rate && ost->st->codec->bit_rate < 1000)
2545 av_log(NULL, AV_LOG_WARNING, "The bitrate parameter is set too low."
2546 "It takes bits/s as argument, not kbits/s\n");
2547 extra_size += ost->st->codec->extradata_size;
2548
2549 if (ost->st->codec->me_threshold)
2550 input_streams[ost->source_index].st->codec->debug |= FF_DEBUG_MV;
2551 }
2552 }
2553
2554 /* init input streams */
2555 for (i = 0; i < nb_input_streams; i++)
2556 if ((ret = init_input_stream(i, output_streams, nb_output_streams, error, sizeof(error))) < 0)
2557 goto dump_format;
2558
2559 /* discard unused programs */
2560 for (i = 0; i < nb_input_files; i++) {
2561 InputFile *ifile = &input_files[i];
2562 for (j = 0; j < ifile->ctx->nb_programs; j++) {
2563 AVProgram *p = ifile->ctx->programs[j];
2564 int discard = AVDISCARD_ALL;
2565
2566 for (k = 0; k < p->nb_stream_indexes; k++)
2567 if (!input_streams[ifile->ist_index + p->stream_index[k]].discard) {
2568 discard = AVDISCARD_DEFAULT;
2569 break;
2570 }
2571 p->discard = discard;
2572 }
2573 }
2574
2575 /* open files and write file headers */
2576 for (i = 0; i < nb_output_files; i++) {
2577 oc = output_files[i].ctx;
2578 oc->interrupt_callback = int_cb;
2579 if (avformat_write_header(oc, &output_files[i].opts) < 0) {
2580 snprintf(error, sizeof(error), "Could not write header for output file #%d (incorrect codec parameters ?)", i);
2581 ret = AVERROR(EINVAL);
2582 goto dump_format;
2583 }
2584 assert_avoptions(output_files[i].opts);
2585 if (strcmp(oc->oformat->name, "rtp")) {
2586 want_sdp = 0;
2587 }
2588 }
2589
2590 dump_format:
2591 /* dump the file output parameters - cannot be done before in case
2592 of stream copy */
2593 for (i = 0; i < nb_output_files; i++) {
2594 av_dump_format(output_files[i].ctx, i, output_files[i].ctx->filename, 1);
2595 }
2596
2597 /* dump the stream mapping */
2598 av_log(NULL, AV_LOG_INFO, "Stream mapping:\n");
2599 for (i = 0; i < nb_output_streams; i++) {
2600 ost = &output_streams[i];
2601
2602 if (ost->attachment_filename) {
2603 /* an attached file */
2604 av_log(NULL, AV_LOG_INFO, " File %s -> Stream #%d:%d\n",
2605 ost->attachment_filename, ost->file_index, ost->index);
2606 continue;
2607 }
2608 av_log(NULL, AV_LOG_INFO, " Stream #%d:%d -> #%d:%d",
2609 input_streams[ost->source_index].file_index,
2610 input_streams[ost->source_index].st->index,
2611 ost->file_index,
2612 ost->index);
2613 if (ost->sync_ist != &input_streams[ost->source_index])
2614 av_log(NULL, AV_LOG_INFO, " [sync #%d:%d]",
2615 ost->sync_ist->file_index,
2616 ost->sync_ist->st->index);
2617 if (ost->stream_copy)
2618 av_log(NULL, AV_LOG_INFO, " (copy)");
2619 else
2620 av_log(NULL, AV_LOG_INFO, " (%s -> %s)", input_streams[ost->source_index].dec ?
2621 input_streams[ost->source_index].dec->name : "?",
2622 ost->enc ? ost->enc->name : "?");
2623 av_log(NULL, AV_LOG_INFO, "\n");
2624 }
2625
2626 if (ret) {
2627 av_log(NULL, AV_LOG_ERROR, "%s\n", error);
2628 return ret;
2629 }
2630
2631 if (want_sdp) {
2632 print_sdp(output_files, nb_output_files);
2633 }
2634
2635 return 0;
2636 }
2637
2638 /*
2639 * The following code is the main loop of the file converter
2640 */
2641 static int transcode(OutputFile *output_files,
2642 int nb_output_files,
2643 InputFile *input_files,
2644 int nb_input_files)
2645 {
2646 int ret, i;
2647 AVFormatContext *is, *os;
2648 OutputStream *ost;
2649 InputStream *ist;
2650 uint8_t *no_packet;
2651 int no_packet_count = 0;
2652 int64_t timer_start;
2653
2654 if (!(no_packet = av_mallocz(nb_input_files)))
2655 exit_program(1);
2656
2657 ret = transcode_init(output_files, nb_output_files, input_files, nb_input_files);
2658 if (ret < 0)
2659 goto fail;
2660
2661 av_log(NULL, AV_LOG_INFO, "Press ctrl-c to stop encoding\n");
2662 term_init();
2663
2664 timer_start = av_gettime();
2665
2666 for (; received_sigterm == 0;) {
2667 int file_index, ist_index;
2668 AVPacket pkt;
2669 int64_t ipts_min;
2670 double opts_min;
2671
2672 ipts_min = INT64_MAX;
2673 opts_min = 1e100;
2674
2675 /* select the stream that we must read now by looking at the
2676 smallest output pts */
2677 file_index = -1;
2678 for (i = 0; i < nb_output_streams; i++) {
2679 OutputFile *of;
2680 int64_t ipts;
2681 double opts;
2682 ost = &output_streams[i];
2683 of = &output_files[ost->file_index];
2684 os = output_files[ost->file_index].ctx;
2685 ist = &input_streams[ost->source_index];
2686 if (ost->is_past_recording_time || no_packet[ist->file_index] ||
2687 (os->pb && avio_tell(os->pb) >= of->limit_filesize))
2688 continue;
2689 opts = ost->st->pts.val * av_q2d(ost->st->time_base);
2690 ipts = ist->pts;
2691 if (!input_files[ist->file_index].eof_reached) {
2692 if (ipts < ipts_min) {
2693 ipts_min = ipts;
2694 if (input_sync)
2695 file_index = ist->file_index;
2696 }
2697 if (opts < opts_min) {
2698 opts_min = opts;
2699 if (!input_sync) file_index = ist->file_index;
2700 }
2701 }
2702 if (ost->frame_number >= ost->max_frames) {
2703 int j;
2704 for (j = 0; j < of->ctx->nb_streams; j++)
2705 output_streams[of->ost_index + j].is_past_recording_time = 1;
2706 continue;
2707 }
2708 }
2709 /* if none, if is finished */
2710 if (file_index < 0) {
2711 if (no_packet_count) {
2712 no_packet_count = 0;
2713 memset(no_packet, 0, nb_input_files);
2714 usleep(10000);
2715 continue;
2716 }
2717 break;
2718 }
2719
2720 /* read a frame from it and output it in the fifo */
2721 is = input_files[file_index].ctx;
2722 ret = av_read_frame(is, &pkt);
2723 if (ret == AVERROR(EAGAIN)) {
2724 no_packet[file_index] = 1;
2725 no_packet_count++;
2726 continue;
2727 }
2728 if (ret < 0) {
2729 input_files[file_index].eof_reached = 1;
2730 if (opt_shortest)
2731 break;
2732 else
2733 continue;
2734 }
2735
2736 no_packet_count = 0;
2737 memset(no_packet, 0, nb_input_files);
2738
2739 if (do_pkt_dump) {
2740 av_pkt_dump_log2(NULL, AV_LOG_DEBUG, &pkt, do_hex_dump,
2741 is->streams[pkt.stream_index]);
2742 }
2743 /* the following test is needed in case new streams appear
2744 dynamically in stream : we ignore them */
2745 if (pkt.stream_index >= input_files[file_index].nb_streams)
2746 goto discard_packet;
2747 ist_index = input_files[file_index].ist_index + pkt.stream_index;
2748 ist = &input_streams[ist_index];
2749 if (ist->discard)
2750 goto discard_packet;
2751
2752 if (pkt.dts != AV_NOPTS_VALUE)
2753 pkt.dts += av_rescale_q(input_files[ist->file_index].ts_offset, AV_TIME_BASE_Q, ist->st->time_base);
2754 if (pkt.pts != AV_NOPTS_VALUE)
2755 pkt.pts += av_rescale_q(input_files[ist->file_index].ts_offset, AV_TIME_BASE_Q, ist->st->time_base);
2756
2757 if (pkt.pts != AV_NOPTS_VALUE)
2758 pkt.pts *= ist->ts_scale;
2759 if (pkt.dts != AV_NOPTS_VALUE)
2760 pkt.dts *= ist->ts_scale;
2761
2762 //fprintf(stderr, "next:%"PRId64" dts:%"PRId64" off:%"PRId64" %d\n",
2763 // ist->next_dts,
2764 // pkt.dts, input_files[ist->file_index].ts_offset,
2765 // ist->st->codec->codec_type);
2766 if (pkt.dts != AV_NOPTS_VALUE && ist->next_dts != AV_NOPTS_VALUE
2767 && (is->iformat->flags & AVFMT_TS_DISCONT)) {
2768 int64_t pkt_dts = av_rescale_q(pkt.dts, ist->st->time_base, AV_TIME_BASE_Q);
2769 int64_t delta = pkt_dts - ist->next_dts;
2770 if ((FFABS(delta) > 1LL * dts_delta_threshold * AV_TIME_BASE || pkt_dts + 1 < ist->pts) && !copy_ts) {
2771 input_files[ist->file_index].ts_offset -= delta;
2772 av_log(NULL, AV_LOG_DEBUG,
2773 "timestamp discontinuity %"PRId64", new offset= %"PRId64"\n",
2774 delta, input_files[ist->file_index].ts_offset);
2775 pkt.dts-= av_rescale_q(delta, AV_TIME_BASE_Q, ist->st->time_base);
2776 if (pkt.pts != AV_NOPTS_VALUE)
2777 pkt.pts-= av_rescale_q(delta, AV_TIME_BASE_Q, ist->st->time_base);
2778 }
2779 }
2780
2781 // fprintf(stderr,"read #%d.%d size=%d\n", ist->file_index, ist->st->index, pkt.size);
2782 if (output_packet(ist, output_streams, nb_output_streams, &pkt) < 0) {
2783
2784 av_log(NULL, AV_LOG_ERROR, "Error while decoding stream #%d:%d\n",
2785 ist->file_index, ist->st->index);
2786 if (exit_on_error)
2787 exit_program(1);
2788 av_free_packet(&pkt);
2789 continue;
2790 }
2791
2792 discard_packet:
2793 av_free_packet(&pkt);
2794
2795 /* dump report by using the output first video and audio streams */
2796 print_report(output_files, output_streams, nb_output_streams, 0, timer_start);
2797 }
2798
2799 /* at the end of stream, we must flush the decoder buffers */
2800 for (i = 0; i < nb_input_streams; i++) {
2801 ist = &input_streams[i];
2802 if (ist->decoding_needed) {
2803 output_packet(ist, output_streams, nb_output_streams, NULL);
2804 }
2805 }
2806 flush_encoders(output_streams, nb_output_streams);
2807
2808 term_exit();
2809
2810 /* write the trailer if needed and close file */
2811 for (i = 0; i < nb_output_files; i++) {
2812 os = output_files[i].ctx;
2813 av_write_trailer(os);
2814 }
2815
2816 /* dump report by using the first video and audio streams */
2817 print_report(output_files, output_streams, nb_output_streams, 1, timer_start);
2818
2819 /* close each encoder */
2820 for (i = 0; i < nb_output_streams; i++) {
2821 ost = &output_streams[i];
2822 if (ost->encoding_needed) {
2823 av_freep(&ost->st->codec->stats_in);
2824 avcodec_close(ost->st->codec);
2825 }
2826 #if CONFIG_AVFILTER
2827 avfilter_graph_free(&ost->graph);
2828 #endif
2829 }
2830
2831 /* close each decoder */
2832 for (i = 0; i < nb_input_streams; i++) {
2833 ist = &input_streams[i];
2834 if (ist->decoding_needed) {
2835 avcodec_close(ist->st->codec);
2836 }
2837 }
2838
2839 /* finished ! */
2840 ret = 0;
2841
2842 fail:
2843 av_freep(&bit_buffer);
2844 av_freep(&no_packet);
2845
2846 if (output_streams) {
2847 for (i = 0; i < nb_output_streams; i++) {
2848 ost = &output_streams[i];
2849 if (ost) {
2850 if (ost->stream_copy)
2851 av_freep(&ost->st->codec->extradata);
2852 if (ost->logfile) {
2853 fclose(ost->logfile);
2854 ost->logfile = NULL;
2855 }
2856 av_fifo_free(ost->fifo); /* works even if fifo is not
2857 initialized but set to zero */
2858 av_freep(&ost->st->codec->subtitle_header);
2859 av_free(ost->pict_tmp.data[0]);
2860 av_free(ost->forced_kf_pts);
2861 if (ost->video_resample)
2862 sws_freeContext(ost->img_resample_ctx);
2863 if (ost->resample)
2864 audio_resample_close(ost->resample);
2865 if (ost->reformat_ctx)
2866 av_audio_convert_free(ost->reformat_ctx);
2867 av_dict_free(&ost->opts);
2868 }
2869 }
2870 }
2871 return ret;
2872 }
2873
2874 static double parse_frame_aspect_ratio(const char *arg)
2875 {
2876 int x = 0, y = 0;
2877 double ar = 0;
2878 const char *p;
2879 char *end;
2880
2881 p = strchr(arg, ':');
2882 if (p) {
2883 x = strtol(arg, &end, 10);
2884 if (end == p)
2885 y = strtol(end + 1, &end, 10);
2886 if (x > 0 && y > 0)
2887 ar = (double)x / (double)y;
2888 } else
2889 ar = strtod(arg, NULL);
2890
2891 if (!ar) {
2892 av_log(NULL, AV_LOG_FATAL, "Incorrect aspect ratio specification.\n");
2893 exit_program(1);
2894 }
2895 return ar;
2896 }
2897
2898 static int opt_audio_codec(OptionsContext *o, const char *opt, const char *arg)
2899 {
2900 return parse_option(o, "codec:a", arg, options);
2901 }
2902
2903 static int opt_video_codec(OptionsContext *o, const char *opt, const char *arg)
2904 {
2905 return parse_option(o, "codec:v", arg, options);
2906 }
2907
2908 static int opt_subtitle_codec(OptionsContext *o, const char *opt, const char *arg)
2909 {
2910 return parse_option(o, "codec:s", arg, options);
2911 }
2912
2913 static int opt_data_codec(OptionsContext *o, const char *opt, const char *arg)
2914 {
2915 return parse_option(o, "codec:d", arg, options);
2916 }
2917
2918 static int opt_map(OptionsContext *o, const char *opt, const char *arg)
2919 {
2920 StreamMap *m = NULL;
2921 int i, negative = 0, file_idx;
2922 int sync_file_idx = -1, sync_stream_idx;
2923 char *p, *sync;
2924 char *map;
2925
2926 if (*arg == '-') {
2927 negative = 1;
2928 arg++;
2929 }
2930 map = av_strdup(arg);
2931
2932 /* parse sync stream first, just pick first matching stream */
2933 if (sync = strchr(map, ',')) {
2934 *sync = 0;
2935 sync_file_idx = strtol(sync + 1, &sync, 0);
2936 if (sync_file_idx >= nb_input_files || sync_file_idx < 0) {
2937 av_log(NULL, AV_LOG_FATAL, "Invalid sync file index: %d.\n", sync_file_idx);
2938 exit_program(1);
2939 }
2940 if (*sync)
2941 sync++;
2942 for (i = 0; i < input_files[sync_file_idx].nb_streams; i++)
2943 if (check_stream_specifier(input_files[sync_file_idx].ctx,
2944 input_files[sync_file_idx].ctx->streams[i], sync) == 1) {
2945 sync_stream_idx = i;
2946 break;
2947 }
2948 if (i == input_files[sync_file_idx].nb_streams) {
2949 av_log(NULL, AV_LOG_FATAL, "Sync stream specification in map %s does not "
2950 "match any streams.\n", arg);
2951 exit_program(1);
2952 }
2953 }
2954
2955
2956 file_idx = strtol(map, &p, 0);
2957 if (file_idx >= nb_input_files || file_idx < 0) {
2958 av_log(NULL, AV_LOG_FATAL, "Invalid input file index: %d.\n", file_idx);
2959 exit_program(1);
2960 }
2961 if (negative)
2962 /* disable some already defined maps */
2963 for (i = 0; i < o->nb_stream_maps; i++) {
2964 m = &o->stream_maps[i];
2965 if (file_idx == m->file_index &&
2966 check_stream_specifier(input_files[m->file_index].ctx,
2967 input_files[m->file_index].ctx->streams[m->stream_index],
2968 *p == ':' ? p + 1 : p) > 0)
2969 m->disabled = 1;
2970 }
2971 else
2972 for (i = 0; i < input_files[file_idx].nb_streams; i++) {
2973 if (check_stream_specifier(input_files[file_idx].ctx, input_files[file_idx].ctx->streams[i],
2974 *p == ':' ? p + 1 : p) <= 0)
2975 continue;
2976 o->stream_maps = grow_array(o->stream_maps, sizeof(*o->stream_maps),
2977 &o->nb_stream_maps, o->nb_stream_maps + 1);
2978 m = &o->stream_maps[o->nb_stream_maps - 1];
2979
2980 m->file_index = file_idx;
2981 m->stream_index = i;
2982
2983 if (sync_file_idx >= 0) {
2984 m->sync_file_index = sync_file_idx;
2985 m->sync_stream_index = sync_stream_idx;
2986 } else {
2987 m->sync_file_index = file_idx;
2988 m->sync_stream_index = i;
2989 }
2990 }
2991
2992 if (!m) {
2993 av_log(NULL, AV_LOG_FATAL, "Stream map '%s' matches no streams.\n", arg);
2994 exit_program(1);
2995 }
2996
2997 av_freep(&map);
2998 return 0;
2999 }
3000
3001 static int opt_attach(OptionsContext *o, const char *opt, const char *arg)
3002 {
3003 o->attachments = grow_array(o->attachments, sizeof(*o->attachments),
3004 &o->nb_attachments, o->nb_attachments + 1);
3005 o->attachments[o->nb_attachments - 1] = arg;
3006 return 0;
3007 }
3008
3009 /**
3010 * Parse a metadata specifier in arg.
3011 * @param type metadata type is written here -- g(lobal)/s(tream)/c(hapter)/p(rogram)
3012 * @param index for type c/p, chapter/program index is written here
3013 * @param stream_spec for type s, the stream specifier is written here
3014 */
3015 static void parse_meta_type(char *arg, char *type, int *index, const char **stream_spec)
3016 {
3017 if (*arg) {
3018 *type = *arg;
3019 switch (*arg) {
3020 case 'g':
3021 break;
3022 case 's':
3023 if (*(++arg) && *arg != ':') {
3024 av_log(NULL, AV_LOG_FATAL, "Invalid metadata specifier %s.\n", arg);
3025 exit_program(1);
3026 }
3027 *stream_spec = *arg == ':' ? arg + 1 : "";
3028 break;
3029 case 'c':
3030 case 'p':
3031 if (*(++arg) == ':')
3032 *index = strtol(++arg, NULL, 0);
3033 break;
3034 default:
3035 av_log(NULL, AV_LOG_FATAL, "Invalid metadata type %c.\n", *arg);
3036 exit_program(1);
3037 }
3038 } else
3039 *type = 'g';
3040 }
3041
3042 static int copy_metadata(char *outspec, char *inspec, AVFormatContext *oc, AVFormatContext *ic, OptionsContext *o)
3043 {
3044 AVDictionary **meta_in = NULL;
3045 AVDictionary **meta_out;
3046 int i, ret = 0;
3047 char type_in, type_out;
3048 const char *istream_spec = NULL, *ostream_spec = NULL;
3049 int idx_in = 0, idx_out = 0;
3050
3051 parse_meta_type(inspec, &type_in, &idx_in, &istream_spec);
3052 parse_meta_type(outspec, &type_out, &idx_out, &ostream_spec);
3053
3054 if (type_in == 'g' || type_out == 'g')
3055 o->metadata_global_manual = 1;
3056 if (type_in == 's' || type_out == 's')
3057 o->metadata_streams_manual = 1;
3058 if (type_in == 'c' || type_out == 'c')
3059 o->metadata_chapters_manual = 1;
3060
3061 #define METADATA_CHECK_INDEX(index, nb_elems, desc)\
3062 if ((index) < 0 || (index) >= (nb_elems)) {\
3063 av_log(NULL, AV_LOG_FATAL, "Invalid %s index %d while processing metadata maps.\n",\
3064 (desc), (index));\
3065 exit_program(1);\
3066 }
3067
3068 #define SET_DICT(type, meta, context, index)\
3069 switch (type) {\
3070 case 'g':\
3071 meta = &context->metadata;\
3072 break;\
3073 case 'c':\
3074 METADATA_CHECK_INDEX(index, context->nb_chapters, "chapter")\
3075 meta = &context->chapters[index]->metadata;\
3076 break;\
3077 case 'p':\
3078 METADATA_CHECK_INDEX(index, context->nb_programs, "program")\
3079 meta = &context->programs[index]->metadata;\
3080 break;\
3081 }\
3082
3083 SET_DICT(type_in, meta_in, ic, idx_in);
3084 SET_DICT(type_out, meta_out, oc, idx_out);
3085
3086 /* for input streams choose first matching stream */
3087 if (type_in == 's') {
3088 for (i = 0; i < ic->nb_streams; i++) {
3089 if ((ret = check_stream_specifier(ic, ic->streams[i], istream_spec)) > 0) {
3090 meta_in = &ic->streams[i]->metadata;
3091 break;
3092 } else if (ret < 0)
3093 exit_program(1);
3094 }
3095 if (!meta_in) {
3096 av_log(NULL, AV_LOG_FATAL, "Stream specifier %s does not match any streams.\n", istream_spec);
3097 exit_program(1);
3098 }
3099 }
3100
3101 if (type_out == 's') {
3102 for (i = 0; i < oc->nb_streams; i++) {
3103 if ((ret = check_stream_specifier(oc, oc->streams[i], ostream_spec)) > 0) {
3104 meta_out = &oc->streams[i]->metadata;
3105 av_dict_copy(meta_out, *meta_in, AV_DICT_DONT_OVERWRITE);
3106 } else if (ret < 0)
3107 exit_program(1);
3108 }
3109 } else
3110 av_dict_copy(meta_out, *meta_in, AV_DICT_DONT_OVERWRITE);
3111
3112 return 0;
3113 }
3114
3115 static AVCodec *find_codec_or_die(const char *name, enum AVMediaType type, int encoder)
3116 {
3117 const char *codec_string = encoder ? "encoder" : "decoder";
3118 AVCodec *codec;
3119
3120 codec = encoder ?
3121 avcodec_find_encoder_by_name(name) :
3122 avcodec_find_decoder_by_name(name);
3123 if (!codec) {
3124 av_log(NULL, AV_LOG_FATAL, "Unknown %s '%s'\n", codec_string, name);
3125 exit_program(1);
3126 }
3127 if (codec->type != type) {
3128 av_log(NULL, AV_LOG_FATAL, "Invalid %s type '%s'\n", codec_string, name);
3129 exit_program(1);
3130 }
3131 return codec;
3132 }
3133
3134 static AVCodec *choose_decoder(OptionsContext *o, AVFormatContext *s, AVStream *st)
3135 {
3136 char *codec_name = NULL;
3137
3138 MATCH_PER_STREAM_OPT(codec_names, str, codec_name, s, st);
3139 if (codec_name) {
3140 AVCodec *codec = find_codec_or_die(codec_name, st->codec->codec_type, 0);
3141 st->codec->codec_id = codec->id;
3142 return codec;
3143 } else
3144 return avcodec_find_decoder(st->codec->codec_id);
3145 }
3146
3147 /**
3148 * Add all the streams from the given input file to the global
3149 * list of input streams.
3150 */
3151 static void add_input_streams(OptionsContext *o, AVFormatContext *ic)
3152 {
3153 int i;
3154
3155 for (i = 0; i < ic->nb_streams; i++) {
3156 AVStream *st = ic->streams[i];
3157 AVCodecContext *dec = st->codec;
3158 InputStream *ist;
3159
3160 input_streams = grow_array(input_streams, sizeof(*input_streams), &nb_input_streams, nb_input_streams + 1);
3161 ist = &input_streams[nb_input_streams - 1];
3162 ist->st = st;
3163 ist->file_index = nb_input_files;
3164 ist->discard = 1;
3165 ist->opts = filter_codec_opts(codec_opts, ist->st->codec->codec_id, ic, st);
3166
3167 ist->ts_scale = 1.0;
3168 MATCH_PER_STREAM_OPT(ts_scale, dbl, ist->ts_scale, ic, st);
3169
3170 ist->dec = choose_decoder(o, ic, st);
3171
3172 switch (dec->codec_type) {
3173 case AVMEDIA_TYPE_AUDIO:
3174 if (o->audio_disable)
3175 st->discard = AVDISCARD_ALL;
3176 break;
3177 case AVMEDIA_TYPE_VIDEO:
3178 if (dec->lowres) {
3179 dec->flags |= CODEC_FLAG_EMU_EDGE;
3180 dec->height >>= dec->lowres;
3181 dec->width >>= dec->lowres;
3182 }
3183
3184 if (o->video_disable)
3185 st->discard = AVDISCARD_ALL;
3186 else if (video_discard)
3187 st->discard = video_discard;
3188 break;
3189 case AVMEDIA_TYPE_DATA:
3190 break;
3191 case AVMEDIA_TYPE_SUBTITLE:
3192 if (o->subtitle_disable)
3193 st->discard = AVDISCARD_ALL;
3194 break;
3195 case AVMEDIA_TYPE_ATTACHMENT:
3196 case AVMEDIA_TYPE_UNKNOWN:
3197 break;
3198 default:
3199 abort();
3200 }
3201 }
3202 }
3203
3204 static void assert_file_overwrite(const char *filename)
3205 {
3206 if (!file_overwrite &&
3207 (strchr(filename, ':') == NULL || filename[1] == ':' ||
3208 av_strstart(filename, "file:", NULL))) {
3209 if (avio_check(filename, 0) == 0) {
3210 if (!using_stdin) {
3211 fprintf(stderr,"File '%s' already exists. Overwrite ? [y/N] ", filename);
3212 fflush(stderr);
3213 if (!read_yesno()) {
3214 fprintf(stderr, "Not overwriting - exiting\n");
3215 exit_program(1);
3216 }
3217 }
3218 else {
3219 fprintf(stderr,"File '%s' already exists. Exiting.\n", filename);
3220 exit_program(1);
3221 }
3222 }
3223 }
3224 }
3225
3226 static void dump_attachment(AVStream *st, const char *filename)
3227 {
3228 int ret;
3229 AVIOContext *out = NULL;
3230 AVDictionaryEntry *e;
3231
3232 if (!st->codec->extradata_size) {
3233 av_log(NULL, AV_LOG_WARNING, "No extradata to dump in stream #%d:%d.\n",
3234 nb_input_files - 1, st->index);
3235 return;
3236 }
3237 if (!*filename && (e = av_dict_get(st->metadata, "filename", NULL, 0)))
3238 filename = e->value;
3239 if (!*filename) {
3240 av_log(NULL, AV_LOG_FATAL, "No filename specified and no 'filename' tag"
3241 "in stream #%d:%d.\n", nb_input_files - 1, st->index);
3242 exit_program(1);
3243 }
3244
3245 assert_file_overwrite(filename);
3246
3247 if ((ret = avio_open2(&out, filename, AVIO_FLAG_WRITE, &int_cb, NULL)) < 0) {
3248 av_log(NULL, AV_LOG_FATAL, "Could not open file %s for writing.\n",
3249 filename);
3250 exit_program(1);
3251 }
3252
3253 avio_write(out, st->codec->extradata, st->codec->extradata_size);
3254 avio_flush(out);
3255 avio_close(out);
3256 }
3257
3258 static int opt_input_file(OptionsContext *o, const char *opt, const char *filename)
3259 {
3260 AVFormatContext *ic;
3261 AVInputFormat *file_iformat = NULL;
3262 int err, i, ret;
3263 int64_t timestamp;
3264 uint8_t buf[128];
3265 AVDictionary **opts;
3266 int orig_nb_streams; // number of streams before avformat_find_stream_info
3267
3268 if (o->format) {
3269 if (!(file_iformat = av_find_input_format(o->format))) {
3270 av_log(NULL, AV_LOG_FATAL, "Unknown input format: '%s'\n", o->format);
3271 exit_program(1);
3272 }
3273 }
3274
3275 if (!strcmp(filename, "-"))
3276 filename = "pipe:";
3277
3278 using_stdin |= !strncmp(filename, "pipe:", 5) ||
3279 !strcmp(filename, "/dev/stdin");
3280
3281 /* get default parameters from command line */
3282 ic = avformat_alloc_context();
3283 if (!ic) {
3284 print_error(filename, AVERROR(ENOMEM));
3285 exit_program(1);
3286 }
3287 if (o->nb_audio_sample_rate) {
3288 snprintf(buf, sizeof(buf), "%d", o->audio_sample_rate[o->nb_audio_sample_rate - 1].u.i);
3289 av_dict_set(&format_opts, "sample_rate", buf, 0);
3290 }
3291 if (o->nb_audio_channels) {
3292 snprintf(buf, sizeof(buf), "%d", o->audio_channels[o->nb_audio_channels - 1].u.i);
3293 av_dict_set(&format_opts, "channels", buf, 0);
3294 }
3295 if (o->nb_frame_rates) {
3296 av_dict_set(&format_opts, "framerate", o->frame_rates[o->nb_frame_rates - 1].u.str, 0);
3297 }
3298 if (o->nb_frame_sizes) {
3299 av_dict_set(&format_opts, "video_size", o->frame_sizes[o->nb_frame_sizes - 1].u.str, 0);
3300 }
3301 if (o->nb_frame_pix_fmts)
3302 av_dict_set(&format_opts, "pixel_format", o->frame_pix_fmts[o->nb_frame_pix_fmts - 1].u.str, 0);
3303
3304 ic->flags |= AVFMT_FLAG_NONBLOCK;
3305 ic->interrupt_callback = int_cb;
3306
3307 /* open the input file with generic libav function */
3308 err = avformat_open_input(&ic, filename, file_iformat, &format_opts);
3309 if (err < 0) {
3310 print_error(filename, err);
3311 exit_program(1);
3312 }
3313 assert_avoptions(format_opts);
3314
3315 /* apply forced codec ids */
3316 for (i = 0; i < ic->nb_streams; i++)
3317 choose_decoder(o, ic, ic->streams[i]);
3318
3319 /* Set AVCodecContext options for avformat_find_stream_info */
3320 opts = setup_find_stream_info_opts(ic, codec_opts);
3321 orig_nb_streams = ic->nb_streams;
3322
3323 /* If not enough info to get the stream parameters, we decode the
3324 first frames to get it. (used in mpeg case for example) */
3325 ret = avformat_find_stream_info(ic, opts);
3326 if (ret < 0) {
3327 av_log(NULL, AV_LOG_FATAL, "%s: could not find codec parameters\n", filename);
3328 avformat_close_input(&ic);
3329 exit_program(1);
3330 }
3331
3332 timestamp = o->start_time;
3333 /* add the stream start time */
3334 if (ic->start_time != AV_NOPTS_VALUE)
3335 timestamp += ic->start_time;
3336
3337 /* if seeking requested, we execute it */
3338 if (o->start_time != 0) {
3339 ret = av_seek_frame(ic, -1, timestamp, AVSEEK_FLAG_BACKWARD);
3340 if (ret < 0) {
3341 av_log(NULL, AV_LOG_WARNING, "%s: could not seek to position %0.3f\n",
3342 filename, (double)timestamp / AV_TIME_BASE);
3343 }
3344 }
3345
3346 /* update the current parameters so that they match the one of the input stream */
3347 add_input_streams(o, ic);
3348
3349 /* dump the file content */
3350 av_dump_format(ic, nb_input_files, filename, 0);
3351
3352 input_files = grow_array(input_files, sizeof(*input_files), &nb_input_files, nb_input_files + 1);
3353 input_files[nb_input_files - 1].ctx = ic;
3354 input_files[nb_input_files - 1].ist_index = nb_input_streams - ic->nb_streams;
3355 input_files[nb_input_files - 1].ts_offset = o->input_ts_offset - (copy_ts ? 0 : timestamp);
3356 input_files[nb_input_files - 1].nb_streams = ic->nb_streams;
3357 input_files[nb_input_files - 1].rate_emu = o->rate_emu;
3358
3359 for (i = 0; i < o->nb_dump_attachment; i++) {
3360 int j;
3361
3362 for (j = 0; j < ic->nb_streams; j++) {
3363 AVStream *st = ic->streams[j];
3364
3365 if (check_stream_specifier(ic, st, o->dump_attachment[i].specifier) == 1)
3366 dump_attachment(st, o->dump_attachment[i].u.str);
3367 }
3368 }
3369
3370 for (i = 0; i < orig_nb_streams; i++)
3371 av_dict_free(&opts[i]);
3372 av_freep(&opts);
3373
3374 reset_options(o);
3375 return 0;
3376 }
3377
3378 static void parse_forced_key_frames(char *kf, OutputStream *ost,
3379 AVCodecContext *avctx)
3380 {
3381 char *p;
3382 int n = 1, i;
3383 int64_t t;
3384
3385 for (p = kf; *p; p++)
3386 if (*p == ',')
3387 n++;
3388 ost->forced_kf_count = n;
3389 ost->forced_kf_pts = av_malloc(sizeof(*ost->forced_kf_pts) * n);
3390 if (!ost->forced_kf_pts) {
3391 av_log(NULL, AV_LOG_FATAL, "Could not allocate forced key frames array.\n");
3392 exit_program(1);
3393 }
3394 for (i = 0; i < n; i++) {
3395 p = i ? strchr(p, ',') + 1 : kf;
3396 t = parse_time_or_die("force_key_frames", p, 1);
3397 ost->forced_kf_pts[i] = av_rescale_q(t, AV_TIME_BASE_Q, avctx->time_base);
3398 }
3399 }
3400
3401 static uint8_t *get_line(AVIOContext *s)
3402 {
3403 AVIOContext *line;
3404 uint8_t *buf;
3405 char c;
3406
3407 if (avio_open_dyn_buf(&line) < 0) {
3408 av_log(NULL, AV_LOG_FATAL, "Could not alloc buffer for reading preset.\n");
3409 exit_program(1);
3410 }
3411
3412 while ((c = avio_r8(s)) && c != '\n')
3413 avio_w8(line, c);
3414 avio_w8(line, 0);
3415 avio_close_dyn_buf(line, &buf);
3416
3417 return buf;
3418 }
3419
3420 static int get_preset_file_2(const char *preset_name, const char *codec_name, AVIOContext **s)
3421 {
3422 int i, ret = 1;
3423 char filename[1000];
3424 const char *base[3] = { getenv("AVCONV_DATADIR"),
3425 getenv("HOME"),
3426 AVCONV_DATADIR,
3427 };
3428
3429 for (i = 0; i < FF_ARRAY_ELEMS(base) && ret; i++) {
3430 if (!base[i])
3431 continue;
3432 if (codec_name) {
3433 snprintf(filename, sizeof(filename), "%s%s/%s-%s.avpreset", base[i],
3434 i != 1 ? "" : "/.avconv", codec_name, preset_name);
3435 ret = avio_open2(s, filename, AVIO_FLAG_READ, &int_cb, NULL);
3436 }
3437 if (ret) {
3438 snprintf(filename, sizeof(filename), "%s%s/%s.avpreset", base[i],
3439 i != 1 ? "" : "/.avconv", preset_name);
3440 ret = avio_open2(s, filename, AVIO_FLAG_READ, &int_cb, NULL);
3441 }
3442 }
3443 return ret;
3444 }
3445
3446 static void choose_encoder(OptionsContext *o, AVFormatContext *s, OutputStream *ost)
3447 {
3448 char *codec_name = NULL;
3449
3450 MATCH_PER_STREAM_OPT(codec_names, str, codec_name, s, ost->st);
3451 if (!codec_name) {
3452 ost->st->codec->codec_id = av_guess_codec(s->oformat, NULL, s->filename,
3453 NULL, ost->st->codec->codec_type);
3454 ost->enc = avcodec_find_encoder(ost->st->codec->codec_id);
3455 } else if (!strcmp(codec_name, "copy"))
3456 ost->stream_copy = 1;
3457 else {
3458 ost->enc = find_codec_or_die(codec_name, ost->st->codec->codec_type, 1);
3459 ost->st->codec->codec_id = ost->enc->id;
3460 }
3461 }
3462
3463 static OutputStream *new_output_stream(OptionsContext *o, AVFormatContext *oc, enum AVMediaType type)
3464 {
3465 OutputStream *ost;
3466 AVStream *st = avformat_new_stream(oc, NULL);
3467 int idx = oc->nb_streams - 1, ret = 0;
3468 char *bsf = NULL, *next, *codec_tag = NULL;
3469 AVBitStreamFilterContext *bsfc, *bsfc_prev = NULL;
3470 double qscale = -1;
3471 char *buf = NULL, *arg = NULL, *preset = NULL;
3472 AVIOContext *s = NULL;
3473
3474 if (!st) {
3475 av_log(NULL, AV_LOG_FATAL, "Could not alloc stream.\n");
3476 exit_program(1);
3477 }
3478
3479 if (oc->nb_streams - 1 < o->nb_streamid_map)
3480 st->id = o->streamid_map[oc->nb_streams - 1];
3481
3482 output_streams = grow_array(output_streams, sizeof(*output_streams), &nb_output_streams,
3483 nb_output_streams + 1);
3484 ost = &output_streams[nb_output_streams - 1];
3485 ost->file_index = nb_output_files;
3486 ost->index = idx;
3487 ost->st = st;
3488 st->codec->codec_type = type;
3489 choose_encoder(o, oc, ost);
3490 if (ost->enc) {
3491 ost->opts = filter_codec_opts(codec_opts, ost->enc->id, oc, st);
3492 }
3493
3494 avcodec_get_context_defaults3(st->codec, ost->enc);
3495 st->codec->codec_type = type; // XXX hack, avcodec_get_context_defaults2() sets type to unknown for stream copy
3496
3497 MATCH_PER_STREAM_OPT(presets, str, preset, oc, st);
3498 if (preset && (!(ret = get_preset_file_2(preset, ost->enc->name, &s)))) {
3499 do {
3500 buf = get_line(s);
3501 if (!buf[0] || buf[0] == '#') {
3502 av_free(buf);
3503 continue;
3504 }
3505 if (!(arg = strchr(buf, '='))) {
3506 av_log(NULL, AV_LOG_FATAL, "Invalid line found in the preset file.\n");
3507 exit_program(1);
3508 }
3509 *arg++ = 0;
3510 av_dict_set(&ost->opts, buf, arg, AV_DICT_DONT_OVERWRITE);
3511 av_free(buf);
3512 } while (!s->eof_reached);
3513 avio_close(s);
3514 }
3515 if (ret) {
3516 av_log(NULL, AV_LOG_FATAL,
3517 "Preset %s specified for stream %d:%d, but could not be opened.\n",
3518 preset, ost->file_index, ost->index);
3519 exit_program(1);
3520 }
3521
3522 ost->max_frames = INT64_MAX;
3523 MATCH_PER_STREAM_OPT(max_frames, i64, ost->max_frames, oc, st);
3524
3525 MATCH_PER_STREAM_OPT(bitstream_filters, str, bsf, oc, st);
3526 while (bsf) {
3527 if (next = strchr(bsf, ','))
3528 *next++ = 0;
3529 if (!(bsfc = av_bitstream_filter_init(bsf))) {
3530 av_log(NULL, AV_LOG_FATAL, "Unknown bitstream filter %s\n", bsf);
3531 exit_program(1);
3532 }
3533 if (bsfc_prev)
3534 bsfc_prev->next = bsfc;
3535 else
3536 ost->bitstream_filters = bsfc;
3537
3538 bsfc_prev = bsfc;
3539 bsf = next;
3540 }
3541
3542 MATCH_PER_STREAM_OPT(codec_tags, str, codec_tag, oc, st);
3543 if (codec_tag) {
3544 uint32_t tag = strtol(codec_tag, &next, 0);
3545 if (*next)
3546 tag = AV_RL32(codec_tag);
3547 st->codec->codec_tag = tag;
3548 }
3549
3550 MATCH_PER_STREAM_OPT(qscale, dbl, qscale, oc, st);
3551 if (qscale >= 0 || same_quant) {
3552 st->codec->flags |= CODEC_FLAG_QSCALE;
3553 st->codec->global_quality = FF_QP2LAMBDA * qscale;
3554 }
3555
3556 if (oc->oformat->flags & AVFMT_GLOBALHEADER)
3557 st->codec->flags |= CODEC_FLAG_GLOBAL_HEADER;
3558
3559 av_opt_get_int(sws_opts, "sws_flags", 0, &ost->sws_flags);
3560 return ost;
3561 }
3562
3563 static void parse_matrix_coeffs(uint16_t *dest, const char *str)
3564 {
3565 int i;
3566 const char *p = str;
3567 for (i = 0;; i++) {
3568 dest[i] = atoi(p);
3569 if (i == 63)
3570 break;
3571 p = strchr(p, ',');
3572 if (!p) {
3573 av_log(NULL, AV_LOG_FATAL, "Syntax error in matrix \"%s\" at coeff %d\n", str, i);
3574 exit_program(1);
3575 }
3576 p++;
3577 }
3578 }
3579
3580 static OutputStream *new_video_stream(OptionsContext *o, AVFormatContext *oc)
3581 {
3582 AVStream *st;
3583 OutputStream *ost;
3584 AVCodecContext *video_enc;
3585
3586 ost = new_output_stream(o, oc, AVMEDIA_TYPE_VIDEO);
3587 st = ost->st;
3588 video_enc = st->codec;
3589
3590 if (!ost->stream_copy) {
3591 const char *p = NULL;
3592 char *forced_key_frames = NULL, *frame_rate = NULL, *frame_size = NULL;
3593 char *frame_aspect_ratio = NULL, *frame_pix_fmt = NULL;
3594 char *intra_matrix = NULL, *inter_matrix = NULL, *filters = NULL;
3595 int i;
3596
3597 MATCH_PER_STREAM_OPT(frame_rates, str, frame_rate, oc, st);
3598 if (frame_rate && av_parse_video_rate(&ost->frame_rate, frame_rate) < 0) {
3599 av_log(NULL, AV_LOG_FATAL, "Invalid framerate value: %s\n", frame_rate);
3600 exit_program(1);
3601 }
3602
3603 MATCH_PER_STREAM_OPT(frame_sizes, str, frame_size, oc, st);
3604 if (frame_size && av_parse_video_size(&video_enc->width, &video_enc->height, frame_size) < 0) {
3605 av_log(NULL, AV_LOG_FATAL, "Invalid frame size: %s.\n", frame_size);
3606 exit_program(1);
3607 }
3608
3609 MATCH_PER_STREAM_OPT(frame_aspect_ratios, str, frame_aspect_ratio, oc, st);
3610 if (frame_aspect_ratio)
3611 ost->frame_aspect_ratio = parse_frame_aspect_ratio(frame_aspect_ratio);
3612
3613 MATCH_PER_STREAM_OPT(frame_pix_fmts, str, frame_pix_fmt, oc, st);
3614 if (frame_pix_fmt && (video_enc->pix_fmt = av_get_pix_fmt(frame_pix_fmt)) == PIX_FMT_NONE) {
3615 av_log(NULL, AV_LOG_FATAL, "Unknown pixel format requested: %s.\n", frame_pix_fmt);
3616 exit_program(1);
3617 }
3618 st->sample_aspect_ratio = video_enc->sample_aspect_ratio;
3619
3620 MATCH_PER_STREAM_OPT(intra_matrices, str, intra_matrix, oc, st);
3621 if (intra_matrix) {
3622 if (!(video_enc->intra_matrix = av_mallocz(sizeof(*video_enc->intra_matrix) * 64))) {
3623 av_log(NULL, AV_LOG_FATAL, "Could not allocate memory for intra matrix.\n");
3624 exit_program(1);
3625 }
3626 parse_matrix_coeffs(video_enc->intra_matrix, intra_matrix);
3627 }
3628 MATCH_PER_STREAM_OPT(inter_matrices, str, inter_matrix, oc, st);
3629 if (inter_matrix) {
3630 if (!(video_enc->inter_matrix = av_mallocz(sizeof(*video_enc->inter_matrix) * 64))) {
3631 av_log(NULL, AV_LOG_FATAL, "Could not allocate memory for inter matrix.\n");
3632 exit_program(1);
3633 }
3634 parse_matrix_coeffs(video_enc->inter_matrix, inter_matrix);
3635 }
3636
3637 MATCH_PER_STREAM_OPT(rc_overrides, str, p, oc, st);
3638 for (i = 0; p; i++) {
3639 int start, end, q;
3640 int e = sscanf(p, "%d,%d,%d", &start, &end, &q);
3641 if (e != 3) {
3642 av_log(NULL, AV_LOG_FATAL, "error parsing rc_override\n");
3643 exit_program(1);
3644 }
3645 video_enc->rc_override =
3646 av_realloc(video_enc->rc_override,
3647 sizeof(RcOverride) * (i + 1));
3648 video_enc->rc_override[i].start_frame = start;
3649 video_enc->rc_override[i].end_frame = end;
3650 if (q > 0) {
3651 video_enc->rc_override[i].qscale = q;
3652 video_enc->rc_override[i].quality_factor = 1.0;
3653 }
3654 else {
3655 video_enc->rc_override[i].qscale = 0;
3656 video_enc->rc_override[i].quality_factor = -q/100.0;
3657 }
3658 p = strchr(p, '/');
3659 if (p) p++;
3660 }
3661 video_enc->rc_override_count = i;
3662 if (!video_enc->rc_initial_buffer_occupancy)
3663 video_enc->rc_initial_buffer_occupancy = video_enc->rc_buffer_size * 3 / 4;
3664 video_enc->intra_dc_precision = intra_dc_precision - 8;
3665
3666 /* two pass mode */
3667 if (do_pass) {
3668 if (do_pass == 1) {
3669 video_enc->flags |= CODEC_FLAG_PASS1;
3670 } else {
3671 video_enc->flags |= CODEC_FLAG_PASS2;
3672 }
3673 }
3674
3675 MATCH_PER_STREAM_OPT(forced_key_frames, str, forced_key_frames, oc, st);
3676 if (forced_key_frames)
3677 parse_forced_key_frames(forced_key_frames, ost, video_enc);
3678
3679 MATCH_PER_STREAM_OPT(force_fps, i, ost->force_fps, oc, st);
3680
3681 ost->top_field_first = -1;
3682 MATCH_PER_STREAM_OPT(top_field_first, i, ost->top_field_first, oc, st);
3683
3684 #if CONFIG_AVFILTER
3685 MATCH_PER_STREAM_OPT(filters, str, filters, oc, st);
3686 if (filters)
3687 ost->avfilter = av_strdup(filters);
3688 #endif
3689