]> git.sesse.net Git - ffmpeg/blob - libavutil/opt.c
Merge commit '9ce02e14f01de50fcc6f7f459544b140be66d615'
[ffmpeg] / libavutil / opt.c
1 /*
2  * AVOptions
3  * Copyright (c) 2005 Michael Niedermayer <michaelni@gmx.at>
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  * @file
24  * AVOptions
25  * @author Michael Niedermayer <michaelni@gmx.at>
26  */
27
28 #include "avutil.h"
29 #include "avstring.h"
30 #include "common.h"
31 #include "opt.h"
32 #include "eval.h"
33 #include "dict.h"
34 #include "log.h"
35 #include "parseutils.h"
36 #include "pixdesc.h"
37 #include "mathematics.h"
38 #include "samplefmt.h"
39
40 #if FF_API_FIND_OPT
41 //FIXME order them and do a bin search
42 const AVOption *av_find_opt(void *v, const char *name, const char *unit, int mask, int flags)
43 {
44     const AVOption *o = NULL;
45
46     while ((o = av_next_option(v, o))) {
47         if (!strcmp(o->name, name) && (!unit || (o->unit && !strcmp(o->unit, unit))) && (o->flags & mask) == flags)
48             return o;
49     }
50     return NULL;
51 }
52 #endif
53
54 #if FF_API_OLD_AVOPTIONS
55 const AVOption *av_next_option(void *obj, const AVOption *last)
56 {
57     return av_opt_next(obj, last);
58 }
59 #endif
60
61 const AVOption *av_opt_next(void *obj, const AVOption *last)
62 {
63     AVClass *class = *(AVClass**)obj;
64     if (!last && class->option && class->option[0].name)
65         return class->option;
66     if (last && last[1].name)           return ++last;
67     return NULL;
68 }
69
70 static int read_number(const AVOption *o, void *dst, double *num, int *den, int64_t *intnum)
71 {
72     switch (o->type) {
73     case AV_OPT_TYPE_FLAGS:     *intnum = *(unsigned int*)dst;return 0;
74     case AV_OPT_TYPE_INT:       *intnum = *(int         *)dst;return 0;
75     case AV_OPT_TYPE_INT64:     *intnum = *(int64_t     *)dst;return 0;
76     case AV_OPT_TYPE_FLOAT:     *num    = *(float       *)dst;return 0;
77     case AV_OPT_TYPE_DOUBLE:    *num    = *(double      *)dst;return 0;
78     case AV_OPT_TYPE_RATIONAL:  *intnum = ((AVRational*)dst)->num;
79                                 *den    = ((AVRational*)dst)->den;
80                                                         return 0;
81     case AV_OPT_TYPE_CONST:     *num    = o->default_val.dbl; return 0;
82     }
83     return AVERROR(EINVAL);
84 }
85
86 static int write_number(void *obj, const AVOption *o, void *dst, double num, int den, int64_t intnum)
87 {
88     if (o->max*den < num*intnum || o->min*den > num*intnum) {
89         av_log(obj, AV_LOG_ERROR, "Value %f for parameter '%s' out of range\n",
90                num*intnum/den, o->name);
91         return AVERROR(ERANGE);
92     }
93
94     switch (o->type) {
95     case AV_OPT_TYPE_FLAGS:
96     case AV_OPT_TYPE_INT:   *(int       *)dst= llrint(num/den)*intnum; break;
97     case AV_OPT_TYPE_INT64: *(int64_t   *)dst= llrint(num/den)*intnum; break;
98     case AV_OPT_TYPE_FLOAT: *(float     *)dst= num*intnum/den;         break;
99     case AV_OPT_TYPE_DOUBLE:*(double    *)dst= num*intnum/den;         break;
100     case AV_OPT_TYPE_RATIONAL:
101         if ((int)num == num) *(AVRational*)dst= (AVRational){num*intnum, den};
102         else                 *(AVRational*)dst= av_d2q(num*intnum/den, 1<<24);
103         break;
104     default:
105         return AVERROR(EINVAL);
106     }
107     return 0;
108 }
109
110 static const double const_values[] = {
111     M_PI,
112     M_E,
113     FF_QP2LAMBDA,
114     0
115 };
116
117 static const char * const const_names[] = {
118     "PI",
119     "E",
120     "QP2LAMBDA",
121     0
122 };
123
124 static int hexchar2int(char c) {
125     if (c >= '0' && c <= '9') return c - '0';
126     if (c >= 'a' && c <= 'f') return c - 'a' + 10;
127     if (c >= 'A' && c <= 'F') return c - 'A' + 10;
128     return -1;
129 }
130
131 static int set_string_binary(void *obj, const AVOption *o, const char *val, uint8_t **dst)
132 {
133     int *lendst = (int *)(dst + 1);
134     uint8_t *bin, *ptr;
135     int len = strlen(val);
136
137     av_freep(dst);
138     *lendst = 0;
139
140     if (len & 1)
141         return AVERROR(EINVAL);
142     len /= 2;
143
144     ptr = bin = av_malloc(len);
145     while (*val) {
146         int a = hexchar2int(*val++);
147         int b = hexchar2int(*val++);
148         if (a < 0 || b < 0) {
149             av_free(bin);
150             return AVERROR(EINVAL);
151         }
152         *ptr++ = (a << 4) | b;
153     }
154     *dst = bin;
155     *lendst = len;
156
157     return 0;
158 }
159
160 static int set_string(void *obj, const AVOption *o, const char *val, uint8_t **dst)
161 {
162     av_freep(dst);
163     *dst = av_strdup(val);
164     return 0;
165 }
166
167 #define DEFAULT_NUMVAL(opt) ((opt->type == AV_OPT_TYPE_INT64 || \
168                               opt->type == AV_OPT_TYPE_CONST || \
169                               opt->type == AV_OPT_TYPE_FLAGS || \
170                               opt->type == AV_OPT_TYPE_INT) ? \
171                              opt->default_val.i64 : opt->default_val.dbl)
172
173 static int set_string_number(void *obj, const AVOption *o, const char *val, void *dst)
174 {
175     int ret = 0, notfirst = 0;
176     for (;;) {
177         int i, den = 1;
178         char buf[256];
179         int cmd = 0;
180         double d, num = 1;
181         int64_t intnum = 1;
182
183         if (*val == '+' || *val == '-')
184             cmd = *(val++);
185
186         for (i = 0; i < sizeof(buf) - 1 && val[i] && val[i] != '+' && val[i] != '-'; i++)
187             buf[i] = val[i];
188         buf[i] = 0;
189
190         {
191             const AVOption *o_named = av_opt_find(obj, buf, o->unit, 0, 0);
192             if (o_named && o_named->type == AV_OPT_TYPE_CONST)
193                 d = DEFAULT_NUMVAL(o_named);
194             else if (!strcmp(buf, "default")) d = DEFAULT_NUMVAL(o);
195             else if (!strcmp(buf, "max"    )) d = o->max;
196             else if (!strcmp(buf, "min"    )) d = o->min;
197             else if (!strcmp(buf, "none"   )) d = 0;
198             else if (!strcmp(buf, "all"    )) d = ~0;
199             else {
200                 int res = av_expr_parse_and_eval(&d, buf, const_names, const_values, NULL, NULL, NULL, NULL, NULL, 0, obj);
201                 if (res < 0) {
202                     av_log(obj, AV_LOG_ERROR, "Unable to parse option value \"%s\"\n", val);
203                     return res;
204                 }
205             }
206         }
207         if (o->type == AV_OPT_TYPE_FLAGS) {
208             read_number(o, dst, NULL, NULL, &intnum);
209             if      (cmd == '+') d = intnum | (int64_t)d;
210             else if (cmd == '-') d = intnum &~(int64_t)d;
211         } else {
212             read_number(o, dst, &num, &den, &intnum);
213             if      (cmd == '+') d = notfirst*num*intnum/den + d;
214             else if (cmd == '-') d = notfirst*num*intnum/den - d;
215         }
216
217         if ((ret = write_number(obj, o, dst, d, 1, 1)) < 0)
218             return ret;
219         val += i;
220         if (!*val)
221             return 0;
222         notfirst = 1;
223     }
224
225     return 0;
226 }
227
228 #if FF_API_OLD_AVOPTIONS
229 int av_set_string3(void *obj, const char *name, const char *val, int alloc, const AVOption **o_out)
230 {
231     const AVOption *o = av_opt_find(obj, name, NULL, 0, 0);
232     if (o_out)
233         *o_out = o;
234     return av_opt_set(obj, name, val, 0);
235 }
236 #endif
237
238 int av_opt_set(void *obj, const char *name, const char *val, int search_flags)
239 {
240     int ret;
241     void *dst, *target_obj;
242     const AVOption *o = av_opt_find2(obj, name, NULL, 0, search_flags, &target_obj);
243     if (!o || !target_obj)
244         return AVERROR_OPTION_NOT_FOUND;
245     if (!val && (o->type != AV_OPT_TYPE_STRING && o->type != AV_OPT_TYPE_PIXEL_FMT && o->type != AV_OPT_TYPE_IMAGE_SIZE))
246         return AVERROR(EINVAL);
247
248     dst = ((uint8_t*)target_obj) + o->offset;
249     switch (o->type) {
250     case AV_OPT_TYPE_STRING:   return set_string(obj, o, val, dst);
251     case AV_OPT_TYPE_BINARY:   return set_string_binary(obj, o, val, dst);
252     case AV_OPT_TYPE_FLAGS:
253     case AV_OPT_TYPE_INT:
254     case AV_OPT_TYPE_INT64:
255     case AV_OPT_TYPE_FLOAT:
256     case AV_OPT_TYPE_DOUBLE:
257     case AV_OPT_TYPE_RATIONAL: return set_string_number(obj, o, val, dst);
258     case AV_OPT_TYPE_IMAGE_SIZE:
259         if (!val || !strcmp(val, "none")) {
260             *(int *)dst = *((int *)dst + 1) = 0;
261             return 0;
262         }
263         ret = av_parse_video_size(dst, ((int *)dst) + 1, val);
264         if (ret < 0)
265             av_log(obj, AV_LOG_ERROR, "Unable to parse option value \"%s\" as image size\n", val);
266         return ret;
267     case AV_OPT_TYPE_PIXEL_FMT:
268         if (!val || !strcmp(val, "none")) {
269             ret = AV_PIX_FMT_NONE;
270         } else {
271             ret = av_get_pix_fmt(val);
272             if (ret == AV_PIX_FMT_NONE) {
273                 char *tail;
274                 ret = strtol(val, &tail, 0);
275                 if (*tail || (unsigned)ret >= AV_PIX_FMT_NB) {
276                     av_log(obj, AV_LOG_ERROR, "Unable to parse option value \"%s\" as pixel format\n", val);
277                     return AVERROR(EINVAL);
278                 }
279             }
280         }
281         *(enum AVPixelFormat *)dst = ret;
282         return 0;
283     case AV_OPT_TYPE_SAMPLE_FMT:
284         if (!val || !strcmp(val, "none")) {
285             ret = AV_SAMPLE_FMT_NONE;
286         } else {
287             ret = av_get_sample_fmt(val);
288             if (ret == AV_SAMPLE_FMT_NONE) {
289                 char *tail;
290                 ret = strtol(val, &tail, 0);
291                 if (*tail || (unsigned)ret >= AV_SAMPLE_FMT_NB) {
292                     av_log(obj, AV_LOG_ERROR, "Unable to parse option value \"%s\" as sample format\n", val);
293                     return AVERROR(EINVAL);
294                 }
295             }
296         }
297         *(enum AVSampleFormat *)dst = ret;
298         return 0;
299     }
300
301     av_log(obj, AV_LOG_ERROR, "Invalid option type.\n");
302     return AVERROR(EINVAL);
303 }
304
305 #define OPT_EVAL_NUMBER(name, opttype, vartype)\
306     int av_opt_eval_ ## name(void *obj, const AVOption *o, const char *val, vartype *name ## _out)\
307     {\
308         if (!o || o->type != opttype)\
309             return AVERROR(EINVAL);\
310         return set_string_number(obj, o, val, name ## _out);\
311     }
312
313 OPT_EVAL_NUMBER(flags,  AV_OPT_TYPE_FLAGS,    int)
314 OPT_EVAL_NUMBER(int,    AV_OPT_TYPE_INT,      int)
315 OPT_EVAL_NUMBER(int64,  AV_OPT_TYPE_INT64,    int64_t)
316 OPT_EVAL_NUMBER(float,  AV_OPT_TYPE_FLOAT,    float)
317 OPT_EVAL_NUMBER(double, AV_OPT_TYPE_DOUBLE,   double)
318 OPT_EVAL_NUMBER(q,      AV_OPT_TYPE_RATIONAL, AVRational)
319
320 static int set_number(void *obj, const char *name, double num, int den, int64_t intnum,
321                                   int search_flags)
322 {
323     void *dst, *target_obj;
324     const AVOption *o = av_opt_find2(obj, name, NULL, 0, search_flags, &target_obj);
325
326     if (!o || !target_obj)
327         return AVERROR_OPTION_NOT_FOUND;
328
329     dst = ((uint8_t*)target_obj) + o->offset;
330     return write_number(obj, o, dst, num, den, intnum);
331 }
332
333 #if FF_API_OLD_AVOPTIONS
334 const AVOption *av_set_double(void *obj, const char *name, double n)
335 {
336     const AVOption *o = av_opt_find(obj, name, NULL, 0, 0);
337     if (set_number(obj, name, n, 1, 1, 0) < 0)
338         return NULL;
339     return o;
340 }
341
342 const AVOption *av_set_q(void *obj, const char *name, AVRational n)
343 {
344     const AVOption *o = av_opt_find(obj, name, NULL, 0, 0);
345     if (set_number(obj, name, n.num, n.den, 1, 0) < 0)
346         return NULL;
347     return o;
348 }
349
350 const AVOption *av_set_int(void *obj, const char *name, int64_t n)
351 {
352     const AVOption *o = av_opt_find(obj, name, NULL, 0, 0);
353     if (set_number(obj, name, 1, 1, n, 0) < 0)
354         return NULL;
355     return o;
356 }
357 #endif
358
359 int av_opt_set_int(void *obj, const char *name, int64_t val, int search_flags)
360 {
361     return set_number(obj, name, 1, 1, val, search_flags);
362 }
363
364 int av_opt_set_double(void *obj, const char *name, double val, int search_flags)
365 {
366     return set_number(obj, name, val, 1, 1, search_flags);
367 }
368
369 int av_opt_set_q(void *obj, const char *name, AVRational val, int search_flags)
370 {
371     return set_number(obj, name, val.num, val.den, 1, search_flags);
372 }
373
374 int av_opt_set_bin(void *obj, const char *name, const uint8_t *val, int len, int search_flags)
375 {
376     void *target_obj;
377     const AVOption *o = av_opt_find2(obj, name, NULL, 0, search_flags, &target_obj);
378     uint8_t *ptr;
379     uint8_t **dst;
380     int *lendst;
381
382     if (!o || !target_obj)
383         return AVERROR_OPTION_NOT_FOUND;
384
385     if (o->type != AV_OPT_TYPE_BINARY)
386         return AVERROR(EINVAL);
387
388     ptr = av_malloc(len);
389     if (!ptr)
390         return AVERROR(ENOMEM);
391
392     dst = (uint8_t **)(((uint8_t *)target_obj) + o->offset);
393     lendst = (int *)(dst + 1);
394
395     av_free(*dst);
396     *dst = ptr;
397     *lendst = len;
398     memcpy(ptr, val, len);
399
400     return 0;
401 }
402
403 #if FF_API_OLD_AVOPTIONS
404 /**
405  *
406  * @param buf a buffer which is used for returning non string values as strings, can be NULL
407  * @param buf_len allocated length in bytes of buf
408  */
409 const char *av_get_string(void *obj, const char *name, const AVOption **o_out, char *buf, int buf_len)
410 {
411     const AVOption *o = av_opt_find(obj, name, NULL, 0, AV_OPT_SEARCH_CHILDREN);
412     void *dst;
413     uint8_t *bin;
414     int len, i;
415     if (!o)
416         return NULL;
417     if (o->type != AV_OPT_TYPE_STRING && (!buf || !buf_len))
418         return NULL;
419
420     dst= ((uint8_t*)obj) + o->offset;
421     if (o_out) *o_out= o;
422
423     switch (o->type) {
424     case AV_OPT_TYPE_FLAGS:     snprintf(buf, buf_len, "0x%08X",*(int    *)dst);break;
425     case AV_OPT_TYPE_INT:       snprintf(buf, buf_len, "%d" , *(int    *)dst);break;
426     case AV_OPT_TYPE_INT64:     snprintf(buf, buf_len, "%"PRId64, *(int64_t*)dst);break;
427     case AV_OPT_TYPE_FLOAT:     snprintf(buf, buf_len, "%f" , *(float  *)dst);break;
428     case AV_OPT_TYPE_DOUBLE:    snprintf(buf, buf_len, "%f" , *(double *)dst);break;
429     case AV_OPT_TYPE_RATIONAL:  snprintf(buf, buf_len, "%d/%d", ((AVRational*)dst)->num, ((AVRational*)dst)->den);break;
430     case AV_OPT_TYPE_CONST:     snprintf(buf, buf_len, "%f" , o->default_val.dbl);break;
431     case AV_OPT_TYPE_STRING:    return *(void**)dst;
432     case AV_OPT_TYPE_BINARY:
433         len = *(int*)(((uint8_t *)dst) + sizeof(uint8_t *));
434         if (len >= (buf_len + 1)/2) return NULL;
435         bin = *(uint8_t**)dst;
436         for (i = 0; i < len; i++) snprintf(buf + i*2, 3, "%02X", bin[i]);
437         break;
438     default: return NULL;
439     }
440     return buf;
441 }
442 #endif
443
444 int av_opt_get(void *obj, const char *name, int search_flags, uint8_t **out_val)
445 {
446     void *dst, *target_obj;
447     const AVOption *o = av_opt_find2(obj, name, NULL, 0, search_flags, &target_obj);
448     uint8_t *bin, buf[128];
449     int len, i, ret;
450
451     if (!o || !target_obj || (o->offset<=0 && o->type != AV_OPT_TYPE_CONST))
452         return AVERROR_OPTION_NOT_FOUND;
453
454     dst = (uint8_t*)target_obj + o->offset;
455
456     buf[0] = 0;
457     switch (o->type) {
458     case AV_OPT_TYPE_FLAGS:     ret = snprintf(buf, sizeof(buf), "0x%08X",  *(int    *)dst);break;
459     case AV_OPT_TYPE_INT:       ret = snprintf(buf, sizeof(buf), "%d" ,     *(int    *)dst);break;
460     case AV_OPT_TYPE_INT64:     ret = snprintf(buf, sizeof(buf), "%"PRId64, *(int64_t*)dst);break;
461     case AV_OPT_TYPE_FLOAT:     ret = snprintf(buf, sizeof(buf), "%f" ,     *(float  *)dst);break;
462     case AV_OPT_TYPE_DOUBLE:    ret = snprintf(buf, sizeof(buf), "%f" ,     *(double *)dst);break;
463     case AV_OPT_TYPE_RATIONAL:  ret = snprintf(buf, sizeof(buf), "%d/%d",   ((AVRational*)dst)->num, ((AVRational*)dst)->den);break;
464     case AV_OPT_TYPE_CONST:     ret = snprintf(buf, sizeof(buf), "%f" ,     o->default_val.dbl);break;
465     case AV_OPT_TYPE_STRING:
466         if (*(uint8_t**)dst)
467             *out_val = av_strdup(*(uint8_t**)dst);
468         else
469             *out_val = av_strdup("");
470         return 0;
471     case AV_OPT_TYPE_BINARY:
472         len = *(int*)(((uint8_t *)dst) + sizeof(uint8_t *));
473         if ((uint64_t)len*2 + 1 > INT_MAX)
474             return AVERROR(EINVAL);
475         if (!(*out_val = av_malloc(len*2 + 1)))
476             return AVERROR(ENOMEM);
477         bin = *(uint8_t**)dst;
478         for (i = 0; i < len; i++)
479             snprintf(*out_val + i*2, 3, "%02X", bin[i]);
480         return 0;
481     case AV_OPT_TYPE_IMAGE_SIZE:
482         ret = snprintf(buf, sizeof(buf), "%dx%d", ((int *)dst)[0], ((int *)dst)[1]);
483         break;
484     case AV_OPT_TYPE_PIXEL_FMT:
485         ret = snprintf(buf, sizeof(buf), "%s", (char *)av_x_if_null(av_get_pix_fmt_name(*(enum AVPixelFormat *)dst), "none"));
486         break;
487     case AV_OPT_TYPE_SAMPLE_FMT:
488         ret = snprintf(buf, sizeof(buf), "%s", (char *)av_x_if_null(av_get_sample_fmt_name(*(enum AVSampleFormat *)dst), "none"));
489         break;
490     default:
491         return AVERROR(EINVAL);
492     }
493
494     if (ret >= sizeof(buf))
495         return AVERROR(EINVAL);
496     *out_val = av_strdup(buf);
497     return 0;
498 }
499
500 static int get_number(void *obj, const char *name, const AVOption **o_out, double *num, int *den, int64_t *intnum,
501                       int search_flags)
502 {
503     void *dst, *target_obj;
504     const AVOption *o = av_opt_find2(obj, name, NULL, 0, search_flags, &target_obj);
505     if (!o || !target_obj)
506         goto error;
507
508     dst = ((uint8_t*)target_obj) + o->offset;
509
510     if (o_out) *o_out= o;
511
512     return read_number(o, dst, num, den, intnum);
513
514 error:
515     *den=*intnum=0;
516     return -1;
517 }
518
519 #if FF_API_OLD_AVOPTIONS
520 double av_get_double(void *obj, const char *name, const AVOption **o_out)
521 {
522     int64_t intnum=1;
523     double num=1;
524     int den=1;
525
526     if (get_number(obj, name, o_out, &num, &den, &intnum, 0) < 0)
527         return NAN;
528     return num*intnum/den;
529 }
530
531 AVRational av_get_q(void *obj, const char *name, const AVOption **o_out)
532 {
533     int64_t intnum=1;
534     double num=1;
535     int den=1;
536
537     if (get_number(obj, name, o_out, &num, &den, &intnum, 0) < 0)
538         return (AVRational){0, 0};
539     if (num == 1.0 && (int)intnum == intnum)
540         return (AVRational){intnum, den};
541     else
542         return av_d2q(num*intnum/den, 1<<24);
543 }
544
545 int64_t av_get_int(void *obj, const char *name, const AVOption **o_out)
546 {
547     int64_t intnum=1;
548     double num=1;
549     int den=1;
550
551     if (get_number(obj, name, o_out, &num, &den, &intnum, 0) < 0)
552         return -1;
553     return num*intnum/den;
554 }
555 #endif
556
557 int av_opt_get_int(void *obj, const char *name, int search_flags, int64_t *out_val)
558 {
559     int64_t intnum = 1;
560     double     num = 1;
561     int   ret, den = 1;
562
563     if ((ret = get_number(obj, name, NULL, &num, &den, &intnum, search_flags)) < 0)
564         return ret;
565     *out_val = num*intnum/den;
566     return 0;
567 }
568
569 int av_opt_get_double(void *obj, const char *name, int search_flags, double *out_val)
570 {
571     int64_t intnum = 1;
572     double     num = 1;
573     int   ret, den = 1;
574
575     if ((ret = get_number(obj, name, NULL, &num, &den, &intnum, search_flags)) < 0)
576         return ret;
577     *out_val = num*intnum/den;
578     return 0;
579 }
580
581 int av_opt_get_q(void *obj, const char *name, int search_flags, AVRational *out_val)
582 {
583     int64_t intnum = 1;
584     double     num = 1;
585     int   ret, den = 1;
586
587     if ((ret = get_number(obj, name, NULL, &num, &den, &intnum, search_flags)) < 0)
588         return ret;
589
590     if (num == 1.0 && (int)intnum == intnum)
591         *out_val = (AVRational){intnum, den};
592     else
593         *out_val = av_d2q(num*intnum/den, 1<<24);
594     return 0;
595 }
596
597 int av_opt_flag_is_set(void *obj, const char *field_name, const char *flag_name)
598 {
599     const AVOption *field = av_opt_find(obj, field_name, NULL, 0, 0);
600     const AVOption *flag  = av_opt_find(obj, flag_name,
601                                         field ? field->unit : NULL, 0, 0);
602     int64_t res;
603
604     if (!field || !flag || flag->type != AV_OPT_TYPE_CONST ||
605         av_opt_get_int(obj, field_name, 0, &res) < 0)
606         return 0;
607     return res & flag->default_val.i64;
608 }
609
610 static void opt_list(void *obj, void *av_log_obj, const char *unit,
611                      int req_flags, int rej_flags)
612 {
613     const AVOption *opt=NULL;
614
615     while ((opt = av_opt_next(obj, opt))) {
616         if (!(opt->flags & req_flags) || (opt->flags & rej_flags))
617             continue;
618
619         /* Don't print CONST's on level one.
620          * Don't print anything but CONST's on level two.
621          * Only print items from the requested unit.
622          */
623         if (!unit && opt->type==AV_OPT_TYPE_CONST)
624             continue;
625         else if (unit && opt->type!=AV_OPT_TYPE_CONST)
626             continue;
627         else if (unit && opt->type==AV_OPT_TYPE_CONST && strcmp(unit, opt->unit))
628             continue;
629         else if (unit && opt->type == AV_OPT_TYPE_CONST)
630             av_log(av_log_obj, AV_LOG_INFO, "   %-15s ", opt->name);
631         else
632             av_log(av_log_obj, AV_LOG_INFO, "-%-17s ", opt->name);
633
634         switch (opt->type) {
635             case AV_OPT_TYPE_FLAGS:
636                 av_log(av_log_obj, AV_LOG_INFO, "%-7s ", "<flags>");
637                 break;
638             case AV_OPT_TYPE_INT:
639                 av_log(av_log_obj, AV_LOG_INFO, "%-7s ", "<int>");
640                 break;
641             case AV_OPT_TYPE_INT64:
642                 av_log(av_log_obj, AV_LOG_INFO, "%-7s ", "<int64>");
643                 break;
644             case AV_OPT_TYPE_DOUBLE:
645                 av_log(av_log_obj, AV_LOG_INFO, "%-7s ", "<double>");
646                 break;
647             case AV_OPT_TYPE_FLOAT:
648                 av_log(av_log_obj, AV_LOG_INFO, "%-7s ", "<float>");
649                 break;
650             case AV_OPT_TYPE_STRING:
651                 av_log(av_log_obj, AV_LOG_INFO, "%-7s ", "<string>");
652                 break;
653             case AV_OPT_TYPE_RATIONAL:
654                 av_log(av_log_obj, AV_LOG_INFO, "%-7s ", "<rational>");
655                 break;
656             case AV_OPT_TYPE_BINARY:
657                 av_log(av_log_obj, AV_LOG_INFO, "%-7s ", "<binary>");
658                 break;
659             case AV_OPT_TYPE_IMAGE_SIZE:
660                 av_log(av_log_obj, AV_LOG_INFO, "%-7s ", "<image_size>");
661                 break;
662             case AV_OPT_TYPE_PIXEL_FMT:
663                 av_log(av_log_obj, AV_LOG_INFO, "%-7s ", "<pix_fmt>");
664                 break;
665             case AV_OPT_TYPE_SAMPLE_FMT:
666                 av_log(av_log_obj, AV_LOG_INFO, "%-7s ", "<sample_fmt>");
667                 break;
668             case AV_OPT_TYPE_CONST:
669             default:
670                 av_log(av_log_obj, AV_LOG_INFO, "%-7s ", "");
671                 break;
672         }
673         av_log(av_log_obj, AV_LOG_INFO, "%c", (opt->flags & AV_OPT_FLAG_ENCODING_PARAM) ? 'E' : '.');
674         av_log(av_log_obj, AV_LOG_INFO, "%c", (opt->flags & AV_OPT_FLAG_DECODING_PARAM) ? 'D' : '.');
675         av_log(av_log_obj, AV_LOG_INFO, "%c", (opt->flags & AV_OPT_FLAG_FILTERING_PARAM)? 'F' : '.');
676         av_log(av_log_obj, AV_LOG_INFO, "%c", (opt->flags & AV_OPT_FLAG_VIDEO_PARAM   ) ? 'V' : '.');
677         av_log(av_log_obj, AV_LOG_INFO, "%c", (opt->flags & AV_OPT_FLAG_AUDIO_PARAM   ) ? 'A' : '.');
678         av_log(av_log_obj, AV_LOG_INFO, "%c", (opt->flags & AV_OPT_FLAG_SUBTITLE_PARAM) ? 'S' : '.');
679
680         if (opt->help)
681             av_log(av_log_obj, AV_LOG_INFO, " %s", opt->help);
682         av_log(av_log_obj, AV_LOG_INFO, "\n");
683         if (opt->unit && opt->type != AV_OPT_TYPE_CONST) {
684             opt_list(obj, av_log_obj, opt->unit, req_flags, rej_flags);
685         }
686     }
687 }
688
689 int av_opt_show2(void *obj, void *av_log_obj, int req_flags, int rej_flags)
690 {
691     if (!obj)
692         return -1;
693
694     av_log(av_log_obj, AV_LOG_INFO, "%s AVOptions:\n", (*(AVClass**)obj)->class_name);
695
696     opt_list(obj, av_log_obj, NULL, req_flags, rej_flags);
697
698     return 0;
699 }
700
701 void av_opt_set_defaults(void *s)
702 {
703 #if FF_API_OLD_AVOPTIONS
704     av_opt_set_defaults2(s, 0, 0);
705 }
706
707 void av_opt_set_defaults2(void *s, int mask, int flags)
708 {
709 #endif
710     const AVOption *opt = NULL;
711     while ((opt = av_opt_next(s, opt)) != NULL) {
712 #if FF_API_OLD_AVOPTIONS
713         if ((opt->flags & mask) != flags)
714             continue;
715 #endif
716         switch (opt->type) {
717             case AV_OPT_TYPE_CONST:
718                 /* Nothing to be done here */
719             break;
720             case AV_OPT_TYPE_FLAGS:
721             case AV_OPT_TYPE_INT:
722             case AV_OPT_TYPE_INT64:
723                 av_opt_set_int(s, opt->name, opt->default_val.i64, 0);
724             break;
725             case AV_OPT_TYPE_DOUBLE:
726             case AV_OPT_TYPE_FLOAT: {
727                 double val;
728                 val = opt->default_val.dbl;
729                 av_opt_set_double(s, opt->name, val, 0);
730             }
731             break;
732             case AV_OPT_TYPE_RATIONAL: {
733                 AVRational val;
734                 val = av_d2q(opt->default_val.dbl, INT_MAX);
735                 av_opt_set_q(s, opt->name, val, 0);
736             }
737             break;
738             case AV_OPT_TYPE_STRING:
739             case AV_OPT_TYPE_IMAGE_SIZE:
740             case AV_OPT_TYPE_PIXEL_FMT:
741                 av_opt_set(s, opt->name, opt->default_val.str, 0);
742                 break;
743             case AV_OPT_TYPE_BINARY:
744                 /* Cannot set default for binary */
745             break;
746             default:
747                 av_log(s, AV_LOG_DEBUG, "AVOption type %d of option %s not implemented yet\n", opt->type, opt->name);
748         }
749     }
750 }
751
752 /**
753  * Store the value in the field in ctx that is named like key.
754  * ctx must be an AVClass context, storing is done using AVOptions.
755  *
756  * @param buf the string to parse, buf will be updated to point at the
757  * separator just after the parsed key/value pair
758  * @param key_val_sep a 0-terminated list of characters used to
759  * separate key from value
760  * @param pairs_sep a 0-terminated list of characters used to separate
761  * two pairs from each other
762  * @return 0 if the key/value pair has been successfully parsed and
763  * set, or a negative value corresponding to an AVERROR code in case
764  * of error:
765  * AVERROR(EINVAL) if the key/value pair cannot be parsed,
766  * the error code issued by av_opt_set() if the key/value pair
767  * cannot be set
768  */
769 static int parse_key_value_pair(void *ctx, const char **buf,
770                                 const char *key_val_sep, const char *pairs_sep)
771 {
772     char *key = av_get_token(buf, key_val_sep);
773     char *val;
774     int ret;
775
776     if (*key && strspn(*buf, key_val_sep)) {
777         (*buf)++;
778         val = av_get_token(buf, pairs_sep);
779     } else {
780         av_log(ctx, AV_LOG_ERROR, "Missing key or no key/value separator found after key '%s'\n", key);
781         av_free(key);
782         return AVERROR(EINVAL);
783     }
784
785     av_log(ctx, AV_LOG_DEBUG, "Setting entry with key '%s' to value '%s'\n", key, val);
786
787     ret = av_opt_set(ctx, key, val, 0);
788     if (ret == AVERROR_OPTION_NOT_FOUND)
789         av_log(ctx, AV_LOG_ERROR, "Key '%s' not found.\n", key);
790
791     av_free(key);
792     av_free(val);
793     return ret;
794 }
795
796 int av_set_options_string(void *ctx, const char *opts,
797                           const char *key_val_sep, const char *pairs_sep)
798 {
799     int ret, count = 0;
800
801     if (!opts)
802         return 0;
803
804     while (*opts) {
805         if ((ret = parse_key_value_pair(ctx, &opts, key_val_sep, pairs_sep)) < 0)
806             return ret;
807         count++;
808
809         if (*opts)
810             opts++;
811     }
812
813     return count;
814 }
815
816 #define WHITESPACES " \n\t"
817
818 static int is_key_char(char c)
819 {
820     return (unsigned)((c | 32) - 'a') < 26 ||
821            (unsigned)(c - '0') < 10 ||
822            c == '-' || c == '_' || c == '/' || c == '.';
823 }
824
825 /**
826  * Read a key from a string.
827  *
828  * The key consists of is_key_char characters and must be terminated by a
829  * character from the delim string; spaces are ignored. The key buffer must
830  * be 4 bytes larger than the longest acceptable key. If the key is too
831  * long, an ellipsis will be written at the end.
832  *
833  * @return  0 for success (even with ellipsis), <0 for failure
834  */
835 static int get_key(const char **ropts, const char *delim, char *key, unsigned key_size)
836 {
837     unsigned key_pos = 0;
838     const char *opts = *ropts;
839
840     opts += strspn(opts, WHITESPACES);
841     while (is_key_char(*opts)) {
842         key[key_pos++] = *opts;
843         if (key_pos == key_size)
844             key_pos--;
845         (opts)++;
846     }
847     opts += strspn(opts, WHITESPACES);
848     if (!*opts || !strchr(delim, *opts))
849         return AVERROR(EINVAL);
850     opts++;
851     key[key_pos++] = 0;
852     if (key_pos == key_size)
853         key[key_pos - 4] = key[key_pos - 3] = key[key_pos - 2] = '.';
854     *ropts = opts;
855     return 0;
856 }
857
858 int av_opt_set_from_string(void *ctx, const char *opts,
859                            const char *const *shorthand,
860                            const char *key_val_sep, const char *pairs_sep)
861 {
862     int ret, count = 0;
863     const char *dummy_shorthand = NULL;
864     char key_buf[68], *value;
865     const char *key;
866
867     if (!opts)
868         return 0;
869     if (!shorthand)
870         shorthand = &dummy_shorthand;
871
872     while (*opts) {
873         if ((ret = get_key(&opts, key_val_sep, key_buf, sizeof(key_buf))) < 0) {
874             if (*shorthand) {
875                 key = *(shorthand++);
876             } else {
877                 av_log(ctx, AV_LOG_ERROR, "No option name near '%s'\n", opts);
878                 return AVERROR(EINVAL);
879             }
880         } else {
881             key = key_buf;
882             while (*shorthand) /* discard all remaining shorthand */
883                 shorthand++;
884         }
885
886         if (!(value = av_get_token(&opts, pairs_sep)))
887             return AVERROR(ENOMEM);
888         if (*opts && strchr(pairs_sep, *opts))
889             opts++;
890
891         av_log(ctx, AV_LOG_DEBUG, "Setting '%s' to value '%s'\n", key, value);
892         if ((ret = av_opt_set(ctx, key, value, 0)) < 0) {
893             if (ret == AVERROR_OPTION_NOT_FOUND)
894                 av_log(ctx, AV_LOG_ERROR, "Option '%s' not found\n", key);
895             av_free(value);
896             return ret;
897         }
898
899         av_free(value);
900         count++;
901     }
902     return count;
903 }
904
905 void av_opt_free(void *obj)
906 {
907     const AVOption *o = NULL;
908     while ((o = av_opt_next(obj, o)))
909         if (o->type == AV_OPT_TYPE_STRING || o->type == AV_OPT_TYPE_BINARY)
910             av_freep((uint8_t *)obj + o->offset);
911 }
912
913 int av_opt_set_dict(void *obj, AVDictionary **options)
914 {
915     AVDictionaryEntry *t = NULL;
916     AVDictionary    *tmp = NULL;
917     int ret = 0;
918
919     while ((t = av_dict_get(*options, "", t, AV_DICT_IGNORE_SUFFIX))) {
920         ret = av_opt_set(obj, t->key, t->value, 0);
921         if (ret == AVERROR_OPTION_NOT_FOUND)
922             av_dict_set(&tmp, t->key, t->value, 0);
923         else if (ret < 0) {
924             av_log(obj, AV_LOG_ERROR, "Error setting option %s to value %s.\n", t->key, t->value);
925             break;
926         }
927         ret = 0;
928     }
929     av_dict_free(options);
930     *options = tmp;
931     return ret;
932 }
933
934 const AVOption *av_opt_find(void *obj, const char *name, const char *unit,
935                             int opt_flags, int search_flags)
936 {
937     return av_opt_find2(obj, name, unit, opt_flags, search_flags, NULL);
938 }
939
940 const AVOption *av_opt_find2(void *obj, const char *name, const char *unit,
941                              int opt_flags, int search_flags, void **target_obj)
942 {
943     const AVClass  *c;
944     const AVOption *o = NULL;
945
946     if(!obj)
947         return NULL;
948
949     c= *(AVClass**)obj;
950
951     if (search_flags & AV_OPT_SEARCH_CHILDREN) {
952         if (search_flags & AV_OPT_SEARCH_FAKE_OBJ) {
953             const AVClass *child = NULL;
954             while (child = av_opt_child_class_next(c, child))
955                 if (o = av_opt_find2(&child, name, unit, opt_flags, search_flags, NULL))
956                     return o;
957         } else {
958             void *child = NULL;
959             while (child = av_opt_child_next(obj, child))
960                 if (o = av_opt_find2(child, name, unit, opt_flags, search_flags, target_obj))
961                     return o;
962         }
963     }
964
965     while (o = av_opt_next(obj, o)) {
966         if (!strcmp(o->name, name) && (o->flags & opt_flags) == opt_flags &&
967             ((!unit && o->type != AV_OPT_TYPE_CONST) ||
968              (unit  && o->type == AV_OPT_TYPE_CONST && o->unit && !strcmp(o->unit, unit)))) {
969             if (target_obj) {
970                 if (!(search_flags & AV_OPT_SEARCH_FAKE_OBJ))
971                     *target_obj = obj;
972                 else
973                     *target_obj = NULL;
974             }
975             return o;
976         }
977     }
978     return NULL;
979 }
980
981 void *av_opt_child_next(void *obj, void *prev)
982 {
983     const AVClass *c = *(AVClass**)obj;
984     if (c->child_next)
985         return c->child_next(obj, prev);
986     return NULL;
987 }
988
989 const AVClass *av_opt_child_class_next(const AVClass *parent, const AVClass *prev)
990 {
991     if (parent->child_class_next)
992         return parent->child_class_next(prev);
993     return NULL;
994 }
995
996 void *av_opt_ptr(const AVClass *class, void *obj, const char *name)
997 {
998     const AVOption *opt= av_opt_find2(&class, name, NULL, 0, AV_OPT_SEARCH_FAKE_OBJ, NULL);
999     if(!opt)
1000         return NULL;
1001     return (uint8_t*)obj + opt->offset;
1002 }
1003
1004 #ifdef TEST
1005
1006 #undef printf
1007
1008 typedef struct TestContext
1009 {
1010     const AVClass *class;
1011     int num;
1012     int toggle;
1013     char *string;
1014     int flags;
1015     AVRational rational;
1016     int w, h;
1017     enum AVPixelFormat pix_fmt;
1018     enum AVSampleFormat sample_fmt;
1019 } TestContext;
1020
1021 #define OFFSET(x) offsetof(TestContext, x)
1022
1023 #define TEST_FLAG_COOL 01
1024 #define TEST_FLAG_LAME 02
1025 #define TEST_FLAG_MU   04
1026
1027 static const AVOption test_options[]= {
1028 {"num",      "set num",        OFFSET(num),      AV_OPT_TYPE_INT,      {.i64 = 0},       0,        100                 },
1029 {"toggle",   "set toggle",     OFFSET(toggle),   AV_OPT_TYPE_INT,      {.i64 = 0},       0,        1                   },
1030 {"rational", "set rational",   OFFSET(rational), AV_OPT_TYPE_RATIONAL, {.dbl = 0},  0,        10                  },
1031 {"string",   "set string",     OFFSET(string),   AV_OPT_TYPE_STRING,   {0},              CHAR_MIN, CHAR_MAX            },
1032 {"flags",    "set flags",      OFFSET(flags),    AV_OPT_TYPE_FLAGS,    {.i64 = 0},       0,        INT_MAX, 0, "flags" },
1033 {"cool",     "set cool flag ", 0,                AV_OPT_TYPE_CONST,    {.i64 = TEST_FLAG_COOL}, INT_MIN,  INT_MAX, 0, "flags" },
1034 {"lame",     "set lame flag ", 0,                AV_OPT_TYPE_CONST,    {.i64 = TEST_FLAG_LAME}, INT_MIN,  INT_MAX, 0, "flags" },
1035 {"mu",       "set mu flag ",   0,                AV_OPT_TYPE_CONST,    {.i64 = TEST_FLAG_MU},   INT_MIN,  INT_MAX, 0, "flags" },
1036 {"size",     "set size",       OFFSET(w),        AV_OPT_TYPE_IMAGE_SIZE,{0},             0,        0                   },
1037 {"pix_fmt",  "set pixfmt",     OFFSET(pix_fmt),  AV_OPT_TYPE_PIXEL_FMT,{0},              0,        0                   },
1038 {"sample_fmt", "set samplefmt", OFFSET(sample_fmt), AV_OPT_TYPE_SAMPLE_FMT,{0},          0,        0                   },
1039 {NULL},
1040 };
1041
1042 static const char *test_get_name(void *ctx)
1043 {
1044     return "test";
1045 }
1046
1047 static const AVClass test_class = {
1048     "TestContext",
1049     test_get_name,
1050     test_options
1051 };
1052
1053 int main(void)
1054 {
1055     int i;
1056
1057     printf("\nTesting av_set_options_string()\n");
1058     {
1059         TestContext test_ctx = { 0 };
1060         const char *options[] = {
1061             "",
1062             ":",
1063             "=",
1064             "foo=:",
1065             ":=foo",
1066             "=foo",
1067             "foo=",
1068             "foo",
1069             "foo=val",
1070             "foo==val",
1071             "toggle=:",
1072             "string=:",
1073             "toggle=1 : foo",
1074             "toggle=100",
1075             "toggle==1",
1076             "flags=+mu-lame : num=42: toggle=0",
1077             "num=42 : string=blahblah",
1078             "rational=0 : rational=1/2 : rational=1/-1",
1079             "rational=-1/0",
1080             "size=1024x768",
1081             "size=pal",
1082             "size=bogus",
1083             "pix_fmt=yuv420p",
1084             "pix_fmt=2",
1085             "pix_fmt=bogus",
1086             "sample_fmt=s16",
1087             "sample_fmt=2",
1088             "sample_fmt=bogus",
1089         };
1090
1091         test_ctx.class = &test_class;
1092         av_opt_set_defaults(&test_ctx);
1093         test_ctx.string = av_strdup("default");
1094
1095         av_log_set_level(AV_LOG_DEBUG);
1096
1097         for (i=0; i < FF_ARRAY_ELEMS(options); i++) {
1098             av_log(&test_ctx, AV_LOG_DEBUG, "Setting options string '%s'\n", options[i]);
1099             if (av_set_options_string(&test_ctx, options[i], "=", ":") < 0)
1100                 av_log(&test_ctx, AV_LOG_ERROR, "Error setting options string: '%s'\n", options[i]);
1101             printf("\n");
1102         }
1103         av_freep(&test_ctx.string);
1104     }
1105
1106     printf("\nTesting av_opt_set_from_string()\n");
1107     {
1108         TestContext test_ctx = { 0 };
1109         const char *options[] = {
1110             "",
1111             "5",
1112             "5:hello",
1113             "5:hello:size=pal",
1114             "5:size=pal:hello",
1115             ":",
1116             "=",
1117             " 5 : hello : size = pal ",
1118             "a_very_long_option_name_that_will_need_to_be_ellipsized_around_here=42"
1119         };
1120         const char *shorthand[] = { "num", "string", NULL };
1121
1122         test_ctx.class = &test_class;
1123         av_opt_set_defaults(&test_ctx);
1124         test_ctx.string = av_strdup("default");
1125
1126         av_log_set_level(AV_LOG_DEBUG);
1127
1128         for (i=0; i < FF_ARRAY_ELEMS(options); i++) {
1129             av_log(&test_ctx, AV_LOG_DEBUG, "Setting options string '%s'\n", options[i]);
1130             if (av_opt_set_from_string(&test_ctx, options[i], shorthand, "=", ":") < 0)
1131                 av_log(&test_ctx, AV_LOG_ERROR, "Error setting options string: '%s'\n", options[i]);
1132             printf("\n");
1133         }
1134         av_freep(&test_ctx.string);
1135     }
1136
1137     return 0;
1138 }
1139
1140 #endif