]> git.sesse.net Git - vlc/blob - src/misc/objects.c
4a16e1bc2903ba3b20e02b6b5b0fe1ce51e90caf
[vlc] / src / misc / objects.c
1 /*****************************************************************************
2  * objects.c: vlc_object_t handling
3  *****************************************************************************
4  * Copyright (C) 2004-2008 the VideoLAN team
5  * $Id$
6  *
7  * Authors: Samuel Hocevar <sam@zoy.org>
8  *
9  * This program is free software; you can redistribute it and/or modify
10  * it under the terms of the GNU General Public License as published by
11  * the Free Software Foundation; either version 2 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 General Public License for more details.
18  *
19  * You should have received a copy of the GNU General Public License
20  * along with this program; if not, write to the Free Software
21  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
22  *****************************************************************************/
23
24 /**
25  * \file
26  * This file contains the functions to handle the vlc_object_t type
27  */
28
29
30 /*****************************************************************************
31  * Preamble
32  *****************************************************************************/
33 #ifdef HAVE_CONFIG_H
34 # include "config.h"
35 #endif
36
37 #include <vlc/vlc.h>
38
39 #include "../libvlc.h"
40 #include <vlc_vout.h>
41 #include <vlc_aout.h>
42 #include "audio_output/aout_internal.h"
43
44 #include <vlc_access.h>
45 #include <vlc_demux.h>
46 #include <vlc_stream.h>
47
48 #include <vlc_sout.h>
49 #include "stream_output/stream_output.h"
50
51 #include "vlc_interface.h"
52 #include "vlc_codec.h"
53 #include "vlc_filter.h"
54
55 #include "variables.h"
56 #ifndef WIN32
57 # include <unistd.h>
58 #else
59 # include <io.h>
60 # include <fcntl.h>
61 # include <errno.h> /* ENOSYS */
62 #endif
63 #include <assert.h>
64
65 /*****************************************************************************
66  * Local prototypes
67  *****************************************************************************/
68 static int  DumpCommand( vlc_object_t *, char const *,
69                          vlc_value_t, vlc_value_t, void * );
70
71 static vlc_object_t * FindObject    ( vlc_object_t *, int, int );
72 static vlc_object_t * FindObjectName( vlc_object_t *, const char *, int );
73 static void           PrintObject   ( vlc_object_t *, const char * );
74 static void           DumpStructure ( vlc_object_t *, int, char * );
75
76 static vlc_list_t   * NewList       ( int );
77 static void           ListReplace   ( vlc_list_t *, vlc_object_t *, int );
78 /*static void           ListAppend    ( vlc_list_t *, vlc_object_t * );*/
79 static int            CountChildren ( vlc_object_t *, int );
80 static void           ListChildren  ( vlc_list_t *, vlc_object_t *, int );
81
82 static void vlc_object_destroy( vlc_object_t *p_this );
83 static void vlc_object_detach_unlocked (vlc_object_t *p_this);
84
85 /*****************************************************************************
86  * Local structure lock
87  *****************************************************************************/
88 static vlc_mutex_t    structure_lock;
89
90 void *vlc_custom_create( vlc_object_t *p_this, size_t i_size,
91                          int i_type, const char *psz_type )
92 {
93     vlc_object_t *p_new;
94     vlc_object_internals_t *p_priv;
95
96     /* NOTE:
97      * VLC objects are laid out as follow:
98      * - first the LibVLC-private per-object data,
99      * - then VLC_COMMON members from vlc_object_t,
100      * - finally, the type-specific data (if any).
101      *
102      * This function initializes the LibVLC and common data,
103      * and zeroes the rest.
104      */
105     p_priv = calloc( 1, sizeof( *p_priv ) + i_size );
106     if( p_priv == NULL )
107         return NULL;
108
109     assert (i_size >= sizeof (vlc_object_t));
110     p_new = (vlc_object_t *)(p_priv + 1);
111
112     p_new->i_object_type = i_type;
113     p_new->psz_object_type = psz_type;
114     p_new->psz_object_name = NULL;
115
116     p_new->b_die = false;
117     p_new->b_error = false;
118     p_new->b_dead = false;
119     p_new->b_force = false;
120
121     p_new->psz_header = NULL;
122
123     if (p_this)
124         p_new->i_flags = p_this->i_flags
125             & (OBJECT_FLAGS_NODBG|OBJECT_FLAGS_QUIET|OBJECT_FLAGS_NOINTERACT);
126
127     p_priv->p_vars = calloc( sizeof( variable_t ), 16 );
128
129     if( !p_priv->p_vars )
130     {
131         free( p_priv );
132         return NULL;
133     }
134
135     libvlc_global_data_t *p_libvlc_global;
136     if( p_this == NULL )
137     {
138         /* Only the global root object is created out of the blue */
139         p_libvlc_global = (libvlc_global_data_t *)p_new;
140         p_new->p_libvlc = NULL;
141
142         p_libvlc_global->i_counter = 0;
143         p_priv->next = p_priv->prev = p_new;
144         vlc_mutex_init( &structure_lock );
145     }
146     else
147     {
148         p_libvlc_global = vlc_global();
149         if( i_type == VLC_OBJECT_LIBVLC )
150             p_new->p_libvlc = (libvlc_int_t*)p_new;
151         else
152             p_new->p_libvlc = p_this->p_libvlc;
153     }
154
155     vlc_spin_init( &p_priv->ref_spin );
156     p_priv->i_refcount = 1;
157     p_priv->pf_destructor = NULL;
158     p_priv->b_thread = false;
159     p_new->p_parent = NULL;
160     p_priv->pp_children = NULL;
161     p_priv->i_children = 0;
162
163     p_new->p_private = NULL;
164
165     /* Initialize mutexes and condvars */
166     vlc_mutex_init( &p_new->object_lock );
167     vlc_cond_init( p_new, &p_new->object_wait );
168     vlc_mutex_init( &p_priv->var_lock );
169     vlc_spin_init( &p_priv->spin );
170     p_priv->pipes[0] = p_priv->pipes[1] = -1;
171
172     p_priv->next = VLC_OBJECT (p_libvlc_global);
173     vlc_mutex_lock( &structure_lock );
174     p_priv->prev = vlc_internals (p_libvlc_global)->prev;
175     vlc_internals (p_libvlc_global)->prev = p_new;
176     vlc_internals (p_priv->prev)->next = p_new;
177     p_new->i_object_id = p_libvlc_global->i_counter++;
178     vlc_mutex_unlock( &structure_lock );
179
180     if( i_type == VLC_OBJECT_LIBVLC )
181     {
182         var_Create( p_new, "list", VLC_VAR_STRING | VLC_VAR_ISCOMMAND );
183         var_AddCallback( p_new, "list", DumpCommand, NULL );
184         var_Create( p_new, "tree", VLC_VAR_STRING | VLC_VAR_ISCOMMAND );
185         var_AddCallback( p_new, "tree", DumpCommand, NULL );
186         var_Create( p_new, "vars", VLC_VAR_STRING | VLC_VAR_ISCOMMAND );
187         var_AddCallback( p_new, "vars", DumpCommand, NULL );
188     }
189
190     return p_new;
191 }
192
193
194 /**
195  * Allocates and initializes a vlc object.
196  *
197  * @param i_type known object type (all of them are negative integer values),
198  *               or object byte size (always positive).
199  *
200  * @return the new object, or NULL on error.
201  */
202 void * __vlc_object_create( vlc_object_t *p_this, int i_type )
203 {
204     const char   * psz_type;
205     size_t         i_size;
206
207     switch( i_type )
208     {
209         case VLC_OBJECT_LIBVLC:
210             i_size = sizeof(libvlc_int_t);
211             psz_type = "libvlc";
212             break;
213         case VLC_OBJECT_INTF:
214             i_size = sizeof(intf_thread_t);
215             psz_type = "interface";
216             break;
217         case VLC_OBJECT_DIALOGS:
218             i_size = sizeof(intf_thread_t);
219             psz_type = "dialogs";
220             break;
221         case VLC_OBJECT_DEMUX:
222             i_size = sizeof(demux_t);
223             psz_type = "demux";
224             break;
225         case VLC_OBJECT_ACCESS:
226             i_size = sizeof(access_t);
227             psz_type = "access";
228             break;
229         case VLC_OBJECT_DECODER:
230             i_size = sizeof(decoder_t);
231             psz_type = "decoder";
232             break;
233         case VLC_OBJECT_PACKETIZER:
234             i_size = sizeof(decoder_t);
235             psz_type = "packetizer";
236             break;
237         case VLC_OBJECT_ENCODER:
238             i_size = sizeof(encoder_t);
239             psz_type = "encoder";
240             break;
241         case VLC_OBJECT_FILTER:
242             i_size = sizeof(filter_t);
243             psz_type = "filter";
244             break;
245         case VLC_OBJECT_VOUT:
246             i_size = sizeof(vout_thread_t);
247             psz_type = "video output";
248             break;
249         case VLC_OBJECT_AOUT:
250             i_size = sizeof(aout_instance_t);
251             psz_type = "audio output";
252             break;
253         case VLC_OBJECT_SOUT:
254             i_size = sizeof(sout_instance_t);
255             psz_type = "stream output";
256             break;
257         case VLC_OBJECT_OPENGL:
258             i_size = sizeof( vout_thread_t );
259             psz_type = "opengl";
260             break;
261         case VLC_OBJECT_ANNOUNCE:
262             i_size = sizeof( announce_handler_t );
263             psz_type = "announce";
264             break;
265         case VLC_OBJECT_INTERACTION:
266             i_size = sizeof( interaction_t );
267             psz_type = "interaction";
268             break;
269         default:
270             i_size = i_type > (int)sizeof(vlc_object_t)
271                          ? i_type : (int)sizeof(vlc_object_t);
272             i_type = VLC_OBJECT_GENERIC;
273             psz_type = "generic";
274             break;
275     }
276
277     return vlc_custom_create( p_this, i_size, i_type, psz_type );
278 }
279
280
281 /**
282  ****************************************************************************
283  * Set the destructor of a vlc object
284  *
285  * This function sets the destructor of the vlc object. It will be called
286  * when the object is destroyed when the its refcount reaches 0.
287  * (It is called by the internal function vlc_object_destroy())
288  *****************************************************************************/
289 void __vlc_object_set_destructor( vlc_object_t *p_this,
290                                   vlc_destructor_t pf_destructor )
291 {
292     vlc_object_internals_t *p_priv = vlc_internals(p_this );
293     p_priv->pf_destructor = pf_destructor;
294 }
295
296 /**
297  ****************************************************************************
298  * Destroy a vlc object (Internal)
299  *
300  * This function destroys an object that has been previously allocated with
301  * vlc_object_create. The object's refcount must be zero and it must not be
302  * attached to other objects in any way.
303  *****************************************************************************/
304 static void vlc_object_destroy( vlc_object_t *p_this )
305 {
306     vlc_object_internals_t *p_priv = vlc_internals( p_this );
307
308     /* Objects are always detached beforehand */
309     assert( !p_this->p_parent );
310
311     /* Send a kill to the object's thread if applicable */
312     vlc_object_kill( p_this );
313
314     /* If we are running on a thread, wait until it ends */
315     if( p_priv->b_thread )
316         vlc_thread_join( p_this );
317
318     /* Call the custom "subclass" destructor */
319     if( p_priv->pf_destructor )
320         p_priv->pf_destructor( p_this );
321
322     /* Destroy the associated variables, starting from the end so that
323      * no memmove calls have to be done. */
324     while( p_priv->i_vars )
325     {
326         var_Destroy( p_this, p_priv->p_vars[p_priv->i_vars - 1].psz_name );
327     }
328
329     free( p_priv->p_vars );
330     vlc_mutex_destroy( &p_priv->var_lock );
331
332     free( p_this->psz_header );
333
334     if( p_this->p_libvlc == NULL )
335     {
336         libvlc_global_data_t *p_global = (libvlc_global_data_t *)p_this;
337
338 #ifndef NDEBUG
339         assert( p_global == vlc_global() );
340         /* Test for leaks */
341         for( vlc_object_t *leaked = p_priv->next;
342              leaked != p_this;
343              leaked = vlc_internals (leaked)->next )
344         {
345             /* We are leaking this object */
346             fprintf( stderr,
347                      "ERROR: leaking object (id:%i, type:%s, name:%s)\n",
348                      leaked->i_object_id, leaked->psz_object_type,
349                      leaked->psz_object_name );
350             /* Dump libvlc object to ease debugging */
351             vlc_object_dump( leaked );
352             fflush(stderr);
353         }
354
355         if( p_priv->next != p_this )
356         {
357             /* Dump libvlc object to ease debugging */
358             vlc_object_dump( p_this );
359             /* Strongly abort, cause we want these to be fixed */
360             abort();
361         }
362 #endif
363
364         /* We are the global object ... no need to lock. */
365         vlc_mutex_destroy( &structure_lock );
366     }
367
368     FREENULL( p_this->psz_object_name );
369
370 #if defined(WIN32) || defined(UNDER_CE)
371     /* if object has an associated thread, close it now */
372     if( p_priv->thread_id )
373        CloseHandle(p_priv->thread_id);
374 #endif
375
376     vlc_spin_destroy( &p_priv->ref_spin );
377     vlc_mutex_destroy( &p_this->object_lock );
378     vlc_cond_destroy( &p_this->object_wait );
379     vlc_spin_destroy( &p_priv->spin );
380     if( p_priv->pipes[1] != -1 )
381         close( p_priv->pipes[1] );
382     if( p_priv->pipes[0] != -1 )
383         close( p_priv->pipes[0] );
384
385     free( p_priv );
386 }
387
388
389 /** Inter-object signaling */
390
391 void __vlc_object_lock( vlc_object_t *obj )
392 {
393     vlc_mutex_lock( &obj->object_lock );
394 }
395
396 void __vlc_object_unlock( vlc_object_t *obj )
397 {
398     vlc_assert_locked( &obj->object_lock );
399     vlc_mutex_unlock( &obj->object_lock );
400 }
401
402 #ifdef WIN32
403 # include <winsock2.h>
404 # include <ws2tcpip.h>
405
406 /**
407  * select()-able pipes emulated using Winsock
408  */
409 static int pipe (int fd[2])
410 {
411     SOCKADDR_IN addr;
412     int addrlen = sizeof (addr);
413
414     SOCKET l = socket (PF_INET, SOCK_STREAM, IPPROTO_TCP), a,
415            c = socket (PF_INET, SOCK_STREAM, IPPROTO_TCP);
416     if ((l == INVALID_SOCKET) || (c == INVALID_SOCKET))
417         goto error;
418
419     memset (&addr, 0, sizeof (addr));
420     addr.sin_family = AF_INET;
421     addr.sin_addr.s_addr = htonl (INADDR_LOOPBACK);
422     if (bind (l, (PSOCKADDR)&addr, sizeof (addr))
423      || getsockname (l, (PSOCKADDR)&addr, &addrlen)
424      || listen (l, 1)
425      || connect (c, (PSOCKADDR)&addr, addrlen))
426         goto error;
427
428     a = accept (l, NULL, NULL);
429     if (a == INVALID_SOCKET)
430         goto error;
431
432     closesocket (l);
433     //shutdown (a, 0);
434     //shutdown (c, 1);
435     fd[0] = c;
436     fd[1] = a;
437     return 0;
438
439 error:
440     if (l != INVALID_SOCKET)
441         closesocket (l);
442     if (c != INVALID_SOCKET)
443         closesocket (c);
444     return -1;
445 }
446
447 #undef  read
448 #define read( a, b, c )  recv (a, b, c, 0)
449 #undef  write
450 #define write( a, b, c ) send (a, b, c, 0)
451 #undef  close
452 #define close( a )       closesocket (a)
453 #endif /* WIN32 */
454
455 /**
456  * Returns the readable end of a pipe that becomes readable once termination
457  * of the object is requested (vlc_object_kill()).
458  * This can be used to wake-up out of a select() or poll() event loop, such
459  * typically when doing network I/O.
460  *
461  * Note that the pipe will remain the same for the lifetime of the object.
462  * DO NOT read the pipe nor close it yourself. Ever.
463  *
464  * @param obj object that would be "killed"
465  * @return a readable pipe descriptor, or -1 on error.
466  */
467 int __vlc_object_waitpipe( vlc_object_t *obj )
468 {
469     int pfd[2] = { -1, -1 };
470     vlc_object_internals_t *internals = vlc_internals( obj );
471     bool killed = false;
472
473     vlc_spin_lock (&internals->spin);
474     if (internals->pipes[0] == -1)
475     {
476         /* This can only ever happen if someone killed us without locking: */
477         assert (internals->pipes[1] == -1);
478         vlc_spin_unlock (&internals->spin);
479
480         if (pipe (pfd))
481             return -1;
482
483         vlc_spin_lock (&internals->spin);
484         if (internals->pipes[0] == -1)
485         {
486             internals->pipes[0] = pfd[0];
487             internals->pipes[1] = pfd[1];
488             pfd[0] = pfd[1] = -1;
489         }
490         killed = obj->b_die;
491     }
492     vlc_spin_unlock (&internals->spin);
493
494     if (killed)
495     {
496         /* Race condition: vlc_object_kill() already invoked! */
497         int fd;
498
499         vlc_spin_lock (&internals->spin);
500         fd = internals->pipes[1];
501         internals->pipes[1] = -1;
502         vlc_spin_unlock (&internals->spin);
503
504         msg_Dbg (obj, "waitpipe: object already dying");
505         if (fd != -1)
506             close (fd);
507     }
508
509     /* Race condition: two threads call pipe() - unlikely */
510     if (pfd[0] != -1)
511         close (pfd[0]);
512     if (pfd[1] != -1)
513         close (pfd[1]);
514
515     return internals->pipes[0];
516 }
517
518
519 /**
520  * Waits for the object to be signaled (using vlc_object_signal()).
521  * If the object already has a signal pending, this function will return
522  * immediately. It is asserted that the caller holds the object lock.
523  *
524  * @return true if the object is dying and should terminate.
525  */
526 bool __vlc_object_wait( vlc_object_t *obj )
527 {
528     vlc_assert_locked( &obj->object_lock );
529     vlc_cond_wait( &obj->object_wait, &obj->object_lock );
530     return obj->b_die;
531 }
532
533
534 /**
535  * Waits for the object to be signaled (using vlc_object_signal()), or for
536  * a timer to expire.
537  * If the object already has a signal pending, this function will return
538  * immediately. It is asserted that the caller holds the object lock.
539  *
540  * @return negative if the object is dying and should terminate,
541  * positive if the the object has been signaled but is not dying,
542  * 0 if timeout has been reached.
543  */
544 int __vlc_object_timedwait( vlc_object_t *obj, mtime_t deadline )
545 {
546     int v;
547
548     vlc_assert_locked( &obj->object_lock );
549     v = vlc_cond_timedwait( &obj->object_wait, &obj->object_lock, deadline );
550     if( v == 0 ) /* signaled */
551         return obj->b_die ? -1 : 1;
552     return 0;
553 }
554
555
556 /**
557  * Checks whether an object has been "killed".
558  * The object lock must be held.
559  *
560  * Typical code for an object thread could be:
561  *
562    vlc_object_lock (self);
563    ...initialization...
564    while (vlc_object_alive (self))
565    {
566        ...preprocessing...
567
568        if (vlc_object_wait (self))
569            continue;
570
571        ...postprocessing...
572    }
573    ...deinitialization...
574    vlc_object_unlock (self);
575  *
576  *
577  * @return true iff the object has not been killed yet
578  */
579 bool __vlc_object_alive( vlc_object_t *obj )
580 {
581     vlc_assert_locked( &obj->object_lock );
582     return !obj->b_die;
583 }
584
585
586 /**
587  * Signals an object for which the lock is held.
588  */
589 void __vlc_object_signal_unlocked( vlc_object_t *obj )
590 {
591     vlc_assert_locked (&obj->object_lock);
592     vlc_cond_signal( &obj->object_wait );
593 }
594
595
596 /**
597  * Requests termination of an object.
598  * If the object is LibVLC, also request to terminate all its children.
599  */
600 void __vlc_object_kill( vlc_object_t *p_this )
601 {
602     vlc_object_internals_t *internals = vlc_internals( p_this );
603     int fd;
604
605     vlc_mutex_lock( &p_this->object_lock );
606     p_this->b_die = true;
607
608     vlc_spin_lock (&internals->spin);
609     fd = internals->pipes[1];
610     internals->pipes[1] = -1;
611     vlc_spin_unlock (&internals->spin);
612
613     if( fd != -1 )
614     {
615         msg_Dbg (p_this, "waitpipe: object killed");
616         close (fd);
617     }
618
619     if( p_this->i_object_type == VLC_OBJECT_LIBVLC )
620         for( int i = 0; i < internals->i_children ; i++ )
621             vlc_object_kill( internals->pp_children[i] );
622
623     vlc_object_signal_unlocked( p_this );
624     vlc_mutex_unlock( &p_this->object_lock );
625 }
626
627
628 /**
629  * Find an object given its ID.
630  *
631  * This function looks for the object whose i_object_id field is i_id.
632  * This function is slow, and often used to hide bugs. Do not use it.
633  * If you need to retain reference to an object, yield the object pointer with
634  * vlc_object_yield(), use the pointer as your reference, and call
635  * vlc_object_release() when you're done.
636  */
637 void * vlc_object_get( int i_id )
638 {
639     libvlc_global_data_t *p_libvlc_global = vlc_global();
640     vlc_object_t *obj = NULL;
641
642     vlc_mutex_lock( &structure_lock );
643
644     for( obj = vlc_internals (p_libvlc_global)->next;
645          obj != VLC_OBJECT (p_libvlc_global);
646          obj = vlc_internals (obj)->next )
647     {
648         if( obj->i_object_id == i_id )
649         {
650             vlc_object_yield( obj );
651             goto out;
652         }
653     }
654     obj = NULL;
655
656 out:
657     vlc_mutex_unlock( &structure_lock );
658     return obj;
659 }
660
661 /**
662  ****************************************************************************
663  * find a typed object and increment its refcount
664  *****************************************************************************
665  * This function recursively looks for a given object type. i_mode can be one
666  * of FIND_PARENT, FIND_CHILD or FIND_ANYWHERE.
667  *****************************************************************************/
668 void * __vlc_object_find( vlc_object_t *p_this, int i_type, int i_mode )
669 {
670     vlc_object_t *p_found;
671
672     /* If we are of the requested type ourselves, don't look further */
673     if( !(i_mode & FIND_STRICT) && p_this->i_object_type == i_type )
674     {
675         vlc_object_yield( p_this );
676         return p_this;
677     }
678
679     /* Otherwise, recursively look for the object */
680     if ((i_mode & 0x000f) == FIND_ANYWHERE)
681     {
682 #ifndef NDEBUG
683         if (i_type == VLC_OBJECT_PLAYLIST)
684             msg_Warn (p_this, "using vlc_object_find(VLC_OBJECT_PLAYLIST) "
685                       "instead of pl_Yield()");
686 #endif
687         return vlc_object_find (p_this->p_libvlc, i_type,
688                                 (i_mode & ~0x000f)|FIND_CHILD);
689     }
690
691     vlc_mutex_lock( &structure_lock );
692     p_found = FindObject( p_this, i_type, i_mode );
693     vlc_mutex_unlock( &structure_lock );
694     return p_found;
695 }
696
697 /**
698  ****************************************************************************
699  * find a named object and increment its refcount
700  *****************************************************************************
701  * This function recursively looks for a given object name. i_mode can be one
702  * of FIND_PARENT, FIND_CHILD or FIND_ANYWHERE.
703  *****************************************************************************/
704 void * __vlc_object_find_name( vlc_object_t *p_this, const char *psz_name,
705                                int i_mode )
706 {
707     vlc_object_t *p_found;
708
709     /* If have the requested name ourselves, don't look further */
710     if( !(i_mode & FIND_STRICT)
711         && p_this->psz_object_name
712         && !strcmp( p_this->psz_object_name, psz_name ) )
713     {
714         vlc_object_yield( p_this );
715         return p_this;
716     }
717
718     vlc_mutex_lock( &structure_lock );
719
720     /* Otherwise, recursively look for the object */
721     if( (i_mode & 0x000f) == FIND_ANYWHERE )
722     {
723         vlc_object_t *p_root = p_this;
724
725         /* Find the root */
726         while( p_root->p_parent != NULL &&
727                p_root != VLC_OBJECT( p_this->p_libvlc ) )
728         {
729             p_root = p_root->p_parent;
730         }
731
732         p_found = FindObjectName( p_root, psz_name,
733                                  (i_mode & ~0x000f)|FIND_CHILD );
734         if( p_found == NULL && p_root != VLC_OBJECT( p_this->p_libvlc ) )
735         {
736             p_found = FindObjectName( VLC_OBJECT( p_this->p_libvlc ),
737                                       psz_name, (i_mode & ~0x000f)|FIND_CHILD );
738         }
739     }
740     else
741     {
742         p_found = FindObjectName( p_this, psz_name, i_mode );
743     }
744
745     vlc_mutex_unlock( &structure_lock );
746
747     return p_found;
748 }
749
750 /**
751  * Increment an object reference counter.
752  */
753 void __vlc_object_yield( vlc_object_t *p_this )
754 {
755     vlc_object_internals_t *internals = vlc_internals( p_this );
756
757     vlc_spin_lock( &internals->ref_spin );
758     /* Avoid obvious freed object uses */
759     assert( internals->i_refcount > 0 );
760     /* Increment the counter */
761     internals->i_refcount++;
762     vlc_spin_unlock( &internals->ref_spin );
763 }
764
765 /*****************************************************************************
766  * decrement an object refcount
767  * And destroy the object if its refcount reach zero.
768  *****************************************************************************/
769 void __vlc_object_release( vlc_object_t *p_this )
770 {
771     vlc_object_internals_t *internals = vlc_internals( p_this );
772     bool b_should_destroy;
773
774     vlc_spin_lock( &internals->ref_spin );
775     assert( internals->i_refcount > 0 );
776
777     if( internals->i_refcount > 1 )
778     {
779         /* Fast path */
780         /* There are still other references to the object */
781         internals->i_refcount--;
782         vlc_spin_unlock( &internals->ref_spin );
783         return;
784     }
785     vlc_spin_unlock( &internals->ref_spin );
786
787     /* Slow path */
788     /* Remember that we cannot hold the spin while waiting on the mutex */
789     vlc_mutex_lock( &structure_lock );
790     /* Take the spin again. Note that another thread may have yielded the
791      * object in the (very short) mean time. */
792     vlc_spin_lock( &internals->ref_spin );
793     b_should_destroy = --internals->i_refcount == 0;
794     vlc_spin_unlock( &internals->ref_spin );
795
796     if( b_should_destroy )
797     {
798         /* Remove the object from object list
799          * so that it cannot be encountered by vlc_object_get() */
800         vlc_internals (internals->next)->prev = internals->prev;
801         vlc_internals (internals->prev)->next = internals->next;
802
803         /* Detach from parent to protect against FIND_CHILDREN */
804         vlc_object_detach_unlocked (p_this);
805         /* Detach from children to protect against FIND_PARENT */
806         for (int i = 0; i < internals->i_children; i++)
807             internals->pp_children[i]->p_parent = NULL;
808     }
809
810     vlc_mutex_unlock( &structure_lock );
811
812     if( b_should_destroy )
813     {
814         free( internals->pp_children );
815         internals->pp_children = NULL;
816         internals->i_children = 0;
817         vlc_object_destroy( p_this );
818     }
819 }
820
821 /**
822  ****************************************************************************
823  * attach object to a parent object
824  *****************************************************************************
825  * This function sets p_this as a child of p_parent, and p_parent as a parent
826  * of p_this. This link can be undone using vlc_object_detach.
827  *****************************************************************************/
828 void __vlc_object_attach( vlc_object_t *p_this, vlc_object_t *p_parent )
829 {
830     if( !p_this ) return;
831
832     vlc_mutex_lock( &structure_lock );
833
834     /* Attach the parent to its child */
835     assert (!p_this->p_parent);
836     p_this->p_parent = p_parent;
837
838     /* Attach the child to its parent */
839     vlc_object_internals_t *priv = vlc_internals( p_parent );
840     INSERT_ELEM( priv->pp_children, priv->i_children, priv->i_children,
841                  p_this );
842
843     vlc_mutex_unlock( &structure_lock );
844 }
845
846
847 static void vlc_object_detach_unlocked (vlc_object_t *p_this)
848 {
849     vlc_assert_locked (&structure_lock);
850
851     if (p_this->p_parent == NULL)
852         return;
853
854     vlc_object_internals_t *priv = vlc_internals( p_this->p_parent );
855
856     int i_index, i;
857
858     /* Remove p_this's parent */
859     p_this->p_parent = NULL;
860
861     /* Remove all of p_parent's children which are p_this */
862     for( i_index = priv->i_children ; i_index-- ; )
863     {
864         if( priv->pp_children[i_index] == p_this )
865         {
866             priv->i_children--;
867             for( i = i_index ; i < priv->i_children ; i++ )
868                 priv->pp_children[i] = priv->pp_children[i+1];
869         }
870     }
871
872     if( priv->i_children )
873     {
874         priv->pp_children = (vlc_object_t **)realloc( priv->pp_children,
875                                priv->i_children * sizeof(vlc_object_t *) );
876     }
877     else
878     {
879         /* Special case - don't realloc() to zero to avoid leaking */
880         free( priv->pp_children );
881         priv->pp_children = NULL;
882     }
883 }
884
885
886 /**
887  ****************************************************************************
888  * detach object from its parent
889  *****************************************************************************
890  * This function removes all links between an object and its parent.
891  *****************************************************************************/
892 void __vlc_object_detach( vlc_object_t *p_this )
893 {
894     if( !p_this ) return;
895
896     vlc_mutex_lock( &structure_lock );
897     if( !p_this->p_parent )
898         msg_Err( p_this, "object is not attached" );
899     else
900         vlc_object_detach_unlocked( p_this );
901     vlc_mutex_unlock( &structure_lock );
902 }
903
904
905 /**
906  ****************************************************************************
907  * find a list typed objects and increment their refcount
908  *****************************************************************************
909  * This function recursively looks for a given object type. i_mode can be one
910  * of FIND_PARENT, FIND_CHILD or FIND_ANYWHERE.
911  *****************************************************************************/
912 vlc_list_t * __vlc_list_find( vlc_object_t *p_this, int i_type, int i_mode )
913 {
914     vlc_list_t *p_list;
915     int i_count = 0;
916
917     /* Look for the objects */
918     switch( i_mode & 0x000f )
919     {
920     case FIND_ANYWHERE:
921         /* Modules should probably not be object, and the module should perhaps
922          * not be shared across LibVLC instances. In the mean time, this ugly
923          * hack is brought to you by Courmisch. */
924         if (i_type == VLC_OBJECT_MODULE)
925             return vlc_list_find ((vlc_object_t *)vlc_global ()->p_module_bank,
926                                   i_type, FIND_CHILD);
927         return vlc_list_find (p_this->p_libvlc, i_type, FIND_CHILD);
928
929     case FIND_CHILD:
930         vlc_mutex_lock( &structure_lock );
931         i_count = CountChildren( p_this, i_type );
932         p_list = NewList( i_count );
933
934         /* Check allocation was successful */
935         if( p_list->i_count != i_count )
936         {
937             vlc_mutex_unlock( &structure_lock );
938             msg_Err( p_this, "list allocation failed!" );
939             p_list->i_count = 0;
940             break;
941         }
942
943         p_list->i_count = 0;
944         ListChildren( p_list, p_this, i_type );
945         vlc_mutex_unlock( &structure_lock );
946         break;
947
948     default:
949         msg_Err( p_this, "unimplemented!" );
950         p_list = NewList( 0 );
951         break;
952     }
953
954     return p_list;
955 }
956
957 /**
958  * Gets the list of children of an objects, and increment their reference
959  * count.
960  * @return a list (possibly empty) or NULL in case of error.
961  */
962 vlc_list_t *__vlc_list_children( vlc_object_t *obj )
963 {
964     vlc_list_t *l;
965     vlc_object_internals_t *priv = vlc_internals( obj );
966
967     vlc_mutex_lock( &structure_lock );
968     l = NewList( priv->i_children );
969     for (int i = 0; i < l->i_count; i++)
970     {
971         vlc_object_yield( priv->pp_children[i] );
972         l->p_values[i].p_object = priv->pp_children[i];
973     }
974     vlc_mutex_unlock( &structure_lock );
975     return l;
976 }
977
978 /*****************************************************************************
979  * DumpCommand: print the current vlc structure
980  *****************************************************************************
981  * This function prints either an ASCII tree showing the connections between
982  * vlc objects, and additional information such as their refcount, thread ID,
983  * etc. (command "tree"), or the same data as a simple list (command "list").
984  *****************************************************************************/
985 static int DumpCommand( vlc_object_t *p_this, char const *psz_cmd,
986                         vlc_value_t oldval, vlc_value_t newval, void *p_data )
987 {
988     (void)oldval; (void)p_data;
989     if( *psz_cmd == 'l' )
990     {
991         vlc_object_t *root = VLC_OBJECT (vlc_global ()), *cur = root; 
992
993         vlc_mutex_lock( &structure_lock );
994         do
995         {
996             PrintObject (cur, "");
997             cur = vlc_internals (cur)->next;
998         }
999         while (cur != root);
1000         vlc_mutex_unlock( &structure_lock );
1001     }
1002     else
1003     {
1004         vlc_object_t *p_object = NULL;
1005
1006         if( *newval.psz_string )
1007         {
1008             char *end;
1009             int i_id = strtol( newval.psz_string, &end, 0 );
1010             if( end != newval.psz_string )
1011                 p_object = vlc_object_get( i_id );
1012             else
1013             {
1014                 /* try using the object's name to find it */
1015                 vlc_object_t *p_libvlc = vlc_object_get( 1 );
1016                 if( p_libvlc )
1017                 {
1018                     /* Look in p_libvlc's children tree */
1019                     p_object = vlc_object_find_name( p_libvlc,
1020                                                      newval.psz_string,
1021                                                      FIND_CHILD );
1022                     vlc_object_release( p_libvlc );
1023                 }
1024                 if( !p_object )
1025                 {
1026                     /* If it's not in libvlc, look in libvlc_global (== p_this) */
1027                     p_object = vlc_object_find_name( p_this,
1028                                                      newval.psz_string,
1029                                                      FIND_CHILD );
1030                 }
1031             }
1032
1033             if( !p_object )
1034             {
1035                 return VLC_ENOOBJ;
1036             }
1037         }
1038
1039         vlc_mutex_lock( &structure_lock );
1040
1041         if( *psz_cmd == 't' )
1042         {
1043             char psz_foo[2 * MAX_DUMPSTRUCTURE_DEPTH + 1];
1044
1045             if( !p_object )
1046                 p_object = p_this->p_libvlc ? VLC_OBJECT(p_this->p_libvlc) : p_this;
1047
1048             psz_foo[0] = '|';
1049             DumpStructure( p_object, 0, psz_foo );
1050         }
1051         else if( *psz_cmd == 'v' )
1052         {
1053             int i;
1054
1055             if( !p_object )
1056                 p_object = p_this->p_libvlc ? VLC_OBJECT(p_this->p_libvlc) : p_this;
1057
1058             PrintObject( p_object, "" );
1059
1060             if( !vlc_internals( p_object )->i_vars )
1061                 printf( " `-o No variables\n" );
1062             for( i = 0; i < vlc_internals( p_object )->i_vars; i++ )
1063             {
1064                 variable_t *p_var = vlc_internals( p_object )->p_vars + i;
1065
1066                 const char *psz_type = "unknown";
1067                 switch( p_var->i_type & VLC_VAR_TYPE )
1068                 {
1069 #define MYCASE( type, nice )                \
1070                     case VLC_VAR_ ## type:  \
1071                         psz_type = nice;    \
1072                         break;
1073                     MYCASE( VOID, "void" );
1074                     MYCASE( BOOL, "bool" );
1075                     MYCASE( INTEGER, "integer" );
1076                     MYCASE( HOTKEY, "hotkey" );
1077                     MYCASE( STRING, "string" );
1078                     MYCASE( MODULE, "module" );
1079                     MYCASE( FILE, "file" );
1080                     MYCASE( DIRECTORY, "directory" );
1081                     MYCASE( VARIABLE, "variable" );
1082                     MYCASE( FLOAT, "float" );
1083                     MYCASE( TIME, "time" );
1084                     MYCASE( ADDRESS, "address" );
1085                     MYCASE( MUTEX, "mutex" );
1086                     MYCASE( LIST, "list" );
1087 #undef MYCASE
1088                 }
1089                 printf( " %c-o \"%s\" (%s",
1090                         i + 1 == vlc_internals( p_object )->i_vars ? '`' : '|',
1091                         p_var->psz_name, psz_type );
1092                 if( p_var->psz_text )
1093                     printf( ", %s", p_var->psz_text );
1094                 printf( ")" );
1095                 if( p_var->i_type & VLC_VAR_ISCOMMAND )
1096                     printf( ", command" );
1097                 if( p_var->i_entries )
1098                     printf( ", %d callbacks", p_var->i_entries );
1099                 switch( p_var->i_type & 0x00f0 )
1100                 {
1101                     case VLC_VAR_VOID:
1102                     case VLC_VAR_MUTEX:
1103                         break;
1104                     case VLC_VAR_BOOL:
1105                         printf( ": %s", p_var->val.b_bool ? "true" : "false" );
1106                         break;
1107                     case VLC_VAR_INTEGER:
1108                         printf( ": %d", p_var->val.i_int );
1109                         break;
1110                     case VLC_VAR_STRING:
1111                         printf( ": \"%s\"", p_var->val.psz_string );
1112                         break;
1113                     case VLC_VAR_FLOAT:
1114                         printf( ": %f", p_var->val.f_float );
1115                         break;
1116                     case VLC_VAR_TIME:
1117                         printf( ": %"PRIi64, (int64_t)p_var->val.i_time );
1118                         break;
1119                     case VLC_VAR_ADDRESS:
1120                         printf( ": %p", p_var->val.p_address );
1121                         break;
1122                     case VLC_VAR_LIST:
1123                         printf( ": TODO" );
1124                         break;
1125                 }
1126                 printf( "\n" );
1127             }
1128         }
1129
1130         vlc_mutex_unlock( &structure_lock );
1131
1132         if( *newval.psz_string )
1133         {
1134             vlc_object_release( p_object );
1135         }
1136     }
1137
1138     return VLC_SUCCESS;
1139 }
1140
1141 /*****************************************************************************
1142  * vlc_list_release: free a list previously allocated by vlc_list_find
1143  *****************************************************************************
1144  * This function decreases the refcount of all objects in the list and
1145  * frees the list.
1146  *****************************************************************************/
1147 void vlc_list_release( vlc_list_t *p_list )
1148 {
1149     int i_index;
1150
1151     for( i_index = 0; i_index < p_list->i_count; i_index++ )
1152     {
1153         vlc_object_release( p_list->p_values[i_index].p_object );
1154     }
1155
1156     free( p_list->p_values );
1157     free( p_list );
1158 }
1159
1160 /*****************************************************************************
1161  * dump an object. (Debug function)
1162  *****************************************************************************/
1163 void __vlc_object_dump( vlc_object_t *p_this )
1164 {
1165     vlc_mutex_lock( &structure_lock );
1166     char psz_foo[2 * MAX_DUMPSTRUCTURE_DEPTH + 1];
1167     psz_foo[0] = '|';
1168     DumpStructure( p_this, 0, psz_foo );
1169     vlc_mutex_unlock( &structure_lock );
1170 }
1171
1172 /* Following functions are local */
1173
1174 static vlc_object_t * FindObject( vlc_object_t *p_this, int i_type, int i_mode )
1175 {
1176     int i;
1177     vlc_object_t *p_tmp;
1178
1179     switch( i_mode & 0x000f )
1180     {
1181     case FIND_PARENT:
1182         p_tmp = p_this->p_parent;
1183         if( p_tmp )
1184         {
1185             if( p_tmp->i_object_type == i_type )
1186             {
1187                 vlc_object_yield( p_tmp );
1188                 return p_tmp;
1189             }
1190             else
1191             {
1192                 return FindObject( p_tmp, i_type, i_mode );
1193             }
1194         }
1195         break;
1196
1197     case FIND_CHILD:
1198         for( i = vlc_internals( p_this )->i_children; i--; )
1199         {
1200             p_tmp = vlc_internals( p_this )->pp_children[i];
1201             if( p_tmp->i_object_type == i_type )
1202             {
1203                 vlc_object_yield( p_tmp );
1204                 return p_tmp;
1205             }
1206             else if( vlc_internals( p_tmp )->i_children )
1207             {
1208                 p_tmp = FindObject( p_tmp, i_type, i_mode );
1209                 if( p_tmp )
1210                 {
1211                     return p_tmp;
1212                 }
1213             }
1214         }
1215         break;
1216
1217     case FIND_ANYWHERE:
1218         /* Handled in vlc_object_find */
1219         break;
1220     }
1221
1222     return NULL;
1223 }
1224
1225 static vlc_object_t * FindObjectName( vlc_object_t *p_this,
1226                                       const char *psz_name,
1227                                       int i_mode )
1228 {
1229     int i;
1230     vlc_object_t *p_tmp;
1231
1232     switch( i_mode & 0x000f )
1233     {
1234     case FIND_PARENT:
1235         p_tmp = p_this->p_parent;
1236         if( p_tmp )
1237         {
1238             if( p_tmp->psz_object_name
1239                 && !strcmp( p_tmp->psz_object_name, psz_name ) )
1240             {
1241                 vlc_object_yield( p_tmp );
1242                 return p_tmp;
1243             }
1244             else
1245             {
1246                 return FindObjectName( p_tmp, psz_name, i_mode );
1247             }
1248         }
1249         break;
1250
1251     case FIND_CHILD:
1252         for( i = vlc_internals( p_this )->i_children; i--; )
1253         {
1254             p_tmp = vlc_internals( p_this )->pp_children[i];
1255             if( p_tmp->psz_object_name
1256                 && !strcmp( p_tmp->psz_object_name, psz_name ) )
1257             {
1258                 vlc_object_yield( p_tmp );
1259                 return p_tmp;
1260             }
1261             else if( vlc_internals( p_tmp )->i_children )
1262             {
1263                 p_tmp = FindObjectName( p_tmp, psz_name, i_mode );
1264                 if( p_tmp )
1265                 {
1266                     return p_tmp;
1267                 }
1268             }
1269         }
1270         break;
1271
1272     case FIND_ANYWHERE:
1273         /* Handled in vlc_object_find */
1274         break;
1275     }
1276
1277     return NULL;
1278 }
1279
1280
1281 static void PrintObject( vlc_object_t *p_this, const char *psz_prefix )
1282 {
1283     char psz_children[20], psz_refcount[20], psz_thread[30], psz_name[50],
1284          psz_parent[20];
1285
1286     memset( &psz_name, 0, sizeof(psz_name) );
1287     if( p_this->psz_object_name )
1288     {
1289         snprintf( psz_name, 49, " \"%s\"", p_this->psz_object_name );
1290         if( psz_name[48] )
1291             psz_name[48] = '\"';
1292     }
1293
1294     psz_children[0] = '\0';
1295     switch( vlc_internals( p_this )->i_children )
1296     {
1297         case 0:
1298             break;
1299         case 1:
1300             strcpy( psz_children, ", 1 child" );
1301             break;
1302         default:
1303             snprintf( psz_children, 19, ", %i children",
1304                       vlc_internals( p_this )->i_children );
1305             break;
1306     }
1307
1308     psz_refcount[0] = '\0';
1309     if( vlc_internals( p_this )->i_refcount > 0 )
1310         snprintf( psz_refcount, 19, ", refcount %u",
1311                   vlc_internals( p_this )->i_refcount );
1312
1313     psz_thread[0] = '\0';
1314     if( vlc_internals( p_this )->b_thread )
1315         snprintf( psz_thread, 29, " (thread %lu)",
1316                   (unsigned long)vlc_internals( p_this )->thread_id );
1317
1318     psz_parent[0] = '\0';
1319     if( p_this->p_parent )
1320         snprintf( psz_parent, 19, ", parent %i", p_this->p_parent->i_object_id );
1321
1322     printf( " %so %.8i %s%s%s%s%s%s\n", psz_prefix,
1323             p_this->i_object_id, p_this->psz_object_type,
1324             psz_name, psz_thread, psz_refcount, psz_children,
1325             psz_parent );
1326 }
1327
1328 static void DumpStructure( vlc_object_t *p_this, int i_level, char *psz_foo )
1329 {
1330     int i;
1331     char i_back = psz_foo[i_level];
1332     psz_foo[i_level] = '\0';
1333
1334     PrintObject( p_this, psz_foo );
1335
1336     psz_foo[i_level] = i_back;
1337
1338     if( i_level / 2 >= MAX_DUMPSTRUCTURE_DEPTH )
1339     {
1340         msg_Warn( p_this, "structure tree is too deep" );
1341         return;
1342     }
1343
1344     for( i = 0 ; i < vlc_internals( p_this )->i_children ; i++ )
1345     {
1346         if( i_level )
1347         {
1348             psz_foo[i_level-1] = ' ';
1349
1350             if( psz_foo[i_level-2] == '`' )
1351             {
1352                 psz_foo[i_level-2] = ' ';
1353             }
1354         }
1355
1356         if( i == vlc_internals( p_this )->i_children - 1 )
1357         {
1358             psz_foo[i_level] = '`';
1359         }
1360         else
1361         {
1362             psz_foo[i_level] = '|';
1363         }
1364
1365         psz_foo[i_level+1] = '-';
1366         psz_foo[i_level+2] = '\0';
1367
1368         DumpStructure( vlc_internals( p_this )->pp_children[i], i_level + 2,
1369                        psz_foo );
1370     }
1371 }
1372
1373 static vlc_list_t * NewList( int i_count )
1374 {
1375     vlc_list_t * p_list = (vlc_list_t *)malloc( sizeof( vlc_list_t ) );
1376     if( p_list == NULL )
1377     {
1378         return NULL;
1379     }
1380
1381     p_list->i_count = i_count;
1382
1383     if( i_count == 0 )
1384     {
1385         p_list->p_values = NULL;
1386         return p_list;
1387     }
1388
1389     p_list->p_values = malloc( i_count * sizeof( vlc_value_t ) );
1390     if( p_list->p_values == NULL )
1391     {
1392         p_list->i_count = 0;
1393         return p_list;
1394     }
1395
1396     return p_list;
1397 }
1398
1399 static void ListReplace( vlc_list_t *p_list, vlc_object_t *p_object,
1400                          int i_index )
1401 {
1402     if( p_list == NULL || i_index >= p_list->i_count )
1403     {
1404         return;
1405     }
1406
1407     vlc_object_yield( p_object );
1408
1409     p_list->p_values[i_index].p_object = p_object;
1410
1411     return;
1412 }
1413
1414 /*static void ListAppend( vlc_list_t *p_list, vlc_object_t *p_object )
1415 {
1416     if( p_list == NULL )
1417     {
1418         return;
1419     }
1420
1421     p_list->p_values = realloc( p_list->p_values, (p_list->i_count + 1)
1422                                 * sizeof( vlc_value_t ) );
1423     if( p_list->p_values == NULL )
1424     {
1425         p_list->i_count = 0;
1426         return;
1427     }
1428
1429     vlc_object_yield( p_object );
1430
1431     p_list->p_values[p_list->i_count].p_object = p_object;
1432     p_list->i_count++;
1433
1434     return;
1435 }*/
1436
1437 static int CountChildren( vlc_object_t *p_this, int i_type )
1438 {
1439     vlc_object_t *p_tmp;
1440     int i, i_count = 0;
1441
1442     for( i = 0; i < vlc_internals( p_this )->i_children; i++ )
1443     {
1444         p_tmp = vlc_internals( p_this )->pp_children[i];
1445
1446         if( p_tmp->i_object_type == i_type )
1447         {
1448             i_count++;
1449         }
1450         i_count += CountChildren( p_tmp, i_type );
1451     }
1452
1453     return i_count;
1454 }
1455
1456 static void ListChildren( vlc_list_t *p_list, vlc_object_t *p_this, int i_type )
1457 {
1458     vlc_object_t *p_tmp;
1459     int i;
1460
1461     for( i = 0; i < vlc_internals( p_this )->i_children; i++ )
1462     {
1463         p_tmp = vlc_internals( p_this )->pp_children[i];
1464
1465         if( p_tmp->i_object_type == i_type )
1466             ListReplace( p_list, p_tmp, p_list->i_count++ );
1467
1468         ListChildren( p_list, p_tmp, i_type );
1469     }
1470 }