]> git.sesse.net Git - vlc/blob - src/misc/variables.c
variables: add internal type callback_table_t for storing a list of callbacks
[vlc] / src / misc / variables.c
1 /*****************************************************************************
2  * variables.c: routines for object variables handling
3  *****************************************************************************
4  * Copyright (C) 2002-2009 VLC authors and VideoLAN
5  * $Id$
6  *
7  * Authors: Samuel Hocevar <sam@zoy.org>
8  *
9  * This program is free software; you can redistribute it and/or modify it
10  * under the terms of the GNU Lesser General Public License as published by
11  * the Free Software Foundation; either version 2.1 of the License, or
12  * (at your option) any later version.
13  *
14  * This program 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
17  * GNU Lesser General Public License for more details.
18  *
19  * You should have received a copy of the GNU Lesser General Public License
20  * along with this program; if not, write to the Free Software Foundation,
21  * Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
22  *****************************************************************************/
23
24 /*****************************************************************************
25  * Preamble
26  *****************************************************************************/
27 #ifdef HAVE_CONFIG_H
28 # include "config.h"
29 #endif
30
31 #ifdef HAVE_SEARCH_H
32 # include <search.h>
33 #endif
34 #include <assert.h>
35 #include <math.h>
36 #include <limits.h>
37 #ifdef __GLIBC__
38 # include <dlfcn.h>
39 #endif
40
41 #include <vlc_common.h>
42 #include <vlc_charset.h>
43 #include "libvlc.h"
44 #include "variables.h"
45 #include "config/configuration.h"
46
47 /*****************************************************************************
48  * Private types
49  *****************************************************************************/
50 struct callback_entry_t
51 {
52     vlc_callback_t pf_callback;
53     void *         p_data;
54 };
55
56 /*****************************************************************************
57  * Local comparison functions, returns 0 if v == w, < 0 if v < w, > 0 if v > w
58  *****************************************************************************/
59 static int CmpBool( vlc_value_t v, vlc_value_t w )
60 {
61     return v.b_bool ? w.b_bool ? 0 : 1 : w.b_bool ? -1 : 0;
62 }
63
64 static int CmpInt( vlc_value_t v, vlc_value_t w )
65 {
66     return v.i_int == w.i_int ? 0 : v.i_int > w.i_int ? 1 : -1;
67 }
68
69 static int CmpTime( vlc_value_t v, vlc_value_t w )
70 {
71     return v.i_time == w.i_time ? 0 : v.i_time > w.i_time ? 1 : -1;
72 }
73
74 static int CmpString( vlc_value_t v, vlc_value_t w )
75 {
76     if( !v.psz_string )
77         return !w.psz_string ? 0 : -1;
78     else
79         return !w.psz_string ? 1 : strcmp( v.psz_string, w.psz_string );
80 }
81 static int CmpFloat( vlc_value_t v, vlc_value_t w ) { return v.f_float == w.f_float ? 0 : v.f_float > w.f_float ? 1 : -1; }
82 static int CmpAddress( vlc_value_t v, vlc_value_t w ) { return v.p_address == w.p_address ? 0 : v.p_address > w.p_address ? 1 : -1; }
83
84 /*****************************************************************************
85  * Local duplication functions, and local deallocation functions
86  *****************************************************************************/
87 static void DupDummy( vlc_value_t *p_val ) { (void)p_val; /* unused */ }
88 static void DupString( vlc_value_t *p_val )
89 {
90     p_val->psz_string = strdup( p_val->psz_string ? p_val->psz_string :  "" );
91 }
92
93 static void FreeDummy( vlc_value_t *p_val ) { (void)p_val; /* unused */ }
94 static void FreeString( vlc_value_t *p_val ) { free( p_val->psz_string ); }
95
96 static void FreeList( vlc_value_t *p_val )
97 {
98     int i;
99     for( i = 0; i < p_val->p_list->i_count; i++ )
100     {
101         switch( p_val->p_list->pi_types[i] & VLC_VAR_CLASS )
102         {
103         case VLC_VAR_STRING:
104             FreeString( &p_val->p_list->p_values[i] );
105             break;
106         default:
107             break;
108         }
109     }
110
111     if( p_val->p_list->i_count )
112     {
113         free( p_val->p_list->p_values );
114         free( p_val->p_list->pi_types );
115     }
116     free( p_val->p_list );
117 }
118
119 static const struct variable_ops_t
120 void_ops   = { NULL,       DupDummy,  FreeDummy,  },
121 addr_ops   = { CmpAddress, DupDummy,  FreeDummy,  },
122 bool_ops   = { CmpBool,    DupDummy,  FreeDummy,  },
123 float_ops  = { CmpFloat,   DupDummy,  FreeDummy,  },
124 int_ops    = { CmpInt,     DupDummy,  FreeDummy,  },
125 string_ops = { CmpString,  DupString, FreeString, },
126 time_ops   = { CmpTime,    DupDummy,  FreeDummy,  },
127 coords_ops = { NULL,       DupDummy,  FreeDummy,  };
128
129 /*****************************************************************************
130  * Local prototypes
131  *****************************************************************************/
132 static void     WaitUnused  ( vlc_object_t *, variable_t * );
133
134 static void     CheckValue  ( variable_t *, vlc_value_t * );
135
136 static int      TriggerCallback( vlc_object_t *, variable_t *, const char *,
137                                  vlc_value_t );
138
139 static int varcmp( const void *a, const void *b )
140 {
141     const variable_t *va = a, *vb = b;
142
143     /* psz_name must be first */
144     assert( va == (const void *)&va->psz_name );
145     return strcmp( va->psz_name, vb->psz_name );
146 }
147
148 static variable_t *Lookup( vlc_object_t *obj, const char *psz_name )
149 {
150     vlc_object_internals_t *priv = vlc_internals( obj );
151     variable_t **pp_var;
152
153     vlc_assert_locked( &priv->var_lock );
154     pp_var = tfind( &psz_name, &priv->var_root, varcmp );
155     return (pp_var != NULL) ? *pp_var : NULL;
156 }
157
158 static void Destroy( variable_t *p_var )
159 {
160     p_var->ops->pf_free( &p_var->val );
161     if( p_var->choices.i_count )
162     {
163         for( int i = 0 ; i < p_var->choices.i_count ; i++ )
164         {
165             p_var->ops->pf_free( &p_var->choices.p_values[i] );
166             free( p_var->choices_text.p_values[i].psz_string );
167         }
168         free( p_var->choices.p_values );
169         free( p_var->choices_text.p_values );
170     }
171 #if 0 // ndef NDEBUG
172     callback_table_t *p_table = &p_var->value_callbacks;
173     for (int i = 0; i < p_table->i_entries; i++)
174     {
175         const char *file = "?", *symbol = "?";
176         const void *addr = p_table->p_entries[i].pf_callback;
177 # ifdef __GLIBC__
178         Dl_info info;
179
180         if (dladdr (addr, &info))
181         {
182             if (info.dli_fname) file = info.dli_fname;
183             if (info.dli_sname) symbol = info.dli_sname;
184         }
185 # endif
186         fprintf (stderr, "Error: callback on \"%s\" dangling %s(%s)[%p]\n",
187                  p_var->psz_name, file, symbol, addr);
188     }
189 #endif
190
191     free( p_var->psz_name );
192     free( p_var->psz_text );
193     free( p_var->value_callbacks.p_entries );
194     free( p_var );
195 }
196
197 #undef var_Create
198 /**
199  * Initialize a vlc variable
200  *
201  * We hash the given string and insert it into the sorted list. The insertion
202  * may require slow memory copies, but think about what we gain in the log(n)
203  * lookup phase when setting/getting the variable value!
204  *
205  * \param p_this The object in which to create the variable
206  * \param psz_name The name of the variable
207  * \param i_type The variables type. Must be one of \ref var_type combined with
208  *               zero or more \ref var_flags
209  */
210 int var_Create( vlc_object_t *p_this, const char *psz_name, int i_type )
211 {
212     assert( p_this );
213
214     variable_t *p_var = calloc( 1, sizeof( *p_var ) );
215     if( p_var == NULL )
216         return VLC_ENOMEM;
217
218     p_var->psz_name = strdup( psz_name );
219     p_var->psz_text = NULL;
220
221     p_var->i_type = i_type & ~VLC_VAR_DOINHERIT;
222
223     p_var->i_usage = 1;
224
225     p_var->i_default = -1;
226     p_var->choices.i_count = 0;
227     p_var->choices.p_values = NULL;
228     p_var->choices_text.i_count = 0;
229     p_var->choices_text.p_values = NULL;
230
231     p_var->b_incallback = false;
232     p_var->value_callbacks = (callback_table_t){ 0 };
233
234     /* Always initialize the variable, even if it is a list variable; this
235      * will lead to errors if the variable is not initialized, but it will
236      * not cause crashes in the variable handling. */
237     switch( i_type & VLC_VAR_CLASS )
238     {
239         case VLC_VAR_BOOL:
240             p_var->ops = &bool_ops;
241             p_var->val.b_bool = false;
242             break;
243         case VLC_VAR_INTEGER:
244             p_var->ops = &int_ops;
245             p_var->val.i_int = 0;
246             break;
247         case VLC_VAR_STRING:
248             p_var->ops = &string_ops;
249             p_var->val.psz_string = NULL;
250             break;
251         case VLC_VAR_FLOAT:
252             p_var->ops = &float_ops;
253             p_var->val.f_float = 0.0;
254             break;
255         case VLC_VAR_TIME:
256             p_var->ops = &time_ops;
257             p_var->val.i_time = 0;
258             break;
259         case VLC_VAR_COORDS:
260             p_var->ops = &coords_ops;
261             p_var->val.coords.x = p_var->val.coords.y = 0;
262             break;
263         case VLC_VAR_ADDRESS:
264             p_var->ops = &addr_ops;
265             p_var->val.p_address = NULL;
266             break;
267         case VLC_VAR_VOID:
268             p_var->ops = &void_ops;
269             break;
270         default:
271             assert (0);
272     }
273
274     if( (i_type & VLC_VAR_DOINHERIT)
275      && var_Inherit( p_this, psz_name, i_type, &p_var->val ) == 0 )
276     {
277         if( i_type & VLC_VAR_HASCHOICE )
278         {
279             /* We must add the inherited value to our choice list */
280             p_var->i_default = 0;
281
282             INSERT_ELEM( p_var->choices.p_values, p_var->choices.i_count,
283                          0, p_var->val );
284             INSERT_ELEM( p_var->choices_text.p_values,
285                          p_var->choices_text.i_count, 0, p_var->val );
286             p_var->ops->pf_dup( &p_var->choices.p_values[0] );
287             p_var->choices_text.p_values[0].psz_string = NULL;
288         }
289     }
290
291     vlc_object_internals_t *p_priv = vlc_internals( p_this );
292     variable_t **pp_var, *p_oldvar;
293     int ret = VLC_SUCCESS;
294
295     vlc_mutex_lock( &p_priv->var_lock );
296
297     pp_var = tsearch( p_var, &p_priv->var_root, varcmp );
298     if( unlikely(pp_var == NULL) )
299         ret = VLC_ENOMEM;
300     else if( (p_oldvar = *pp_var) == p_var ) /* Variable create */
301         p_var = NULL; /* Variable created */
302     else /* Variable already exists */
303     {
304         assert (((i_type ^ p_oldvar->i_type) & VLC_VAR_CLASS) == 0);
305         p_oldvar->i_usage++;
306         p_oldvar->i_type |= i_type & (VLC_VAR_ISCOMMAND|VLC_VAR_HASCHOICE);
307     }
308     vlc_mutex_unlock( &p_priv->var_lock );
309
310     /* If we did not need to create a new variable, free everything... */
311     if( p_var != NULL )
312         Destroy( p_var );
313     return ret;
314 }
315
316 #undef var_Destroy
317 /**
318  * Destroy a vlc variable
319  *
320  * Look for the variable and destroy it if it is found. As in var_Create we
321  * do a call to memmove() but we have performance counterparts elsewhere.
322  *
323  * \param p_this The object that holds the variable
324  * \param psz_name The name of the variable
325  */
326 int var_Destroy( vlc_object_t *p_this, const char *psz_name )
327 {
328     variable_t *p_var;
329
330     assert( p_this );
331
332     vlc_object_internals_t *p_priv = vlc_internals( p_this );
333
334     vlc_mutex_lock( &p_priv->var_lock );
335
336     p_var = Lookup( p_this, psz_name );
337     if( p_var == NULL )
338     {
339         vlc_mutex_unlock( &p_priv->var_lock );
340         return VLC_ENOVAR;
341     }
342
343     WaitUnused( p_this, p_var );
344
345     if( --p_var->i_usage == 0 )
346         tdelete( p_var, &p_priv->var_root, varcmp );
347     else
348         p_var = NULL;
349     vlc_mutex_unlock( &p_priv->var_lock );
350
351     if( p_var != NULL )
352         Destroy( p_var );
353     return VLC_SUCCESS;
354 }
355
356 static void CleanupVar( void *var )
357 {
358     Destroy( var );
359 }
360
361 void var_DestroyAll( vlc_object_t *obj )
362 {
363     vlc_object_internals_t *priv = vlc_internals( obj );
364
365     tdestroy( priv->var_root, CleanupVar );
366     priv->var_root = NULL;
367 }
368
369 #undef var_Change
370 /**
371  * Perform an action on a variable
372  *
373  * \param p_this The object that holds the variable
374  * \param psz_name The name of the variable
375  * \param i_action The action to perform. Must be one of \ref var_action
376  * \param p_val First action parameter
377  * \param p_val2 Second action parameter
378  */
379 int var_Change( vlc_object_t *p_this, const char *psz_name,
380                 int i_action, vlc_value_t *p_val, vlc_value_t *p_val2 )
381 {
382     int ret = VLC_SUCCESS;
383     variable_t *p_var;
384     vlc_value_t oldval;
385     vlc_value_t newval;
386
387     assert( p_this );
388
389     vlc_object_internals_t *p_priv = vlc_internals( p_this );
390
391     vlc_mutex_lock( &p_priv->var_lock );
392
393     p_var = Lookup( p_this, psz_name );
394     if( p_var == NULL )
395     {
396         vlc_mutex_unlock( &p_priv->var_lock );
397         return VLC_ENOVAR;
398     }
399
400     switch( i_action )
401     {
402         case VLC_VAR_SETMIN:
403             if( p_var->i_type & VLC_VAR_HASMIN )
404             {
405                 p_var->ops->pf_free( &p_var->min );
406             }
407             p_var->i_type |= VLC_VAR_HASMIN;
408             p_var->min = *p_val;
409             p_var->ops->pf_dup( &p_var->min );
410             CheckValue( p_var, &p_var->val );
411             break;
412         case VLC_VAR_GETMIN:
413             if( p_var->i_type & VLC_VAR_HASMIN )
414                 *p_val = p_var->min;
415             else
416                 ret = VLC_EGENERIC;
417             break;
418         case VLC_VAR_SETMAX:
419             if( p_var->i_type & VLC_VAR_HASMAX )
420             {
421                 p_var->ops->pf_free( &p_var->max );
422             }
423             p_var->i_type |= VLC_VAR_HASMAX;
424             p_var->max = *p_val;
425             p_var->ops->pf_dup( &p_var->max );
426             CheckValue( p_var, &p_var->val );
427             break;
428         case VLC_VAR_GETMAX:
429             if( p_var->i_type & VLC_VAR_HASMAX )
430                 *p_val = p_var->max;
431             else
432                 ret = VLC_EGENERIC;
433             break;
434         case VLC_VAR_SETSTEP:
435             if( p_var->i_type & VLC_VAR_HASSTEP )
436             {
437                 p_var->ops->pf_free( &p_var->step );
438             }
439             p_var->i_type |= VLC_VAR_HASSTEP;
440             p_var->step = *p_val;
441             p_var->ops->pf_dup( &p_var->step );
442             CheckValue( p_var, &p_var->val );
443             break;
444         case VLC_VAR_GETSTEP:
445             if( p_var->i_type & VLC_VAR_HASSTEP )
446                 *p_val = p_var->step;
447             else
448                 ret = VLC_EGENERIC;
449             break;
450         case VLC_VAR_ADDCHOICE:
451         {
452             int i = p_var->choices.i_count;
453
454             INSERT_ELEM( p_var->choices.p_values, p_var->choices.i_count,
455                          i, *p_val );
456             INSERT_ELEM( p_var->choices_text.p_values,
457                          p_var->choices_text.i_count, i, *p_val );
458             p_var->ops->pf_dup( &p_var->choices.p_values[i] );
459             p_var->choices_text.p_values[i].psz_string =
460                 ( p_val2 && p_val2->psz_string ) ?
461                 strdup( p_val2->psz_string ) : NULL;
462
463             CheckValue( p_var, &p_var->val );
464             break;
465         }
466         case VLC_VAR_DELCHOICE:
467         {
468             int i;
469
470             for( i = 0 ; i < p_var->choices.i_count ; i++ )
471                 if( p_var->ops->pf_cmp( p_var->choices.p_values[i], *p_val ) == 0 )
472                     break;
473
474             if( i == p_var->choices.i_count )
475             {
476                 /* Not found */
477                 vlc_mutex_unlock( &p_priv->var_lock );
478                 return VLC_EGENERIC;
479             }
480
481             if( p_var->i_default > i )
482                 p_var->i_default--;
483             else if( p_var->i_default == i )
484                 p_var->i_default = -1;
485
486             p_var->ops->pf_free( &p_var->choices.p_values[i] );
487             free( p_var->choices_text.p_values[i].psz_string );
488             REMOVE_ELEM( p_var->choices.p_values, p_var->choices.i_count, i );
489             REMOVE_ELEM( p_var->choices_text.p_values,
490                          p_var->choices_text.i_count, i );
491
492             CheckValue( p_var, &p_var->val );
493             break;
494         }
495         case VLC_VAR_CHOICESCOUNT:
496             p_val->i_int = p_var->choices.i_count;
497             break;
498         case VLC_VAR_CLEARCHOICES:
499             for( int i = 0 ; i < p_var->choices.i_count ; i++ )
500                 p_var->ops->pf_free( &p_var->choices.p_values[i] );
501             for( int i = 0 ; i < p_var->choices_text.i_count ; i++ )
502                 free( p_var->choices_text.p_values[i].psz_string );
503
504             if( p_var->choices.i_count ) free( p_var->choices.p_values );
505             if( p_var->choices_text.i_count ) free( p_var->choices_text.p_values );
506
507             p_var->choices.i_count = 0;
508             p_var->choices.p_values = NULL;
509             p_var->choices_text.i_count = 0;
510             p_var->choices_text.p_values = NULL;
511             p_var->i_default = -1;
512             break;
513         case VLC_VAR_SETDEFAULT:
514         {
515             int i;
516             /* FIXME: the list is sorted, dude. Use something cleverer. */
517             for( i = 0 ; i < p_var->choices.i_count ; i++ )
518                 if( p_var->ops->pf_cmp( p_var->choices.p_values[i], *p_val ) == 0 )
519                     break;
520
521             if( i == p_var->choices.i_count )
522                 /* Not found */
523                 break;
524
525             p_var->i_default = i;
526             CheckValue( p_var, &p_var->val );
527             break;
528         }
529         case VLC_VAR_SETVALUE:
530             /* Duplicate data if needed */
531             newval = *p_val;
532             p_var->ops->pf_dup( &newval );
533             /* Backup needed stuff */
534             oldval = p_var->val;
535             /* Check boundaries and list */
536             CheckValue( p_var, &newval );
537             /* Set the variable */
538             p_var->val = newval;
539             /* Free data if needed */
540             p_var->ops->pf_free( &oldval );
541             break;
542         case VLC_VAR_GETCHOICES:
543         case VLC_VAR_GETLIST:
544             p_val->p_list = malloc( sizeof(vlc_list_t) );
545             if( p_val2 ) p_val2->p_list = malloc( sizeof(vlc_list_t) );
546             if( p_var->choices.i_count )
547             {
548                 p_val->p_list->p_values = malloc( p_var->choices.i_count
549                                                   * sizeof(vlc_value_t) );
550                 p_val->p_list->pi_types = malloc( p_var->choices.i_count
551                                                   * sizeof(int) );
552                 if( p_val2 )
553                 {
554                     p_val2->p_list->p_values =
555                         malloc( p_var->choices.i_count * sizeof(vlc_value_t) );
556                     p_val2->p_list->pi_types =
557                         malloc( p_var->choices.i_count * sizeof(int) );
558                 }
559             }
560             p_val->p_list->i_count = p_var->choices.i_count;
561             if( p_val2 ) p_val2->p_list->i_count = p_var->choices.i_count;
562             for( int i = 0 ; i < p_var->choices.i_count ; i++ )
563             {
564                 p_val->p_list->p_values[i] = p_var->choices.p_values[i];
565                 p_val->p_list->pi_types[i] = p_var->i_type;
566                 p_var->ops->pf_dup( &p_val->p_list->p_values[i] );
567                 if( p_val2 )
568                 {
569                     p_val2->p_list->p_values[i].psz_string =
570                         p_var->choices_text.p_values[i].psz_string ?
571                     strdup(p_var->choices_text.p_values[i].psz_string) : NULL;
572                     p_val2->p_list->pi_types[i] = VLC_VAR_STRING;
573                 }
574             }
575             break;
576         case VLC_VAR_SETTEXT:
577             free( p_var->psz_text );
578             if( p_val && p_val->psz_string )
579                 p_var->psz_text = strdup( p_val->psz_string );
580             else
581                 p_var->psz_text = NULL;
582             break;
583         case VLC_VAR_GETTEXT:
584             p_val->psz_string = p_var->psz_text ? strdup( p_var->psz_text )
585                                                 : NULL;
586             break;
587         default:
588             break;
589     }
590
591     vlc_mutex_unlock( &p_priv->var_lock );
592
593     return ret;
594 }
595
596 #undef var_GetAndSet
597 /**
598  * Perform a Get and Set on a variable
599  *
600  * \param p_this: The object that hold the variable
601  * \param psz_name: the name of the variable
602  * \param i_action: the action to perform
603  * \param p_val: The action parameter
604  * \return vlc error codes
605  */
606 int var_GetAndSet( vlc_object_t *p_this, const char *psz_name, int i_action,
607                    vlc_value_t *p_val )
608 {
609     int i_ret;
610     variable_t *p_var;
611     vlc_value_t oldval;
612
613     assert( p_this );
614     assert( p_val );
615
616     vlc_object_internals_t *p_priv = vlc_internals( p_this );
617
618     vlc_mutex_lock( &p_priv->var_lock );
619     p_var = Lookup( p_this, psz_name );
620     if( p_var == NULL )
621     {
622         vlc_mutex_unlock( &p_priv->var_lock );
623         return VLC_ENOVAR;
624     }
625
626     WaitUnused( p_this, p_var );
627
628     /* Duplicated data if needed */
629     //p_var->ops->pf_dup( &val );
630
631     /* Backup needed stuff */
632     oldval = p_var->val;
633
634     /* depending of the action requiered */
635     switch( i_action )
636     {
637     case VLC_VAR_BOOL_TOGGLE:
638         assert( ( p_var->i_type & VLC_VAR_BOOL ) == VLC_VAR_BOOL );
639         p_var->val.b_bool = !p_var->val.b_bool;
640         break;
641     case VLC_VAR_INTEGER_ADD:
642         assert( ( p_var->i_type & VLC_VAR_INTEGER ) == VLC_VAR_INTEGER );
643         p_var->val.i_int += p_val->i_int;
644         break;
645     case VLC_VAR_INTEGER_OR:
646         assert( ( p_var->i_type & VLC_VAR_INTEGER ) == VLC_VAR_INTEGER );
647         p_var->val.i_int |= p_val->i_int;
648         break;
649     case VLC_VAR_INTEGER_NAND:
650         assert( ( p_var->i_type & VLC_VAR_INTEGER ) == VLC_VAR_INTEGER );
651         p_var->val.i_int &= ~p_val->i_int;
652         break;
653     default:
654         vlc_mutex_unlock( &p_priv->var_lock );
655         return VLC_EGENERIC;
656     }
657
658     /*  Check boundaries */
659     CheckValue( p_var, &p_var->val );
660     *p_val = p_var->val;
661
662     /* Deal with callbacks.*/
663     i_ret = TriggerCallback( p_this, p_var, psz_name, oldval );
664
665     vlc_mutex_unlock( &p_priv->var_lock );
666
667     return i_ret;
668 }
669
670 #undef var_Type
671 /**
672  * Request a variable's type
673  *
674  * \return The variable type if it exists, or 0 if the
675  * variable could not be found.
676  * \see \ref var_type
677  */
678 int var_Type( vlc_object_t *p_this, const char *psz_name )
679 {
680     variable_t *p_var;
681     int i_type = 0;
682
683     assert( p_this );
684
685     vlc_object_internals_t *p_priv = vlc_internals( p_this );
686
687     vlc_mutex_lock( &p_priv->var_lock );
688
689     p_var = Lookup( p_this, psz_name );
690     if( p_var != NULL )
691         i_type = p_var->i_type;
692
693     vlc_mutex_unlock( &p_priv->var_lock );
694
695     return i_type;
696 }
697
698 #undef var_SetChecked
699 int var_SetChecked( vlc_object_t *p_this, const char *psz_name,
700                     int expected_type, vlc_value_t val )
701 {
702     int i_ret = VLC_SUCCESS;
703     variable_t *p_var;
704     vlc_value_t oldval;
705
706     assert( p_this );
707
708     vlc_object_internals_t *p_priv = vlc_internals( p_this );
709
710     vlc_mutex_lock( &p_priv->var_lock );
711
712     p_var = Lookup( p_this, psz_name );
713     if( p_var == NULL )
714     {
715         vlc_mutex_unlock( &p_priv->var_lock );
716         return VLC_ENOVAR;
717     }
718
719     assert( expected_type == 0 ||
720             (p_var->i_type & VLC_VAR_CLASS) == expected_type );
721     assert ((p_var->i_type & VLC_VAR_CLASS) != VLC_VAR_VOID);
722
723     WaitUnused( p_this, p_var );
724
725     /* Duplicate data if needed */
726     p_var->ops->pf_dup( &val );
727
728     /* Backup needed stuff */
729     oldval = p_var->val;
730
731     /* Check boundaries and list */
732     CheckValue( p_var, &val );
733
734     /* Set the variable */
735     p_var->val = val;
736
737     /* Deal with callbacks */
738     i_ret = TriggerCallback( p_this, p_var, psz_name, oldval );
739
740     /* Free data if needed */
741     p_var->ops->pf_free( &oldval );
742
743     vlc_mutex_unlock( &p_priv->var_lock );
744
745     return i_ret;
746 }
747
748 #undef var_Set
749 /**
750  * Set a variable's value
751  *
752  * \param p_this The object that hold the variable
753  * \param psz_name The name of the variable
754  * \param val the value to set
755  */
756 int var_Set( vlc_object_t *p_this, const char *psz_name, vlc_value_t val )
757 {
758     return var_SetChecked( p_this, psz_name, 0, val );
759 }
760
761 #undef var_GetChecked
762 int var_GetChecked( vlc_object_t *p_this, const char *psz_name,
763                     int expected_type, vlc_value_t *p_val )
764 {
765     assert( p_this );
766
767     vlc_object_internals_t *p_priv = vlc_internals( p_this );
768     variable_t *p_var;
769     int err = VLC_SUCCESS;
770
771     vlc_mutex_lock( &p_priv->var_lock );
772
773     p_var = Lookup( p_this, psz_name );
774     if( p_var != NULL )
775     {
776         assert( expected_type == 0 ||
777                 (p_var->i_type & VLC_VAR_CLASS) == expected_type );
778         assert ((p_var->i_type & VLC_VAR_CLASS) != VLC_VAR_VOID);
779
780         /* Really get the variable */
781         *p_val = p_var->val;
782
783         /* Duplicate value if needed */
784         p_var->ops->pf_dup( p_val );
785     }
786     else
787         err = VLC_ENOVAR;
788
789     vlc_mutex_unlock( &p_priv->var_lock );
790     return err;
791 }
792
793 #undef var_Get
794 /**
795  * Get a variable's value
796  *
797  * \param p_this The object that holds the variable
798  * \param psz_name The name of the variable
799  * \param p_val Pointer to a vlc_value_t that will hold the variable's value
800  *              after the function is finished
801  */
802 int var_Get( vlc_object_t *p_this, const char *psz_name, vlc_value_t *p_val )
803 {
804     return var_GetChecked( p_this, psz_name, 0, p_val );
805 }
806
807 static int AddCallback( vlc_object_t *p_this, const char *psz_name,
808                         callback_entry_t entry )
809 {
810     variable_t *p_var;
811
812     assert( p_this );
813
814     vlc_object_internals_t *p_priv = vlc_internals( p_this );
815
816     vlc_mutex_lock( &p_priv->var_lock );
817
818     p_var = Lookup( p_this, psz_name );
819     if( p_var == NULL )
820     {
821         vlc_mutex_unlock( &p_priv->var_lock );
822         msg_Err( p_this, "cannot add callback %p to nonexistent "
823                          "variable '%s'", entry.pf_callback, psz_name );
824         return VLC_ENOVAR;
825     }
826
827     WaitUnused( p_this, p_var );
828     callback_table_t *p_table = &p_var->value_callbacks;
829     INSERT_ELEM( p_table->p_entries,
830                  p_table->i_entries,
831                  p_table->i_entries,
832                  entry);
833
834     vlc_mutex_unlock( &p_priv->var_lock );
835
836     return VLC_SUCCESS;
837 }
838
839 #undef var_AddCallback
840 /**
841  * Register a callback in a variable
842  *
843  * We store a function pointer that will be called upon variable
844  * modification.
845  *
846  * \param p_this The object that holds the variable
847  * \param psz_name The name of the variable
848  * \param pf_callback The function pointer
849  * \param p_data A generic pointer that will be passed as the last
850  *               argument to the callback function.
851  *
852  * \warning The callback function is run in the thread that calls var_Set on
853  *          the variable. Use proper locking. This thread may not have much
854  *          time to spare, so keep callback functions short.
855  */
856 int var_AddCallback( vlc_object_t *p_this, const char *psz_name,
857                      vlc_callback_t pf_callback, void *p_data )
858 {
859     callback_entry_t entry;
860     entry.pf_callback = pf_callback;
861     entry.p_data = p_data;
862
863     return AddCallback(p_this, psz_name, entry);
864 }
865
866 static int DelCallback( vlc_object_t *p_this, const char *psz_name,
867                         callback_entry_t entry )
868 {
869     int i_entry;
870     variable_t *p_var;
871 #ifndef NDEBUG
872     bool b_found_similar = false;
873 #endif
874
875     assert( p_this );
876
877     vlc_object_internals_t *p_priv = vlc_internals( p_this );
878
879     vlc_mutex_lock( &p_priv->var_lock );
880
881     p_var = Lookup( p_this, psz_name );
882     if( p_var == NULL )
883     {
884         vlc_mutex_unlock( &p_priv->var_lock );
885         return VLC_ENOVAR;
886     }
887
888     WaitUnused( p_this, p_var );
889
890     callback_table_t *p_table = &p_var->value_callbacks;
891     for( i_entry = p_table->i_entries ; i_entry-- ; )
892     {
893         if( p_table->p_entries[i_entry].pf_callback == entry.pf_callback
894             && p_table->p_entries[i_entry].p_data == entry.p_data )
895         {
896             break;
897         }
898 #ifndef NDEBUG
899         else if( p_table->p_entries[i_entry].pf_callback == entry.pf_callback )
900             b_found_similar = true;
901 #endif
902     }
903
904     if( i_entry < 0 )
905     {
906 #ifndef NDEBUG
907         if( b_found_similar )
908             fprintf( stderr, "Calling var_DelCallback for '%s' with the same "
909                              "function but not the same data.", psz_name );
910         assert( 0 );
911 #endif
912         vlc_mutex_unlock( &p_priv->var_lock );
913         return VLC_EGENERIC;
914     }
915
916     REMOVE_ELEM( p_table->p_entries, p_table->i_entries, i_entry );
917
918     vlc_mutex_unlock( &p_priv->var_lock );
919
920     return VLC_SUCCESS;
921 }
922
923 #undef var_DelCallback
924 /**
925  * Remove a callback from a variable
926  *
927  * pf_callback and p_data have to be given again, because different objects
928  * might have registered the same callback function.
929  */
930 int var_DelCallback( vlc_object_t *p_this, const char *psz_name,
931                      vlc_callback_t pf_callback, void *p_data )
932 {
933     callback_entry_t entry;
934     entry.pf_callback = pf_callback;
935     entry.p_data = p_data;
936
937     return DelCallback(p_this, psz_name, entry);
938 }
939
940 #undef var_TriggerCallback
941 /**
942  * Trigger callback on a variable
943  *
944  * \param p_this The object that hold the variable
945  * \param psz_name The name of the variable
946  */
947 int var_TriggerCallback( vlc_object_t *p_this, const char *psz_name )
948 {
949     int i_ret;
950     variable_t *p_var;
951
952     assert( p_this );
953
954     vlc_object_internals_t *p_priv = vlc_internals( p_this );
955
956     vlc_mutex_lock( &p_priv->var_lock );
957
958     p_var = Lookup( p_this, psz_name );
959     if( p_var == NULL )
960     {
961         vlc_mutex_unlock( &p_priv->var_lock );
962         return VLC_ENOVAR;
963     }
964
965     WaitUnused( p_this, p_var );
966
967     /* Deal with callbacks. Tell we're in a callback, release the lock,
968      * call stored functions, retake the lock. */
969     i_ret = TriggerCallback( p_this, p_var, psz_name, p_var->val );
970
971     vlc_mutex_unlock( &p_priv->var_lock );
972     return i_ret;
973 }
974
975 /** Parse a stringified option
976  * This function parse a string option and create the associated object
977  * variable
978  * The option must be of the form "[no[-]]foo[=bar]" where foo is the
979  * option name and bar is the value of the option.
980  * \param p_obj the object in which the variable must be created
981  * \param psz_option the option to parse
982  * \param trusted whether the option is set by a trusted input or not
983  * \return nothing
984  */
985 void var_OptionParse( vlc_object_t *p_obj, const char *psz_option,
986                       bool trusted )
987 {
988     char *psz_name, *psz_value;
989     int  i_type;
990     bool b_isno = false;
991     vlc_value_t val;
992
993     val.psz_string = NULL;
994
995     /* It's too much of a hassle to remove the ':' when we parse
996      * the cmd line :) */
997     if( psz_option[0] == ':' )
998         psz_option++;
999
1000     if( !psz_option[0] )
1001         return;
1002
1003     psz_name = strdup( psz_option );
1004     if( psz_name == NULL )
1005         return;
1006
1007     psz_value = strchr( psz_name, '=' );
1008     if( psz_value != NULL )
1009         *psz_value++ = '\0';
1010
1011     i_type = config_GetType( p_obj, psz_name );
1012     if( !i_type && !psz_value )
1013     {
1014         /* check for "no-foo" or "nofoo" */
1015         if( !strncmp( psz_name, "no-", 3 ) )
1016         {
1017             memmove( psz_name, psz_name + 3, strlen(psz_name) + 1 - 3 );
1018         }
1019         else if( !strncmp( psz_name, "no", 2 ) )
1020         {
1021             memmove( psz_name, psz_name + 2, strlen(psz_name) + 1 - 2 );
1022         }
1023         else goto cleanup;           /* Option doesn't exist */
1024
1025         b_isno = true;
1026         i_type = config_GetType( p_obj, psz_name );
1027     }
1028     if( !i_type ) goto cleanup; /* Option doesn't exist */
1029
1030     if( ( i_type != VLC_VAR_BOOL ) &&
1031         ( !psz_value || !*psz_value ) ) goto cleanup; /* Invalid value */
1032
1033     /* check if option is unsafe */
1034     if( !trusted && !config_IsSafe( psz_name ) )
1035     {
1036         msg_Err( p_obj, "unsafe option \"%s\" has been ignored for "
1037                         "security reasons", psz_name );
1038         free( psz_name );
1039         return;
1040     }
1041
1042     /* Create the variable in the input object.
1043      * Children of the input object will be able to retreive this value
1044      * thanks to the inheritance property of the object variables. */
1045     var_Create( p_obj, psz_name, i_type );
1046
1047     switch( i_type )
1048     {
1049     case VLC_VAR_BOOL:
1050         val.b_bool = !b_isno;
1051         break;
1052
1053     case VLC_VAR_INTEGER:
1054         val.i_int = strtoll( psz_value, NULL, 0 );
1055         break;
1056
1057     case VLC_VAR_FLOAT:
1058         val.f_float = us_atof( psz_value );
1059         break;
1060
1061     case VLC_VAR_STRING:
1062         val.psz_string = psz_value;
1063         break;
1064
1065     default:
1066         goto cleanup;
1067     }
1068
1069     var_Set( p_obj, psz_name, val );
1070
1071 cleanup:
1072     free( psz_name );
1073 }
1074
1075 #undef var_LocationParse
1076 /**
1077  * Parses a set of colon-separated or semicolon-separated
1078  * <variable name>=<value> pairs.
1079  * Some access (or access_demux) plugins uses this scheme
1080  * in media resource location.
1081  * @note Only trusted/safe variables are allowed. This is intended.
1082  *
1083  * @warning Only use this for plugins implementing VLC-specific resource
1084  * location schemes. This would not make any sense for standardized ones.
1085  *
1086  * @param obj VLC object on which to set variables (and emit error messages)
1087  * @param mrl string to parse
1088  * @param pref prefix to prepend to option names in the string
1089  *
1090  * @return VLC_ENOMEM on error, VLC_SUCCESS on success.
1091  */
1092 int var_LocationParse (vlc_object_t *obj, const char *mrl, const char *pref)
1093 {
1094     int ret = VLC_SUCCESS;
1095     size_t preflen = strlen (pref) + 1;
1096
1097     assert(mrl != NULL);
1098     while (*mrl != '\0')
1099     {
1100         mrl += strspn (mrl, ":;"); /* skip leading colon(s) */
1101
1102         size_t len = strcspn (mrl, ":;");
1103         char *buf = malloc (preflen + len);
1104
1105         if (likely(buf != NULL))
1106         {
1107             /* NOTE: this does not support the "no-<varname>" bool syntax. */
1108             /* DO NOT use asprintf() here; it won't work! Think again. */
1109             snprintf (buf, preflen + len, "%s%s", pref, mrl);
1110             var_OptionParse (obj, buf, false);
1111             free (buf);
1112         }
1113         else
1114             ret = VLC_ENOMEM;
1115         mrl += len;
1116     }
1117
1118     return ret;
1119 }
1120
1121 /**
1122  * Waits until the variable is inactive (i.e. not executing a callback)
1123  */
1124 static void WaitUnused( vlc_object_t *p_this, variable_t *p_var )
1125 {
1126     vlc_object_internals_t *p_priv = vlc_internals( p_this );
1127
1128     mutex_cleanup_push( &p_priv->var_lock );
1129     while( p_var->b_incallback )
1130         vlc_cond_wait( &p_priv->var_wait, &p_priv->var_lock );
1131     vlc_cleanup_pop( );
1132 }
1133
1134 /*****************************************************************************
1135  * CheckValue: check that a value is valid wrt. a variable
1136  *****************************************************************************
1137  * This function checks p_val's value against p_var's limitations such as
1138  * minimal and maximal value, step, in-list position, and modifies p_val if
1139  * necessary.
1140  ****************************************************************************/
1141 static void CheckValue ( variable_t *p_var, vlc_value_t *p_val )
1142 {
1143     /* Check that our variable is in the list */
1144     if( p_var->i_type & VLC_VAR_HASCHOICE && p_var->choices.i_count )
1145     {
1146         int i;
1147
1148         /* This list is not sorted so go throug it (this is a small list) */
1149         for( i = p_var->choices.i_count ; i-- ; )
1150         {
1151             if( p_var->ops->pf_cmp( *p_val, p_var->choices.p_values[i] ) == 0 )
1152             {
1153                 break;
1154             }
1155         }
1156
1157         /* If not found, change it to anything vaguely valid */
1158         if( i < 0 )
1159         {
1160             /* Free the old variable, get the new one, dup it */
1161             p_var->ops->pf_free( p_val );
1162             *p_val = p_var->choices.p_values[p_var->i_default >= 0
1163                                           ? p_var->i_default : 0 ];
1164             p_var->ops->pf_dup( p_val );
1165         }
1166     }
1167
1168     /* Check that our variable is within the bounds */
1169     switch( p_var->i_type & VLC_VAR_TYPE )
1170     {
1171         case VLC_VAR_INTEGER:
1172             if( p_var->i_type & VLC_VAR_HASSTEP && p_var->step.i_int
1173                  && (p_val->i_int % p_var->step.i_int) )
1174             {
1175                 p_val->i_int = (p_val->i_int + (p_var->step.i_int / 2))
1176                                / p_var->step.i_int * p_var->step.i_int;
1177             }
1178             if( p_var->i_type & VLC_VAR_HASMIN
1179                  && p_val->i_int < p_var->min.i_int )
1180             {
1181                 p_val->i_int = p_var->min.i_int;
1182             }
1183             if( p_var->i_type & VLC_VAR_HASMAX
1184                  && p_val->i_int > p_var->max.i_int )
1185             {
1186                 p_val->i_int = p_var->max.i_int;
1187             }
1188             break;
1189         case VLC_VAR_FLOAT:
1190             if( p_var->i_type & VLC_VAR_HASSTEP && p_var->step.f_float )
1191             {
1192                 float f_round = p_var->step.f_float * (float)(int)( 0.5 +
1193                                         p_val->f_float / p_var->step.f_float );
1194                 if( p_val->f_float != f_round )
1195                 {
1196                     p_val->f_float = f_round;
1197                 }
1198             }
1199             if( p_var->i_type & VLC_VAR_HASMIN
1200                  && p_val->f_float < p_var->min.f_float )
1201             {
1202                 p_val->f_float = p_var->min.f_float;
1203             }
1204             if( p_var->i_type & VLC_VAR_HASMAX
1205                  && p_val->f_float > p_var->max.f_float )
1206             {
1207                 p_val->f_float = p_var->max.f_float;
1208             }
1209             break;
1210         case VLC_VAR_TIME:
1211             /* FIXME: TODO */
1212             break;
1213     }
1214 }
1215
1216 /**
1217  * Finds the value of a variable. If the specified object does not hold a
1218  * variable with the specified name, try the parent object, and iterate until
1219  * the top of the tree. If no match is found, the value is read from the
1220  * configuration.
1221  */
1222 int var_Inherit( vlc_object_t *p_this, const char *psz_name, int i_type,
1223                  vlc_value_t *p_val )
1224 {
1225     i_type &= VLC_VAR_CLASS;
1226     for( vlc_object_t *obj = p_this; obj != NULL; obj = obj->p_parent )
1227     {
1228         if( var_GetChecked( obj, psz_name, i_type, p_val ) == VLC_SUCCESS )
1229             return VLC_SUCCESS;
1230     }
1231
1232     /* else take value from config */
1233     switch( i_type & VLC_VAR_CLASS )
1234     {
1235         case VLC_VAR_STRING:
1236             p_val->psz_string = config_GetPsz( p_this, psz_name );
1237             if( !p_val->psz_string ) p_val->psz_string = strdup("");
1238             break;
1239         case VLC_VAR_FLOAT:
1240             p_val->f_float = config_GetFloat( p_this, psz_name );
1241             break;
1242         case VLC_VAR_INTEGER:
1243             p_val->i_int = config_GetInt( p_this, psz_name );
1244             break;
1245         case VLC_VAR_BOOL:
1246             p_val->b_bool = config_GetInt( p_this, psz_name );
1247             break;
1248         default:
1249             assert(0);
1250         case VLC_VAR_ADDRESS:
1251             return VLC_ENOOBJ;
1252     }
1253     return VLC_SUCCESS;
1254 }
1255
1256
1257 /**
1258  * It inherits a string as an unsigned rational number (it also accepts basic
1259  * float number).
1260  *
1261  * It returns an error if the rational number cannot be parsed (0/0 is valid).
1262  * The rational is already reduced.
1263  */
1264 int (var_InheritURational)(vlc_object_t *object,
1265                            unsigned *num, unsigned *den,
1266                            const char *var)
1267 {
1268     /* */
1269     *num = 0;
1270     *den = 0;
1271
1272     /* */
1273     char *tmp = var_InheritString(object, var);
1274     if (!tmp)
1275         goto error;
1276
1277     char *next;
1278     unsigned n = strtol(tmp,  &next, 0);
1279     unsigned d = strtol(*next ? &next[1] : "0", NULL, 0);
1280
1281     if (*next == '.') {
1282         /* Interpret as a float number */
1283         double r = us_atof(tmp);
1284         double c = ceil(r);
1285         if (c >= UINT_MAX)
1286             goto error;
1287         unsigned m = c;
1288         if (m > 0) {
1289             d = UINT_MAX / m;
1290             n = r * d;
1291         } else {
1292             n = 0;
1293             d = 0;
1294         }
1295     } else if ( *next == '\0' ) {
1296         /* plain integer given */
1297         *num = n;
1298         *den = 1;
1299     }
1300
1301     if (n > 0 && d > 0)
1302         vlc_ureduce(num, den, n, d, 0);
1303
1304     free(tmp);
1305     return VLC_SUCCESS;
1306
1307 error:
1308     free(tmp);
1309     return VLC_EGENERIC;
1310 }
1311
1312 /**********************************************************************
1313  * Trigger the callbacks.
1314  * Tell we're in a callback, release the lock, call stored functions,
1315  * retake the lock.
1316  **********************************************************************/
1317 static int TriggerCallback( vlc_object_t *p_this, variable_t *p_var,
1318                             const char *psz_name, vlc_value_t oldval )
1319 {
1320     assert( p_this );
1321
1322     callback_table_t *p_table = &p_var->value_callbacks;
1323     int i_entries = p_table->i_entries;
1324     if( i_entries == 0 )
1325         return VLC_SUCCESS;
1326
1327     callback_entry_t *p_entries = p_table->p_entries;
1328     vlc_object_internals_t *p_priv = vlc_internals( p_this );
1329
1330     assert( !p_var->b_incallback );
1331     p_var->b_incallback = true;
1332     vlc_mutex_unlock( &p_priv->var_lock );
1333
1334     /* The real calls */
1335     for( ; i_entries-- ; )
1336     {
1337         p_entries[i_entries].pf_callback( p_this, psz_name, oldval, p_var->val,
1338                                           p_entries[i_entries].p_data );
1339     }
1340
1341     vlc_mutex_lock( &p_priv->var_lock );
1342     p_var->b_incallback = false;
1343     vlc_cond_broadcast( &p_priv->var_wait );
1344
1345     return VLC_SUCCESS;
1346 }
1347
1348 /**
1349  * Free a list and the associated strings
1350  * @param p_val: the list variable
1351  * @param p_val2: the variable associated or NULL
1352  */
1353 void var_FreeList( vlc_value_t *p_val, vlc_value_t *p_val2 )
1354 {
1355     FreeList( p_val );
1356     if( p_val2 && p_val2->p_list )
1357     {
1358         for( int i = 0; i < p_val2->p_list->i_count; i++ )
1359             free( p_val2->p_list->p_values[i].psz_string );
1360         if( p_val2->p_list->i_count )
1361         {
1362             free( p_val2->p_list->p_values );
1363             free( p_val2->p_list->pi_types );
1364         }
1365         free( p_val2->p_list );
1366     }
1367 }