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