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