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