FFmpegKit Linux API 6.0
Loading...
Searching...
No Matches
fftools_cmdutils.c
Go to the documentation of this file.
1/*
2 * Various utilities for command line tools
3 * Copyright (c) 2000-2003 Fabrice Bellard
4 * Copyright (c) 2018-2022 Taner Sener
5 * Copyright (c) 2023 ARTHENICA LTD
6 *
7 * This file is part of FFmpeg.
8 *
9 * FFmpeg is free software; you can redistribute it and/or
10 * modify it under the terms of the GNU Lesser General Public
11 * License as published by the Free Software Foundation; either
12 * version 2.1 of the License, or (at your option) any later version.
13 *
14 * FFmpeg is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
17 * Lesser General Public License for more details.
18 *
19 * You should have received a copy of the GNU Lesser General Public
20 * License along with FFmpeg; if not, write to the Free Software
21 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
22 */
23
24/*
25 * This file is the modified version of cmdutils.c file living in ffmpeg source code under the fftools folder. We
26 * manually update it each time we depend on a new ffmpeg version. Below you can see the list of changes applied
27 * by us to develop mobile-ffmpeg and later ffmpeg-kit libraries.
28 *
29 * ffmpeg-kit changes by ARTHENICA LTD
30 *
31 * 07.2023
32 * --------------------------------------------------------
33 * - FFmpeg 6.0 changes migrated
34 *
35 * mobile-ffmpeg / ffmpeg-kit changes by Taner Sener
36 *
37 * 09.2022
38 * --------------------------------------------------------
39 * - Dropped the prototypes of init_report, ffmpegkit_log_callback_function and report_callback functions
40 * - volatile dropped from thread local variables
41 *
42 * 01.2020
43 * --------------------------------------------------------
44 * - ffprobe support added (variables used by ffprobe marked with "__thread" specifier, logs with AV_LOG_INFO level
45 * migrated to use AV_LOG_STDERR)
46 * - (optindex < argc) validation in parse_options() method updated with (optindex >= argc) check
47 *
48 * 12.2019
49 * --------------------------------------------------------
50 * - concurrent execution support ("__thread" specifier added to variables used by multiple threads)
51 * - log_callback_report method re-added to fix -report option issues
52 *
53 * 08.2018
54 * --------------------------------------------------------
55 * - fftools_ prefix added to the file name and parent header
56 *
57 * 07.2018
58 * --------------------------------------------------------
59 * - unused headers removed
60 * - parentheses placed around assignments in conditions to prevent -Wparentheses warning
61 * - exit_program updated with longjmp, disabling exit
62 * - longjmp_value added to store exit code
63 * - (optindex < argc) validation added before accessing argv[optindex] inside split_commandline()
64 * and parse_options()
65 * - all av_log_set_callback invocations updated to set ffmpegkit_log_callback_function from ffmpegkit.c
66 * - unused log_callback_help method removed
67 * - (idx + 1 < argc) validation added in parse_loglevel()
68 */
69
70#include <string.h>
71#include <stdint.h>
72#include <stdlib.h>
73#include <errno.h>
74#include <math.h>
75
76/* Include only the enabled headers since some compilers (namely, Sun
77 Studio) will not omit unused inline functions and create undefined
78 references to libraries that are not being built. */
79
80#include "config.h"
81#include "libavformat/avformat.h"
82#include "libswscale/swscale.h"
83#include "libswresample/swresample.h"
84#include "libavutil/avassert.h"
85#include "libavutil/avstring.h"
86#include "libavutil/channel_layout.h"
87#include "libavutil/display.h"
88#include "libavutil/getenv_utf8.h"
89#include "libavutil/mathematics.h"
90#include "libavutil/imgutils.h"
91#include "libavutil/libm.h"
92#include "libavutil/parseutils.h"
93#include "libavutil/eval.h"
94#include "libavutil/dict.h"
95#include "libavutil/opt.h"
96#include "fftools_cmdutils.h"
97#include "fftools_fopen_utf8.h"
98#include "fftools_opt_common.h"
99#include "ffmpegkit_exception.h"
100#ifdef _WIN32
101#include <windows.h>
102#include "compat/w32dlfcn.h"
103#endif
104
105__thread char *program_name;
107
108__thread AVDictionary *sws_dict;
109__thread AVDictionary *swr_opts;
110__thread AVDictionary *format_opts, *codec_opts;
111
112__thread int hide_banner = 0;
113__thread int longjmp_value = 0;
114
115void uninit_opts(void)
116{
117 av_dict_free(&swr_opts);
118 av_dict_free(&sws_dict);
119 av_dict_free(&format_opts);
120 av_dict_free(&codec_opts);
121}
122
123void init_dynload(void)
124{
125#if HAVE_SETDLLDIRECTORY && defined(_WIN32)
126 /* Calling SetDllDirectory with the empty string (but not NULL) removes the
127 * current working directory from the DLL search path as a security pre-caution. */
128 SetDllDirectory("");
129#endif
130}
131
132static __thread void (*program_exit)(int ret);
133
134void register_exit(void (*cb)(int ret))
135{
136 program_exit = cb;
137}
138
139void report_and_exit(int ret)
140{
141 av_log(NULL, AV_LOG_FATAL, "%s\n", av_err2str(ret));
142 exit_program(AVUNERROR(ret));
143}
144
145void exit_program(int ret)
146{
147 if (program_exit)
148 program_exit(ret);
149
150 // FFmpegKit
151 // exit disabled and replaced with longjmp, exit value stored in longjmp_value
152 // exit(ret);
153 longjmp_value = ret;
154 longjmp(ex_buf__, ret);
155}
156
157double parse_number_or_die(const char *context, const char *numstr, int type,
158 double min, double max)
159{
160 char *tail;
161 const char *error;
162 double d = av_strtod(numstr, &tail);
163 if (*tail)
164 error = "Expected number for %s but found: %s\n";
165 else if (d < min || d > max)
166 error = "The value for %s was %s which is not within %f - %f\n";
167 else if (type == OPT_INT64 && (int64_t)d != d)
168 error = "Expected int64 for %s but found %s\n";
169 else if (type == OPT_INT && (int)d != d)
170 error = "Expected int for %s but found %s\n";
171 else
172 return d;
173 av_log(NULL, AV_LOG_FATAL, error, context, numstr, min, max);
174 exit_program(1);
175 return 0;
176}
177
178int64_t parse_time_or_die(const char *context, const char *timestr,
179 int is_duration)
180{
181 int64_t us;
182 if (av_parse_time(&us, timestr, is_duration) < 0) {
183 av_log(NULL, AV_LOG_FATAL, "Invalid %s specification for %s: %s\n",
184 is_duration ? "duration" : "date", context, timestr);
185 exit_program(1);
186 }
187 return us;
188}
189
190void show_help_options(const OptionDef *options, const char *msg, int req_flags,
191 int rej_flags, int alt_flags)
192{
193 const OptionDef *po;
194 int first;
195
196 first = 1;
197 for (po = options; po->name; po++) {
198 char buf[128];
199
200 if (((po->flags & req_flags) != req_flags) ||
201 (alt_flags && !(po->flags & alt_flags)) ||
202 (po->flags & rej_flags))
203 continue;
204
205 if (first) {
206 av_log(NULL, AV_LOG_STDERR, "%s\n", msg);
207 first = 0;
208 }
209 av_strlcpy(buf, po->name, sizeof(buf));
210 if (po->argname) {
211 av_strlcat(buf, " ", sizeof(buf));
212 av_strlcat(buf, po->argname, sizeof(buf));
213 }
214 av_log(NULL, AV_LOG_STDERR, "-%-17s %s\n", buf, po->help);
215 }
216 av_log(NULL, AV_LOG_STDERR, "\n");
217}
218
219void show_help_children(const AVClass *class, int flags)
220{
221 void *iter = NULL;
222 const AVClass *child;
223 if (class->option) {
224 av_opt_show2(&class, NULL, flags, 0);
225 av_log(NULL, AV_LOG_STDERR, "\n");
226 }
227
228 while ((child = av_opt_child_class_iterate(class, &iter)))
229 show_help_children(child, flags);
230}
231
232static const OptionDef *find_option(const OptionDef *po, const char *name)
233{
234 while (po->name) {
235 const char *end;
236 if (av_strstart(name, po->name, &end) && (!*end || *end == ':'))
237 break;
238 po++;
239 }
240 return po;
241}
242
243/* _WIN32 means using the windows libc - cygwin doesn't define that
244 * by default. HAVE_COMMANDLINETOARGVW is true on cygwin, while
245 * it doesn't provide the actual command line via GetCommandLineW(). */
246#if HAVE_COMMANDLINETOARGVW && defined(_WIN32)
247#include <shellapi.h>
248/* Will be leaked on exit */
249static char** win32_argv_utf8 = NULL;
250static int win32_argc = 0;
251
259static void prepare_app_arguments(int *argc_ptr, char ***argv_ptr)
260{
261 char *argstr_flat;
262 wchar_t **argv_w;
263 int i, buffsize = 0, offset = 0;
264
265 if (win32_argv_utf8) {
266 *argc_ptr = win32_argc;
267 *argv_ptr = win32_argv_utf8;
268 return;
269 }
270
271 win32_argc = 0;
272 argv_w = CommandLineToArgvW(GetCommandLineW(), &win32_argc);
273 if (win32_argc <= 0 || !argv_w)
274 return;
275
276 /* determine the UTF-8 buffer size (including NULL-termination symbols) */
277 for (i = 0; i < win32_argc; i++)
278 buffsize += WideCharToMultiByte(CP_UTF8, 0, argv_w[i], -1,
279 NULL, 0, NULL, NULL);
280
281 win32_argv_utf8 = av_mallocz(sizeof(char *) * (win32_argc + 1) + buffsize);
282 argstr_flat = (char *)win32_argv_utf8 + sizeof(char *) * (win32_argc + 1);
283 if (!win32_argv_utf8) {
284 LocalFree(argv_w);
285 return;
286 }
287
288 for (i = 0; i < win32_argc; i++) {
289 win32_argv_utf8[i] = &argstr_flat[offset];
290 offset += WideCharToMultiByte(CP_UTF8, 0, argv_w[i], -1,
291 &argstr_flat[offset],
292 buffsize - offset, NULL, NULL);
293 }
294 win32_argv_utf8[i] = NULL;
295 LocalFree(argv_w);
296
297 *argc_ptr = win32_argc;
298 *argv_ptr = win32_argv_utf8;
299}
300#else
301static inline void prepare_app_arguments(int *argc_ptr, char ***argv_ptr)
302{
303 /* nothing to do */
304}
305#endif /* HAVE_COMMANDLINETOARGVW */
306
307static int write_option(void *optctx, const OptionDef *po, const char *opt,
308 const char *arg)
309{
310 /* new-style options contain an offset into optctx, old-style address of
311 * a global var*/
312 void *dst = po->flags & (OPT_OFFSET | OPT_SPEC) ?
313 (uint8_t *)optctx + po->u.off : po->u.dst_ptr;
314 int *dstcount;
315
316 if (po->flags & OPT_SPEC) {
317 SpecifierOpt **so = dst;
318 char *p = strchr(opt, ':');
319 char *str;
320
321 dstcount = (int *)(so + 1);
322 *so = grow_array(*so, sizeof(**so), dstcount, *dstcount + 1);
323 str = av_strdup(p ? p + 1 : "");
324 if (!str)
325 return AVERROR(ENOMEM);
326 (*so)[*dstcount - 1].specifier = str;
327 dst = &(*so)[*dstcount - 1].u;
328 }
329
330 if (po->flags & OPT_STRING) {
331 char *str;
332 str = av_strdup(arg);
333 av_freep(dst);
334 if (!str)
335 return AVERROR(ENOMEM);
336 *(char **)dst = str;
337 } else if (po->flags & OPT_BOOL || po->flags & OPT_INT) {
338 *(int *)dst = parse_number_or_die(opt, arg, OPT_INT64, INT_MIN, INT_MAX);
339 } else if (po->flags & OPT_INT64) {
340 *(int64_t *)dst = parse_number_or_die(opt, arg, OPT_INT64, INT64_MIN, (double)INT64_MAX);
341 } else if (po->flags & OPT_TIME) {
342 *(int64_t *)dst = parse_time_or_die(opt, arg, 1);
343 } else if (po->flags & OPT_FLOAT) {
344 *(float *)dst = parse_number_or_die(opt, arg, OPT_FLOAT, -INFINITY, INFINITY);
345 } else if (po->flags & OPT_DOUBLE) {
346 *(double *)dst = parse_number_or_die(opt, arg, OPT_DOUBLE, -INFINITY, INFINITY);
347 } else if (po->u.func_arg) {
348 int ret = po->u.func_arg(optctx, opt, arg);
349 if (ret < 0) {
350 av_log(NULL, AV_LOG_ERROR,
351 "Failed to set value '%s' for option '%s': %s\n",
352 arg, opt, av_err2str(ret));
353 return ret;
354 }
355 }
356 if (po->flags & OPT_EXIT)
357 exit_program(0);
358
359 return 0;
360}
361
362int parse_option(void *optctx, const char *opt, const char *arg,
363 const OptionDef *options)
364{
365 static const OptionDef opt_avoptions = {
366 .name = "AVOption passthrough",
367 .flags = HAS_ARG,
368 .u.func_arg = opt_default,
369 };
370
371 const OptionDef *po;
372 int ret;
373
374 po = find_option(options, opt);
375 if (!po->name && opt[0] == 'n' && opt[1] == 'o') {
376 /* handle 'no' bool option */
377 po = find_option(options, opt + 2);
378 if ((po->name && (po->flags & OPT_BOOL)))
379 arg = "0";
380 } else if (po->flags & OPT_BOOL)
381 arg = "1";
382
383 if (!po->name)
384 po = &opt_avoptions;
385 if (!po->name) {
386 av_log(NULL, AV_LOG_ERROR, "Unrecognized option '%s'\n", opt);
387 return AVERROR(EINVAL);
388 }
389 if (po->flags & HAS_ARG && !arg) {
390 av_log(NULL, AV_LOG_ERROR, "Missing argument for option '%s'\n", opt);
391 return AVERROR(EINVAL);
392 }
393
394 ret = write_option(optctx, po, opt, arg);
395 if (ret < 0)
396 return ret;
397
398 return !!(po->flags & HAS_ARG);
399}
400
401void parse_options(void *optctx, int argc, char **argv, const OptionDef *options,
402 void (*parse_arg_function)(void *, const char*))
403{
404 const char *opt;
405 int optindex, handleoptions = 1, ret;
406
407 /* perform system-dependent conversions for arguments list */
408 prepare_app_arguments(&argc, &argv);
409
410 /* parse options */
411 optindex = 1;
412 while (optindex < argc) {
413 opt = argv[optindex++];
414
415 if (handleoptions && opt[0] == '-' && opt[1] != '\0') {
416 if (opt[1] == '-' && opt[2] == '\0') {
417 handleoptions = 0;
418 continue;
419 }
420 opt++;
421 if (optindex >= argc) {
422 if ((ret = parse_option(optctx, opt, NULL, options)) < 0)
423 exit_program(1);
424 } else {
425 if ((ret = parse_option(optctx, opt, argv[optindex], options)) < 0)
426 exit_program(1);
427 }
428 optindex += ret;
429 } else {
430 if (parse_arg_function)
431 parse_arg_function(optctx, opt);
432 }
433 }
434}
435
436int parse_optgroup(void *optctx, OptionGroup *g)
437{
438 int i, ret;
439
440 av_log(NULL, AV_LOG_DEBUG, "Parsing a group of options: %s %s.\n",
441 g->group_def->name, g->arg);
442
443 for (i = 0; i < g->nb_opts; i++) {
444 Option *o = &g->opts[i];
445
446 if (g->group_def->flags &&
447 !(g->group_def->flags & o->opt->flags)) {
448 av_log(NULL, AV_LOG_ERROR, "Option %s (%s) cannot be applied to "
449 "%s %s -- you are trying to apply an input option to an "
450 "output file or vice versa. Move this option before the "
451 "file it belongs to.\n", o->key, o->opt->help,
452 g->group_def->name, g->arg);
453 return AVERROR(EINVAL);
454 }
455
456 av_log(NULL, AV_LOG_DEBUG, "Applying option %s (%s) with argument %s.\n",
457 o->key, o->opt->help, o->val);
458
459 ret = write_option(optctx, o->opt, o->key, o->val);
460 if (ret < 0)
461 return ret;
462 }
463
464 av_log(NULL, AV_LOG_DEBUG, "Successfully parsed a group of options.\n");
465
466 return 0;
467}
468
469int locate_option(int argc, char **argv, const OptionDef *options,
470 const char *optname)
471{
472 const OptionDef *po;
473 int i;
474
475 for (i = 1; i < argc; i++) {
476 const char *cur_opt = argv[i];
477
478 if (*cur_opt++ != '-')
479 continue;
480
481 po = find_option(options, cur_opt);
482 if (!po->name && cur_opt[0] == 'n' && cur_opt[1] == 'o')
483 po = find_option(options, cur_opt + 2);
484
485 if ((!po->name && !strcmp(cur_opt, optname)) ||
486 (po->name && !strcmp(optname, po->name)))
487 return i;
488
489 if (!po->name || po->flags & HAS_ARG)
490 i++;
491 }
492 return 0;
493}
494
495static void dump_argument(FILE *report_file, const char *a)
496{
497 const unsigned char *p;
498
499 for (p = a; *p; p++)
500 if (!((*p >= '+' && *p <= ':') || (*p >= '@' && *p <= 'Z') ||
501 *p == '_' || (*p >= 'a' && *p <= 'z')))
502 break;
503 if (!*p) {
504 fputs(a, report_file);
505 return;
506 }
507 fputc('"', report_file);
508 for (p = a; *p; p++) {
509 if (*p == '\\' || *p == '"' || *p == '$' || *p == '`')
510 fprintf(report_file, "\\%c", *p);
511 else if (*p < ' ' || *p > '~')
512 fprintf(report_file, "\\x%02x", *p);
513 else
514 fputc(*p, report_file);
515 }
516 fputc('"', report_file);
517}
518
519static void check_options(const OptionDef *po)
520{
521 while (po->name) {
522 if (po->flags & OPT_PERFILE)
523 av_assert0(po->flags & (OPT_INPUT | OPT_OUTPUT));
524 po++;
525 }
526}
527
528void parse_loglevel(int argc, char **argv, const OptionDef *options)
529{
530 int idx = locate_option(argc, argv, options, "loglevel");
531 char *env;
532
533 check_options(options);
534
535 if (!idx)
536 idx = locate_option(argc, argv, options, "v");
537 if (idx && (idx + 1 < argc) && argv[idx + 1])
538 opt_loglevel(NULL, "loglevel", argv[idx + 1]);
539 idx = locate_option(argc, argv, options, "report");
540 env = getenv_utf8("FFREPORT");
541 if (env || idx) {
542 FILE *report_file = NULL;
544 if (report_file) {
545 int i;
546 fprintf(report_file, "Command line:\n");
547 for (i = 0; i < argc; i++) {
548 dump_argument(report_file, argv[i]);
549 fputc(i < argc - 1 ? ' ' : '\n', report_file);
550 }
551 fflush(report_file);
552 }
553 }
554 freeenv_utf8(env);
555 idx = locate_option(argc, argv, options, "hide_banner");
556 if (idx)
557 hide_banner = 1;
558}
559
560static const AVOption *opt_find(void *obj, const char *name, const char *unit,
561 int opt_flags, int search_flags)
562{
563 const AVOption *o = av_opt_find(obj, name, unit, opt_flags, search_flags);
564 if(o && !o->flags)
565 return NULL;
566 return o;
567}
568
569#define FLAGS (o->type == AV_OPT_TYPE_FLAGS && (arg[0]=='-' || arg[0]=='+')) ? AV_DICT_APPEND : 0
570int opt_default(void *optctx, const char *opt, const char *arg)
571{
572 const AVOption *o;
573 int consumed = 0;
574 char opt_stripped[128];
575 const char *p;
576 const AVClass *cc = avcodec_get_class(), *fc = avformat_get_class();
577#if CONFIG_SWSCALE
578 const AVClass *sc = sws_get_class();
579#endif
580#if CONFIG_SWRESAMPLE
581 const AVClass *swr_class = swr_get_class();
582#endif
583
584 if (!strcmp(opt, "debug") || !strcmp(opt, "fdebug"))
585 av_log_set_level(AV_LOG_DEBUG);
586
587 if (!(p = strchr(opt, ':')))
588 p = opt + strlen(opt);
589 av_strlcpy(opt_stripped, opt, FFMIN(sizeof(opt_stripped), p - opt + 1));
590
591 if ((o = opt_find(&cc, opt_stripped, NULL, 0,
592 AV_OPT_SEARCH_CHILDREN | AV_OPT_SEARCH_FAKE_OBJ)) ||
593 ((opt[0] == 'v' || opt[0] == 'a' || opt[0] == 's') &&
594 (o = opt_find(&cc, opt + 1, NULL, 0, AV_OPT_SEARCH_FAKE_OBJ)))) {
595 av_dict_set(&codec_opts, opt, arg, FLAGS);
596 consumed = 1;
597 }
598 if ((o = opt_find(&fc, opt, NULL, 0,
599 AV_OPT_SEARCH_CHILDREN | AV_OPT_SEARCH_FAKE_OBJ))) {
600 av_dict_set(&format_opts, opt, arg, FLAGS);
601 if (consumed)
602 av_log(NULL, AV_LOG_VERBOSE, "Routing option %s to both codec and muxer layer\n", opt);
603 consumed = 1;
604 }
605#if CONFIG_SWSCALE
606 if (!consumed && (o = opt_find(&sc, opt, NULL, 0,
607 AV_OPT_SEARCH_CHILDREN | AV_OPT_SEARCH_FAKE_OBJ))) {
608 if (!strcmp(opt, "srcw") || !strcmp(opt, "srch") ||
609 !strcmp(opt, "dstw") || !strcmp(opt, "dsth") ||
610 !strcmp(opt, "src_format") || !strcmp(opt, "dst_format")) {
611 av_log(NULL, AV_LOG_ERROR, "Directly using swscale dimensions/format options is not supported, please use the -s or -pix_fmt options\n");
612 return AVERROR(EINVAL);
613 }
614 av_dict_set(&sws_dict, opt, arg, FLAGS);
615
616 consumed = 1;
617 }
618#else
619 if (!consumed && !strcmp(opt, "sws_flags")) {
620 av_log(NULL, AV_LOG_WARNING, "Ignoring %s %s, due to disabled swscale\n", opt, arg);
621 consumed = 1;
622 }
623#endif
624#if CONFIG_SWRESAMPLE
625 if (!consumed && (o=opt_find(&swr_class, opt, NULL, 0,
626 AV_OPT_SEARCH_CHILDREN | AV_OPT_SEARCH_FAKE_OBJ))) {
627 av_dict_set(&swr_opts, opt, arg, FLAGS);
628 consumed = 1;
629 }
630#endif
631
632 if (consumed)
633 return 0;
634 return AVERROR_OPTION_NOT_FOUND;
635}
636
637/*
638 * Check whether given option is a group separator.
639 *
640 * @return index of the group definition that matched or -1 if none
641 */
642static int match_group_separator(const OptionGroupDef *groups, int nb_groups,
643 const char *opt)
644{
645 int i;
646
647 for (i = 0; i < nb_groups; i++) {
648 const OptionGroupDef *p = &groups[i];
649 if (p->sep && !strcmp(p->sep, opt))
650 return i;
651 }
652
653 return -1;
654}
655
656/*
657 * Finish parsing an option group.
658 *
659 * @param group_idx which group definition should this group belong to
660 * @param arg argument of the group delimiting option
661 */
662static void finish_group(OptionParseContext *octx, int group_idx,
663 const char *arg)
664{
665 OptionGroupList *l = &octx->groups[group_idx];
666 OptionGroup *g;
667
669 g = &l->groups[l->nb_groups - 1];
670
671 *g = octx->cur_group;
672 g->arg = arg;
673 g->group_def = l->group_def;
674 g->sws_dict = sws_dict;
675 g->swr_opts = swr_opts;
678
679 codec_opts = NULL;
680 format_opts = NULL;
681 sws_dict = NULL;
682 swr_opts = NULL;
683
684 memset(&octx->cur_group, 0, sizeof(octx->cur_group));
685}
686
687/*
688 * Add an option instance to currently parsed group.
689 */
690static void add_opt(OptionParseContext *octx, const OptionDef *opt,
691 const char *key, const char *val)
692{
693 int global = !(opt->flags & (OPT_PERFILE | OPT_SPEC | OPT_OFFSET));
694 OptionGroup *g = global ? &octx->global_opts : &octx->cur_group;
695
696 GROW_ARRAY(g->opts, g->nb_opts);
697 g->opts[g->nb_opts - 1].opt = opt;
698 g->opts[g->nb_opts - 1].key = key;
699 g->opts[g->nb_opts - 1].val = val;
700}
701
703 const OptionGroupDef *groups, int nb_groups)
704{
705 static const OptionGroupDef global_group = { "global" };
706 int i;
707
708 memset(octx, 0, sizeof(*octx));
709
710 octx->nb_groups = nb_groups;
711 octx->groups = av_calloc(octx->nb_groups, sizeof(*octx->groups));
712 if (!octx->groups)
713 report_and_exit(AVERROR(ENOMEM));
714
715 for (i = 0; i < octx->nb_groups; i++)
716 octx->groups[i].group_def = &groups[i];
717
718 octx->global_opts.group_def = &global_group;
719 octx->global_opts.arg = "";
720}
721
723{
724 int i, j;
725
726 for (i = 0; i < octx->nb_groups; i++) {
727 OptionGroupList *l = &octx->groups[i];
728
729 for (j = 0; j < l->nb_groups; j++) {
730 av_freep(&l->groups[j].opts);
731 av_dict_free(&l->groups[j].codec_opts);
732 av_dict_free(&l->groups[j].format_opts);
733
734 av_dict_free(&l->groups[j].sws_dict);
735 av_dict_free(&l->groups[j].swr_opts);
736 }
737 av_freep(&l->groups);
738 }
739 av_freep(&octx->groups);
740
741 av_freep(&octx->cur_group.opts);
742 av_freep(&octx->global_opts.opts);
743
744 uninit_opts();
745}
746
747int split_commandline(OptionParseContext *octx, int argc, char *argv[],
748 const OptionDef *options,
749 const OptionGroupDef *groups, int nb_groups)
750{
751 int optindex = 1;
752 int dashdash = -2;
753
754 /* perform system-dependent conversions for arguments list */
755 prepare_app_arguments(&argc, &argv);
756
757 init_parse_context(octx, groups, nb_groups);
758 av_log(NULL, AV_LOG_DEBUG, "Splitting the commandline.\n");
759
760 while (optindex < argc) {
761 const char *opt = argv[optindex++], *arg;
762 const OptionDef *po;
763 int ret;
764
765 av_log(NULL, AV_LOG_DEBUG, "Reading option '%s' ...", opt);
766
767 if (opt[0] == '-' && opt[1] == '-' && !opt[2]) {
768 dashdash = optindex;
769 continue;
770 }
771 /* unnamed group separators, e.g. output filename */
772 if (opt[0] != '-' || !opt[1] || dashdash+1 == optindex) {
773 finish_group(octx, 0, opt);
774 av_log(NULL, AV_LOG_DEBUG, " matched as %s.\n", groups[0].name);
775 continue;
776 }
777 opt++;
778
779#define GET_ARG(arg) \
780do { \
781 if (optindex < argc) { \
782 arg = argv[optindex++]; \
783 } else { \
784 av_log(NULL, AV_LOG_ERROR, "Missing argument for option '%s'.\n", opt);\
785 return AVERROR(EINVAL); \
786 } \
787} while (0)
788
789 /* named group separators, e.g. -i */
790 if ((ret = match_group_separator(groups, nb_groups, opt)) >= 0) {
791 GET_ARG(arg);
792 finish_group(octx, ret, arg);
793 av_log(NULL, AV_LOG_DEBUG, " matched as %s with argument '%s'.\n",
794 groups[ret].name, arg);
795 continue;
796 }
797
798 /* normal options */
799 po = find_option(options, opt);
800 if (po->name) {
801 if (po->flags & OPT_EXIT) {
802 /* optional argument, e.g. -h */
803 if (optindex < argc) {
804 arg = argv[optindex++];
805 } else {
806 arg = NULL;
807 }
808 } else if (po->flags & HAS_ARG) {
809 GET_ARG(arg);
810 } else {
811 arg = "1";
812 }
813
814 add_opt(octx, po, opt, arg);
815 av_log(NULL, AV_LOG_DEBUG, " matched as option '%s' (%s) with "
816 "argument '%s'.\n", po->name, po->help, arg);
817 continue;
818 }
819
820 /* AVOptions */
821 if ((optindex < argc) && argv[optindex]) {
822 ret = opt_default(NULL, opt, argv[optindex]);
823 if (ret >= 0) {
824 av_log(NULL, AV_LOG_DEBUG, " matched as AVOption '%s' with "
825 "argument '%s'.\n", opt, argv[optindex]);
826 optindex++;
827 continue;
828 } else if (ret != AVERROR_OPTION_NOT_FOUND) {
829 av_log(NULL, AV_LOG_ERROR, "Error parsing option '%s' "
830 "with argument '%s'.\n", opt, argv[optindex]);
831 return ret;
832 }
833 }
834
835 /* boolean -nofoo options */
836 if (opt[0] == 'n' && opt[1] == 'o' &&
837 (po = find_option(options, opt + 2)) &&
838 po->name && po->flags & OPT_BOOL) {
839 add_opt(octx, po, opt, "0");
840 av_log(NULL, AV_LOG_DEBUG, " matched as option '%s' (%s) with "
841 "argument 0.\n", po->name, po->help);
842 continue;
843 }
844
845 av_log(NULL, AV_LOG_ERROR, "Unrecognized option '%s'.\n", opt);
846 return AVERROR_OPTION_NOT_FOUND;
847 }
848
849 if (octx->cur_group.nb_opts || codec_opts || format_opts)
850 av_log(NULL, AV_LOG_WARNING, "Trailing option(s) found in the "
851 "command: may be ignored.\n");
852
853 av_log(NULL, AV_LOG_DEBUG, "Finished splitting the commandline.\n");
854
855 return 0;
856}
857
858void print_error(const char *filename, int err)
859{
860 av_log(NULL, AV_LOG_ERROR, "%s: %s\n", filename, av_err2str(err));
861}
862
863int read_yesno(void)
864{
865 int c = getchar();
866 int yesno = (av_toupper(c) == 'Y');
867
868 while (c != '\n' && c != EOF)
869 c = getchar();
870
871 return yesno;
872}
873
874FILE *get_preset_file(char *filename, size_t filename_size,
875 const char *preset_name, int is_path,
876 const char *codec_name)
877{
878 FILE *f = NULL;
879 int i;
880#if HAVE_GETMODULEHANDLE && defined(_WIN32)
881 char *datadir = NULL;
882#endif
883 char *env_home = getenv_utf8("HOME");
884 char *env_ffmpeg_datadir = getenv_utf8("FFMPEG_DATADIR");
885 const char *base[3] = { env_ffmpeg_datadir,
886 env_home, /* index=1(HOME) is special: search in a .ffmpeg subfolder */
887 FFMPEG_DATADIR, };
888
889 if (is_path) {
890 av_strlcpy(filename, preset_name, filename_size);
891 f = fopen_utf8(filename, "r");
892 } else {
893#if HAVE_GETMODULEHANDLE && defined(_WIN32)
894 wchar_t *datadir_w = get_module_filename(NULL);
895 base[2] = NULL;
896
897 if (wchartoutf8(datadir_w, &datadir))
898 datadir = NULL;
899 av_free(datadir_w);
900
901 if (datadir)
902 {
903 char *ls;
904 for (ls = datadir; *ls; ls++)
905 if (*ls == '\\') *ls = '/';
906
907 if (ls = strrchr(datadir, '/'))
908 {
909 ptrdiff_t datadir_len = ls - datadir;
910 size_t desired_size = datadir_len + strlen("/ffpresets") + 1;
911 char *new_datadir = av_realloc_array(
912 datadir, desired_size, sizeof *datadir);
913 if (new_datadir) {
914 datadir = new_datadir;
915 datadir[datadir_len] = 0;
916 strncat(datadir, "/ffpresets", desired_size - 1 - datadir_len);
917 base[2] = datadir;
918 }
919 }
920 }
921#endif
922 for (i = 0; i < 3 && !f; i++) {
923 if (!base[i])
924 continue;
925 snprintf(filename, filename_size, "%s%s/%s.ffpreset", base[i],
926 i != 1 ? "" : "/.ffmpeg", preset_name);
927 f = fopen_utf8(filename, "r");
928 if (!f && codec_name) {
929 snprintf(filename, filename_size,
930 "%s%s/%s-%s.ffpreset",
931 base[i], i != 1 ? "" : "/.ffmpeg", codec_name,
932 preset_name);
933 f = fopen_utf8(filename, "r");
934 }
935 }
936 }
937
938#if HAVE_GETMODULEHANDLE && defined(_WIN32)
939 av_free(datadir);
940#endif
941 freeenv_utf8(env_ffmpeg_datadir);
942 freeenv_utf8(env_home);
943 return f;
944}
945
946int check_stream_specifier(AVFormatContext *s, AVStream *st, const char *spec)
947{
948 int ret = avformat_match_stream_specifier(s, st, spec);
949 if (ret < 0)
950 av_log(s, AV_LOG_ERROR, "Invalid stream specifier: %s.\n", spec);
951 return ret;
952}
953
954AVDictionary *filter_codec_opts(AVDictionary *opts, enum AVCodecID codec_id,
955 AVFormatContext *s, AVStream *st, const AVCodec *codec)
956{
957 AVDictionary *ret = NULL;
958 const AVDictionaryEntry *t = NULL;
959 int flags = s->oformat ? AV_OPT_FLAG_ENCODING_PARAM
960 : AV_OPT_FLAG_DECODING_PARAM;
961 char prefix = 0;
962 const AVClass *cc = avcodec_get_class();
963
964 if (!codec)
965 codec = s->oformat ? avcodec_find_encoder(codec_id)
966 : avcodec_find_decoder(codec_id);
967
968 switch (st->codecpar->codec_type) {
969 case AVMEDIA_TYPE_VIDEO:
970 prefix = 'v';
971 flags |= AV_OPT_FLAG_VIDEO_PARAM;
972 break;
973 case AVMEDIA_TYPE_AUDIO:
974 prefix = 'a';
975 flags |= AV_OPT_FLAG_AUDIO_PARAM;
976 break;
977 case AVMEDIA_TYPE_SUBTITLE:
978 prefix = 's';
979 flags |= AV_OPT_FLAG_SUBTITLE_PARAM;
980 break;
981 }
982
983 while ((t = av_dict_iterate(opts, t))) {
984 const AVClass *priv_class;
985 char *p = strchr(t->key, ':');
986
987 /* check stream specification in opt name */
988 if (p)
989 switch (check_stream_specifier(s, st, p + 1)) {
990 case 1: *p = 0; break;
991 case 0: continue;
992 default: exit_program(1);
993 }
994
995 if (av_opt_find(&cc, t->key, NULL, flags, AV_OPT_SEARCH_FAKE_OBJ) ||
996 !codec ||
997 ((priv_class = codec->priv_class) &&
998 av_opt_find(&priv_class, t->key, NULL, flags,
999 AV_OPT_SEARCH_FAKE_OBJ)))
1000 av_dict_set(&ret, t->key, t->value, 0);
1001 else if (t->key[0] == prefix &&
1002 av_opt_find(&cc, t->key + 1, NULL, flags,
1003 AV_OPT_SEARCH_FAKE_OBJ))
1004 av_dict_set(&ret, t->key + 1, t->value, 0);
1005
1006 if (p)
1007 *p = ':';
1008 }
1009 return ret;
1010}
1011
1012AVDictionary **setup_find_stream_info_opts(AVFormatContext *s,
1013 AVDictionary *codec_opts)
1014{
1015 int i;
1016 AVDictionary **opts;
1017
1018 if (!s->nb_streams)
1019 return NULL;
1020 opts = av_calloc(s->nb_streams, sizeof(*opts));
1021 if (!opts)
1022 report_and_exit(AVERROR(ENOMEM));
1023 for (i = 0; i < s->nb_streams; i++)
1024 opts[i] = filter_codec_opts(codec_opts, s->streams[i]->codecpar->codec_id,
1025 s, s->streams[i], NULL);
1026 return opts;
1027}
1028
1029void *grow_array(void *array, int elem_size, int *size, int new_size)
1030{
1031 if (new_size >= INT_MAX / elem_size) {
1032 av_log(NULL, AV_LOG_ERROR, "Array too big.\n");
1033 exit_program(1);
1034 }
1035 if (*size < new_size) {
1036 uint8_t *tmp = av_realloc_array(array, new_size, elem_size);
1037 if (!tmp)
1038 report_and_exit(AVERROR(ENOMEM));
1039 memset(tmp + *size*elem_size, 0, (new_size-*size) * elem_size);
1040 *size = new_size;
1041 return tmp;
1042 }
1043 return array;
1044}
1045
1046void *allocate_array_elem(void *ptr, size_t elem_size, int *nb_elems)
1047{
1048 void *new_elem;
1049
1050 if (!(new_elem = av_mallocz(elem_size)) ||
1051 av_dynarray_add_nofree(ptr, nb_elems, new_elem) < 0)
1052 report_and_exit(AVERROR(ENOMEM));
1053 return new_elem;
1054}
1055
1056double get_rotation(int32_t *displaymatrix)
1057{
1058 double theta = 0;
1059 if (displaymatrix)
1060 theta = -round(av_display_rotation_get((int32_t*) displaymatrix));
1061
1062 theta -= 360*floor(theta/360 + 0.9/360);
1063
1064 if (fabs(theta - 90*round(theta/90)) > 2)
1065 av_log(NULL, AV_LOG_WARNING, "Odd rotation angle.\n"
1066 "If you want to help, upload a sample "
1067 "of this file to https://streams.videolan.org/upload/ "
1068 "and contact the ffmpeg-devel mailing list. (ffmpeg-devel@ffmpeg.org)");
1069
1070 return theta;
1071}
__thread jmp_buf ex_buf__
void exit_program(int ret)
__thread AVDictionary * swr_opts
static int match_group_separator(const OptionGroupDef *groups, int nb_groups, const char *opt)
void show_help_children(const AVClass *class, int flags)
__thread AVDictionary * codec_opts
static void prepare_app_arguments(int *argc_ptr, char ***argv_ptr)
void init_dynload(void)
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)
double get_rotation(int32_t *displaymatrix)
void report_and_exit(int ret)
int read_yesno(void)
int locate_option(int argc, char **argv, const OptionDef *options, const char *optname)
static void dump_argument(FILE *report_file, const char *a)
static const AVOption * opt_find(void *obj, const char *name, const char *unit, int opt_flags, int search_flags)
static int write_option(void *optctx, const OptionDef *po, const char *opt, const char *arg)
int check_stream_specifier(AVFormatContext *s, AVStream *st, const char *spec)
static void init_parse_context(OptionParseContext *octx, const OptionGroupDef *groups, int nb_groups)
static void add_opt(OptionParseContext *octx, const OptionDef *opt, const char *key, const char *val)
__thread char * program_name
#define FLAGS
static __thread void(* program_exit)(int ret)
#define GET_ARG(arg)
static void finish_group(OptionParseContext *octx, int group_idx, const char *arg)
__thread int longjmp_value
void parse_loglevel(int argc, char **argv, const OptionDef *options)
__thread int program_birth_year
void parse_options(void *optctx, int argc, char **argv, const OptionDef *options, void(*parse_arg_function)(void *, const char *))
void uninit_parse_context(OptionParseContext *octx)
__thread AVDictionary * sws_dict
int split_commandline(OptionParseContext *octx, int argc, char *argv[], const OptionDef *options, const OptionGroupDef *groups, int nb_groups)
void * allocate_array_elem(void *ptr, size_t elem_size, int *nb_elems)
int64_t parse_time_or_die(const char *context, const char *timestr, int is_duration)
void register_exit(void(*cb)(int ret))
FILE * get_preset_file(char *filename, size_t filename_size, const char *preset_name, int is_path, const char *codec_name)
void uninit_opts(void)
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)
static const OptionDef * find_option(const OptionDef *po, const char *name)
__thread int hide_banner
int parse_optgroup(void *optctx, OptionGroup *g)
static void check_options(const OptionDef *po)
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_SPEC
#define OPT_BOOL
#define OPT_INT64
#define OPT_PERFILE
#define OPT_INT
#define OPT_FLOAT
#define AV_LOG_STDERR
#define OPT_INPUT
#define OPT_DOUBLE
#define OPT_STRING
#define GROW_ARRAY(array, nb_elems)
#define OPT_EXIT
#define OPT_OUTPUT
#define OPT_TIME
#define OPT_OFFSET
#define HAS_ARG
static const OptionGroupDef groups[]
static FILE * fopen_utf8(const char *path, const char *mode)
int opt_loglevel(void *optctx, const char *opt, const char *arg)
static __thread FILE * report_file
int init_report(const char *env, FILE **file)
union OptionDef::@1 u
const char * name
const char * argname
const char * help
int(* func_arg)(void *, const char *, const char *)
const char * name
const OptionGroupDef * group_def
AVDictionary * codec_opts
AVDictionary * swr_opts
AVDictionary * sws_dict
const char * arg
AVDictionary * format_opts
OptionGroup * groups
const OptionGroupDef * group_def
const char * key
const OptionDef * opt
const char * val
OptionGroupList * groups