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