FFmpegKit Linux API 5.1
fftools_ffmpeg_opt.c
Go to the documentation of this file.
1/*
2 * ffmpeg option parsing
3 * copyright (c) 2018 Taner Sener ( tanersener gmail com )
4 *
5 * This file is part of FFmpeg.
6 *
7 * FFmpeg 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 * FFmpeg 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 FFmpeg; if not, write to the Free Software
19 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20 */
21
22/*
23 * This file is the modified version of ffmpeg_opt.c file living in ffmpeg source code under the fftools folder. We
24 * manually update it each time we depend on a new ffmpeg version. Below you can see the list of changes applied
25 * by us to develop mobile-ffmpeg and later ffmpeg-kit libraries.
26 *
27 * mobile-ffmpeg / ffmpeg-kit changes by Taner Sener
28 *
29 * 08.2020
30 * --------------------------------------------------------
31 * - read_file renamed as fftools_read_file
32 *
33 * 01.2020
34 * --------------------------------------------------------
35 * - ffprobe support (added ffmpeg_ prefix to options used by ffmpeg, logs with AV_LOG_INFO level migrated to
36 * use AV_LOG_STDERR)
37 *
38 * 12.2019
39 * --------------------------------------------------------
40 * - concurrent execution support ("__thread" specifier added to variables used by multiple threads, static keyword
41 * removed from methods called by both ffmpeg and ffprobe, options replaced with global_options, options definition
42 * deleted)
43 *
44 * 08.2018
45 * --------------------------------------------------------
46 * - fftools_ prefix added to file name and parent headers
47 *
48 * 07.2018
49 * --------------------------------------------------------
50 * - parentheses placed around assignments in condition to prevent -Wparentheses warning
51 */
52
53#include "config.h"
54
55#include <stdint.h>
56
57#if HAVE_SYS_RESOURCE_H
58#include <sys/time.h>
59#include <sys/resource.h>
60#endif
61
62#include "fftools_ffmpeg.h"
63#include "fftools_fopen_utf8.h"
64#include "fftools_cmdutils.h"
65
66#include "libavformat/avformat.h"
67
68#include "libavcodec/avcodec.h"
69#include "libavcodec/bsf.h"
70
71#include "libavfilter/avfilter.h"
72
73#include "libavutil/avassert.h"
74#include "libavutil/avstring.h"
75#include "libavutil/avutil.h"
76#include "libavutil/bprint.h"
77#include "libavutil/channel_layout.h"
78#include "libavutil/getenv_utf8.h"
79#include "libavutil/intreadwrite.h"
80#include "libavutil/fifo.h"
81#include "libavutil/mathematics.h"
82#include "libavutil/opt.h"
83#include "libavutil/parseutils.h"
84#include "libavutil/pixdesc.h"
85#include "libavutil/pixfmt.h"
86
87#define DEFAULT_PASS_LOGFILENAME_PREFIX "ffmpeg2pass"
88
89#define SPECIFIER_OPT_FMT_str "%s"
90#define SPECIFIER_OPT_FMT_i "%i"
91#define SPECIFIER_OPT_FMT_i64 "%"PRId64
92#define SPECIFIER_OPT_FMT_ui64 "%"PRIu64
93#define SPECIFIER_OPT_FMT_f "%f"
94#define SPECIFIER_OPT_FMT_dbl "%lf"
95
96static const char *const opt_name_codec_names[] = {"c", "codec", "acodec", "vcodec", "scodec", "dcodec", NULL};
97static const char *const opt_name_audio_channels[] = {"ac", NULL};
98static const char *const opt_name_audio_ch_layouts[] = {"channel_layout", "ch_layout", NULL};
99static const char *const opt_name_audio_sample_rate[] = {"ar", NULL};
100static const char *const opt_name_frame_rates[] = {"r", NULL};
101static const char *const opt_name_max_frame_rates[] = {"fpsmax", NULL};
102static const char *const opt_name_frame_sizes[] = {"s", NULL};
103static const char *const opt_name_frame_pix_fmts[] = {"pix_fmt", NULL};
104static const char *const opt_name_ts_scale[] = {"itsscale", NULL};
105static const char *const opt_name_hwaccels[] = {"hwaccel", NULL};
106static const char *const opt_name_hwaccel_devices[] = {"hwaccel_device", NULL};
107static const char *const opt_name_hwaccel_output_formats[] = {"hwaccel_output_format", NULL};
108static const char *const opt_name_autorotate[] = {"autorotate", NULL};
109static const char *const opt_name_autoscale[] = {"autoscale", NULL};
110static const char *const opt_name_max_frames[] = {"frames", "aframes", "vframes", "dframes", NULL};
111static const char *const opt_name_bitstream_filters[] = {"bsf", "absf", "vbsf", NULL};
112static const char *const opt_name_codec_tags[] = {"tag", "atag", "vtag", "stag", NULL};
113static const char *const opt_name_sample_fmts[] = {"sample_fmt", NULL};
114static const char *const opt_name_qscale[] = {"q", "qscale", NULL};
115static const char *const opt_name_forced_key_frames[] = {"forced_key_frames", NULL};
116static const char *const opt_name_fps_mode[] = {"fps_mode", NULL};
117static const char *const opt_name_force_fps[] = {"force_fps", NULL};
118static const char *const opt_name_frame_aspect_ratios[] = {"aspect", NULL};
119static const char *const opt_name_rc_overrides[] = {"rc_override", NULL};
120static const char *const opt_name_intra_matrices[] = {"intra_matrix", NULL};
121static const char *const opt_name_inter_matrices[] = {"inter_matrix", NULL};
122static const char *const opt_name_chroma_intra_matrices[] = {"chroma_intra_matrix", NULL};
123static const char *const opt_name_top_field_first[] = {"top", NULL};
124static const char *const opt_name_presets[] = {"pre", "apre", "vpre", "spre", NULL};
125static const char *const opt_name_copy_initial_nonkeyframes[] = {"copyinkf", NULL};
126static const char *const opt_name_copy_prior_start[] = {"copypriorss", NULL};
127static const char *const opt_name_filters[] = {"filter", "af", "vf", NULL};
128static const char *const opt_name_filter_scripts[] = {"filter_script", NULL};
129static const char *const opt_name_reinit_filters[] = {"reinit_filter", NULL};
130static const char *const opt_name_fix_sub_duration[] = {"fix_sub_duration", NULL};
131static const char *const opt_name_canvas_sizes[] = {"canvas_size", NULL};
132static const char *const opt_name_pass[] = {"pass", NULL};
133static const char *const opt_name_passlogfiles[] = {"passlogfile", NULL};
134static const char *const opt_name_max_muxing_queue_size[] = {"max_muxing_queue_size", NULL};
135static const char *const opt_name_muxing_queue_data_threshold[] = {"muxing_queue_data_threshold", NULL};
136static const char *const opt_name_guess_layout_max[] = {"guess_layout_max", NULL};
137static const char *const opt_name_apad[] = {"apad", NULL};
138static const char *const opt_name_discard[] = {"discard", NULL};
139static const char *const opt_name_disposition[] = {"disposition", NULL};
140static const char *const opt_name_time_bases[] = {"time_base", NULL};
141static const char *const opt_name_enc_time_bases[] = {"enc_time_base", NULL};
142static const char *const opt_name_bits_per_raw_sample[] = {"bits_per_raw_sample", NULL};
143
144#define WARN_MULTIPLE_OPT_USAGE(name, type, so, st)\
145{\
146 char namestr[128] = "";\
147 const char *spec = so->specifier && so->specifier[0] ? so->specifier : "";\
148 for (i = 0; opt_name_##name[i]; i++)\
149 av_strlcatf(namestr, sizeof(namestr), "-%s%s", opt_name_##name[i], opt_name_##name[i+1] ? (opt_name_##name[i+2] ? ", " : " or ") : "");\
150 av_log(NULL, AV_LOG_WARNING, "Multiple %s options specified for stream %d, only the last option '-%s%s%s "SPECIFIER_OPT_FMT_##type"' will be used.\n",\
151 namestr, st->index, opt_name_##name[0], spec[0] ? ":" : "", spec, so->u.type);\
152}
153
154#define MATCH_PER_STREAM_OPT(name, type, outvar, fmtctx, st)\
155{\
156 int i, ret, matches = 0;\
157 SpecifierOpt *so;\
158 for (i = 0; i < o->nb_ ## name; i++) {\
159 char *spec = o->name[i].specifier;\
160 if ((ret = check_stream_specifier(fmtctx, st, spec)) > 0) {\
161 outvar = o->name[i].u.type;\
162 so = &o->name[i];\
163 matches++;\
164 } else if (ret < 0)\
165 exit_program(1);\
166 }\
167 if (matches > 1)\
168 WARN_MULTIPLE_OPT_USAGE(name, type, so, st);\
169}
170
171#define MATCH_PER_TYPE_OPT(name, type, outvar, fmtctx, mediatype)\
172{\
173 int i;\
174 for (i = 0; i < o->nb_ ## name; i++) {\
175 char *spec = o->name[i].specifier;\
176 if (!strcmp(spec, mediatype))\
177 outvar = o->name[i].u.type;\
178 }\
179}
180
182
183__thread char *vstats_filename;
184__thread char *sdp_filename;
185
186__thread float audio_drift_threshold = 0.1;
187__thread float dts_delta_threshold = 10;
188__thread float dts_error_threshold = 3600*30;
189
190__thread int audio_volume = 256;
191__thread int audio_sync_method = 0;
193__thread float frame_drop_threshold = 0;
194__thread int do_benchmark = 0;
195__thread int do_benchmark_all = 0;
196__thread int do_hex_dump = 0;
197__thread int do_pkt_dump = 0;
198__thread int copy_ts = 0;
199__thread int start_at_zero = 0;
200__thread int copy_tb = -1;
201__thread int debug_ts = 0;
202__thread int exit_on_error = 0;
203__thread int abort_on_flags = 0;
204__thread int print_stats = -1;
205__thread int qp_hist = 0;
206__thread int stdin_interaction = 1;
207__thread float max_error_rate = 2.0/3;
208__thread char *filter_nbthreads = NULL;
210__thread int vstats_version = 2;
211__thread int auto_conversion_filters = 1;
212__thread int64_t stats_period = 500000;
213
214
215__thread int file_overwrite = 0;
216__thread int no_file_overwrite = 0;
217__thread int do_psnr = 0;
219__thread int ignore_unknown_streams = 0;
220__thread int copy_unknown_streams = 0;
221__thread int recast_media = 0;
222__thread int find_stream_info = 1;
223
224extern __thread OptionDef *ffmpeg_options;
225
227{
228 const OptionDef *po = ffmpeg_options;
229 int i;
230
231 /* all OPT_SPEC and OPT_STRING can be freed in generic way */
232 while (po->name) {
233 void *dst = (uint8_t*)o + po->u.off;
234
235 if (po->flags & OPT_SPEC) {
236 SpecifierOpt **so = dst;
237 int i, *count = (int*)(so + 1);
238 for (i = 0; i < *count; i++) {
239 av_freep(&(*so)[i].specifier);
240 if (po->flags & OPT_STRING)
241 av_freep(&(*so)[i].u.str);
242 }
243 av_freep(so);
244 *count = 0;
245 } else if (po->flags & OPT_OFFSET && po->flags & OPT_STRING)
246 av_freep(dst);
247 po++;
248 }
249
250 for (i = 0; i < o->nb_stream_maps; i++)
251 av_freep(&o->stream_maps[i].linklabel);
252 av_freep(&o->stream_maps);
253 av_freep(&o->audio_channel_maps);
254 av_freep(&o->streamid_map);
255 av_freep(&o->attachments);
256}
257
259{
260 memset(o, 0, sizeof(*o));
261
262 o->stop_time = INT64_MAX;
263 o->mux_max_delay = 0.7;
264 o->start_time = AV_NOPTS_VALUE;
265 o->start_time_eof = AV_NOPTS_VALUE;
266 o->recording_time = INT64_MAX;
267 o->limit_filesize = UINT64_MAX;
268 o->chapters_input_file = INT_MAX;
269 o->accurate_seek = 1;
270 o->thread_queue_size = -1;
271 o->input_sync_ref = -1;
272}
273
274int show_hwaccels(void *optctx, const char *opt, const char *arg)
275{
276 enum AVHWDeviceType type = AV_HWDEVICE_TYPE_NONE;
277
278 av_log(NULL, AV_LOG_STDERR, "Hardware acceleration methods:\n");
279 while ((type = av_hwdevice_iterate_types(type)) !=
280 AV_HWDEVICE_TYPE_NONE)
281 av_log(NULL, AV_LOG_STDERR, "%s\n", av_hwdevice_get_type_name(type));
282 av_log(NULL, AV_LOG_STDERR, "\n");
283 return 0;
284}
285
286/* return a copy of the input with the stream specifiers removed from the keys */
287AVDictionary *strip_specifiers(AVDictionary *dict)
288{
289 const AVDictionaryEntry *e = NULL;
290 AVDictionary *ret = NULL;
291
292 while ((e = av_dict_get(dict, "", e, AV_DICT_IGNORE_SUFFIX))) {
293 char *p = strchr(e->key, ':');
294
295 if (p)
296 *p = 0;
297 av_dict_set(&ret, e->key, e->value, 0);
298 if (p)
299 *p = ':';
300 }
301 return ret;
302}
303
304int parse_and_set_vsync(const char *arg, int *vsync_var, int file_idx, int st_idx, int is_global)
305{
306 if (!av_strcasecmp(arg, "cfr")) *vsync_var = VSYNC_CFR;
307 else if (!av_strcasecmp(arg, "vfr")) *vsync_var = VSYNC_VFR;
308 else if (!av_strcasecmp(arg, "passthrough")) *vsync_var = VSYNC_PASSTHROUGH;
309 else if (!av_strcasecmp(arg, "drop")) *vsync_var = VSYNC_DROP;
310 else if (!is_global && !av_strcasecmp(arg, "auto")) *vsync_var = VSYNC_AUTO;
311 else if (!is_global) {
312 av_log(NULL, AV_LOG_FATAL, "Invalid value %s specified for fps_mode of #%d:%d.\n", arg, file_idx, st_idx);
313 exit_program(1);
314 }
315
316 if (is_global && *vsync_var == VSYNC_AUTO) {
318 av_log(NULL, AV_LOG_WARNING, "Passing a number to -vsync is deprecated,"
319 " use a string argument as described in the manual.\n");
320 }
321 return 0;
322}
323
325{
326 for (int i = 0; i < nb_input_files; i++) {
327 InputFile *ref, *self = input_files[i];
328 int64_t adjustment;
329 int64_t self_start_time, ref_start_time, self_seek_start, ref_seek_start;
330 int start_times_set = 1;
331
332 if (self->input_sync_ref == -1 || self->input_sync_ref == i) continue;
333 if (self->input_sync_ref >= nb_input_files || self->input_sync_ref < -1) {
334 av_log(NULL, AV_LOG_FATAL, "-isync for input %d references non-existent input %d.\n", i, self->input_sync_ref);
335 exit_program(1);
336 }
337
338 if (copy_ts && !start_at_zero) {
339 av_log(NULL, AV_LOG_FATAL, "Use of -isync requires that start_at_zero be set if copyts is set.\n");
340 exit_program(1);
341 }
342
343 ref = input_files[self->input_sync_ref];
344 if (ref->input_sync_ref != -1 && ref->input_sync_ref != self->input_sync_ref) {
345 av_log(NULL, AV_LOG_ERROR, "-isync for input %d references a resynced input %d. Sync not set.\n", i, self->input_sync_ref);
346 continue;
347 }
348
349 if (self->ctx->start_time_realtime != AV_NOPTS_VALUE && ref->ctx->start_time_realtime != AV_NOPTS_VALUE) {
350 self_start_time = self->ctx->start_time_realtime;
351 ref_start_time = ref->ctx->start_time_realtime;
352 } else if (self->ctx->start_time != AV_NOPTS_VALUE && ref->ctx->start_time != AV_NOPTS_VALUE) {
353 self_start_time = self->ctx->start_time;
354 ref_start_time = ref->ctx->start_time;
355 } else {
356 start_times_set = 0;
357 }
358
359 if (start_times_set) {
360 self_seek_start = self->start_time == AV_NOPTS_VALUE ? 0 : self->start_time;
361 ref_seek_start = ref->start_time == AV_NOPTS_VALUE ? 0 : ref->start_time;
362
363 adjustment = (self_start_time - ref_start_time) + !copy_ts*(self_seek_start - ref_seek_start) + ref->input_ts_offset;
364
365 self->ts_offset += adjustment;
366
367 av_log(NULL, AV_LOG_INFO, "Adjusted ts offset for Input #%d by %"PRId64" us to sync with Input #%d.\n", i, adjustment, self->input_sync_ref);
368 } else {
369 av_log(NULL, AV_LOG_INFO, "Unable to identify start times for Inputs #%d and %d both. No sync adjustment made.\n", i, self->input_sync_ref);
370 }
371 }
372
373 return 0;
374}
375
376int opt_filter_threads(void *optctx, const char *opt, const char *arg)
377{
378 av_free(filter_nbthreads);
379 filter_nbthreads = av_strdup(arg);
380 return 0;
381}
382
383int opt_abort_on(void *optctx, const char *opt, const char *arg)
384{
385 static const AVOption opts[] = {
386 { "abort_on" , NULL, 0, AV_OPT_TYPE_FLAGS, { .i64 = 0 }, INT64_MIN, (double)INT64_MAX, .unit = "flags" },
387 { "empty_output" , NULL, 0, AV_OPT_TYPE_CONST, { .i64 = ABORT_ON_FLAG_EMPTY_OUTPUT }, .unit = "flags" },
388 { "empty_output_stream", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = ABORT_ON_FLAG_EMPTY_OUTPUT_STREAM }, .unit = "flags" },
389 { NULL },
390 };
391 static const AVClass class = {
392 .class_name = "",
393 .item_name = av_default_item_name,
394 .option = opts,
395 .version = LIBAVUTIL_VERSION_INT,
396 };
397 const AVClass *pclass = &class;
398
399 return av_opt_eval_flags(&pclass, &opts[0], arg, &abort_on_flags);
400}
401
402int opt_stats_period(void *optctx, const char *opt, const char *arg)
403{
404 int64_t user_stats_period = parse_time_or_die(opt, arg, 1);
405
406 if (user_stats_period <= 0) {
407 av_log(NULL, AV_LOG_ERROR, "stats_period %s must be positive.\n", arg);
408 return AVERROR(EINVAL);
409 }
410
411 stats_period = user_stats_period;
412 av_log(NULL, AV_LOG_INFO, "ffmpeg stats and -progress period set to %s.\n", arg);
413
414 return 0;
415}
416
417int opt_audio_codec(void *optctx, const char *opt, const char *arg)
418{
419 OptionsContext *o = optctx;
420 return parse_option(o, "codec:a", arg, ffmpeg_options);
421}
422
423int opt_video_codec(void *optctx, const char *opt, const char *arg)
424{
425 OptionsContext *o = optctx;
426 return parse_option(o, "codec:v", arg, ffmpeg_options);
427}
428
429int opt_subtitle_codec(void *optctx, const char *opt, const char *arg)
430{
431 OptionsContext *o = optctx;
432 return parse_option(o, "codec:s", arg, ffmpeg_options);
433}
434
435int opt_data_codec(void *optctx, const char *opt, const char *arg)
436{
437 OptionsContext *o = optctx;
438 return parse_option(o, "codec:d", arg, ffmpeg_options);
439}
440
441int opt_map(void *optctx, const char *opt, const char *arg)
442{
443 OptionsContext *o = optctx;
444 StreamMap *m = NULL;
445 int i, negative = 0, file_idx, disabled = 0;
446 int sync_file_idx = -1, sync_stream_idx = 0;
447 char *p, *sync;
448 char *map;
449 char *allow_unused;
450
451 if (*arg == '-') {
452 negative = 1;
453 arg++;
454 }
455 map = av_strdup(arg);
456 if (!map)
457 return AVERROR(ENOMEM);
458
459 /* parse sync stream first, just pick first matching stream */
460 if ((sync = strchr(map, ','))) {
461 *sync = 0;
462 sync_file_idx = strtol(sync + 1, &sync, 0);
463 if (sync_file_idx >= nb_input_files || sync_file_idx < 0) {
464 av_log(NULL, AV_LOG_FATAL, "Invalid sync file index: %d.\n", sync_file_idx);
465 exit_program(1);
466 }
467 if (*sync)
468 sync++;
469 for (i = 0; i < input_files[sync_file_idx]->nb_streams; i++)
470 if (check_stream_specifier(input_files[sync_file_idx]->ctx,
471 input_files[sync_file_idx]->ctx->streams[i], sync) == 1) {
472 sync_stream_idx = i;
473 break;
474 }
475 if (i == input_files[sync_file_idx]->nb_streams) {
476 av_log(NULL, AV_LOG_FATAL, "Sync stream specification in map %s does not "
477 "match any streams.\n", arg);
478 exit_program(1);
479 }
480 if (input_streams[input_files[sync_file_idx]->ist_index + sync_stream_idx]->user_set_discard == AVDISCARD_ALL) {
481 av_log(NULL, AV_LOG_FATAL, "Sync stream specification in map %s matches a disabled input "
482 "stream.\n", arg);
483 exit_program(1);
484 }
485 }
486
487
488 if (map[0] == '[') {
489 /* this mapping refers to lavfi output */
490 const char *c = map + 1;
492 m = &o->stream_maps[o->nb_stream_maps - 1];
493 m->linklabel = av_get_token(&c, "]");
494 if (!m->linklabel) {
495 av_log(NULL, AV_LOG_ERROR, "Invalid output link label: %s.\n", map);
496 exit_program(1);
497 }
498 } else {
499 if ((allow_unused = strchr(map, '?')))
500 *allow_unused = 0;
501 file_idx = strtol(map, &p, 0);
502 if (file_idx >= nb_input_files || file_idx < 0) {
503 av_log(NULL, AV_LOG_FATAL, "Invalid input file index: %d.\n", file_idx);
504 exit_program(1);
505 }
506 if (negative)
507 /* disable some already defined maps */
508 for (i = 0; i < o->nb_stream_maps; i++) {
509 m = &o->stream_maps[i];
510 if (file_idx == m->file_index &&
512 input_files[m->file_index]->ctx->streams[m->stream_index],
513 *p == ':' ? p + 1 : p) > 0)
514 m->disabled = 1;
515 }
516 else
517 for (i = 0; i < input_files[file_idx]->nb_streams; i++) {
518 if (check_stream_specifier(input_files[file_idx]->ctx, input_files[file_idx]->ctx->streams[i],
519 *p == ':' ? p + 1 : p) <= 0)
520 continue;
521 if (input_streams[input_files[file_idx]->ist_index + i]->user_set_discard == AVDISCARD_ALL) {
522 disabled = 1;
523 continue;
524 }
526 m = &o->stream_maps[o->nb_stream_maps - 1];
527
528 m->file_index = file_idx;
529 m->stream_index = i;
530
531 if (sync_file_idx >= 0) {
532 m->sync_file_index = sync_file_idx;
533 m->sync_stream_index = sync_stream_idx;
534 } else {
535 m->sync_file_index = file_idx;
536 m->sync_stream_index = i;
537 }
538 }
539 }
540
541 if (!m) {
542 if (allow_unused) {
543 av_log(NULL, AV_LOG_VERBOSE, "Stream map '%s' matches no streams; ignoring.\n", arg);
544 } else if (disabled) {
545 av_log(NULL, AV_LOG_FATAL, "Stream map '%s' matches disabled streams.\n"
546 "To ignore this, add a trailing '?' to the map.\n", arg);
547 exit_program(1);
548 } else {
549 av_log(NULL, AV_LOG_FATAL, "Stream map '%s' matches no streams.\n"
550 "To ignore this, add a trailing '?' to the map.\n", arg);
551 exit_program(1);
552 }
553 }
554
555 av_freep(&map);
556 return 0;
557}
558
559int opt_attach(void *optctx, const char *opt, const char *arg)
560{
561 OptionsContext *o = optctx;
563 o->attachments[o->nb_attachments - 1] = arg;
564 return 0;
565}
566
567int opt_map_channel(void *optctx, const char *opt, const char *arg)
568{
569 OptionsContext *o = optctx;
570 int n;
571 AVStream *st;
573 char *allow_unused;
574 char *mapchan;
575 mapchan = av_strdup(arg);
576 if (!mapchan)
577 return AVERROR(ENOMEM);
578
581
582 /* muted channel syntax */
583 n = sscanf(arg, "%d:%d.%d", &m->channel_idx, &m->ofile_idx, &m->ostream_idx);
584 if ((n == 1 || n == 3) && m->channel_idx == -1) {
585 m->file_idx = m->stream_idx = -1;
586 if (n == 1)
587 m->ofile_idx = m->ostream_idx = -1;
588 av_free(mapchan);
589 return 0;
590 }
591
592 /* normal syntax */
593 n = sscanf(arg, "%d.%d.%d:%d.%d",
594 &m->file_idx, &m->stream_idx, &m->channel_idx,
595 &m->ofile_idx, &m->ostream_idx);
596
597 if (n != 3 && n != 5) {
598 av_log(NULL, AV_LOG_FATAL, "Syntax error, mapchan usage: "
599 "[file.stream.channel|-1][:syncfile:syncstream]\n");
600 exit_program(1);
601 }
602
603 if (n != 5) // only file.stream.channel specified
604 m->ofile_idx = m->ostream_idx = -1;
605
606 /* check input */
607 if (m->file_idx < 0 || m->file_idx >= nb_input_files) {
608 av_log(NULL, AV_LOG_FATAL, "mapchan: invalid input file index: %d\n",
609 m->file_idx);
610 exit_program(1);
611 }
612 if (m->stream_idx < 0 ||
614 av_log(NULL, AV_LOG_FATAL, "mapchan: invalid input file stream index #%d.%d\n",
615 m->file_idx, m->stream_idx);
616 exit_program(1);
617 }
618 st = input_files[m->file_idx]->ctx->streams[m->stream_idx];
619 if (st->codecpar->codec_type != AVMEDIA_TYPE_AUDIO) {
620 av_log(NULL, AV_LOG_FATAL, "mapchan: stream #%d.%d is not an audio stream.\n",
621 m->file_idx, m->stream_idx);
622 exit_program(1);
623 }
624 /* allow trailing ? to map_channel */
625 if ((allow_unused = strchr(mapchan, '?')))
626 *allow_unused = 0;
627 if (m->channel_idx < 0 || m->channel_idx >= st->codecpar->ch_layout.nb_channels ||
629 if (allow_unused) {
630 av_log(NULL, AV_LOG_VERBOSE, "mapchan: invalid audio channel #%d.%d.%d\n",
631 m->file_idx, m->stream_idx, m->channel_idx);
632 } else {
633 av_log(NULL, AV_LOG_FATAL, "mapchan: invalid audio channel #%d.%d.%d\n"
634 "To ignore this, add a trailing '?' to the map_channel.\n",
635 m->file_idx, m->stream_idx, m->channel_idx);
636 exit_program(1);
637 }
638
639 }
640 av_free(mapchan);
641 return 0;
642}
643
644int opt_sdp_file(void *optctx, const char *opt, const char *arg)
645{
646 av_free(sdp_filename);
647 sdp_filename = av_strdup(arg);
648 return 0;
649}
650
651#if CONFIG_VAAPI
652int opt_vaapi_device(void *optctx, const char *opt, const char *arg)
653{
654 const char *prefix = "vaapi:";
655 char *tmp;
656 int err;
657 tmp = av_asprintf("%s%s", prefix, arg);
658 if (!tmp)
659 return AVERROR(ENOMEM);
660 err = hw_device_init_from_string(tmp, NULL);
661 av_free(tmp);
662 return err;
663}
664#endif
665
666#if CONFIG_QSV
667int opt_qsv_device(void *optctx, const char *opt, const char *arg)
668{
669 const char *prefix = "qsv=__qsv_device:hw_any,child_device=";
670 int err;
671 char *tmp = av_asprintf("%s%s", prefix, arg);
672
673 if (!tmp)
674 return AVERROR(ENOMEM);
675
676 err = hw_device_init_from_string(tmp, NULL);
677 av_free(tmp);
678
679 return err;
680}
681#endif
682
683int opt_init_hw_device(void *optctx, const char *opt, const char *arg)
684{
685 if (!strcmp(arg, "list")) {
686 enum AVHWDeviceType type = AV_HWDEVICE_TYPE_NONE;
687 av_log(NULL, AV_LOG_STDERR, "Supported hardware device types:\n");
688 while ((type = av_hwdevice_iterate_types(type)) !=
689 AV_HWDEVICE_TYPE_NONE)
690 av_log(NULL, AV_LOG_STDERR, "%s\n", av_hwdevice_get_type_name(type));
691 av_log(NULL, AV_LOG_STDERR, "\n");
692 exit_program(0);
693 } else {
694 return hw_device_init_from_string(arg, NULL);
695 }
696}
697
698int opt_filter_hw_device(void *optctx, const char *opt, const char *arg)
699{
700 if (filter_hw_device) {
701 av_log(NULL, AV_LOG_ERROR, "Only one filter device can be used.\n");
702 return AVERROR(EINVAL);
703 }
705 if (!filter_hw_device) {
706 av_log(NULL, AV_LOG_ERROR, "Invalid filter device %s.\n", arg);
707 return AVERROR(EINVAL);
708 }
709 return 0;
710}
711
719void parse_meta_type(char *arg, char *type, int *index, const char **stream_spec)
720{
721 if (*arg) {
722 *type = *arg;
723 switch (*arg) {
724 case 'g':
725 break;
726 case 's':
727 if (*(++arg) && *arg != ':') {
728 av_log(NULL, AV_LOG_FATAL, "Invalid metadata specifier %s.\n", arg);
729 exit_program(1);
730 }
731 *stream_spec = *arg == ':' ? arg + 1 : "";
732 break;
733 case 'c':
734 case 'p':
735 if (*(++arg) == ':')
736 *index = strtol(++arg, NULL, 0);
737 break;
738 default:
739 av_log(NULL, AV_LOG_FATAL, "Invalid metadata type %c.\n", *arg);
740 exit_program(1);
741 }
742 } else
743 *type = 'g';
744}
745
746int fftools_copy_metadata(char *outspec, char *inspec, AVFormatContext *oc, AVFormatContext *ic, OptionsContext *o)
747{
748 AVDictionary **meta_in = NULL;
749 AVDictionary **meta_out = NULL;
750 int i, ret = 0;
751 char type_in, type_out;
752 const char *istream_spec = NULL, *ostream_spec = NULL;
753 int idx_in = 0, idx_out = 0;
754
755 parse_meta_type(inspec, &type_in, &idx_in, &istream_spec);
756 parse_meta_type(outspec, &type_out, &idx_out, &ostream_spec);
757
758 if (!ic) {
759 if (type_out == 'g' || !*outspec)
761 if (type_out == 's' || !*outspec)
763 if (type_out == 'c' || !*outspec)
765 return 0;
766 }
767
768 if (type_in == 'g' || type_out == 'g')
770 if (type_in == 's' || type_out == 's')
772 if (type_in == 'c' || type_out == 'c')
774
775 /* ic is NULL when just disabling automatic mappings */
776 if (!ic)
777 return 0;
778
779#define METADATA_CHECK_INDEX(index, nb_elems, desc)\
780 if ((index) < 0 || (index) >= (nb_elems)) {\
781 av_log(NULL, AV_LOG_FATAL, "Invalid %s index %d while processing metadata maps.\n",\
782 (desc), (index));\
783 exit_program(1);\
784 }
785
786#define SET_DICT(type, meta, context, index)\
787 switch (type) {\
788 case 'g':\
789 meta = &context->metadata;\
790 break;\
791 case 'c':\
792 METADATA_CHECK_INDEX(index, context->nb_chapters, "chapter")\
793 meta = &context->chapters[index]->metadata;\
794 break;\
795 case 'p':\
796 METADATA_CHECK_INDEX(index, context->nb_programs, "program")\
797 meta = &context->programs[index]->metadata;\
798 break;\
799 case 's':\
800 break; /* handled separately below */ \
801 default: av_assert0(0);\
802 }\
803
804 SET_DICT(type_in, meta_in, ic, idx_in);
805 SET_DICT(type_out, meta_out, oc, idx_out);
806
807 /* for input streams choose first matching stream */
808 if (type_in == 's') {
809 for (i = 0; i < ic->nb_streams; i++) {
810 if ((ret = check_stream_specifier(ic, ic->streams[i], istream_spec)) > 0) {
811 meta_in = &ic->streams[i]->metadata;
812 break;
813 } else if (ret < 0)
814 exit_program(1);
815 }
816 if (!meta_in) {
817 av_log(NULL, AV_LOG_FATAL, "Stream specifier %s does not match any streams.\n", istream_spec);
818 exit_program(1);
819 }
820 }
821
822 if (type_out == 's') {
823 for (i = 0; i < oc->nb_streams; i++) {
824 if ((ret = check_stream_specifier(oc, oc->streams[i], ostream_spec)) > 0) {
825 meta_out = &oc->streams[i]->metadata;
826 av_dict_copy(meta_out, *meta_in, AV_DICT_DONT_OVERWRITE);
827 } else if (ret < 0)
828 exit_program(1);
829 }
830 } else
831 av_dict_copy(meta_out, *meta_in, AV_DICT_DONT_OVERWRITE);
832
833 return 0;
834}
835
836int opt_recording_timestamp(void *optctx, const char *opt, const char *arg)
837{
838 OptionsContext *o = optctx;
839 char buf[128];
840 int64_t recording_timestamp = parse_time_or_die(opt, arg, 0) / 1E6;
841 struct tm time = *gmtime((time_t*)&recording_timestamp);
842 if (!strftime(buf, sizeof(buf), "creation_time=%Y-%m-%dT%H:%M:%S%z", &time))
843 return -1;
844 parse_option(o, "metadata", buf, ffmpeg_options);
845
846 av_log(NULL, AV_LOG_WARNING, "%s is deprecated, set the 'creation_time' metadata "
847 "tag instead.\n", opt);
848 return 0;
849}
850
851const AVCodec *find_codec_or_die(const char *name, enum AVMediaType type, int encoder)
852{
853 const AVCodecDescriptor *desc;
854 const char *codec_string = encoder ? "encoder" : "decoder";
855 const AVCodec *codec;
856
857 codec = encoder ?
858 avcodec_find_encoder_by_name(name) :
859 avcodec_find_decoder_by_name(name);
860
861 if (!codec && (desc = avcodec_descriptor_get_by_name(name))) {
862 codec = encoder ? avcodec_find_encoder(desc->id) :
863 avcodec_find_decoder(desc->id);
864 if (codec)
865 av_log(NULL, AV_LOG_VERBOSE, "Matched %s '%s' for codec '%s'.\n",
866 codec_string, codec->name, desc->name);
867 }
868
869 if (!codec) {
870 av_log(NULL, AV_LOG_FATAL, "Unknown %s '%s'\n", codec_string, name);
871 exit_program(1);
872 }
873 if (codec->type != type && !recast_media) {
874 av_log(NULL, AV_LOG_FATAL, "Invalid %s type '%s'\n", codec_string, name);
875 exit_program(1);
876 }
877 return codec;
878}
879
880const AVCodec *choose_decoder(OptionsContext *o, AVFormatContext *s, AVStream *st)
881{
882 char *codec_name = NULL;
883
884 MATCH_PER_STREAM_OPT(codec_names, str, codec_name, s, st);
885 if (codec_name) {
886 const AVCodec *codec = find_codec_or_die(codec_name, st->codecpar->codec_type, 0);
887 st->codecpar->codec_id = codec->id;
888 if (recast_media && st->codecpar->codec_type != codec->type)
889 st->codecpar->codec_type = codec->type;
890 return codec;
891 } else
892 return avcodec_find_decoder(st->codecpar->codec_id);
893}
894
895/* Add all the streams from the given input file to the global
896 * list of input streams. */
897void add_input_streams(OptionsContext *o, AVFormatContext *ic)
898{
899 int i, ret;
900
901 for (i = 0; i < ic->nb_streams; i++) {
902 AVStream *st = ic->streams[i];
903 AVCodecParameters *par = st->codecpar;
904 InputStream *ist;
905 char *framerate = NULL, *hwaccel_device = NULL;
906 const char *hwaccel = NULL;
907 char *hwaccel_output_format = NULL;
908 char *codec_tag = NULL;
909 char *next;
910 char *discard_str = NULL;
911 const AVClass *cc = avcodec_get_class();
912 const AVOption *discard_opt = av_opt_find(&cc, "skip_frame", NULL,
913 0, AV_OPT_SEARCH_FAKE_OBJ);
914
916 ist->st = st;
918 ist->discard = 1;
919 st->discard = AVDISCARD_ALL;
920 ist->nb_samples = 0;
921 ist->first_dts = AV_NOPTS_VALUE;
922 ist->min_pts = INT64_MAX;
923 ist->max_pts = INT64_MIN;
924
925 ist->ts_scale = 1.0;
926 MATCH_PER_STREAM_OPT(ts_scale, dbl, ist->ts_scale, ic, st);
927
928 ist->autorotate = 1;
929 MATCH_PER_STREAM_OPT(autorotate, i, ist->autorotate, ic, st);
930
931 MATCH_PER_STREAM_OPT(codec_tags, str, codec_tag, ic, st);
932 if (codec_tag) {
933 uint32_t tag = strtol(codec_tag, &next, 0);
934 if (*next)
935 tag = AV_RL32(codec_tag);
936 st->codecpar->codec_tag = tag;
937 }
938
939 ist->dec = choose_decoder(o, ic, st);
940 ist->decoder_opts = filter_codec_opts(o->g->codec_opts, ist->st->codecpar->codec_id, ic, st, ist->dec);
941
942 ist->reinit_filters = -1;
943 MATCH_PER_STREAM_OPT(reinit_filters, i, ist->reinit_filters, ic, st);
944
945 MATCH_PER_STREAM_OPT(discard, str, discard_str, ic, st);
946 ist->user_set_discard = AVDISCARD_NONE;
947
948 if ((o->video_disable && ist->st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) ||
949 (o->audio_disable && ist->st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) ||
950 (o->subtitle_disable && ist->st->codecpar->codec_type == AVMEDIA_TYPE_SUBTITLE) ||
951 (o->data_disable && ist->st->codecpar->codec_type == AVMEDIA_TYPE_DATA))
952 ist->user_set_discard = AVDISCARD_ALL;
953
954 if (discard_str && av_opt_eval_int(&cc, discard_opt, discard_str, &ist->user_set_discard) < 0) {
955 av_log(NULL, AV_LOG_ERROR, "Error parsing discard %s.\n",
956 discard_str);
957 exit_program(1);
958 }
959
960 ist->filter_in_rescale_delta_last = AV_NOPTS_VALUE;
961 ist->prev_pkt_pts = AV_NOPTS_VALUE;
962
963 ist->dec_ctx = avcodec_alloc_context3(ist->dec);
964 if (!ist->dec_ctx) {
965 av_log(NULL, AV_LOG_ERROR, "Error allocating the decoder context.\n");
966 exit_program(1);
967 }
968
969 ret = avcodec_parameters_to_context(ist->dec_ctx, par);
970 if (ret < 0) {
971 av_log(NULL, AV_LOG_ERROR, "Error initializing the decoder context.\n");
972 exit_program(1);
973 }
974
975 ist->decoded_frame = av_frame_alloc();
976 if (!ist->decoded_frame)
977 exit_program(1);
978
979 ist->pkt = av_packet_alloc();
980 if (!ist->pkt)
981 exit_program(1);
982
983 if (o->bitexact)
984 ist->dec_ctx->flags |= AV_CODEC_FLAG_BITEXACT;
985
986 switch (par->codec_type) {
987 case AVMEDIA_TYPE_VIDEO:
988 if(!ist->dec)
989 ist->dec = avcodec_find_decoder(par->codec_id);
990
991 // avformat_find_stream_info() doesn't set this for us anymore.
992 ist->dec_ctx->framerate = st->avg_frame_rate;
993
994 MATCH_PER_STREAM_OPT(frame_rates, str, framerate, ic, st);
995 if (framerate && av_parse_video_rate(&ist->framerate,
996 framerate) < 0) {
997 av_log(NULL, AV_LOG_ERROR, "Error parsing framerate %s.\n",
998 framerate);
999 exit_program(1);
1000 }
1001
1002 ist->top_field_first = -1;
1003 MATCH_PER_STREAM_OPT(top_field_first, i, ist->top_field_first, ic, st);
1004
1005 MATCH_PER_STREAM_OPT(hwaccels, str, hwaccel, ic, st);
1006 MATCH_PER_STREAM_OPT(hwaccel_output_formats, str,
1007 hwaccel_output_format, ic, st);
1008
1009 if (!hwaccel_output_format && hwaccel && !strcmp(hwaccel, "cuvid")) {
1010 av_log(NULL, AV_LOG_WARNING,
1011 "WARNING: defaulting hwaccel_output_format to cuda for compatibility "
1012 "with old commandlines. This behaviour is DEPRECATED and will be removed "
1013 "in the future. Please explicitly set \"-hwaccel_output_format cuda\".\n");
1014 ist->hwaccel_output_format = AV_PIX_FMT_CUDA;
1015 } else if (!hwaccel_output_format && hwaccel && !strcmp(hwaccel, "qsv")) {
1016 av_log(NULL, AV_LOG_WARNING,
1017 "WARNING: defaulting hwaccel_output_format to qsv for compatibility "
1018 "with old commandlines. This behaviour is DEPRECATED and will be removed "
1019 "in the future. Please explicitly set \"-hwaccel_output_format qsv\".\n");
1020 ist->hwaccel_output_format = AV_PIX_FMT_QSV;
1021 } else if (hwaccel_output_format) {
1022 ist->hwaccel_output_format = av_get_pix_fmt(hwaccel_output_format);
1023 if (ist->hwaccel_output_format == AV_PIX_FMT_NONE) {
1024 av_log(NULL, AV_LOG_FATAL, "Unrecognised hwaccel output "
1025 "format: %s", hwaccel_output_format);
1026 }
1027 } else {
1028 ist->hwaccel_output_format = AV_PIX_FMT_NONE;
1029 }
1030
1031 if (hwaccel) {
1032 // The NVDEC hwaccels use a CUDA device, so remap the name here.
1033 if (!strcmp(hwaccel, "nvdec") || !strcmp(hwaccel, "cuvid"))
1034 hwaccel = "cuda";
1035
1036 if (!strcmp(hwaccel, "none"))
1037 ist->hwaccel_id = HWACCEL_NONE;
1038 else if (!strcmp(hwaccel, "auto"))
1039 ist->hwaccel_id = HWACCEL_AUTO;
1040 else {
1041 enum AVHWDeviceType type = av_hwdevice_find_type_by_name(hwaccel);
1042 if (type != AV_HWDEVICE_TYPE_NONE) {
1044 ist->hwaccel_device_type = type;
1045 }
1046
1047 if (!ist->hwaccel_id) {
1048 av_log(NULL, AV_LOG_FATAL, "Unrecognized hwaccel: %s.\n",
1049 hwaccel);
1050 av_log(NULL, AV_LOG_FATAL, "Supported hwaccels: ");
1051 type = AV_HWDEVICE_TYPE_NONE;
1052 while ((type = av_hwdevice_iterate_types(type)) !=
1053 AV_HWDEVICE_TYPE_NONE)
1054 av_log(NULL, AV_LOG_FATAL, "%s ",
1055 av_hwdevice_get_type_name(type));
1056 av_log(NULL, AV_LOG_FATAL, "\n");
1057 exit_program(1);
1058 }
1059 }
1060 }
1061
1062 MATCH_PER_STREAM_OPT(hwaccel_devices, str, hwaccel_device, ic, st);
1063 if (hwaccel_device) {
1064 ist->hwaccel_device = av_strdup(hwaccel_device);
1065 if (!ist->hwaccel_device)
1066 exit_program(1);
1067 }
1068
1069 ist->hwaccel_pix_fmt = AV_PIX_FMT_NONE;
1070
1071 break;
1072 case AVMEDIA_TYPE_AUDIO:
1073 ist->guess_layout_max = INT_MAX;
1074 MATCH_PER_STREAM_OPT(guess_layout_max, i, ist->guess_layout_max, ic, st);
1076 break;
1077 case AVMEDIA_TYPE_DATA:
1078 case AVMEDIA_TYPE_SUBTITLE: {
1079 char *canvas_size = NULL;
1080 if(!ist->dec)
1081 ist->dec = avcodec_find_decoder(par->codec_id);
1082 MATCH_PER_STREAM_OPT(fix_sub_duration, i, ist->fix_sub_duration, ic, st);
1083 MATCH_PER_STREAM_OPT(canvas_sizes, str, canvas_size, ic, st);
1084 if (canvas_size &&
1085 av_parse_video_size(&ist->dec_ctx->width, &ist->dec_ctx->height, canvas_size) < 0) {
1086 av_log(NULL, AV_LOG_FATAL, "Invalid canvas size: %s.\n", canvas_size);
1087 exit_program(1);
1088 }
1089 break;
1090 }
1091 case AVMEDIA_TYPE_ATTACHMENT:
1092 case AVMEDIA_TYPE_UNKNOWN:
1093 break;
1094 default:
1095 abort();
1096 }
1097
1098 ret = avcodec_parameters_from_context(par, ist->dec_ctx);
1099 if (ret < 0) {
1100 av_log(NULL, AV_LOG_ERROR, "Error initializing the decoder context.\n");
1101 exit_program(1);
1102 }
1103 }
1104}
1105
1106void assert_file_overwrite(const char *filename)
1107{
1108 const char *proto_name = avio_find_protocol_name(filename);
1109
1111 av_log(NULL, AV_LOG_FATAL, "Error, both -y and -n supplied. Exiting.\n");
1112 exit_program(1);
1113 }
1114
1115 if (!file_overwrite) {
1116 if (proto_name && !strcmp(proto_name, "file") && avio_check(filename, 0) == 0) {
1118 av_log(NULL, AV_LOG_FATAL, "File '%s' already exists. Overwrite? [y/N] ", filename);
1119 term_exit();
1120 signal(SIGINT, SIG_DFL);
1121 if (!read_yesno()) {
1122 av_log(NULL, AV_LOG_FATAL, "Not overwriting - exiting\n");
1123 exit_program(1);
1124 }
1125 term_init();
1126 }
1127 else {
1128 av_log(NULL, AV_LOG_FATAL, "File '%s' already exists. Exiting.\n", filename);
1129 exit_program(1);
1130 }
1131 }
1132 }
1133
1134 if (proto_name && !strcmp(proto_name, "file")) {
1135 for (int i = 0; i < nb_input_files; i++) {
1136 InputFile *file = input_files[i];
1137 if (file->ctx->iformat->flags & AVFMT_NOFILE)
1138 continue;
1139 if (!strcmp(filename, file->ctx->url)) {
1140 av_log(NULL, AV_LOG_FATAL, "Output %s same as Input #%d - exiting\n", filename, i);
1141 av_log(NULL, AV_LOG_WARNING, "FFmpeg cannot edit existing files in-place.\n");
1142 exit_program(1);
1143 }
1144 }
1145 }
1146}
1147
1148void dump_attachment(AVStream *st, const char *filename)
1149{
1150 int ret;
1151 AVIOContext *out = NULL;
1152 const AVDictionaryEntry *e;
1153
1154 if (!st->codecpar->extradata_size) {
1155 av_log(NULL, AV_LOG_WARNING, "No extradata to dump in stream #%d:%d.\n",
1156 nb_input_files - 1, st->index);
1157 return;
1158 }
1159 if (!*filename && (e = av_dict_get(st->metadata, "filename", NULL, 0)))
1160 filename = e->value;
1161 if (!*filename) {
1162 av_log(NULL, AV_LOG_FATAL, "No filename specified and no 'filename' tag"
1163 "in stream #%d:%d.\n", nb_input_files - 1, st->index);
1164 exit_program(1);
1165 }
1166
1167 assert_file_overwrite(filename);
1168
1169 if ((ret = avio_open2(&out, filename, AVIO_FLAG_WRITE, &int_cb, NULL)) < 0) {
1170 av_log(NULL, AV_LOG_FATAL, "Could not open file %s for writing.\n",
1171 filename);
1172 exit_program(1);
1173 }
1174
1175 avio_write(out, st->codecpar->extradata, st->codecpar->extradata_size);
1176 avio_flush(out);
1177 avio_close(out);
1178}
1179
1180int open_input_file(OptionsContext *o, const char *filename)
1181{
1182 InputFile *f;
1183 AVFormatContext *ic;
1184 const AVInputFormat *file_iformat = NULL;
1185 int err, i, ret;
1186 int64_t timestamp;
1187 AVDictionary *unused_opts = NULL;
1188 const AVDictionaryEntry *e = NULL;
1189 char * video_codec_name = NULL;
1190 char * audio_codec_name = NULL;
1191 char *subtitle_codec_name = NULL;
1192 char * data_codec_name = NULL;
1193 int scan_all_pmts_set = 0;
1194
1195 if (o->stop_time != INT64_MAX && o->recording_time != INT64_MAX) {
1196 o->stop_time = INT64_MAX;
1197 av_log(NULL, AV_LOG_WARNING, "-t and -to cannot be used together; using -t.\n");
1198 }
1199
1200 if (o->stop_time != INT64_MAX && o->recording_time == INT64_MAX) {
1201 int64_t start_time = o->start_time == AV_NOPTS_VALUE ? 0 : o->start_time;
1202 if (o->stop_time <= start_time) {
1203 av_log(NULL, AV_LOG_ERROR, "-to value smaller than -ss; aborting.\n");
1204 exit_program(1);
1205 } else {
1206 o->recording_time = o->stop_time - start_time;
1207 }
1208 }
1209
1210 if (o->format) {
1211 if (!(file_iformat = av_find_input_format(o->format))) {
1212 av_log(NULL, AV_LOG_FATAL, "Unknown input format: '%s'\n", o->format);
1213 exit_program(1);
1214 }
1215 }
1216
1217 if (!strcmp(filename, "-"))
1218 filename = "pipe:";
1219
1220 stdin_interaction &= strncmp(filename, "pipe:", 5) &&
1221 strcmp(filename, "/dev/stdin");
1222
1223 /* get default parameters from command line */
1224 ic = avformat_alloc_context();
1225 if (!ic) {
1226 print_error(filename, AVERROR(ENOMEM));
1227 exit_program(1);
1228 }
1229 if (o->nb_audio_sample_rate) {
1230 av_dict_set_int(&o->g->format_opts, "sample_rate", o->audio_sample_rate[o->nb_audio_sample_rate - 1].u.i, 0);
1231 }
1232 if (o->nb_audio_channels) {
1233 const AVClass *priv_class;
1234 if (file_iformat && (priv_class = file_iformat->priv_class) &&
1235 av_opt_find(&priv_class, "ch_layout", NULL, 0,
1236 AV_OPT_SEARCH_FAKE_OBJ)) {
1237 char buf[32];
1238 snprintf(buf, sizeof(buf), "%dC", o->audio_channels[o->nb_audio_channels - 1].u.i);
1239 av_dict_set(&o->g->format_opts, "ch_layout", buf, 0);
1240 }
1241 }
1242 if (o->nb_audio_ch_layouts) {
1243 const AVClass *priv_class;
1244 if (file_iformat && (priv_class = file_iformat->priv_class) &&
1245 av_opt_find(&priv_class, "ch_layout", NULL, 0,
1246 AV_OPT_SEARCH_FAKE_OBJ)) {
1247 av_dict_set(&o->g->format_opts, "ch_layout", o->audio_ch_layouts[o->nb_audio_ch_layouts - 1].u.str, 0);
1248 }
1249 }
1250 if (o->nb_frame_rates) {
1251 const AVClass *priv_class;
1252 /* set the format-level framerate option;
1253 * this is important for video grabbers, e.g. x11 */
1254 if (file_iformat && (priv_class = file_iformat->priv_class) &&
1255 av_opt_find(&priv_class, "framerate", NULL, 0,
1256 AV_OPT_SEARCH_FAKE_OBJ)) {
1257 av_dict_set(&o->g->format_opts, "framerate",
1258 o->frame_rates[o->nb_frame_rates - 1].u.str, 0);
1259 }
1260 }
1261 if (o->nb_frame_sizes) {
1262 av_dict_set(&o->g->format_opts, "video_size", o->frame_sizes[o->nb_frame_sizes - 1].u.str, 0);
1263 }
1264 if (o->nb_frame_pix_fmts)
1265 av_dict_set(&o->g->format_opts, "pixel_format", o->frame_pix_fmts[o->nb_frame_pix_fmts - 1].u.str, 0);
1266
1267 MATCH_PER_TYPE_OPT(codec_names, str, video_codec_name, ic, "v");
1268 MATCH_PER_TYPE_OPT(codec_names, str, audio_codec_name, ic, "a");
1269 MATCH_PER_TYPE_OPT(codec_names, str, subtitle_codec_name, ic, "s");
1270 MATCH_PER_TYPE_OPT(codec_names, str, data_codec_name, ic, "d");
1271
1272 if (video_codec_name)
1273 ic->video_codec = find_codec_or_die(video_codec_name , AVMEDIA_TYPE_VIDEO , 0);
1274 if (audio_codec_name)
1275 ic->audio_codec = find_codec_or_die(audio_codec_name , AVMEDIA_TYPE_AUDIO , 0);
1276 if (subtitle_codec_name)
1277 ic->subtitle_codec = find_codec_or_die(subtitle_codec_name, AVMEDIA_TYPE_SUBTITLE, 0);
1278 if (data_codec_name)
1279 ic->data_codec = find_codec_or_die(data_codec_name , AVMEDIA_TYPE_DATA , 0);
1280
1281 ic->video_codec_id = video_codec_name ? ic->video_codec->id : AV_CODEC_ID_NONE;
1282 ic->audio_codec_id = audio_codec_name ? ic->audio_codec->id : AV_CODEC_ID_NONE;
1283 ic->subtitle_codec_id = subtitle_codec_name ? ic->subtitle_codec->id : AV_CODEC_ID_NONE;
1284 ic->data_codec_id = data_codec_name ? ic->data_codec->id : AV_CODEC_ID_NONE;
1285
1286 ic->flags |= AVFMT_FLAG_NONBLOCK;
1287 if (o->bitexact)
1288 ic->flags |= AVFMT_FLAG_BITEXACT;
1289 ic->interrupt_callback = int_cb;
1290
1291 if (!av_dict_get(o->g->format_opts, "scan_all_pmts", NULL, AV_DICT_MATCH_CASE)) {
1292 av_dict_set(&o->g->format_opts, "scan_all_pmts", "1", AV_DICT_DONT_OVERWRITE);
1293 scan_all_pmts_set = 1;
1294 }
1295 /* open the input file with generic avformat function */
1296 err = avformat_open_input(&ic, filename, file_iformat, &o->g->format_opts);
1297 if (err < 0) {
1298 print_error(filename, err);
1299 if (err == AVERROR_PROTOCOL_NOT_FOUND)
1300 av_log(NULL, AV_LOG_ERROR, "Did you mean file:%s?\n", filename);
1301 exit_program(1);
1302 }
1303 if (scan_all_pmts_set)
1304 av_dict_set(&o->g->format_opts, "scan_all_pmts", NULL, AV_DICT_MATCH_CASE);
1307
1308 /* apply forced codec ids */
1309 for (i = 0; i < ic->nb_streams; i++)
1310 choose_decoder(o, ic, ic->streams[i]);
1311
1312 if (find_stream_info) {
1313 AVDictionary **opts = setup_find_stream_info_opts(ic, o->g->codec_opts);
1314 int orig_nb_streams = ic->nb_streams;
1315
1316 /* If not enough info to get the stream parameters, we decode the
1317 first frames to get it. (used in mpeg case for example) */
1318 ret = avformat_find_stream_info(ic, opts);
1319
1320 for (i = 0; i < orig_nb_streams; i++)
1321 av_dict_free(&opts[i]);
1322 av_freep(&opts);
1323
1324 if (ret < 0) {
1325 av_log(NULL, AV_LOG_FATAL, "%s: could not find codec parameters\n", filename);
1326 if (ic->nb_streams == 0) {
1327 avformat_close_input(&ic);
1328 exit_program(1);
1329 }
1330 }
1331 }
1332
1333 if (o->start_time != AV_NOPTS_VALUE && o->start_time_eof != AV_NOPTS_VALUE) {
1334 av_log(NULL, AV_LOG_WARNING, "Cannot use -ss and -sseof both, using -ss for %s\n", filename);
1335 o->start_time_eof = AV_NOPTS_VALUE;
1336 }
1337
1338 if (o->start_time_eof != AV_NOPTS_VALUE) {
1339 if (o->start_time_eof >= 0) {
1340 av_log(NULL, AV_LOG_ERROR, "-sseof value must be negative; aborting\n");
1341 exit_program(1);
1342 }
1343 if (ic->duration > 0) {
1344 o->start_time = o->start_time_eof + ic->duration;
1345 if (o->start_time < 0) {
1346 av_log(NULL, AV_LOG_WARNING, "-sseof value seeks to before start of file %s; ignored\n", filename);
1347 o->start_time = AV_NOPTS_VALUE;
1348 }
1349 } else
1350 av_log(NULL, AV_LOG_WARNING, "Cannot use -sseof, duration of %s not known\n", filename);
1351 }
1352 timestamp = (o->start_time == AV_NOPTS_VALUE) ? 0 : o->start_time;
1353 /* add the stream start time */
1354 if (!o->seek_timestamp && ic->start_time != AV_NOPTS_VALUE)
1355 timestamp += ic->start_time;
1356
1357 /* if seeking requested, we execute it */
1358 if (o->start_time != AV_NOPTS_VALUE) {
1359 int64_t seek_timestamp = timestamp;
1360
1361 if (!(ic->iformat->flags & AVFMT_SEEK_TO_PTS)) {
1362 int dts_heuristic = 0;
1363 for (i=0; i<ic->nb_streams; i++) {
1364 const AVCodecParameters *par = ic->streams[i]->codecpar;
1365 if (par->video_delay) {
1366 dts_heuristic = 1;
1367 break;
1368 }
1369 }
1370 if (dts_heuristic) {
1371 seek_timestamp -= 3*AV_TIME_BASE / 23;
1372 }
1373 }
1374 ret = avformat_seek_file(ic, -1, INT64_MIN, seek_timestamp, seek_timestamp, 0);
1375 if (ret < 0) {
1376 av_log(NULL, AV_LOG_WARNING, "%s: could not seek to position %0.3f\n",
1377 filename, (double)timestamp / AV_TIME_BASE);
1378 }
1379 }
1380
1381 /* update the current parameters so that they match the one of the input stream */
1382 add_input_streams(o, ic);
1383
1384 /* dump the file content */
1385 av_dump_format(ic, nb_input_files, filename, 0);
1386
1388
1389 f->ctx = ic;
1390 f->ist_index = nb_input_streams - ic->nb_streams;
1391 f->start_time = o->start_time;
1395 f->ts_offset = o->input_ts_offset - (copy_ts ? (start_at_zero && ic->start_time != AV_NOPTS_VALUE ? ic->start_time : 0) : timestamp);
1396 f->nb_streams = ic->nb_streams;
1397 f->rate_emu = o->rate_emu;
1399 f->loop = o->loop;
1400 f->duration = 0;
1401 f->time_base = (AVRational){ 1, 1 };
1402
1403 f->readrate = o->readrate ? o->readrate : 0.0;
1404 if (f->readrate < 0.0f) {
1405 av_log(NULL, AV_LOG_ERROR, "Option -readrate for Input #%d is %0.3f; it must be non-negative.\n", nb_input_files, f->readrate);
1406 exit_program(1);
1407 }
1408 if (f->readrate && f->rate_emu) {
1409 av_log(NULL, AV_LOG_WARNING, "Both -readrate and -re set for Input #%d. Using -readrate %0.3f.\n", nb_input_files, f->readrate);
1410 f->rate_emu = 0;
1411 }
1412
1413 f->pkt = av_packet_alloc();
1414 if (!f->pkt)
1415 exit_program(1);
1416#if HAVE_THREADS
1417 f->thread_queue_size = o->thread_queue_size;
1418#endif
1419
1420 /* check if all codec options have been used */
1421 unused_opts = strip_specifiers(o->g->codec_opts);
1422 for (i = f->ist_index; i < nb_input_streams; i++) {
1423 e = NULL;
1424 while ((e = av_dict_get(input_streams[i]->decoder_opts, "", e,
1425 AV_DICT_IGNORE_SUFFIX)))
1426 av_dict_set(&unused_opts, e->key, NULL, 0);
1427 }
1428
1429 e = NULL;
1430 while ((e = av_dict_get(unused_opts, "", e, AV_DICT_IGNORE_SUFFIX))) {
1431 const AVClass *class = avcodec_get_class();
1432 const AVOption *option = av_opt_find(&class, e->key, NULL, 0,
1433 AV_OPT_SEARCH_CHILDREN | AV_OPT_SEARCH_FAKE_OBJ);
1434 const AVClass *fclass = avformat_get_class();
1435 const AVOption *foption = av_opt_find(&fclass, e->key, NULL, 0,
1436 AV_OPT_SEARCH_CHILDREN | AV_OPT_SEARCH_FAKE_OBJ);
1437 if (!option || foption)
1438 continue;
1439
1440
1441 if (!(option->flags & AV_OPT_FLAG_DECODING_PARAM)) {
1442 av_log(NULL, AV_LOG_ERROR, "Codec AVOption %s (%s) specified for "
1443 "input file #%d (%s) is not a decoding option.\n", e->key,
1444 option->help ? option->help : "", nb_input_files - 1,
1445 filename);
1446 exit_program(1);
1447 }
1448
1449 av_log(NULL, AV_LOG_WARNING, "Codec AVOption %s (%s) specified for "
1450 "input file #%d (%s) has not been used for any stream. The most "
1451 "likely reason is either wrong type (e.g. a video option with "
1452 "no video streams) or that it is a private option of some decoder "
1453 "which was not actually used for any stream.\n", e->key,
1454 option->help ? option->help : "", nb_input_files - 1, filename);
1455 }
1456 av_dict_free(&unused_opts);
1457
1458 for (i = 0; i < o->nb_dump_attachment; i++) {
1459 int j;
1460
1461 for (j = 0; j < ic->nb_streams; j++) {
1462 AVStream *st = ic->streams[j];
1463
1464 if (check_stream_specifier(ic, st, o->dump_attachment[i].specifier) == 1)
1466 }
1467 }
1468
1470
1471 return 0;
1472}
1473
1474char *get_line(AVIOContext *s, AVBPrint *bprint)
1475{
1476 char c;
1477
1478 while ((c = avio_r8(s)) && c != '\n')
1479 av_bprint_chars(bprint, c, 1);
1480
1481 if (!av_bprint_is_complete(bprint)) {
1482 av_log(NULL, AV_LOG_FATAL, "Could not alloc buffer for reading preset.\n");
1483 exit_program(1);
1484 }
1485 return bprint->str;
1486}
1487
1488int get_preset_file_2(const char *preset_name, const char *codec_name, AVIOContext **s)
1489{
1490 int i, ret = -1;
1491 char filename[1000];
1492 char *env_avconv_datadir = getenv_utf8("AVCONV_DATADIR");
1493 char *env_home = getenv_utf8("HOME");
1494 const char *base[3] = { env_avconv_datadir,
1495 env_home,
1496 AVCONV_DATADIR,
1497 };
1498
1499 for (i = 0; i < FF_ARRAY_ELEMS(base) && ret < 0; i++) {
1500 if (!base[i])
1501 continue;
1502 if (codec_name) {
1503 snprintf(filename, sizeof(filename), "%s%s/%s-%s.avpreset", base[i],
1504 i != 1 ? "" : "/.avconv", codec_name, preset_name);
1505 ret = avio_open2(s, filename, AVIO_FLAG_READ, &int_cb, NULL);
1506 }
1507 if (ret < 0) {
1508 snprintf(filename, sizeof(filename), "%s%s/%s.avpreset", base[i],
1509 i != 1 ? "" : "/.avconv", preset_name);
1510 ret = avio_open2(s, filename, AVIO_FLAG_READ, &int_cb, NULL);
1511 }
1512 }
1513 freeenv_utf8(env_home);
1514 freeenv_utf8(env_avconv_datadir);
1515 return ret;
1516}
1517
1518int choose_encoder(OptionsContext *o, AVFormatContext *s, OutputStream *ost)
1519{
1520 enum AVMediaType type = ost->st->codecpar->codec_type;
1521 char *codec_name = NULL;
1522
1523 if (type == AVMEDIA_TYPE_VIDEO || type == AVMEDIA_TYPE_AUDIO || type == AVMEDIA_TYPE_SUBTITLE) {
1524 MATCH_PER_STREAM_OPT(codec_names, str, codec_name, s, ost->st);
1525 if (!codec_name) {
1526 ost->st->codecpar->codec_id = av_guess_codec(s->oformat, NULL, s->url,
1527 NULL, ost->st->codecpar->codec_type);
1528 ost->enc = avcodec_find_encoder(ost->st->codecpar->codec_id);
1529 if (!ost->enc) {
1530 av_log(NULL, AV_LOG_FATAL, "Automatic encoder selection failed for "
1531 "output stream #%d:%d. Default encoder for format %s (codec %s) is "
1532 "probably disabled. Please choose an encoder manually.\n",
1533 ost->file_index, ost->index, s->oformat->name,
1534 avcodec_get_name(ost->st->codecpar->codec_id));
1535 return AVERROR_ENCODER_NOT_FOUND;
1536 }
1537 } else if (!strcmp(codec_name, "copy"))
1538 ost->stream_copy = 1;
1539 else {
1540 ost->enc = find_codec_or_die(codec_name, ost->st->codecpar->codec_type, 1);
1541 ost->st->codecpar->codec_id = ost->enc->id;
1542 }
1543 ost->encoding_needed = !ost->stream_copy;
1544 } else {
1545 /* no encoding supported for other media types */
1546 ost->stream_copy = 1;
1547 ost->encoding_needed = 0;
1548 }
1549
1550 return 0;
1551}
1552
1553OutputStream *new_output_stream(OptionsContext *o, AVFormatContext *oc, enum AVMediaType type, int source_index)
1554{
1555 OutputStream *ost;
1556 AVStream *st = avformat_new_stream(oc, NULL);
1557 int idx = oc->nb_streams - 1, ret = 0;
1558 const char *bsfs = NULL, *time_base = NULL;
1559 char *next, *codec_tag = NULL;
1560 double qscale = -1;
1561 int i;
1562
1563 if (!st) {
1564 av_log(NULL, AV_LOG_FATAL, "Could not alloc stream.\n");
1565 exit_program(1);
1566 }
1567
1568 if (oc->nb_streams - 1 < o->nb_streamid_map)
1569 st->id = o->streamid_map[oc->nb_streams - 1];
1570
1572
1573 ost->file_index = nb_output_files - 1;
1574 ost->index = idx;
1575 ost->st = st;
1576 ost->forced_kf_ref_pts = AV_NOPTS_VALUE;
1577 st->codecpar->codec_type = type;
1578
1579 ret = choose_encoder(o, oc, ost);
1580 if (ret < 0) {
1581 av_log(NULL, AV_LOG_FATAL, "Error selecting an encoder for stream "
1582 "%d:%d\n", ost->file_index, ost->index);
1583 exit_program(1);
1584 }
1585
1586 ost->enc_ctx = avcodec_alloc_context3(ost->enc);
1587 if (!ost->enc_ctx) {
1588 av_log(NULL, AV_LOG_ERROR, "Error allocating the encoding context.\n");
1589 exit_program(1);
1590 }
1591 ost->enc_ctx->codec_type = type;
1592
1593 ost->ref_par = avcodec_parameters_alloc();
1594 if (!ost->ref_par) {
1595 av_log(NULL, AV_LOG_ERROR, "Error allocating the encoding parameters.\n");
1596 exit_program(1);
1597 }
1598
1599 ost->filtered_frame = av_frame_alloc();
1600 if (!ost->filtered_frame)
1601 exit_program(1);
1602
1603 ost->pkt = av_packet_alloc();
1604 if (!ost->pkt)
1605 exit_program(1);
1606
1607 if (ost->enc) {
1608 AVIOContext *s = NULL;
1609 char *buf = NULL, *arg = NULL, *preset = NULL;
1610
1611 ost->encoder_opts = filter_codec_opts(o->g->codec_opts, ost->enc->id, oc, st, ost->enc);
1612
1613 MATCH_PER_STREAM_OPT(presets, str, preset, oc, st);
1614 ost->autoscale = 1;
1615 MATCH_PER_STREAM_OPT(autoscale, i, ost->autoscale, oc, st);
1616 if (preset && (!(ret = get_preset_file_2(preset, ost->enc->name, &s)))) {
1617 AVBPrint bprint;
1618 av_bprint_init(&bprint, 0, AV_BPRINT_SIZE_UNLIMITED);
1619 do {
1620 av_bprint_clear(&bprint);
1621 buf = get_line(s, &bprint);
1622 if (!buf[0] || buf[0] == '#')
1623 continue;
1624 if (!(arg = strchr(buf, '='))) {
1625 av_log(NULL, AV_LOG_FATAL, "Invalid line found in the preset file.\n");
1626 exit_program(1);
1627 }
1628 *arg++ = 0;
1629 av_dict_set(&ost->encoder_opts, buf, arg, AV_DICT_DONT_OVERWRITE);
1630 } while (!s->eof_reached);
1631 av_bprint_finalize(&bprint, NULL);
1632 avio_closep(&s);
1633 }
1634 if (ret) {
1635 av_log(NULL, AV_LOG_FATAL,
1636 "Preset %s specified for stream %d:%d, but could not be opened.\n",
1637 preset, ost->file_index, ost->index);
1638 exit_program(1);
1639 }
1640 } else {
1641 ost->encoder_opts = filter_codec_opts(o->g->codec_opts, AV_CODEC_ID_NONE, oc, st, NULL);
1642 }
1643
1644
1645 if (o->bitexact)
1646 ost->enc_ctx->flags |= AV_CODEC_FLAG_BITEXACT;
1647
1648 MATCH_PER_STREAM_OPT(time_bases, str, time_base, oc, st);
1649 if (time_base) {
1650 AVRational q;
1651 if (av_parse_ratio(&q, time_base, INT_MAX, 0, NULL) < 0 ||
1652 q.num <= 0 || q.den <= 0) {
1653 av_log(NULL, AV_LOG_FATAL, "Invalid time base: %s\n", time_base);
1654 exit_program(1);
1655 }
1656 st->time_base = q;
1657 }
1658
1659 MATCH_PER_STREAM_OPT(enc_time_bases, str, time_base, oc, st);
1660 if (time_base) {
1661 AVRational q;
1662 if (av_parse_ratio(&q, time_base, INT_MAX, 0, NULL) < 0 ||
1663 q.den <= 0) {
1664 av_log(NULL, AV_LOG_FATAL, "Invalid time base: %s\n", time_base);
1665 exit_program(1);
1666 }
1667 ost->enc_timebase = q;
1668 }
1669
1670 ost->max_frames = INT64_MAX;
1671 MATCH_PER_STREAM_OPT(max_frames, i64, ost->max_frames, oc, st);
1672 for (i = 0; i<o->nb_max_frames; i++) {
1673 char *p = o->max_frames[i].specifier;
1674 if (!*p && type != AVMEDIA_TYPE_VIDEO) {
1675 av_log(NULL, AV_LOG_WARNING, "Applying unspecific -frames to non video streams, maybe you meant -vframes ?\n");
1676 break;
1677 }
1678 }
1679
1680 ost->copy_prior_start = -1;
1681 MATCH_PER_STREAM_OPT(copy_prior_start, i, ost->copy_prior_start, oc ,st);
1682
1683 MATCH_PER_STREAM_OPT(bitstream_filters, str, bsfs, oc, st);
1684 if (bsfs && *bsfs) {
1685 ret = av_bsf_list_parse_str(bsfs, &ost->bsf_ctx);
1686 if (ret < 0) {
1687 av_log(NULL, AV_LOG_ERROR, "Error parsing bitstream filter sequence '%s': %s\n", bsfs, av_err2str(ret));
1688 exit_program(1);
1689 }
1690 }
1691
1692 MATCH_PER_STREAM_OPT(codec_tags, str, codec_tag, oc, st);
1693 if (codec_tag) {
1694 uint32_t tag = strtol(codec_tag, &next, 0);
1695 if (*next)
1696 tag = AV_RL32(codec_tag);
1697 ost->st->codecpar->codec_tag =
1698 ost->enc_ctx->codec_tag = tag;
1699 }
1700
1701 MATCH_PER_STREAM_OPT(qscale, dbl, qscale, oc, st);
1702 if (qscale >= 0) {
1703 ost->enc_ctx->flags |= AV_CODEC_FLAG_QSCALE;
1704 ost->enc_ctx->global_quality = FF_QP2LAMBDA * qscale;
1705 }
1706
1707 MATCH_PER_STREAM_OPT(disposition, str, ost->disposition, oc, st);
1708 ost->disposition = av_strdup(ost->disposition);
1709
1710 ost->max_muxing_queue_size = 128;
1711 MATCH_PER_STREAM_OPT(max_muxing_queue_size, i, ost->max_muxing_queue_size, oc, st);
1712
1713 ost->muxing_queue_data_size = 0;
1714
1715 ost->muxing_queue_data_threshold = 50*1024*1024;
1716 MATCH_PER_STREAM_OPT(muxing_queue_data_threshold, i, ost->muxing_queue_data_threshold, oc, st);
1717
1718 MATCH_PER_STREAM_OPT(bits_per_raw_sample, i, ost->bits_per_raw_sample,
1719 oc, st);
1720
1721 if (oc->oformat->flags & AVFMT_GLOBALHEADER)
1722 ost->enc_ctx->flags |= AV_CODEC_FLAG_GLOBAL_HEADER;
1723
1724 av_dict_copy(&ost->sws_dict, o->g->sws_dict, 0);
1725
1726 av_dict_copy(&ost->swr_opts, o->g->swr_opts, 0);
1727 if (ost->enc && av_get_exact_bits_per_sample(ost->enc->id) == 24)
1728 av_dict_set(&ost->swr_opts, "output_sample_bits", "24", 0);
1729
1730 ost->source_index = source_index;
1731 if (source_index >= 0) {
1732 ost->sync_ist = input_streams[source_index];
1733 input_streams[source_index]->discard = 0;
1734 input_streams[source_index]->st->discard = input_streams[source_index]->user_set_discard;
1735 }
1736 ost->last_mux_dts = AV_NOPTS_VALUE;
1737
1738 ost->muxing_queue = av_fifo_alloc2(8, sizeof(AVPacket*), 0);
1739 if (!ost->muxing_queue)
1740 exit_program(1);
1741
1742 MATCH_PER_STREAM_OPT(copy_initial_nonkeyframes, i,
1743 ost->copy_initial_nonkeyframes, oc, st);
1744
1745 return ost;
1746}
1747
1748void parse_matrix_coeffs(uint16_t *dest, const char *str)
1749{
1750 int i;
1751 const char *p = str;
1752 for (i = 0;; i++) {
1753 dest[i] = atoi(p);
1754 if (i == 63)
1755 break;
1756 p = strchr(p, ',');
1757 if (!p) {
1758 av_log(NULL, AV_LOG_FATAL, "Syntax error in matrix \"%s\" at coeff %d\n", str, i);
1759 exit_program(1);
1760 }
1761 p++;
1762 }
1763}
1764
1765/* read file contents into a string */
1766char *fftools_read_file(const char *filename)
1767{
1768 AVIOContext *pb = NULL;
1769 int ret = avio_open(&pb, filename, AVIO_FLAG_READ);
1770 AVBPrint bprint;
1771 char *str;
1772
1773 if (ret < 0) {
1774 av_log(NULL, AV_LOG_ERROR, "Error opening file %s.\n", filename);
1775 return NULL;
1776 }
1777
1778 av_bprint_init(&bprint, 0, AV_BPRINT_SIZE_UNLIMITED);
1779 ret = avio_read_to_bprint(pb, &bprint, SIZE_MAX);
1780 avio_closep(&pb);
1781 if (ret < 0) {
1782 av_bprint_finalize(&bprint, NULL);
1783 return NULL;
1784 }
1785 ret = av_bprint_finalize(&bprint, &str);
1786 if (ret < 0)
1787 return NULL;
1788 return str;
1789}
1790
1791char *get_ost_filters(OptionsContext *o, AVFormatContext *oc,
1792 OutputStream *ost)
1793{
1794 AVStream *st = ost->st;
1795
1796 if (ost->filters_script && ost->filters) {
1797 av_log(NULL, AV_LOG_ERROR, "Both -filter and -filter_script set for "
1798 "output stream #%d:%d.\n", nb_output_files, st->index);
1799 exit_program(1);
1800 }
1801
1802 if (ost->filters_script)
1803 return fftools_read_file(ost->filters_script);
1804 else if (ost->filters)
1805 return av_strdup(ost->filters);
1806
1807 return av_strdup(st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO ?
1808 "null" : "anull");
1809}
1810
1811void check_streamcopy_filters(OptionsContext *o, AVFormatContext *oc,
1812 const OutputStream *ost, enum AVMediaType type)
1813{
1814 if (ost->filters_script || ost->filters) {
1815 av_log(NULL, AV_LOG_ERROR,
1816 "%s '%s' was defined for %s output stream %d:%d but codec copy was selected.\n"
1817 "Filtering and streamcopy cannot be used together.\n",
1818 ost->filters ? "Filtergraph" : "Filtergraph script",
1819 ost->filters ? ost->filters : ost->filters_script,
1820 av_get_media_type_string(type), ost->file_index, ost->index);
1821 exit_program(1);
1822 }
1823}
1824
1825OutputStream *new_video_stream(OptionsContext *o, AVFormatContext *oc, int source_index)
1826{
1827 AVStream *st;
1828 OutputStream *ost;
1829 AVCodecContext *video_enc;
1830 char *frame_rate = NULL, *max_frame_rate = NULL, *frame_aspect_ratio = NULL;
1831
1832 ost = new_output_stream(o, oc, AVMEDIA_TYPE_VIDEO, source_index);
1833 st = ost->st;
1834 video_enc = ost->enc_ctx;
1835
1836 MATCH_PER_STREAM_OPT(frame_rates, str, frame_rate, oc, st);
1837 if (frame_rate && av_parse_video_rate(&ost->frame_rate, frame_rate) < 0) {
1838 av_log(NULL, AV_LOG_FATAL, "Invalid framerate value: %s\n", frame_rate);
1839 exit_program(1);
1840 }
1841
1842 MATCH_PER_STREAM_OPT(max_frame_rates, str, max_frame_rate, oc, st);
1843 if (max_frame_rate && av_parse_video_rate(&ost->max_frame_rate, max_frame_rate) < 0) {
1844 av_log(NULL, AV_LOG_FATAL, "Invalid maximum framerate value: %s\n", max_frame_rate);
1845 exit_program(1);
1846 }
1847
1848 if (frame_rate && max_frame_rate) {
1849 av_log(NULL, AV_LOG_ERROR, "Only one of -fpsmax and -r can be set for a stream.\n");
1850 exit_program(1);
1851 }
1852
1853 if ((frame_rate || max_frame_rate) &&
1855 av_log(NULL, AV_LOG_ERROR, "Using -vsync passthrough and -r/-fpsmax can produce invalid output files\n");
1856
1857 MATCH_PER_STREAM_OPT(frame_aspect_ratios, str, frame_aspect_ratio, oc, st);
1858 if (frame_aspect_ratio) {
1859 AVRational q;
1860 if (av_parse_ratio(&q, frame_aspect_ratio, 255, 0, NULL) < 0 ||
1861 q.num <= 0 || q.den <= 0) {
1862 av_log(NULL, AV_LOG_FATAL, "Invalid aspect ratio: %s\n", frame_aspect_ratio);
1863 exit_program(1);
1864 }
1865 ost->frame_aspect_ratio = q;
1866 }
1867
1868 MATCH_PER_STREAM_OPT(filter_scripts, str, ost->filters_script, oc, st);
1869 MATCH_PER_STREAM_OPT(filters, str, ost->filters, oc, st);
1870
1871 if (!ost->stream_copy) {
1872 const char *p = NULL;
1873 char *frame_size = NULL;
1874 char *frame_pix_fmt = NULL;
1875 char *intra_matrix = NULL, *inter_matrix = NULL;
1876 char *chroma_intra_matrix = NULL;
1877 int do_pass = 0;
1878 int i;
1879
1880 MATCH_PER_STREAM_OPT(frame_sizes, str, frame_size, oc, st);
1881 if (frame_size && av_parse_video_size(&video_enc->width, &video_enc->height, frame_size) < 0) {
1882 av_log(NULL, AV_LOG_FATAL, "Invalid frame size: %s.\n", frame_size);
1883 exit_program(1);
1884 }
1885
1886 MATCH_PER_STREAM_OPT(frame_pix_fmts, str, frame_pix_fmt, oc, st);
1887 if (frame_pix_fmt && *frame_pix_fmt == '+') {
1888 ost->keep_pix_fmt = 1;
1889 if (!*++frame_pix_fmt)
1890 frame_pix_fmt = NULL;
1891 }
1892 if (frame_pix_fmt && (video_enc->pix_fmt = av_get_pix_fmt(frame_pix_fmt)) == AV_PIX_FMT_NONE) {
1893 av_log(NULL, AV_LOG_FATAL, "Unknown pixel format requested: %s.\n", frame_pix_fmt);
1894 exit_program(1);
1895 }
1896 st->sample_aspect_ratio = video_enc->sample_aspect_ratio;
1897
1898 MATCH_PER_STREAM_OPT(intra_matrices, str, intra_matrix, oc, st);
1899 if (intra_matrix) {
1900 if (!(video_enc->intra_matrix = av_mallocz(sizeof(*video_enc->intra_matrix) * 64))) {
1901 av_log(NULL, AV_LOG_FATAL, "Could not allocate memory for intra matrix.\n");
1902 exit_program(1);
1903 }
1904 parse_matrix_coeffs(video_enc->intra_matrix, intra_matrix);
1905 }
1906 MATCH_PER_STREAM_OPT(chroma_intra_matrices, str, chroma_intra_matrix, oc, st);
1907 if (chroma_intra_matrix) {
1908 uint16_t *p = av_mallocz(sizeof(*video_enc->chroma_intra_matrix) * 64);
1909 if (!p) {
1910 av_log(NULL, AV_LOG_FATAL, "Could not allocate memory for intra matrix.\n");
1911 exit_program(1);
1912 }
1913 video_enc->chroma_intra_matrix = p;
1914 parse_matrix_coeffs(p, chroma_intra_matrix);
1915 }
1916 MATCH_PER_STREAM_OPT(inter_matrices, str, inter_matrix, oc, st);
1917 if (inter_matrix) {
1918 if (!(video_enc->inter_matrix = av_mallocz(sizeof(*video_enc->inter_matrix) * 64))) {
1919 av_log(NULL, AV_LOG_FATAL, "Could not allocate memory for inter matrix.\n");
1920 exit_program(1);
1921 }
1922 parse_matrix_coeffs(video_enc->inter_matrix, inter_matrix);
1923 }
1924
1925 MATCH_PER_STREAM_OPT(rc_overrides, str, p, oc, st);
1926 for (i = 0; p; i++) {
1927 int start, end, q;
1928 int e = sscanf(p, "%d,%d,%d", &start, &end, &q);
1929 if (e != 3) {
1930 av_log(NULL, AV_LOG_FATAL, "error parsing rc_override\n");
1931 exit_program(1);
1932 }
1933 video_enc->rc_override =
1934 av_realloc_array(video_enc->rc_override,
1935 i + 1, sizeof(RcOverride));
1936 if (!video_enc->rc_override) {
1937 av_log(NULL, AV_LOG_FATAL, "Could not (re)allocate memory for rc_override.\n");
1938 exit_program(1);
1939 }
1940 video_enc->rc_override[i].start_frame = start;
1941 video_enc->rc_override[i].end_frame = end;
1942 if (q > 0) {
1943 video_enc->rc_override[i].qscale = q;
1944 video_enc->rc_override[i].quality_factor = 1.0;
1945 }
1946 else {
1947 video_enc->rc_override[i].qscale = 0;
1948 video_enc->rc_override[i].quality_factor = -q/100.0;
1949 }
1950 p = strchr(p, '/');
1951 if (p) p++;
1952 }
1953 video_enc->rc_override_count = i;
1954
1955 if (do_psnr)
1956 video_enc->flags|= AV_CODEC_FLAG_PSNR;
1957
1958 /* two pass mode */
1959 MATCH_PER_STREAM_OPT(pass, i, do_pass, oc, st);
1960 if (do_pass) {
1961 if (do_pass & 1) {
1962 video_enc->flags |= AV_CODEC_FLAG_PASS1;
1963 av_dict_set(&ost->encoder_opts, "flags", "+pass1", AV_DICT_APPEND);
1964 }
1965 if (do_pass & 2) {
1966 video_enc->flags |= AV_CODEC_FLAG_PASS2;
1967 av_dict_set(&ost->encoder_opts, "flags", "+pass2", AV_DICT_APPEND);
1968 }
1969 }
1970
1971 MATCH_PER_STREAM_OPT(passlogfiles, str, ost->logfile_prefix, oc, st);
1972 if (ost->logfile_prefix &&
1973 !(ost->logfile_prefix = av_strdup(ost->logfile_prefix)))
1974 exit_program(1);
1975
1976 if (do_pass) {
1977 char logfilename[1024];
1978 FILE *f;
1979
1980 snprintf(logfilename, sizeof(logfilename), "%s-%d.log",
1981 ost->logfile_prefix ? ost->logfile_prefix :
1983 nb_output_streams - 1);
1984 if (!strcmp(ost->enc->name, "libx264")) {
1985 av_dict_set(&ost->encoder_opts, "stats", logfilename, AV_DICT_DONT_OVERWRITE);
1986 } else {
1987 if (video_enc->flags & AV_CODEC_FLAG_PASS2) {
1988 char *logbuffer = fftools_read_file(logfilename);
1989
1990 if (!logbuffer) {
1991 av_log(NULL, AV_LOG_FATAL, "Error reading log file '%s' for pass-2 encoding\n",
1992 logfilename);
1993 exit_program(1);
1994 }
1995 video_enc->stats_in = logbuffer;
1996 }
1997 if (video_enc->flags & AV_CODEC_FLAG_PASS1) {
1998 f = fopen_utf8(logfilename, "wb");
1999 if (!f) {
2000 av_log(NULL, AV_LOG_FATAL,
2001 "Cannot write log file '%s' for pass-1 encoding: %s\n",
2002 logfilename, strerror(errno));
2003 exit_program(1);
2004 }
2005 ost->logfile = f;
2006 }
2007 }
2008 }
2009
2010 MATCH_PER_STREAM_OPT(forced_key_frames, str, ost->forced_keyframes, oc, st);
2011 if (ost->forced_keyframes)
2012 ost->forced_keyframes = av_strdup(ost->forced_keyframes);
2013
2014 MATCH_PER_STREAM_OPT(force_fps, i, ost->force_fps, oc, st);
2015
2016 ost->top_field_first = -1;
2017 MATCH_PER_STREAM_OPT(top_field_first, i, ost->top_field_first, oc, st);
2018
2020 MATCH_PER_STREAM_OPT(fps_mode, str, ost->fps_mode, oc, st);
2021 if (ost->fps_mode)
2022 parse_and_set_vsync(ost->fps_mode, &ost->vsync_method, ost->file_index, ost->index, 0);
2023
2024 if (ost->vsync_method == VSYNC_AUTO) {
2025 if (!strcmp(oc->oformat->name, "avi")) {
2026 ost->vsync_method = VSYNC_VFR;
2027 } else {
2028 ost->vsync_method = (oc->oformat->flags & AVFMT_VARIABLE_FPS) ?
2029 ((oc->oformat->flags & AVFMT_NOTIMESTAMPS) ?
2031 VSYNC_CFR;
2032 }
2033
2034 if (ost->source_index >= 0 && ost->vsync_method == VSYNC_CFR) {
2035 const InputStream *ist = input_streams[ost->source_index];
2036 const InputFile *ifile = input_files[ist->file_index];
2037
2038 if (ifile->nb_streams == 1 && ifile->input_ts_offset == 0)
2040 }
2041
2042 if (ost->vsync_method == VSYNC_CFR && copy_ts) {
2044 }
2045 }
2046 ost->is_cfr = (ost->vsync_method == VSYNC_CFR || ost->vsync_method == VSYNC_VSCFR);
2047
2048 ost->avfilter = get_ost_filters(o, oc, ost);
2049 if (!ost->avfilter)
2050 exit_program(1);
2051
2052 ost->last_frame = av_frame_alloc();
2053 if (!ost->last_frame)
2054 exit_program(1);
2055 }
2056
2057 if (ost->stream_copy)
2058 check_streamcopy_filters(o, oc, ost, AVMEDIA_TYPE_VIDEO);
2059
2060 return ost;
2061}
2062
2063OutputStream *new_audio_stream(OptionsContext *o, AVFormatContext *oc, int source_index)
2064{
2065 int n;
2066 AVStream *st;
2067 OutputStream *ost;
2068 AVCodecContext *audio_enc;
2069
2070 ost = new_output_stream(o, oc, AVMEDIA_TYPE_AUDIO, source_index);
2071 st = ost->st;
2072
2073 audio_enc = ost->enc_ctx;
2074 audio_enc->codec_type = AVMEDIA_TYPE_AUDIO;
2075
2076 MATCH_PER_STREAM_OPT(filter_scripts, str, ost->filters_script, oc, st);
2077 MATCH_PER_STREAM_OPT(filters, str, ost->filters, oc, st);
2078
2079 if (!ost->stream_copy) {
2080 int channels = 0;
2081 char *layout = NULL;
2082 char *sample_fmt = NULL;
2083
2084 MATCH_PER_STREAM_OPT(audio_channels, i, channels, oc, st);
2085 if (channels) {
2086 audio_enc->ch_layout.order = AV_CHANNEL_ORDER_UNSPEC;
2087 audio_enc->ch_layout.nb_channels = channels;
2088 }
2089
2090 MATCH_PER_STREAM_OPT(audio_ch_layouts, str, layout, oc, st);
2091 if (layout) {
2092 if (av_channel_layout_from_string(&audio_enc->ch_layout, layout) < 0) {
2093#if FF_API_OLD_CHANNEL_LAYOUT
2094 uint64_t mask;
2095 AV_NOWARN_DEPRECATED({
2096 mask = av_get_channel_layout(layout);
2097 })
2098 if (!mask) {
2099#endif
2100 av_log(NULL, AV_LOG_FATAL, "Unknown channel layout: %s\n", layout);
2101 exit_program(1);
2102#if FF_API_OLD_CHANNEL_LAYOUT
2103 }
2104 av_log(NULL, AV_LOG_WARNING, "Channel layout '%s' uses a deprecated syntax.\n",
2105 layout);
2106 av_channel_layout_from_mask(&audio_enc->ch_layout, mask);
2107#endif
2108 }
2109 }
2110
2111 MATCH_PER_STREAM_OPT(sample_fmts, str, sample_fmt, oc, st);
2112 if (sample_fmt &&
2113 (audio_enc->sample_fmt = av_get_sample_fmt(sample_fmt)) == AV_SAMPLE_FMT_NONE) {
2114 av_log(NULL, AV_LOG_FATAL, "Invalid sample format '%s'\n", sample_fmt);
2115 exit_program(1);
2116 }
2117
2118 MATCH_PER_STREAM_OPT(audio_sample_rate, i, audio_enc->sample_rate, oc, st);
2119
2120 MATCH_PER_STREAM_OPT(apad, str, ost->apad, oc, st);
2121 ost->apad = av_strdup(ost->apad);
2122
2123 ost->avfilter = get_ost_filters(o, oc, ost);
2124 if (!ost->avfilter)
2125 exit_program(1);
2126
2127 /* check for channel mapping for this audio stream */
2128 for (n = 0; n < o->nb_audio_channel_maps; n++) {
2129 AudioChannelMap *map = &o->audio_channel_maps[n];
2130 if ((map->ofile_idx == -1 || ost->file_index == map->ofile_idx) &&
2131 (map->ostream_idx == -1 || ost->st->index == map->ostream_idx)) {
2132 InputStream *ist;
2133
2134 if (map->channel_idx == -1) {
2135 ist = NULL;
2136 } else if (ost->source_index < 0) {
2137 av_log(NULL, AV_LOG_FATAL, "Cannot determine input stream for channel mapping %d.%d\n",
2138 ost->file_index, ost->st->index);
2139 continue;
2140 } else {
2141 ist = input_streams[ost->source_index];
2142 }
2143
2144 if (!ist || (ist->file_index == map->file_idx && ist->st->index == map->stream_idx)) {
2145 if (av_reallocp_array(&ost->audio_channels_map,
2146 ost->audio_channels_mapped + 1,
2147 sizeof(*ost->audio_channels_map)
2148 ) < 0 )
2149 exit_program(1);
2150
2152 }
2153 }
2154 }
2155 }
2156
2157 if (ost->stream_copy)
2158 check_streamcopy_filters(o, oc, ost, AVMEDIA_TYPE_AUDIO);
2159
2160 return ost;
2161}
2162
2163OutputStream *new_data_stream(OptionsContext *o, AVFormatContext *oc, int source_index)
2164{
2165 OutputStream *ost;
2166
2167 ost = new_output_stream(o, oc, AVMEDIA_TYPE_DATA, source_index);
2168 if (!ost->stream_copy) {
2169 av_log(NULL, AV_LOG_FATAL, "Data stream encoding not supported yet (only streamcopy)\n");
2170 exit_program(1);
2171 }
2172
2173 return ost;
2174}
2175
2176OutputStream *new_unknown_stream(OptionsContext *o, AVFormatContext *oc, int source_index)
2177{
2178 OutputStream *ost;
2179
2180 ost = new_output_stream(o, oc, AVMEDIA_TYPE_UNKNOWN, source_index);
2181 if (!ost->stream_copy) {
2182 av_log(NULL, AV_LOG_FATAL, "Unknown stream encoding not supported yet (only streamcopy)\n");
2183 exit_program(1);
2184 }
2185
2186 return ost;
2187}
2188
2189OutputStream *new_attachment_stream(OptionsContext *o, AVFormatContext *oc, int source_index)
2190{
2191 OutputStream *ost = new_output_stream(o, oc, AVMEDIA_TYPE_ATTACHMENT, source_index);
2192 ost->stream_copy = 1;
2193 ost->finished = 1;
2194 return ost;
2195}
2196
2197OutputStream *new_subtitle_stream(OptionsContext *o, AVFormatContext *oc, int source_index)
2198{
2199 AVStream *st;
2200 OutputStream *ost;
2201 AVCodecContext *subtitle_enc;
2202
2203 ost = new_output_stream(o, oc, AVMEDIA_TYPE_SUBTITLE, source_index);
2204 st = ost->st;
2205 subtitle_enc = ost->enc_ctx;
2206
2207 subtitle_enc->codec_type = AVMEDIA_TYPE_SUBTITLE;
2208
2209 if (!ost->stream_copy) {
2210 char *frame_size = NULL;
2211
2212 MATCH_PER_STREAM_OPT(frame_sizes, str, frame_size, oc, st);
2213 if (frame_size && av_parse_video_size(&subtitle_enc->width, &subtitle_enc->height, frame_size) < 0) {
2214 av_log(NULL, AV_LOG_FATAL, "Invalid frame size: %s.\n", frame_size);
2215 exit_program(1);
2216 }
2217 }
2218
2219 return ost;
2220}
2221
2222/* arg format is "output-stream-index:streamid-value". */
2223int opt_streamid(void *optctx, const char *opt, const char *arg)
2224{
2225 OptionsContext *o = optctx;
2226 int idx;
2227 char *p;
2228 char idx_str[16];
2229
2230 av_strlcpy(idx_str, arg, sizeof(idx_str));
2231 p = strchr(idx_str, ':');
2232 if (!p) {
2233 av_log(NULL, AV_LOG_FATAL,
2234 "Invalid value '%s' for option '%s', required syntax is 'index:value'\n",
2235 arg, opt);
2236 exit_program(1);
2237 }
2238 *p++ = '\0';
2239 idx = parse_number_or_die(opt, idx_str, OPT_INT, 0, MAX_STREAMS-1);
2240 o->streamid_map = grow_array(o->streamid_map, sizeof(*o->streamid_map), &o->nb_streamid_map, idx+1);
2241 o->streamid_map[idx] = parse_number_or_die(opt, p, OPT_INT, 0, INT_MAX);
2242 return 0;
2243}
2244
2245int copy_chapters(InputFile *ifile, OutputFile *ofile, AVFormatContext *os,
2246 int copy_metadata)
2247{
2248 AVFormatContext *is = ifile->ctx;
2249 AVChapter **tmp;
2250 int i;
2251
2252 tmp = av_realloc_f(os->chapters, is->nb_chapters + os->nb_chapters, sizeof(*os->chapters));
2253 if (!tmp)
2254 return AVERROR(ENOMEM);
2255 os->chapters = tmp;
2256
2257 for (i = 0; i < is->nb_chapters; i++) {
2258 AVChapter *in_ch = is->chapters[i], *out_ch;
2259 int64_t start_time = (ofile->start_time == AV_NOPTS_VALUE) ? 0 : ofile->start_time;
2260 int64_t ts_off = av_rescale_q(start_time - ifile->ts_offset,
2261 AV_TIME_BASE_Q, in_ch->time_base);
2262 int64_t rt = (ofile->recording_time == INT64_MAX) ? INT64_MAX :
2263 av_rescale_q(ofile->recording_time, AV_TIME_BASE_Q, in_ch->time_base);
2264
2265
2266 if (in_ch->end < ts_off)
2267 continue;
2268 if (rt != INT64_MAX && in_ch->start > rt + ts_off)
2269 break;
2270
2271 out_ch = av_mallocz(sizeof(AVChapter));
2272 if (!out_ch)
2273 return AVERROR(ENOMEM);
2274
2275 out_ch->id = in_ch->id;
2276 out_ch->time_base = in_ch->time_base;
2277 out_ch->start = FFMAX(0, in_ch->start - ts_off);
2278 out_ch->end = FFMIN(rt, in_ch->end - ts_off);
2279
2280 if (copy_metadata)
2281 av_dict_copy(&out_ch->metadata, in_ch->metadata, 0);
2282
2283 os->chapters[os->nb_chapters++] = out_ch;
2284 }
2285 return 0;
2286}
2287
2288int set_dispositions(OutputFile *of, AVFormatContext *ctx)
2289{
2290 int nb_streams[AVMEDIA_TYPE_NB] = { 0 };
2291 int have_default[AVMEDIA_TYPE_NB] = { 0 };
2292 int have_manual = 0;
2293
2294 // first, copy the input dispositions
2295 for (int i = 0; i < ctx->nb_streams; i++) {
2296 OutputStream *ost = output_streams[of->ost_index + i];
2297
2298 nb_streams[ost->st->codecpar->codec_type]++;
2299
2300 have_manual |= !!ost->disposition;
2301
2302 if (ost->source_index >= 0) {
2303 ost->st->disposition = input_streams[ost->source_index]->st->disposition;
2304
2305 if (ost->st->disposition & AV_DISPOSITION_DEFAULT)
2306 have_default[ost->st->codecpar->codec_type] = 1;
2307 }
2308 }
2309
2310 if (have_manual) {
2311 // process manually set dispositions - they override the above copy
2312 for (int i = 0; i < ctx->nb_streams; i++) {
2313 OutputStream *ost = output_streams[of->ost_index + i];
2314 int ret;
2315
2316 if (!ost->disposition)
2317 continue;
2318
2319#if LIBAVFORMAT_VERSION_MAJOR >= 60
2320 ret = av_opt_set(ost->st, "disposition", ost->disposition, 0);
2321#else
2322 {
2323 const AVClass *class = av_stream_get_class();
2324 const AVOption *o = av_opt_find(&class, "disposition", NULL, 0, AV_OPT_SEARCH_FAKE_OBJ);
2325
2326 av_assert0(o);
2327 ret = av_opt_eval_flags(&class, o, ost->disposition, &ost->st->disposition);
2328 }
2329#endif
2330
2331 if (ret < 0)
2332 return ret;
2333 }
2334 } else {
2335 // For each media type with more than one stream, find a suitable stream to
2336 // mark as default, unless one is already marked default.
2337 // "Suitable" means the first of that type, skipping attached pictures.
2338 for (int i = 0; i < ctx->nb_streams; i++) {
2339 OutputStream *ost = output_streams[of->ost_index + i];
2340 enum AVMediaType type = ost->st->codecpar->codec_type;
2341
2342 if (nb_streams[type] < 2 || have_default[type] ||
2343 ost->st->disposition & AV_DISPOSITION_ATTACHED_PIC)
2344 continue;
2345
2346 ost->st->disposition |= AV_DISPOSITION_DEFAULT;
2347 have_default[type] = 1;
2348 }
2349 }
2350
2351 return 0;
2352}
2353
2355 AVFormatContext *oc)
2356{
2357 OutputStream *ost;
2358
2359 switch (ofilter->type) {
2360 case AVMEDIA_TYPE_VIDEO: ost = new_video_stream(o, oc, -1); break;
2361 case AVMEDIA_TYPE_AUDIO: ost = new_audio_stream(o, oc, -1); break;
2362 default:
2363 av_log(NULL, AV_LOG_FATAL, "Only video and audio filters are supported "
2364 "currently.\n");
2365 exit_program(1);
2366 }
2367
2368 ost->filter = ofilter;
2369
2370 ofilter->ost = ost;
2371 ofilter->format = -1;
2372
2373 if (ost->stream_copy) {
2374 av_log(NULL, AV_LOG_ERROR, "Streamcopy requested for output stream %d:%d, "
2375 "which is fed from a complex filtergraph. Filtering and streamcopy "
2376 "cannot be used together.\n", ost->file_index, ost->index);
2377 exit_program(1);
2378 }
2379
2380 if (ost->avfilter && (ost->filters || ost->filters_script)) {
2381 const char *opt = ost->filters ? "-vf/-af/-filter" : "-filter_script";
2382 av_log(NULL, AV_LOG_ERROR,
2383 "%s '%s' was specified through the %s option "
2384 "for output stream %d:%d, which is fed from a complex filtergraph.\n"
2385 "%s and -filter_complex cannot be used together for the same stream.\n",
2386 ost->filters ? "Filtergraph" : "Filtergraph script",
2387 ost->filters ? ost->filters : ost->filters_script,
2388 opt, ost->file_index, ost->index, opt);
2389 exit_program(1);
2390 }
2391
2392 avfilter_inout_free(&ofilter->out_tmp);
2393}
2394
2396{
2397 int i, ret = 0;
2398
2399 for (i = 0; i < nb_filtergraphs; i++) {
2401 if (ret < 0)
2402 return ret;
2403 }
2404 return 0;
2405}
2406
2408{
2409 int i, err;
2410
2411 if (ost->enc_ctx->ch_layout.order != AV_CHANNEL_ORDER_UNSPEC) {
2412 /* Pass the layout through for all orders but UNSPEC */
2413 err = av_channel_layout_copy(&f->ch_layout, &ost->enc_ctx->ch_layout);
2414 if (err < 0)
2415 exit_program(1);
2416 return;
2417 }
2418
2419 /* Requested layout is of order UNSPEC */
2420 if (!ost->enc->ch_layouts) {
2421 /* Use the default native layout for the requested amount of channels when the
2422 encoder doesn't have a list of supported layouts */
2423 av_channel_layout_default(&f->ch_layout, ost->enc_ctx->ch_layout.nb_channels);
2424 return;
2425 }
2426 /* Encoder has a list of supported layouts. Pick the first layout in it with the
2427 same amount of channels as the requested layout */
2428 for (i = 0; ost->enc->ch_layouts[i].nb_channels; i++) {
2429 if (ost->enc->ch_layouts[i].nb_channels == ost->enc_ctx->ch_layout.nb_channels)
2430 break;
2431 }
2432 if (ost->enc->ch_layouts[i].nb_channels) {
2433 /* Use it if one is found */
2434 err = av_channel_layout_copy(&f->ch_layout, &ost->enc->ch_layouts[i]);
2435 if (err < 0)
2436 exit_program(1);
2437 return;
2438 }
2439 /* If no layout for the amount of channels requested was found, use the default
2440 native layout for it. */
2441 av_channel_layout_default(&f->ch_layout, ost->enc_ctx->ch_layout.nb_channels);
2442}
2443
2444int open_output_file(OptionsContext *o, const char *filename)
2445{
2446 AVFormatContext *oc;
2447 int i, j, err;
2448 OutputFile *of;
2449 OutputStream *ost;
2450 InputStream *ist;
2451 AVDictionary *unused_opts = NULL;
2452 const AVDictionaryEntry *e = NULL;
2453
2454 if (o->stop_time != INT64_MAX && o->recording_time != INT64_MAX) {
2455 o->stop_time = INT64_MAX;
2456 av_log(NULL, AV_LOG_WARNING, "-t and -to cannot be used together; using -t.\n");
2457 }
2458
2459 if (o->stop_time != INT64_MAX && o->recording_time == INT64_MAX) {
2460 int64_t start_time = o->start_time == AV_NOPTS_VALUE ? 0 : o->start_time;
2461 if (o->stop_time <= start_time) {
2462 av_log(NULL, AV_LOG_ERROR, "-to value smaller than -ss; aborting.\n");
2463 exit_program(1);
2464 } else {
2465 o->recording_time = o->stop_time - start_time;
2466 }
2467 }
2468
2470
2471 of->index = nb_output_files - 1;
2474 of->start_time = o->start_time;
2476 of->shortest = o->shortest;
2477 av_dict_copy(&of->opts, o->g->format_opts, 0);
2478
2479 if (!strcmp(filename, "-"))
2480 filename = "pipe:";
2481
2482 err = avformat_alloc_output_context2(&oc, NULL, o->format, filename);
2483 if (!oc) {
2484 print_error(filename, err);
2485 exit_program(1);
2486 }
2487
2488 of->ctx = oc;
2489 of->format = oc->oformat;
2490 if (o->recording_time != INT64_MAX)
2491 oc->duration = o->recording_time;
2492
2493 oc->interrupt_callback = int_cb;
2494
2495 if (o->bitexact) {
2496 oc->flags |= AVFMT_FLAG_BITEXACT;
2497 }
2498
2499 /* create streams for all unlabeled output pads */
2500 for (i = 0; i < nb_filtergraphs; i++) {
2501 FilterGraph *fg = filtergraphs[i];
2502 for (j = 0; j < fg->nb_outputs; j++) {
2503 OutputFilter *ofilter = fg->outputs[j];
2504
2505 if (!ofilter->out_tmp || ofilter->out_tmp->name)
2506 continue;
2507
2508 switch (ofilter->type) {
2509 case AVMEDIA_TYPE_VIDEO: o->video_disable = 1; break;
2510 case AVMEDIA_TYPE_AUDIO: o->audio_disable = 1; break;
2511 case AVMEDIA_TYPE_SUBTITLE: o->subtitle_disable = 1; break;
2512 }
2513 init_output_filter(ofilter, o, oc);
2514 }
2515 }
2516
2517 if (!o->nb_stream_maps) {
2518 char *subtitle_codec_name = NULL;
2519 /* pick the "best" stream of each type */
2520
2521 /* video: highest resolution */
2522 if (!o->video_disable && av_guess_codec(oc->oformat, NULL, filename, NULL, AVMEDIA_TYPE_VIDEO) != AV_CODEC_ID_NONE) {
2523 int best_score = 0, idx = -1;
2524 int qcr = avformat_query_codec(oc->oformat, oc->oformat->video_codec, 0);
2525 for (j = 0; j < nb_input_files; j++) {
2526 InputFile *ifile = input_files[j];
2527 int file_best_score = 0, file_best_idx = -1;
2528 for (i = 0; i < ifile->nb_streams; i++) {
2529 int score;
2530 ist = input_streams[ifile->ist_index + i];
2531 score = ist->st->codecpar->width * ist->st->codecpar->height
2532 + 100000000 * !!(ist->st->event_flags & AVSTREAM_EVENT_FLAG_NEW_PACKETS)
2533 + 5000000*!!(ist->st->disposition & AV_DISPOSITION_DEFAULT);
2534 if (ist->user_set_discard == AVDISCARD_ALL)
2535 continue;
2536 if((qcr!=MKTAG('A', 'P', 'I', 'C')) && (ist->st->disposition & AV_DISPOSITION_ATTACHED_PIC))
2537 score = 1;
2538 if (ist->st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO &&
2539 score > file_best_score) {
2540 if((qcr==MKTAG('A', 'P', 'I', 'C')) && !(ist->st->disposition & AV_DISPOSITION_ATTACHED_PIC))
2541 continue;
2542 file_best_score = score;
2543 file_best_idx = ifile->ist_index + i;
2544 }
2545 }
2546 if (file_best_idx >= 0) {
2547 if((qcr == MKTAG('A', 'P', 'I', 'C')) || !(ist->st->disposition & AV_DISPOSITION_ATTACHED_PIC))
2548 file_best_score -= 5000000*!!(input_streams[file_best_idx]->st->disposition & AV_DISPOSITION_DEFAULT);
2549 if (file_best_score > best_score) {
2550 best_score = file_best_score;
2551 idx = file_best_idx;
2552 }
2553 }
2554 }
2555 if (idx >= 0)
2556 new_video_stream(o, oc, idx);
2557 }
2558
2559 /* audio: most channels */
2560 if (!o->audio_disable && av_guess_codec(oc->oformat, NULL, filename, NULL, AVMEDIA_TYPE_AUDIO) != AV_CODEC_ID_NONE) {
2561 int best_score = 0, idx = -1;
2562 for (j = 0; j < nb_input_files; j++) {
2563 InputFile *ifile = input_files[j];
2564 int file_best_score = 0, file_best_idx = -1;
2565 for (i = 0; i < ifile->nb_streams; i++) {
2566 int score;
2567 ist = input_streams[ifile->ist_index + i];
2568 score = ist->st->codecpar->ch_layout.nb_channels
2569 + 100000000 * !!(ist->st->event_flags & AVSTREAM_EVENT_FLAG_NEW_PACKETS)
2570 + 5000000*!!(ist->st->disposition & AV_DISPOSITION_DEFAULT);
2571 if (ist->user_set_discard == AVDISCARD_ALL)
2572 continue;
2573 if (ist->st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO &&
2574 score > file_best_score) {
2575 file_best_score = score;
2576 file_best_idx = ifile->ist_index + i;
2577 }
2578 }
2579 if (file_best_idx >= 0) {
2580 file_best_score -= 5000000*!!(input_streams[file_best_idx]->st->disposition & AV_DISPOSITION_DEFAULT);
2581 if (file_best_score > best_score) {
2582 best_score = file_best_score;
2583 idx = file_best_idx;
2584 }
2585 }
2586 }
2587 if (idx >= 0)
2588 new_audio_stream(o, oc, idx);
2589 }
2590
2591 /* subtitles: pick first */
2592 MATCH_PER_TYPE_OPT(codec_names, str, subtitle_codec_name, oc, "s");
2593 if (!o->subtitle_disable && (avcodec_find_encoder(oc->oformat->subtitle_codec) || subtitle_codec_name)) {
2594 for (i = 0; i < nb_input_streams; i++)
2595 if (input_streams[i]->st->codecpar->codec_type == AVMEDIA_TYPE_SUBTITLE) {
2596 AVCodecDescriptor const *input_descriptor =
2597 avcodec_descriptor_get(input_streams[i]->st->codecpar->codec_id);
2598 AVCodecDescriptor const *output_descriptor = NULL;
2599 AVCodec const *output_codec =
2600 avcodec_find_encoder(oc->oformat->subtitle_codec);
2601 int input_props = 0, output_props = 0;
2602 if (input_streams[i]->user_set_discard == AVDISCARD_ALL)
2603 continue;
2604 if (output_codec)
2605 output_descriptor = avcodec_descriptor_get(output_codec->id);
2606 if (input_descriptor)
2607 input_props = input_descriptor->props & (AV_CODEC_PROP_TEXT_SUB | AV_CODEC_PROP_BITMAP_SUB);
2608 if (output_descriptor)
2609 output_props = output_descriptor->props & (AV_CODEC_PROP_TEXT_SUB | AV_CODEC_PROP_BITMAP_SUB);
2610 if (subtitle_codec_name ||
2611 input_props & output_props ||
2612 // Map dvb teletext which has neither property to any output subtitle encoder
2613 (input_descriptor && output_descriptor &&
2614 (!input_descriptor->props ||
2615 !output_descriptor->props))) {
2616 new_subtitle_stream(o, oc, i);
2617 break;
2618 }
2619 }
2620 }
2621 /* Data only if codec id match */
2622 if (!o->data_disable ) {
2623 enum AVCodecID codec_id = av_guess_codec(oc->oformat, NULL, filename, NULL, AVMEDIA_TYPE_DATA);
2624 for (i = 0; codec_id != AV_CODEC_ID_NONE && i < nb_input_streams; i++) {
2625 if (input_streams[i]->user_set_discard == AVDISCARD_ALL)
2626 continue;
2627 if (input_streams[i]->st->codecpar->codec_type == AVMEDIA_TYPE_DATA
2628 && input_streams[i]->st->codecpar->codec_id == codec_id )
2629 new_data_stream(o, oc, i);
2630 }
2631 }
2632 } else {
2633 for (i = 0; i < o->nb_stream_maps; i++) {
2634 StreamMap *map = &o->stream_maps[i];
2635
2636 if (map->disabled)
2637 continue;
2638
2639 if (map->linklabel) {
2640 FilterGraph *fg;
2641 OutputFilter *ofilter = NULL;
2642 int j, k;
2643
2644 for (j = 0; j < nb_filtergraphs; j++) {
2645 fg = filtergraphs[j];
2646 for (k = 0; k < fg->nb_outputs; k++) {
2647 AVFilterInOut *out = fg->outputs[k]->out_tmp;
2648 if (out && !strcmp(out->name, map->linklabel)) {
2649 ofilter = fg->outputs[k];
2650 goto loop_end;
2651 }
2652 }
2653 }
2654loop_end:
2655 if (!ofilter) {
2656 av_log(NULL, AV_LOG_FATAL, "Output with label '%s' does not exist "
2657 "in any defined filter graph, or was already used elsewhere.\n", map->linklabel);
2658 exit_program(1);
2659 }
2660 init_output_filter(ofilter, o, oc);
2661 } else {
2662 int src_idx = input_files[map->file_index]->ist_index + map->stream_index;
2663
2665 if (ist->user_set_discard == AVDISCARD_ALL) {
2666 av_log(NULL, AV_LOG_FATAL, "Stream #%d:%d is disabled and cannot be mapped.\n",
2667 map->file_index, map->stream_index);
2668 exit_program(1);
2669 }
2670 if(o->subtitle_disable && ist->st->codecpar->codec_type == AVMEDIA_TYPE_SUBTITLE)
2671 continue;
2672 if(o-> audio_disable && ist->st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO)
2673 continue;
2674 if(o-> video_disable && ist->st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO)
2675 continue;
2676 if(o-> data_disable && ist->st->codecpar->codec_type == AVMEDIA_TYPE_DATA)
2677 continue;
2678
2679 ost = NULL;
2680 switch (ist->st->codecpar->codec_type) {
2681 case AVMEDIA_TYPE_VIDEO: ost = new_video_stream (o, oc, src_idx); break;
2682 case AVMEDIA_TYPE_AUDIO: ost = new_audio_stream (o, oc, src_idx); break;
2683 case AVMEDIA_TYPE_SUBTITLE: ost = new_subtitle_stream (o, oc, src_idx); break;
2684 case AVMEDIA_TYPE_DATA: ost = new_data_stream (o, oc, src_idx); break;
2685 case AVMEDIA_TYPE_ATTACHMENT: ost = new_attachment_stream(o, oc, src_idx); break;
2686 case AVMEDIA_TYPE_UNKNOWN:
2688 ost = new_unknown_stream (o, oc, src_idx);
2689 break;
2690 }
2691 default:
2692 av_log(NULL, ignore_unknown_streams ? AV_LOG_WARNING : AV_LOG_FATAL,
2693 "Cannot map stream #%d:%d - unsupported type.\n",
2694 map->file_index, map->stream_index);
2696 av_log(NULL, AV_LOG_FATAL,
2697 "If you want unsupported types ignored instead "
2698 "of failing, please use the -ignore_unknown option\n"
2699 "If you want them copied, please use -copy_unknown\n");
2700 exit_program(1);
2701 }
2702 }
2703 if (ost)
2705 + map->sync_stream_index];
2706 }
2707 }
2708 }
2709
2710 /* handle attached files */
2711 for (i = 0; i < o->nb_attachments; i++) {
2712 AVIOContext *pb;
2713 uint8_t *attachment;
2714 const char *p;
2715 int64_t len;
2716
2717 if ((err = avio_open2(&pb, o->attachments[i], AVIO_FLAG_READ, &int_cb, NULL)) < 0) {
2718 av_log(NULL, AV_LOG_FATAL, "Could not open attachment file %s.\n",
2719 o->attachments[i]);
2720 exit_program(1);
2721 }
2722 if ((len = avio_size(pb)) <= 0) {
2723 av_log(NULL, AV_LOG_FATAL, "Could not get size of the attachment %s.\n",
2724 o->attachments[i]);
2725 exit_program(1);
2726 }
2727 if (len > INT_MAX - AV_INPUT_BUFFER_PADDING_SIZE ||
2728 !(attachment = av_malloc(len + AV_INPUT_BUFFER_PADDING_SIZE))) {
2729 av_log(NULL, AV_LOG_FATAL, "Attachment %s too large.\n",
2730 o->attachments[i]);
2731 exit_program(1);
2732 }
2733 avio_read(pb, attachment, len);
2734 memset(attachment + len, 0, AV_INPUT_BUFFER_PADDING_SIZE);
2735
2736 ost = new_attachment_stream(o, oc, -1);
2737 ost->stream_copy = 0;
2738 ost->attachment_filename = o->attachments[i];
2739 ost->st->codecpar->extradata = attachment;
2740 ost->st->codecpar->extradata_size = len;
2741
2742 p = strrchr(o->attachments[i], '/');
2743 av_dict_set(&ost->st->metadata, "filename", (p && *p) ? p + 1 : o->attachments[i], AV_DICT_DONT_OVERWRITE);
2744 avio_closep(&pb);
2745 }
2746
2747 if (!oc->nb_streams && !(oc->oformat->flags & AVFMT_NOSTREAMS)) {
2748 av_dump_format(oc, nb_output_files - 1, oc->url, 1);
2749 av_log(NULL, AV_LOG_ERROR, "Output file #%d does not contain any stream\n", nb_output_files - 1);
2750 exit_program(1);
2751 }
2752
2753 /* check if all codec options have been used */
2754 unused_opts = strip_specifiers(o->g->codec_opts);
2755 for (i = of->ost_index; i < nb_output_streams; i++) {
2756 e = NULL;
2757 while ((e = av_dict_get(output_streams[i]->encoder_opts, "", e,
2758 AV_DICT_IGNORE_SUFFIX)))
2759 av_dict_set(&unused_opts, e->key, NULL, 0);
2760 }
2761
2762 e = NULL;
2763 while ((e = av_dict_get(unused_opts, "", e, AV_DICT_IGNORE_SUFFIX))) {
2764 const AVClass *class = avcodec_get_class();
2765 const AVOption *option = av_opt_find(&class, e->key, NULL, 0,
2766 AV_OPT_SEARCH_CHILDREN | AV_OPT_SEARCH_FAKE_OBJ);
2767 const AVClass *fclass = avformat_get_class();
2768 const AVOption *foption = av_opt_find(&fclass, e->key, NULL, 0,
2769 AV_OPT_SEARCH_CHILDREN | AV_OPT_SEARCH_FAKE_OBJ);
2770 if (!option || foption)
2771 continue;
2772
2773
2774 if (!(option->flags & AV_OPT_FLAG_ENCODING_PARAM)) {
2775 av_log(NULL, AV_LOG_ERROR, "Codec AVOption %s (%s) specified for "
2776 "output file #%d (%s) is not an encoding option.\n", e->key,
2777 option->help ? option->help : "", nb_output_files - 1,
2778 filename);
2779 exit_program(1);
2780 }
2781
2782 // gop_timecode is injected by generic code but not always used
2783 if (!strcmp(e->key, "gop_timecode"))
2784 continue;
2785
2786 av_log(NULL, AV_LOG_WARNING, "Codec AVOption %s (%s) specified for "
2787 "output file #%d (%s) has not been used for any stream. The most "
2788 "likely reason is either wrong type (e.g. a video option with "
2789 "no video streams) or that it is a private option of some encoder "
2790 "which was not actually used for any stream.\n", e->key,
2791 option->help ? option->help : "", nb_output_files - 1, filename);
2792 }
2793 av_dict_free(&unused_opts);
2794
2795 /* set the decoding_needed flags and create simple filtergraphs */
2796 for (i = of->ost_index; i < nb_output_streams; i++) {
2797 OutputStream *ost = output_streams[i];
2798
2799 if (ost->encoding_needed && ost->source_index >= 0) {
2802 ist->processing_needed = 1;
2803
2804 if (ost->st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO ||
2805 ost->st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) {
2806 err = init_simple_filtergraph(ist, ost);
2807 if (err < 0) {
2808 av_log(NULL, AV_LOG_ERROR,
2809 "Error initializing a simple filtergraph between streams "
2810 "%d:%d->%d:%d\n", ist->file_index, ost->source_index,
2811 nb_output_files - 1, ost->st->index);
2812 exit_program(1);
2813 }
2814 }
2815 } else if (ost->stream_copy && ost->source_index >= 0) {
2817 ist->processing_needed = 1;
2818 }
2819
2820 /* set the filter output constraints */
2821 if (ost->filter) {
2822 OutputFilter *f = ost->filter;
2823 switch (ost->enc_ctx->codec_type) {
2824 case AVMEDIA_TYPE_VIDEO:
2825 f->frame_rate = ost->frame_rate;
2826 f->width = ost->enc_ctx->width;
2827 f->height = ost->enc_ctx->height;
2828 if (ost->enc_ctx->pix_fmt != AV_PIX_FMT_NONE) {
2829 f->format = ost->enc_ctx->pix_fmt;
2830 } else {
2831 f->formats = ost->enc->pix_fmts;
2832 }
2833 break;
2834 case AVMEDIA_TYPE_AUDIO:
2835 if (ost->enc_ctx->sample_fmt != AV_SAMPLE_FMT_NONE) {
2836 f->format = ost->enc_ctx->sample_fmt;
2837 } else {
2838 f->formats = ost->enc->sample_fmts;
2839 }
2840 if (ost->enc_ctx->sample_rate) {
2841 f->sample_rate = ost->enc_ctx->sample_rate;
2842 } else {
2843 f->sample_rates = ost->enc->supported_samplerates;
2844 }
2845 if (ost->enc_ctx->ch_layout.nb_channels) {
2846 set_channel_layout(f, ost);
2847 } else if (ost->enc->ch_layouts) {
2848 f->ch_layouts = ost->enc->ch_layouts;
2849 }
2850 break;
2851 }
2852 }
2853 }
2854
2855 /* check filename in case of an image number is expected */
2856 if (oc->oformat->flags & AVFMT_NEEDNUMBER) {
2857 if (!av_filename_number_test(oc->url)) {
2858 print_error(oc->url, AVERROR(EINVAL));
2859 exit_program(1);
2860 }
2861 }
2862
2863 if (!(oc->oformat->flags & AVFMT_NOSTREAMS) && !input_stream_potentially_available) {
2864 av_log(NULL, AV_LOG_ERROR,
2865 "No input streams but output needs an input stream\n");
2866 exit_program(1);
2867 }
2868
2869 if (!(oc->oformat->flags & AVFMT_NOFILE)) {
2870 /* test if it already exists to avoid losing precious files */
2871 assert_file_overwrite(filename);
2872
2873 /* open the file */
2874 if ((err = avio_open2(&oc->pb, filename, AVIO_FLAG_WRITE,
2875 &oc->interrupt_callback,
2876 &of->opts)) < 0) {
2877 print_error(filename, err);
2878 exit_program(1);
2879 }
2880 } else if (strcmp(oc->oformat->name, "image2")==0 && !av_filename_number_test(filename))
2881 assert_file_overwrite(filename);
2882
2883 if (o->mux_preload) {
2884 av_dict_set_int(&of->opts, "preload", o->mux_preload*AV_TIME_BASE, 0);
2885 }
2886 oc->max_delay = (int)(o->mux_max_delay * AV_TIME_BASE);
2887
2888 /* copy metadata */
2889 for (i = 0; i < o->nb_metadata_map; i++) {
2890 char *p;
2891 int in_file_index = strtol(o->metadata_map[i].u.str, &p, 0);
2892
2893 if (in_file_index >= nb_input_files) {
2894 av_log(NULL, AV_LOG_FATAL, "Invalid input file index %d while processing metadata maps\n", in_file_index);
2895 exit_program(1);
2896 }
2897 fftools_copy_metadata(o->metadata_map[i].specifier, *p ? p + 1 : p, oc,
2898 in_file_index >= 0 ?
2899 input_files[in_file_index]->ctx : NULL, o);
2900 }
2901
2902 /* copy chapters */
2904 if (o->chapters_input_file == INT_MAX) {
2905 /* copy chapters from the first input file that has them*/
2906 o->chapters_input_file = -1;
2907 for (i = 0; i < nb_input_files; i++)
2908 if (input_files[i]->ctx->nb_chapters) {
2909 o->chapters_input_file = i;
2910 break;
2911 }
2912 } else {
2913 av_log(NULL, AV_LOG_FATAL, "Invalid input file index %d in chapter mapping.\n",
2915 exit_program(1);
2916 }
2917 }
2918 if (o->chapters_input_file >= 0)
2921
2922 /* copy global metadata by default */
2924 av_dict_copy(&oc->metadata, input_files[0]->ctx->metadata,
2925 AV_DICT_DONT_OVERWRITE);
2926 if(o->recording_time != INT64_MAX)
2927 av_dict_set(&oc->metadata, "duration", NULL, 0);
2928 av_dict_set(&oc->metadata, "creation_time", NULL, 0);
2929 av_dict_set(&oc->metadata, "company_name", NULL, 0);
2930 av_dict_set(&oc->metadata, "product_name", NULL, 0);
2931 av_dict_set(&oc->metadata, "product_version", NULL, 0);
2932 }
2934 for (i = of->ost_index; i < nb_output_streams; i++) {
2935 InputStream *ist;
2936 if (output_streams[i]->source_index < 0) /* this is true e.g. for attached files */
2937 continue;
2939 av_dict_copy(&output_streams[i]->st->metadata, ist->st->metadata, AV_DICT_DONT_OVERWRITE);
2940 if (!output_streams[i]->stream_copy) {
2941 av_dict_set(&output_streams[i]->st->metadata, "encoder", NULL, 0);
2942 }
2943 }
2944
2945 /* process manually set programs */
2946 for (i = 0; i < o->nb_program; i++) {
2947 const char *p = o->program[i].u.str;
2948 int progid = i+1;
2949 AVProgram *program;
2950
2951 while(*p) {
2952 const char *p2 = av_get_token(&p, ":");
2953 const char *to_dealloc = p2;
2954 char *key;
2955 if (!p2)
2956 break;
2957
2958 if(*p) p++;
2959
2960 key = av_get_token(&p2, "=");
2961 if (!key || !*p2) {
2962 av_freep(&to_dealloc);
2963 av_freep(&key);
2964 break;
2965 }
2966 p2++;
2967
2968 if (!strcmp(key, "program_num"))
2969 progid = strtol(p2, NULL, 0);
2970 av_freep(&to_dealloc);
2971 av_freep(&key);
2972 }
2973
2974 program = av_new_program(oc, progid);
2975
2976 p = o->program[i].u.str;
2977 while(*p) {
2978 const char *p2 = av_get_token(&p, ":");
2979 const char *to_dealloc = p2;
2980 char *key;
2981 if (!p2)
2982 break;
2983 if(*p) p++;
2984
2985 key = av_get_token(&p2, "=");
2986 if (!key) {
2987 av_log(NULL, AV_LOG_FATAL,
2988 "No '=' character in program string %s.\n",
2989 p2);
2990 exit_program(1);
2991 }
2992 if (!*p2)
2993 exit_program(1);
2994 p2++;
2995
2996 if (!strcmp(key, "title")) {
2997 av_dict_set(&program->metadata, "title", p2, 0);
2998 } else if (!strcmp(key, "program_num")) {
2999 } else if (!strcmp(key, "st")) {
3000 int st_num = strtol(p2, NULL, 0);
3001 av_program_add_stream_index(oc, progid, st_num);
3002 } else {
3003 av_log(NULL, AV_LOG_FATAL, "Unknown program key %s.\n", key);
3004 exit_program(1);
3005 }
3006 av_freep(&to_dealloc);
3007 av_freep(&key);
3008 }
3009 }
3010
3011 /* process manually set metadata */
3012 for (i = 0; i < o->nb_metadata; i++) {
3013 AVDictionary **m;
3014 char type, *val;
3015 const char *stream_spec;
3016 int index = 0, j, ret = 0;
3017
3018 val = strchr(o->metadata[i].u.str, '=');
3019 if (!val) {
3020 av_log(NULL, AV_LOG_FATAL, "No '=' character in metadata string %s.\n",
3021 o->metadata[i].u.str);
3022 exit_program(1);
3023 }
3024 *val++ = 0;
3025
3026 parse_meta_type(o->metadata[i].specifier, &type, &index, &stream_spec);
3027 if (type == 's') {
3028 for (j = 0; j < oc->nb_streams; j++) {
3029 ost = output_streams[nb_output_streams - oc->nb_streams + j];
3030 if ((ret = check_stream_specifier(oc, oc->streams[j], stream_spec)) > 0) {
3031 if (!strcmp(o->metadata[i].u.str, "rotate")) {
3032 char *tail;
3033 double theta = av_strtod(val, &tail);
3034 if (!*tail) {
3035 ost->rotate_overridden = 1;
3036 ost->rotate_override_value = theta;
3037 }
3038 } else {
3039 av_dict_set(&oc->streams[j]->metadata, o->metadata[i].u.str, *val ? val : NULL, 0);
3040 }
3041 } else if (ret < 0)
3042 exit_program(1);
3043 }
3044 }
3045 else {
3046 switch (type) {
3047 case 'g':
3048 m = &oc->metadata;
3049 break;
3050 case 'c':
3051 if (index < 0 || index >= oc->nb_chapters) {
3052 av_log(NULL, AV_LOG_FATAL, "Invalid chapter index %d in metadata specifier.\n", index);
3053 exit_program(1);
3054 }
3055 m = &oc->chapters[index]->metadata;
3056 break;
3057 case 'p':
3058 if (index < 0 || index >= oc->nb_programs) {
3059 av_log(NULL, AV_LOG_FATAL, "Invalid program index %d in metadata specifier.\n", index);
3060 exit_program(1);
3061 }
3062 m = &oc->programs[index]->metadata;
3063 break;
3064 default:
3065 av_log(NULL, AV_LOG_FATAL, "Invalid metadata specifier %s.\n", o->metadata[i].specifier);
3066 exit_program(1);
3067 }
3068 av_dict_set(m, o->metadata[i].u.str, *val ? val : NULL, 0);
3069 }
3070 }
3071
3072 err = set_dispositions(of, oc);
3073 if (err < 0) {
3074 av_log(NULL, AV_LOG_FATAL, "Error setting output stream dispositions\n");
3075 exit_program(1);
3076 }
3077
3078 return 0;
3079}
3080
3081int opt_target(void *optctx, const char *opt, const char *arg)
3082{
3083 const OptionDef *options = ffmpeg_options;
3084 OptionsContext *o = optctx;
3085 enum { PAL, NTSC, FILM, UNKNOWN } norm = UNKNOWN;
3086 static const char *const frame_rates[] = { "25", "30000/1001", "24000/1001" };
3087
3088 if (!strncmp(arg, "pal-", 4)) {
3089 norm = PAL;
3090 arg += 4;
3091 } else if (!strncmp(arg, "ntsc-", 5)) {
3092 norm = NTSC;
3093 arg += 5;
3094 } else if (!strncmp(arg, "film-", 5)) {
3095 norm = FILM;
3096 arg += 5;
3097 } else {
3098 /* Try to determine PAL/NTSC by peeking in the input files */
3099 if (nb_input_files) {
3100 int i, j;
3101 for (j = 0; j < nb_input_files; j++) {
3102 for (i = 0; i < input_files[j]->nb_streams; i++) {
3103 AVStream *st = input_files[j]->ctx->streams[i];
3104 int64_t fr;
3105 if (st->codecpar->codec_type != AVMEDIA_TYPE_VIDEO)
3106 continue;
3107 fr = st->time_base.den * 1000LL / st->time_base.num;
3108 if (fr == 25000) {
3109 norm = PAL;
3110 break;
3111 } else if ((fr == 29970) || (fr == 23976)) {
3112 norm = NTSC;
3113 break;
3114 }
3115 }
3116 if (norm != UNKNOWN)
3117 break;
3118 }
3119 }
3120 if (norm != UNKNOWN)
3121 av_log(NULL, AV_LOG_INFO, "Assuming %s for target.\n", norm == PAL ? "PAL" : "NTSC");
3122 }
3123
3124 if (norm == UNKNOWN) {
3125 av_log(NULL, AV_LOG_FATAL, "Could not determine norm (PAL/NTSC/NTSC-Film) for target.\n");
3126 av_log(NULL, AV_LOG_FATAL, "Please prefix target with \"pal-\", \"ntsc-\" or \"film-\",\n");
3127 av_log(NULL, AV_LOG_FATAL, "or set a framerate with \"-r xxx\".\n");
3128 exit_program(1);
3129 }
3130
3131 if (!strcmp(arg, "vcd")) {
3132 opt_video_codec(o, "c:v", "mpeg1video");
3133 opt_audio_codec(o, "c:a", "mp2");
3134 parse_option(o, "f", "vcd", options);
3135
3136 parse_option(o, "s", norm == PAL ? "352x288" : "352x240", options);
3137 parse_option(o, "r", frame_rates[norm], options);
3138 opt_default(NULL, "g", norm == PAL ? "15" : "18");
3139
3140 opt_default(NULL, "b:v", "1150000");
3141 opt_default(NULL, "maxrate:v", "1150000");
3142 opt_default(NULL, "minrate:v", "1150000");
3143 opt_default(NULL, "bufsize:v", "327680"); // 40*1024*8;
3144
3145 opt_default(NULL, "b:a", "224000");
3146 parse_option(o, "ar", "44100", options);
3147 parse_option(o, "ac", "2", options);
3148
3149 opt_default(NULL, "packetsize", "2324");
3150 opt_default(NULL, "muxrate", "1411200"); // 2352 * 75 * 8;
3151
3152 /* We have to offset the PTS, so that it is consistent with the SCR.
3153 SCR starts at 36000, but the first two packs contain only padding
3154 and the first pack from the other stream, respectively, may also have
3155 been written before.
3156 So the real data starts at SCR 36000+3*1200. */
3157 o->mux_preload = (36000 + 3 * 1200) / 90000.0; // 0.44
3158 } else if (!strcmp(arg, "svcd")) {
3159
3160 opt_video_codec(o, "c:v", "mpeg2video");
3161 opt_audio_codec(o, "c:a", "mp2");
3162 parse_option(o, "f", "svcd", options);
3163
3164 parse_option(o, "s", norm == PAL ? "480x576" : "480x480", options);
3165 parse_option(o, "r", frame_rates[norm], options);
3166 parse_option(o, "pix_fmt", "yuv420p", options);
3167 opt_default(NULL, "g", norm == PAL ? "15" : "18");
3168
3169 opt_default(NULL, "b:v", "2040000");
3170 opt_default(NULL, "maxrate:v", "2516000");
3171 opt_default(NULL, "minrate:v", "0"); // 1145000;
3172 opt_default(NULL, "bufsize:v", "1835008"); // 224*1024*8;
3173 opt_default(NULL, "scan_offset", "1");
3174
3175 opt_default(NULL, "b:a", "224000");
3176 parse_option(o, "ar", "44100", options);
3177
3178 opt_default(NULL, "packetsize", "2324");
3179
3180 } else if (!strcmp(arg, "dvd")) {
3181
3182 opt_video_codec(o, "c:v", "mpeg2video");
3183 opt_audio_codec(o, "c:a", "ac3");
3184 parse_option(o, "f", "dvd", options);
3185
3186 parse_option(o, "s", norm == PAL ? "720x576" : "720x480", options);
3187 parse_option(o, "r", frame_rates[norm], options);
3188 parse_option(o, "pix_fmt", "yuv420p", options);
3189 opt_default(NULL, "g", norm == PAL ? "15" : "18");
3190
3191 opt_default(NULL, "b:v", "6000000");
3192 opt_default(NULL, "maxrate:v", "9000000");
3193 opt_default(NULL, "minrate:v", "0"); // 1500000;
3194 opt_default(NULL, "bufsize:v", "1835008"); // 224*1024*8;
3195
3196 opt_default(NULL, "packetsize", "2048"); // from www.mpucoder.com: DVD sectors contain 2048 bytes of data, this is also the size of one pack.
3197 opt_default(NULL, "muxrate", "10080000"); // from mplex project: data_rate = 1260000. mux_rate = data_rate * 8
3198
3199 opt_default(NULL, "b:a", "448000");
3200 parse_option(o, "ar", "48000", options);
3201
3202 } else if (!strncmp(arg, "dv", 2)) {
3203
3204 parse_option(o, "f", "dv", options);
3205
3206 parse_option(o, "s", norm == PAL ? "720x576" : "720x480", options);
3207 parse_option(o, "pix_fmt", !strncmp(arg, "dv50", 4) ? "yuv422p" :
3208 norm == PAL ? "yuv420p" : "yuv411p", options);
3209 parse_option(o, "r", frame_rates[norm], options);
3210
3211 parse_option(o, "ar", "48000", options);
3212 parse_option(o, "ac", "2", options);
3213
3214 } else {
3215 av_log(NULL, AV_LOG_ERROR, "Unknown target: %s\n", arg);
3216 return AVERROR(EINVAL);
3217 }
3218
3219 av_dict_copy(&o->g->codec_opts, codec_opts, AV_DICT_DONT_OVERWRITE);
3220 av_dict_copy(&o->g->format_opts, format_opts, AV_DICT_DONT_OVERWRITE);
3221
3222 return 0;
3223}
3224
3225int opt_vstats_file(void *optctx, const char *opt, const char *arg)
3226{
3227 av_free (vstats_filename);
3228 vstats_filename = av_strdup (arg);
3229 return 0;
3230}
3231
3232int opt_vstats(void *optctx, const char *opt, const char *arg)
3233{
3234 char filename[40];
3235 time_t today2 = time(NULL);
3236 struct tm *today = localtime(&today2);
3237
3238 if (!today) { // maybe tomorrow
3239 av_log(NULL, AV_LOG_FATAL, "Unable to get current time: %s\n", strerror(errno));
3240 exit_program(1);
3241 }
3242
3243 snprintf(filename, sizeof(filename), "vstats_%02d%02d%02d.log", today->tm_hour, today->tm_min,
3244 today->tm_sec);
3245 return opt_vstats_file(NULL, opt, filename);
3246}
3247
3248int opt_video_frames(void *optctx, const char *opt, const char *arg)
3249{
3250 OptionsContext *o = optctx;
3251 return parse_option(o, "frames:v", arg, ffmpeg_options);
3252}
3253
3254int opt_audio_frames(void *optctx, const char *opt, const char *arg)
3255{
3256 OptionsContext *o = optctx;
3257 return parse_option(o, "frames:a", arg, ffmpeg_options);
3258}
3259
3260int opt_data_frames(void *optctx, const char *opt, const char *arg)
3261{
3262 OptionsContext *o = optctx;
3263 return parse_option(o, "frames:d", arg, ffmpeg_options);
3264}
3265
3266int opt_default_new(OptionsContext *o, const char *opt, const char *arg)
3267{
3268 int ret;
3269 AVDictionary *cbak = codec_opts;
3270 AVDictionary *fbak = format_opts;
3271 codec_opts = NULL;
3272 format_opts = NULL;
3273
3274 ret = opt_default(NULL, opt, arg);
3275
3276 av_dict_copy(&o->g->codec_opts , codec_opts, 0);
3277 av_dict_copy(&o->g->format_opts, format_opts, 0);
3278 av_dict_free(&codec_opts);
3279 av_dict_free(&format_opts);
3280 codec_opts = cbak;
3281 format_opts = fbak;
3282
3283 return ret;
3284}
3285
3286int opt_preset(void *optctx, const char *opt, const char *arg)
3287{
3288 OptionsContext *o = optctx;
3289 FILE *f=NULL;
3290 char filename[1000], line[1000], tmp_line[1000];
3291 const char *codec_name = NULL;
3292
3293 tmp_line[0] = *opt;
3294 tmp_line[1] = 0;
3295 MATCH_PER_TYPE_OPT(codec_names, str, codec_name, NULL, tmp_line);
3296
3297 if (!(f = get_preset_file(filename, sizeof(filename), arg, *opt == 'f', codec_name))) {
3298 if(!strncmp(arg, "libx264-lossless", strlen("libx264-lossless"))){
3299 av_log(NULL, AV_LOG_FATAL, "Please use -preset <speed> -qp 0\n");
3300 }else
3301 av_log(NULL, AV_LOG_FATAL, "File for preset '%s' not found\n", arg);
3302 exit_program(1);
3303 }
3304
3305 while (fgets(line, sizeof(line), f)) {
3306 char *key = tmp_line, *value, *endptr;
3307
3308 if (strcspn(line, "#\n\r") == 0)
3309 continue;
3310 av_strlcpy(tmp_line, line, sizeof(tmp_line));
3311 if (!av_strtok(key, "=", &value) ||
3312 !av_strtok(value, "\r\n", &endptr)) {
3313 av_log(NULL, AV_LOG_FATAL, "%s: Invalid syntax: '%s'\n", filename, line);
3314 exit_program(1);
3315 }
3316 av_log(NULL, AV_LOG_DEBUG, "ffpreset[%s]: set '%s' = '%s'\n", filename, key, value);
3317
3318 if (!strcmp(key, "acodec")) opt_audio_codec (o, key, value);
3319 else if (!strcmp(key, "vcodec")) opt_video_codec (o, key, value);
3320 else if (!strcmp(key, "scodec")) opt_subtitle_codec(o, key, value);
3321 else if (!strcmp(key, "dcodec")) opt_data_codec (o, key, value);
3322 else if (opt_default_new(o, key, value) < 0) {
3323 av_log(NULL, AV_LOG_FATAL, "%s: Invalid option or argument: '%s', parsed as '%s' = '%s'\n",
3324 filename, line, key, value);
3325 exit_program(1);
3326 }
3327 }
3328
3329 fclose(f);
3330
3331 return 0;
3332}
3333
3334int opt_old2new(void *optctx, const char *opt, const char *arg)
3335{
3336 OptionsContext *o = optctx;
3337 int ret;
3338 char *s = av_asprintf("%s:%c", opt + 1, *opt);
3339 if (!s)
3340 return AVERROR(ENOMEM);
3341 ret = parse_option(o, s, arg, ffmpeg_options);
3342 av_free(s);
3343 return ret;
3344}
3345
3346int opt_bitrate(void *optctx, const char *opt, const char *arg)
3347{
3348 OptionsContext *o = optctx;
3349
3350 if(!strcmp(opt, "ab")){
3351 av_dict_set(&o->g->codec_opts, "b:a", arg, 0);
3352 return 0;
3353 } else if(!strcmp(opt, "b")){
3354 av_log(NULL, AV_LOG_WARNING, "Please use -b:a or -b:v, -b is ambiguous\n");
3355 av_dict_set(&o->g->codec_opts, "b:v", arg, 0);
3356 return 0;
3357 }
3358 av_dict_set(&o->g->codec_opts, opt, arg, 0);
3359 return 0;
3360}
3361
3362int opt_qscale(void *optctx, const char *opt, const char *arg)
3363{
3364 OptionDef *options = ffmpeg_options;
3365 OptionsContext *o = optctx;
3366 char *s;
3367 int ret;
3368 if(!strcmp(opt, "qscale")){
3369 av_log(NULL, AV_LOG_WARNING, "Please use -q:a or -q:v, -qscale is ambiguous\n");
3370 return parse_option(o, "q:v", arg, options);
3371 }
3372 s = av_asprintf("q%s", opt + 6);
3373 if (!s)
3374 return AVERROR(ENOMEM);
3375 ret = parse_option(o, s, arg, options);
3376 av_free(s);
3377 return ret;
3378}
3379
3380int opt_profile(void *optctx, const char *opt, const char *arg)
3381{
3382 OptionsContext *o = optctx;
3383 if(!strcmp(opt, "profile")){
3384 av_log(NULL, AV_LOG_WARNING, "Please use -profile:a or -profile:v, -profile is ambiguous\n");
3385 av_dict_set(&o->g->codec_opts, "profile:v", arg, 0);
3386 return 0;
3387 }
3388 av_dict_set(&o->g->codec_opts, opt, arg, 0);
3389 return 0;
3390}
3391
3392int opt_video_filters(void *optctx, const char *opt, const char *arg)
3393{
3394 OptionsContext *o = optctx;
3395 return parse_option(o, "filter:v", arg, ffmpeg_options);
3396}
3397
3398int opt_audio_filters(void *optctx, const char *opt, const char *arg)
3399{
3400 OptionsContext *o = optctx;
3401 return parse_option(o, "filter:a", arg, ffmpeg_options);
3402}
3403
3404int opt_vsync(void *optctx, const char *opt, const char *arg)
3405{
3406 av_log(NULL, AV_LOG_WARNING, "-vsync is deprecated. Use -fps_mode\n");
3407 parse_and_set_vsync(arg, &video_sync_method, -1, -1, 1);
3408 return 0;
3409}
3410
3411int opt_timecode(void *optctx, const char *opt, const char *arg)
3412{
3413 OptionsContext *o = optctx;
3414 int ret;
3415 char *tcr = av_asprintf("timecode=%s", arg);
3416 if (!tcr)
3417 return AVERROR(ENOMEM);
3418 ret = parse_option(o, "metadata:g", tcr, ffmpeg_options);
3419 if (ret >= 0)
3420 ret = av_dict_set(&o->g->codec_opts, "gop_timecode", arg, 0);
3421 av_free(tcr);
3422 return ret;
3423}
3424
3425int opt_audio_qscale(void *optctx, const char *opt, const char *arg)
3426{
3427 OptionsContext *o = optctx;
3428 return parse_option(o, "q:a", arg, ffmpeg_options);
3429}
3430
3431int opt_filter_complex(void *optctx, const char *opt, const char *arg)
3432{
3434
3435 fg->index = nb_filtergraphs - 1;
3436 fg->graph_desc = av_strdup(arg);
3437 if (!fg->graph_desc)
3438 return AVERROR(ENOMEM);
3439
3441
3442 return 0;
3443}
3444
3445int opt_filter_complex_script(void *optctx, const char *opt, const char *arg)
3446{
3447 FilterGraph *fg;
3448 char *graph_desc = fftools_read_file(arg);
3449 if (!graph_desc)
3450 return AVERROR(EINVAL);
3451
3453 fg->index = nb_filtergraphs - 1;
3454 fg->graph_desc = graph_desc;
3455
3457
3458 return 0;
3459}
3460
3461void show_help_default_ffmpeg(const char *opt, const char *arg)
3462{
3463 OptionDef *options = ffmpeg_options;
3464 /* per-file options have at least one of those set */
3465 const int per_file = OPT_SPEC | OPT_OFFSET | OPT_PERFILE;
3466 int show_advanced = 0, show_avoptions = 0;
3467
3468 if (opt && *opt) {
3469 if (!strcmp(opt, "long"))
3470 show_advanced = 1;
3471 else if (!strcmp(opt, "full"))
3472 show_advanced = show_avoptions = 1;
3473 else
3474 av_log(NULL, AV_LOG_ERROR, "Unknown help option '%s'.\n", opt);
3475 }
3476
3477 show_usage();
3478
3479 av_log(NULL, AV_LOG_STDERR, "Getting help:\n"
3480 " -h -- print basic options\n"
3481 " -h long -- print more options\n"
3482 " -h full -- print all options (including all format and codec specific options, very long)\n"
3483 " -h type=name -- print all options for the named decoder/encoder/demuxer/muxer/filter/bsf/protocol\n"
3484 " See man %s for detailed description of the options.\n"
3485 "\n", program_name);
3486
3487 show_help_options(options, "Print help / information / capabilities:",
3488 OPT_EXIT, 0, 0);
3489
3490 show_help_options(options, "Global options (affect whole program "
3491 "instead of just one file):",
3492 0, per_file | OPT_EXIT | OPT_EXPERT, 0);
3493 if (show_advanced)
3494 show_help_options(options, "Advanced global options:", OPT_EXPERT,
3495 per_file | OPT_EXIT, 0);
3496
3497 show_help_options(options, "Per-file main options:", 0,
3499 OPT_EXIT, per_file);
3500 if (show_advanced)
3501 show_help_options(options, "Advanced per-file options:",
3503
3504 show_help_options(options, "Video options:",
3506 if (show_advanced)
3507 show_help_options(options, "Advanced Video options:",
3509
3510 show_help_options(options, "Audio options:",
3512 if (show_advanced)
3513 show_help_options(options, "Advanced Audio options:",
3515 show_help_options(options, "Subtitle options:",
3516 OPT_SUBTITLE, 0, 0);
3517 av_log(NULL, AV_LOG_STDERR, "\n");
3518
3519 if (show_avoptions) {
3520 int flags = AV_OPT_FLAG_DECODING_PARAM | AV_OPT_FLAG_ENCODING_PARAM;
3521 show_help_children(avcodec_get_class(), flags);
3522 show_help_children(avformat_get_class(), flags);
3523#if CONFIG_SWSCALE
3524 show_help_children(sws_get_class(), flags);
3525#endif
3526#if CONFIG_SWRESAMPLE
3527 show_help_children(swr_get_class(), AV_OPT_FLAG_AUDIO_PARAM);
3528#endif
3529 show_help_children(avfilter_get_class(), AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_AUDIO_PARAM | AV_OPT_FLAG_FILTERING_PARAM);
3530 show_help_children(av_bsf_get_class(), AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_AUDIO_PARAM | AV_OPT_FLAG_BSF_PARAM);
3531 }
3532}
3533
3534void show_usage(void)
3535{
3536 av_log(NULL, AV_LOG_INFO, "Hyper fast Audio and Video encoder\n");
3537 av_log(NULL, AV_LOG_INFO, "usage: %s [options] [[infile options] -i infile]... {[outfile options] outfile}...\n", program_name);
3538 av_log(NULL, AV_LOG_INFO, "\n");
3539}
3540
3544};
3545
3546static const OptionGroupDef groups[] = {
3547 [GROUP_OUTFILE] = { "output url", NULL, OPT_OUTPUT },
3548 [GROUP_INFILE] = { "input url", "i", OPT_INPUT },
3549};
3550
3551int open_files(OptionGroupList *l, const char *inout,
3552 int (*open_file)(OptionsContext*, const char*))
3553{
3554 int i, ret;
3555
3556 for (i = 0; i < l->nb_groups; i++) {
3557 OptionGroup *g = &l->groups[i];
3559
3560 init_options(&o);
3561 o.g = g;
3562
3563 ret = parse_optgroup(&o, g);
3564 if (ret < 0) {
3565 av_log(NULL, AV_LOG_ERROR, "Error parsing options for %s file "
3566 "%s.\n", inout, g->arg);
3567 uninit_options(&o);
3568 return ret;
3569 }
3570
3571 av_log(NULL, AV_LOG_DEBUG, "Opening an %s file: %s.\n", inout, g->arg);
3572 ret = open_file(&o, g->arg);
3573 uninit_options(&o);
3574 if (ret < 0) {
3575 av_log(NULL, AV_LOG_ERROR, "Error opening %s file %s.\n",
3576 inout, g->arg);
3577 return ret;
3578 }
3579 av_log(NULL, AV_LOG_DEBUG, "Successfully opened the file.\n");
3580 }
3581
3582 return 0;
3583}
3584
3585int ffmpeg_parse_options(int argc, char **argv)
3586{
3587 OptionParseContext octx;
3588 uint8_t error[128];
3589 int ret;
3590
3591 memset(&octx, 0, sizeof(octx));
3592
3593 /* split the commandline into an internal representation */
3594 ret = split_commandline(&octx, argc, argv, ffmpeg_options, groups,
3595 FF_ARRAY_ELEMS(groups));
3596 if (ret < 0) {
3597 av_log(NULL, AV_LOG_FATAL, "Error splitting the argument list: ");
3598 goto fail;
3599 }
3600
3601 /* apply global options */
3602 ret = parse_optgroup(NULL, &octx.global_opts);
3603 if (ret < 0) {
3604 av_log(NULL, AV_LOG_FATAL, "Error parsing global options: ");
3605 goto fail;
3606 }
3607
3608 /* configure terminal and setup signal handlers */
3609 term_init();
3610
3611 /* open input files */
3612 ret = open_files(&octx.groups[GROUP_INFILE], "input", open_input_file);
3613 if (ret < 0) {
3614 av_log(NULL, AV_LOG_FATAL, "Error opening input files: ");
3615 goto fail;
3616 }
3617
3619
3620 /* create the complex filtergraphs */
3621 ret = init_complex_filters();
3622 if (ret < 0) {
3623 av_log(NULL, AV_LOG_FATAL, "Error initializing complex filters.\n");
3624 goto fail;
3625 }
3626
3627 /* open output files */
3628 ret = open_files(&octx.groups[GROUP_OUTFILE], "output", open_output_file);
3629 if (ret < 0) {
3630 av_log(NULL, AV_LOG_FATAL, "Error opening output files: ");
3631 goto fail;
3632 }
3633
3635
3636fail:
3637 uninit_parse_context(&octx);
3638 if (ret < 0) {
3639 av_strerror(ret, error, sizeof(error));
3640 av_log(NULL, AV_LOG_FATAL, "%s\n", error);
3641 }
3642 return ret;
3643}
3644
3645int opt_progress(void *optctx, const char *opt, const char *arg)
3646{
3647 AVIOContext *avio = NULL;
3648 int ret;
3649
3650 if (!strcmp(arg, "-"))
3651 arg = "pipe:";
3652 ret = avio_open2(&avio, arg, AVIO_FLAG_WRITE, &int_cb, NULL);
3653 if (ret < 0) {
3654 av_log(NULL, AV_LOG_ERROR, "Failed to open progress URL \"%s\": %s\n",
3655 arg, av_err2str(ret));
3656 return ret;
3657 }
3658 progress_avio = avio;
3659 return 0;
3660}
3661
3662int opt_timelimit(void *optctx, const char *opt, const char *arg)
3663{
3664#if HAVE_SETRLIMIT
3665 int lim = parse_number_or_die(opt, arg, OPT_INT64, 0, INT_MAX);
3666 struct rlimit rl = { lim, lim + 1 };
3667 if (setrlimit(RLIMIT_CPU, &rl))
3668 perror("setrlimit");
3669#else
3670 av_log(NULL, AV_LOG_WARNING, "-%s not implemented on this OS\n", opt);
3671#endif
3672 return 0;
3673}
void exit_program(int ret)
void show_help_children(const AVClass *class, int flags)
__thread AVDictionary * codec_opts
int parse_option(void *optctx, const char *opt, const char *arg, const OptionDef *options)
void show_help_options(const OptionDef *options, const char *msg, int req_flags, int rej_flags, int alt_flags)
__thread AVDictionary * format_opts
int opt_default(void *optctx, const char *opt, const char *arg)
void print_error(const char *filename, int err)
int read_yesno(void)
int check_stream_specifier(AVFormatContext *s, AVStream *st, const char *spec)
__thread char * program_name
void uninit_parse_context(OptionParseContext *octx)
int split_commandline(OptionParseContext *octx, int argc, char *argv[], const OptionDef *options, const OptionGroupDef *groups, int nb_groups)
int64_t parse_time_or_die(const char *context, const char *timestr, int is_duration)
FILE * get_preset_file(char *filename, size_t filename_size, const char *preset_name, int is_path, const char *codec_name)
void * grow_array(void *array, int elem_size, int *size, int new_size)
AVDictionary * filter_codec_opts(AVDictionary *opts, enum AVCodecID codec_id, AVFormatContext *s, AVStream *st, const AVCodec *codec)
int parse_optgroup(void *optctx, OptionGroup *g)
double parse_number_or_die(const char *context, const char *numstr, int type, double min, double max)
AVDictionary ** setup_find_stream_info_opts(AVFormatContext *s, AVDictionary *codec_opts)
#define OPT_VIDEO
#define OPT_SPEC
#define OPT_INT64
#define OPT_PERFILE
#define OPT_INT
#define ALLOC_ARRAY_ELEM(array, nb_elems)
#define AV_LOG_STDERR
#define OPT_INPUT
#define OPT_STRING
#define GROW_ARRAY(array, nb_elems)
#define OPT_AUDIO
#define OPT_SUBTITLE
#define OPT_EXPERT
#define OPT_EXIT
#define OPT_OUTPUT
#define OPT_OFFSET
__thread InputStream ** input_streams
__thread const AVIOInterruptCB int_cb
__thread int nb_input_streams
void term_exit(void)
__thread OutputStream ** output_streams
__thread OutputFile ** output_files
__thread int nb_output_streams
int guess_input_channel_layout(InputStream *ist)
__thread int nb_input_files
__thread int nb_output_files
__thread AVIOContext * progress_avio
__thread InputFile ** input_files
__thread FilterGraph ** filtergraphs
void remove_avoptions(AVDictionary **a, AVDictionary *b)
__thread int nb_filtergraphs
void term_init(void)
void assert_avoptions(AVDictionary *m)
@ HWACCEL_NONE
@ HWACCEL_GENERIC
@ HWACCEL_AUTO
#define MAX_STREAMS
HWDevice * hw_device_get_by_name(const char *name)
int init_simple_filtergraph(InputStream *ist, OutputStream *ost)
VideoSyncMethod
@ VSYNC_VFR
@ VSYNC_AUTO
@ VSYNC_PASSTHROUGH
@ VSYNC_CFR
@ VSYNC_DROP
@ VSYNC_VSCFR
#define ABORT_ON_FLAG_EMPTY_OUTPUT
#define DECODING_FOR_OST
int hw_device_init_from_string(const char *arg, HWDevice **dev)
void check_filter_outputs(void)
#define ABORT_ON_FLAG_EMPTY_OUTPUT_STREAM
int init_complex_filtergraph(FilterGraph *fg)
__thread float dts_delta_threshold
#define SET_DICT(type, meta, context, index)
static const char *const opt_name_frame_aspect_ratios[]
void uninit_options(OptionsContext *o)
int choose_encoder(OptionsContext *o, AVFormatContext *s, OutputStream *ost)
static const char *const opt_name_max_frames[]
__thread int copy_tb
static const char *const opt_name_audio_channels[]
int opt_sdp_file(void *optctx, const char *opt, const char *arg)
int opt_timecode(void *optctx, const char *opt, const char *arg)
OutputStream * new_unknown_stream(OptionsContext *o, AVFormatContext *oc, int source_index)
__thread OptionDef * ffmpeg_options
static const char *const opt_name_fix_sub_duration[]
int opt_vstats_file(void *optctx, const char *opt, const char *arg)
void parse_meta_type(char *arg, char *type, int *index, const char **stream_spec)
__thread int64_t stats_period
int opt_data_codec(void *optctx, const char *opt, const char *arg)
int opt_streamid(void *optctx, const char *opt, const char *arg)
static const char *const opt_name_canvas_sizes[]
int parse_and_set_vsync(const char *arg, int *vsync_var, int file_idx, int st_idx, int is_global)
int opt_qscale(void *optctx, const char *opt, const char *arg)
char * get_line(AVIOContext *s, AVBPrint *bprint)
int opt_filter_complex_script(void *optctx, const char *opt, const char *arg)
__thread char * sdp_filename
__thread enum VideoSyncMethod video_sync_method
AVDictionary * strip_specifiers(AVDictionary *dict)
static const char *const opt_name_top_field_first[]
int opt_filter_complex(void *optctx, const char *opt, const char *arg)
static const char *const opt_name_audio_ch_layouts[]
static const char *const opt_name_autorotate[]
static const char *const opt_name_inter_matrices[]
int opt_vsync(void *optctx, const char *opt, const char *arg)
__thread int print_stats
__thread int filter_complex_nbthreads
int apply_sync_offsets(void)
__thread int abort_on_flags
static const char *const opt_name_sample_fmts[]
static const char *const opt_name_codec_tags[]
OutputStream * new_output_stream(OptionsContext *o, AVFormatContext *oc, enum AVMediaType type, int source_index)
static const char *const opt_name_force_fps[]
__thread int audio_volume
__thread float max_error_rate
static const char *const opt_name_passlogfiles[]
char * fftools_read_file(const char *filename)
__thread int recast_media
static const char *const opt_name_max_muxing_queue_size[]
OutputStream * new_video_stream(OptionsContext *o, AVFormatContext *oc, int source_index)
static const char *const opt_name_muxing_queue_data_threshold[]
static const char *const opt_name_apad[]
static const char *const opt_name_hwaccels[]
__thread int copy_ts
__thread int stdin_interaction
static const char *const opt_name_copy_prior_start[]
static const char *const opt_name_presets[]
int opt_subtitle_codec(void *optctx, const char *opt, const char *arg)
int copy_chapters(InputFile *ifile, OutputFile *ofile, AVFormatContext *os, int copy_metadata)
#define MATCH_PER_TYPE_OPT(name, type, outvar, fmtctx, mediatype)
__thread float dts_error_threshold
#define DEFAULT_PASS_LOGFILENAME_PREFIX
OutputStream * new_audio_stream(OptionsContext *o, AVFormatContext *oc, int source_index)
static const char *const opt_name_frame_rates[]
int open_input_file(OptionsContext *o, const char *filename)
int opt_profile(void *optctx, const char *opt, const char *arg)
static const char *const opt_name_max_frame_rates[]
int opt_abort_on(void *optctx, const char *opt, const char *arg)
void show_usage(void)
static const char *const opt_name_hwaccel_devices[]
__thread int copy_unknown_streams
int opt_video_codec(void *optctx, const char *opt, const char *arg)
int opt_data_frames(void *optctx, const char *opt, const char *arg)
int opt_video_filters(void *optctx, const char *opt, const char *arg)
__thread char * filter_nbthreads
int opt_attach(void *optctx, const char *opt, const char *arg)
__thread int do_benchmark
int opt_filter_hw_device(void *optctx, const char *opt, const char *arg)
__thread float frame_drop_threshold
__thread int vstats_version
__thread char * vstats_filename
OutputStream * new_attachment_stream(OptionsContext *o, AVFormatContext *oc, int source_index)
int opt_audio_frames(void *optctx, const char *opt, const char *arg)
__thread int no_file_overwrite
int opt_target(void *optctx, const char *opt, const char *arg)
void check_streamcopy_filters(OptionsContext *o, AVFormatContext *oc, const OutputStream *ost, enum AVMediaType type)
static const char *const opt_name_discard[]
static const char *const opt_name_rc_overrides[]
static const char *const opt_name_forced_key_frames[]
__thread int audio_sync_method
int init_complex_filters(void)
static const char *const opt_name_time_bases[]
__thread int file_overwrite
int opt_map(void *optctx, const char *opt, const char *arg)
__thread float audio_drift_threshold
static const char *const opt_name_frame_sizes[]
@ GROUP_OUTFILE
@ GROUP_INFILE
static const char *const opt_name_audio_sample_rate[]
static const char *const opt_name_filter_scripts[]
__thread int do_benchmark_all
int opt_vstats(void *optctx, const char *opt, const char *arg)
__thread int start_at_zero
static const char *const opt_name_enc_time_bases[]
void parse_matrix_coeffs(uint16_t *dest, const char *str)
static const char *const opt_name_reinit_filters[]
int open_files(OptionGroupList *l, const char *inout, int(*open_file)(OptionsContext *, const char *))
__thread int find_stream_info
int opt_video_frames(void *optctx, const char *opt, const char *arg)
void set_channel_layout(OutputFilter *f, OutputStream *ost)
int opt_timelimit(void *optctx, const char *opt, const char *arg)
const AVCodec * find_codec_or_die(const char *name, enum AVMediaType type, int encoder)
void assert_file_overwrite(const char *filename)
int opt_audio_filters(void *optctx, const char *opt, const char *arg)
char * get_ost_filters(OptionsContext *o, AVFormatContext *oc, OutputStream *ost)
__thread int exit_on_error
static const char *const opt_name_guess_layout_max[]
int opt_audio_qscale(void *optctx, const char *opt, const char *arg)
int get_preset_file_2(const char *preset_name, const char *codec_name, AVIOContext **s)
int ffmpeg_parse_options(int argc, char **argv)
int opt_filter_threads(void *optctx, const char *opt, const char *arg)
void init_output_filter(OutputFilter *ofilter, OptionsContext *o, AVFormatContext *oc)
int show_hwaccels(void *optctx, const char *opt, const char *arg)
__thread HWDevice * filter_hw_device
int opt_preset(void *optctx, const char *opt, const char *arg)
OutputStream * new_data_stream(OptionsContext *o, AVFormatContext *oc, int source_index)
OutputStream * new_subtitle_stream(OptionsContext *o, AVFormatContext *oc, int source_index)
static const char *const opt_name_hwaccel_output_formats[]
static const char *const opt_name_chroma_intra_matrices[]
int set_dispositions(OutputFile *of, AVFormatContext *ctx)
int opt_old2new(void *optctx, const char *opt, const char *arg)
static const char *const opt_name_filters[]
static const char *const opt_name_copy_initial_nonkeyframes[]
static const char *const opt_name_fps_mode[]
int opt_stats_period(void *optctx, const char *opt, const char *arg)
static const char *const opt_name_intra_matrices[]
#define MATCH_PER_STREAM_OPT(name, type, outvar, fmtctx, st)
void add_input_streams(OptionsContext *o, AVFormatContext *ic)
static const char *const opt_name_bitstream_filters[]
__thread int qp_hist
static const char *const opt_name_qscale[]
int opt_bitrate(void *optctx, const char *opt, const char *arg)
static const char *const opt_name_codec_names[]
int fftools_copy_metadata(char *outspec, char *inspec, AVFormatContext *oc, AVFormatContext *ic, OptionsContext *o)
int opt_default_new(OptionsContext *o, const char *opt, const char *arg)
__thread int do_psnr
__thread int do_hex_dump
static const char *const opt_name_autoscale[]
__thread int do_pkt_dump
void dump_attachment(AVStream *st, const char *filename)
void init_options(OptionsContext *o)
__thread int debug_ts
int opt_map_channel(void *optctx, const char *opt, const char *arg)
const AVCodec * choose_decoder(OptionsContext *o, AVFormatContext *s, AVStream *st)
int opt_progress(void *optctx, const char *opt, const char *arg)
int open_output_file(OptionsContext *o, const char *filename)
int opt_audio_codec(void *optctx, const char *opt, const char *arg)
int opt_recording_timestamp(void *optctx, const char *opt, const char *arg)
__thread int auto_conversion_filters
static const char *const opt_name_bits_per_raw_sample[]
static const char *const opt_name_ts_scale[]
static const char *const opt_name_disposition[]
void show_help_default_ffmpeg(const char *opt, const char *arg)
__thread int input_stream_potentially_available
static const char *const opt_name_frame_pix_fmts[]
__thread int ignore_unknown_streams
static const char *const opt_name_pass[]
int opt_init_hw_device(void *optctx, const char *opt, const char *arg)
static const OptionGroupDef groups[]
__thread int nb_streams
static FILE * fopen_utf8(const char *path, const char *mode)
OutputFilter ** outputs
const char * graph_desc
AVPacket * pkt
int64_t ts_offset
int64_t duration
InputStream * streams
AVFormatContext * ctx
int64_t input_ts_offset
int64_t recording_time
AVRational time_base
int input_sync_ref
float readrate
int64_t start_time
enum AVPixelFormat hwaccel_pix_fmt
AVFrame * decoded_frame
enum AVPixelFormat hwaccel_output_format
AVCodecContext * dec_ctx
enum HWAccelID hwaccel_id
int64_t filter_in_rescale_delta_last
int64_t max_pts
AVPacket * pkt
int64_t first_dts
dts of the first packet read for this stream (in AV_TIME_BASE units)
AVStream * st
char * hwaccel_device
int64_t prev_pkt_pts
AVDictionary * decoder_opts
int64_t min_pts
const AVCodec * dec
enum AVHWDeviceType hwaccel_device_type
int64_t nb_samples
AVRational framerate
union OptionDef::@1 u
const char * name
AVDictionary * codec_opts
AVDictionary * swr_opts
AVDictionary * sws_dict
const char * arg
AVDictionary * format_opts
OptionGroup * groups
OptionGroupList * groups
SpecifierOpt * metadata_map
SpecifierOpt * frame_pix_fmts
SpecifierOpt * dump_attachment
const char * format
int64_t input_ts_offset
SpecifierOpt * audio_sample_rate
SpecifierOpt * max_frames
StreamMap * stream_maps
SpecifierOpt * frame_sizes
SpecifierOpt * metadata
int64_t recording_time
uint64_t limit_filesize
SpecifierOpt * audio_channels
int64_t start_time_eof
SpecifierOpt * frame_rates
int metadata_chapters_manual
SpecifierOpt * audio_ch_layouts
const char ** attachments
SpecifierOpt * program
AudioChannelMap * audio_channel_maps
OptionGroup * g
const AVOutputFormat * format
uint64_t limit_filesize
AVFormatContext * ctx
int64_t start_time
start time in microseconds == AV_TIME_BASE units
AVDictionary * opts
int64_t recording_time
desired length of the resulting file in microseconds == AV_TIME_BASE units
AVFilterInOut * out_tmp
struct OutputStream * ost
const int * formats
const AVChannelLayout * ch_layouts
AVChannelLayout ch_layout
const int * sample_rates
AVRational frame_rate
enum AVMediaType type
int max_muxing_queue_size
AVDictionary * swr_opts
int copy_initial_nonkeyframes
int64_t last_mux_dts
OSTFinished finished
int * audio_channels_map
AVPacket * pkt
AVRational frame_aspect_ratio
double rotate_override_value
AVFrame * last_frame
const AVCodec * enc
int audio_channels_mapped
int64_t max_frames
size_t muxing_queue_data_threshold
enum VideoSyncMethod vsync_method
AVRational max_frame_rate
AVRational enc_timebase
AVCodecParameters * ref_par
char * forced_keyframes
AVFrame * filtered_frame
const char * attachment_filename
AVRational frame_rate
AVCodecContext * enc_ctx
struct InputStream * sync_ist
AVDictionary * encoder_opts
AVStream * st
char * filters
filtergraph associated to the -filter option
int64_t forced_kf_ref_pts
char * filters_script
filtergraph script associated to the -filter_script option
AVBSFContext * bsf_ctx
AVDictionary * sws_dict
OutputFilter * filter
char * disposition
AVFifo * muxing_queue
const char * fps_mode
size_t muxing_queue_data_size
char * logfile_prefix
union SpecifierOpt::@0 u
int sync_stream_index
char * linklabel
int sync_file_index