]> git.sesse.net Git - vlc/blob - src/misc/objects.c
20deed41aa8133bfed5c5a04c182e308aa0e7ac1
[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     if( p_this->p_libvlc == NULL )
311         /* We are the global object ... no need to lock. */
312         vlc_mutex_destroy( &structure_lock );
313
314     FREENULL( p_this->psz_object_name );
315
316 #if defined(WIN32) || defined(UNDER_CE)
317     /* if object has an associated thread, close it now */
318     if( p_priv->thread_id )
319        CloseHandle(p_priv->thread_id);
320 #endif
321
322     vlc_spin_destroy( &p_priv->ref_spin );
323     vlc_mutex_destroy( &p_priv->lock );
324     vlc_cond_destroy( &p_priv->wait );
325     vlc_spin_destroy( &p_priv->spin );
326     if( p_priv->pipes[1] != -1 )
327         close( p_priv->pipes[1] );
328     if( p_priv->pipes[0] != -1 )
329         close( p_priv->pipes[0] );
330
331     free( p_priv );
332 }
333
334
335 /** Inter-object signaling */
336
337 void __vlc_object_lock( vlc_object_t *obj )
338 {
339     vlc_mutex_lock( &(vlc_internals(obj)->lock) );
340 }
341
342 void __vlc_object_unlock( vlc_object_t *obj )
343 {
344     vlc_assert_locked( &(vlc_internals(obj)->lock) );
345     vlc_mutex_unlock( &(vlc_internals(obj)->lock) );
346 }
347
348 #ifdef WIN32
349 # include <winsock2.h>
350 # include <ws2tcpip.h>
351
352 /**
353  * select()-able pipes emulated using Winsock
354  */
355 static int pipe (int fd[2])
356 {
357     SOCKADDR_IN addr;
358     int addrlen = sizeof (addr);
359
360     SOCKET l = socket (PF_INET, SOCK_STREAM, IPPROTO_TCP), a,
361            c = socket (PF_INET, SOCK_STREAM, IPPROTO_TCP);
362     if ((l == INVALID_SOCKET) || (c == INVALID_SOCKET))
363         goto error;
364
365     memset (&addr, 0, sizeof (addr));
366     addr.sin_family = AF_INET;
367     addr.sin_addr.s_addr = htonl (INADDR_LOOPBACK);
368     if (bind (l, (PSOCKADDR)&addr, sizeof (addr))
369      || getsockname (l, (PSOCKADDR)&addr, &addrlen)
370      || listen (l, 1)
371      || connect (c, (PSOCKADDR)&addr, addrlen))
372         goto error;
373
374     a = accept (l, NULL, NULL);
375     if (a == INVALID_SOCKET)
376         goto error;
377
378     closesocket (l);
379     //shutdown (a, 0);
380     //shutdown (c, 1);
381     fd[0] = c;
382     fd[1] = a;
383     return 0;
384
385 error:
386     if (l != INVALID_SOCKET)
387         closesocket (l);
388     if (c != INVALID_SOCKET)
389         closesocket (c);
390     return -1;
391 }
392
393 #undef  read
394 #define read( a, b, c )  recv (a, b, c, 0)
395 #undef  write
396 #define write( a, b, c ) send (a, b, c, 0)
397 #undef  close
398 #define close( a )       closesocket (a)
399 #endif /* WIN32 */
400
401 /**
402  * Returns the readable end of a pipe that becomes readable once termination
403  * of the object is requested (vlc_object_kill()).
404  * This can be used to wake-up out of a select() or poll() event loop, such
405  * typically when doing network I/O.
406  *
407  * Note that the pipe will remain the same for the lifetime of the object.
408  * DO NOT read the pipe nor close it yourself. Ever.
409  *
410  * @param obj object that would be "killed"
411  * @return a readable pipe descriptor, or -1 on error.
412  */
413 int __vlc_object_waitpipe( vlc_object_t *obj )
414 {
415     int pfd[2] = { -1, -1 };
416     vlc_object_internals_t *internals = vlc_internals( obj );
417     bool killed = false;
418
419     vlc_spin_lock (&internals->spin);
420     if (internals->pipes[0] == -1)
421     {
422         /* This can only ever happen if someone killed us without locking: */
423         assert (internals->pipes[1] == -1);
424         vlc_spin_unlock (&internals->spin);
425
426         if (pipe (pfd))
427             return -1;
428
429         vlc_spin_lock (&internals->spin);
430         if (internals->pipes[0] == -1)
431         {
432             internals->pipes[0] = pfd[0];
433             internals->pipes[1] = pfd[1];
434             pfd[0] = pfd[1] = -1;
435         }
436         killed = obj->b_die;
437     }
438     vlc_spin_unlock (&internals->spin);
439
440     if (killed)
441     {
442         /* Race condition: vlc_object_kill() already invoked! */
443         int fd;
444
445         vlc_spin_lock (&internals->spin);
446         fd = internals->pipes[1];
447         internals->pipes[1] = -1;
448         vlc_spin_unlock (&internals->spin);
449
450         msg_Dbg (obj, "waitpipe: object already dying");
451         if (fd != -1)
452             close (fd);
453     }
454
455     /* Race condition: two threads call pipe() - unlikely */
456     if (pfd[0] != -1)
457         close (pfd[0]);
458     if (pfd[1] != -1)
459         close (pfd[1]);
460
461     return internals->pipes[0];
462 }
463
464
465 /**
466  * Waits for the object to be signaled (using vlc_object_signal()).
467  * It is assumed that the caller has locked the object. This function will
468  * unlock the object, and lock it again before returning.
469  * If the object was signaled before the caller locked the object, it is
470  * undefined whether the signal will be lost or will wake the process.
471  *
472  * This function is a cancellation point. In case of cancellation, the object
473  * will be in locked state.
474  *
475  * @return true if the object is dying and should terminate.
476  */
477 void __vlc_object_wait( vlc_object_t *obj )
478 {
479     vlc_object_internals_t *priv = vlc_internals( obj );
480     vlc_assert_locked( &priv->lock);
481     vlc_cond_wait( &priv->wait, &priv->lock );
482 }
483
484
485 /**
486  * Waits for the object to be signaled (using vlc_object_signal()), or for
487  * a timer to expire. It is asserted that the caller holds the object lock.
488  *
489  * This function is a cancellation point. In case of cancellation, the object
490  * will be in locked state.
491  *
492  * @return 0 if the object was signaled before the timer expiration, or
493  * ETIMEDOUT if the timer expired without any signal.
494  */
495 int __vlc_object_timedwait( vlc_object_t *obj, mtime_t deadline )
496 {
497     vlc_object_internals_t *priv = vlc_internals( obj );
498     vlc_assert_locked( &priv->lock);
499     return vlc_cond_timedwait( &priv->wait, &priv->lock, deadline );
500 }
501
502
503 /**
504  * Signals an object for which the lock is held.
505  * At least one thread currently sleeping in vlc_object_wait() or
506  * vlc_object_timedwait() will wake up, assuming that there is at least one
507  * such thread in the first place. Otherwise, it is undefined whether the
508  * signal will be lost or will wake up one or more thread later.
509  */
510 void __vlc_object_signal_unlocked( vlc_object_t *obj )
511 {
512     vlc_assert_locked (&(vlc_internals(obj)->lock));
513     vlc_cond_signal( &(vlc_internals(obj)->wait) );
514 }
515
516
517 /**
518  * Requests termination of an object.
519  * If the object is LibVLC, also request to terminate all its children.
520  */
521 void __vlc_object_kill( vlc_object_t *p_this )
522 {
523     vlc_object_internals_t *priv = vlc_internals( p_this );
524     int fd;
525
526     vlc_thread_cancel( p_this );
527     vlc_object_lock( p_this );
528     p_this->b_die = true;
529
530     vlc_spin_lock (&priv->spin);
531     fd = priv->pipes[1];
532     priv->pipes[1] = -1;
533     vlc_spin_unlock (&priv->spin);
534
535     if( fd != -1 )
536     {
537         msg_Dbg (p_this, "waitpipe: object killed");
538         close_nocancel (fd);
539     }
540
541     vlc_object_signal_unlocked( p_this );
542     /* This also serves as a memory barrier toward vlc_object_alive(): */
543     vlc_object_unlock( p_this );
544 }
545
546
547 /**
548  * Find an object given its ID.
549  *
550  * This function looks for the object whose i_object_id field is i_id.
551  * This function is slow, and often used to hide bugs. Do not use it.
552  * If you need to retain reference to an object, yield the object pointer with
553  * vlc_object_yield(), use the pointer as your reference, and call
554  * vlc_object_release() when you're done.
555  */
556 void * vlc_object_get( libvlc_int_t *p_anchor, int i_id )
557 {
558     vlc_object_t *obj = NULL;
559 #ifndef NDEBUG
560     int canc = vlc_savecancel ();
561     fprintf (stderr, "Use of deprecated vlc_object_get(%d)\n", i_id);
562     vlc_restorecancel (canc);
563 #endif
564     vlc_mutex_lock( &structure_lock );
565
566     for( obj = vlc_internals (p_anchor)->next;
567          obj != VLC_OBJECT (p_anchor);
568          obj = vlc_internals (obj)->next )
569     {
570         if( obj->i_object_id == i_id )
571         {
572             vlc_object_yield( obj );
573             goto out;
574         }
575     }
576     obj = NULL;
577 #ifndef NDEBUG
578     fprintf (stderr, "Object %d does not exist\n", i_id);
579 #endif
580 out:
581     vlc_mutex_unlock( &structure_lock );
582     return obj;
583 }
584
585 /**
586  ****************************************************************************
587  * find a typed object and increment its refcount
588  *****************************************************************************
589  * This function recursively looks for a given object type. i_mode can be one
590  * of FIND_PARENT, FIND_CHILD or FIND_ANYWHERE.
591  *****************************************************************************/
592 void * __vlc_object_find( vlc_object_t *p_this, int i_type, int i_mode )
593 {
594     vlc_object_t *p_found;
595
596     /* If we are of the requested type ourselves, don't look further */
597     if( !(i_mode & FIND_STRICT) && p_this->i_object_type == i_type )
598     {
599         vlc_object_yield( p_this );
600         return p_this;
601     }
602
603     /* Otherwise, recursively look for the object */
604     if ((i_mode & 0x000f) == FIND_ANYWHERE)
605     {
606 #ifndef NDEBUG
607         if (i_type == VLC_OBJECT_PLAYLIST)
608             msg_Err (p_this, "using vlc_object_find(VLC_OBJECT_PLAYLIST) "
609                      "instead of pl_Yield()");
610 #endif
611         return vlc_object_find (p_this->p_libvlc, i_type,
612                                 (i_mode & ~0x000f)|FIND_CHILD);
613     }
614
615     vlc_mutex_lock( &structure_lock );
616     p_found = FindObject( p_this, i_type, i_mode );
617     vlc_mutex_unlock( &structure_lock );
618     return p_found;
619 }
620
621 /**
622  ****************************************************************************
623  * find a named object and increment its refcount
624  *****************************************************************************
625  * This function recursively looks for a given object name. i_mode can be one
626  * of FIND_PARENT, FIND_CHILD or FIND_ANYWHERE.
627  *****************************************************************************/
628 void * __vlc_object_find_name( vlc_object_t *p_this, const char *psz_name,
629                                int i_mode )
630 {
631     vlc_object_t *p_found;
632
633     /* If have the requested name ourselves, don't look further */
634     if( !(i_mode & FIND_STRICT)
635         && p_this->psz_object_name
636         && !strcmp( p_this->psz_object_name, psz_name ) )
637     {
638         vlc_object_yield( p_this );
639         return p_this;
640     }
641
642     vlc_mutex_lock( &structure_lock );
643
644     /* Otherwise, recursively look for the object */
645     if( (i_mode & 0x000f) == FIND_ANYWHERE )
646     {
647         vlc_object_t *p_root = p_this;
648
649         /* Find the root */
650         while( p_root->p_parent != NULL &&
651                p_root != VLC_OBJECT( p_this->p_libvlc ) )
652         {
653             p_root = p_root->p_parent;
654         }
655
656         p_found = FindObjectName( p_root, psz_name,
657                                  (i_mode & ~0x000f)|FIND_CHILD );
658         if( p_found == NULL && p_root != VLC_OBJECT( p_this->p_libvlc ) )
659         {
660             p_found = FindObjectName( VLC_OBJECT( p_this->p_libvlc ),
661                                       psz_name, (i_mode & ~0x000f)|FIND_CHILD );
662         }
663     }
664     else
665     {
666         p_found = FindObjectName( p_this, psz_name, i_mode );
667     }
668
669     vlc_mutex_unlock( &structure_lock );
670
671     return p_found;
672 }
673
674 /**
675  * Increment an object reference counter.
676  */
677 void __vlc_object_yield( vlc_object_t *p_this )
678 {
679     vlc_object_internals_t *internals = vlc_internals( p_this );
680
681     vlc_spin_lock( &internals->ref_spin );
682     /* Avoid obvious freed object uses */
683     assert( internals->i_refcount > 0 );
684     /* Increment the counter */
685     internals->i_refcount++;
686     vlc_spin_unlock( &internals->ref_spin );
687 }
688
689 /*****************************************************************************
690  * Decrement an object refcount
691  * And destroy the object if its refcount reach zero.
692  *****************************************************************************/
693 void __vlc_object_release( vlc_object_t *p_this )
694 {
695     vlc_object_internals_t *internals = vlc_internals( p_this );
696     bool b_should_destroy;
697
698     vlc_spin_lock( &internals->ref_spin );
699     assert( internals->i_refcount > 0 );
700
701     if( internals->i_refcount > 1 )
702     {
703         /* Fast path */
704         /* There are still other references to the object */
705         internals->i_refcount--;
706         vlc_spin_unlock( &internals->ref_spin );
707         return;
708     }
709     vlc_spin_unlock( &internals->ref_spin );
710
711     /* Slow path */
712     /* Remember that we cannot hold the spin while waiting on the mutex */
713     vlc_mutex_lock( &structure_lock );
714     /* Take the spin again. Note that another thread may have yielded the
715      * object in the (very short) mean time. */
716     vlc_spin_lock( &internals->ref_spin );
717     b_should_destroy = --internals->i_refcount == 0;
718     vlc_spin_unlock( &internals->ref_spin );
719
720     if( b_should_destroy )
721     {
722 #ifndef NDEBUG
723         if( VLC_OBJECT(p_this->p_libvlc) == p_this )
724         {
725             /* Test for leaks */
726             vlc_object_t *leaked = internals->next;
727             while( leaked != p_this )
728             {
729                 /* We are leaking this object */
730                 fprintf( stderr,
731                          "ERROR: leaking object (id:%i, type:%s, name:%s)\n",
732                          leaked->i_object_id, leaked->psz_object_type,
733                          leaked->psz_object_name );
734                 /* Dump object to ease debugging */
735                 vlc_object_dump( leaked );
736                 fflush(stderr);
737                 leaked = vlc_internals (leaked)->next;
738             }
739
740             if( internals->next != p_this )
741                 /* Dump libvlc object to ease debugging */
742                 vlc_object_dump( p_this );
743         }
744 #endif
745         /* Remove the object from object list
746          * so that it cannot be encountered by vlc_object_get() */
747         vlc_internals (internals->next)->prev = internals->prev;
748         vlc_internals (internals->prev)->next = internals->next;
749
750         /* Detach from parent to protect against FIND_CHILDREN */
751         vlc_object_detach_unlocked (p_this);
752         /* Detach from children to protect against FIND_PARENT */
753         for (int i = 0; i < internals->i_children; i++)
754             internals->pp_children[i]->p_parent = NULL;
755     }
756
757     vlc_mutex_unlock( &structure_lock );
758
759     if( b_should_destroy )
760     {
761         int canc;
762
763         free( internals->pp_children );
764         internals->pp_children = NULL;
765         internals->i_children = 0;
766         canc = vlc_savecancel ();
767         vlc_object_destroy( p_this );
768         vlc_restorecancel (canc);
769     }
770 }
771
772 /**
773  ****************************************************************************
774  * attach object to a parent object
775  *****************************************************************************
776  * This function sets p_this as a child of p_parent, and p_parent as a parent
777  * of p_this. This link can be undone using vlc_object_detach.
778  *****************************************************************************/
779 void __vlc_object_attach( vlc_object_t *p_this, vlc_object_t *p_parent )
780 {
781     if( !p_this ) return;
782
783     vlc_mutex_lock( &structure_lock );
784
785     /* Attach the parent to its child */
786     assert (!p_this->p_parent);
787     p_this->p_parent = p_parent;
788
789     /* Attach the child to its parent */
790     vlc_object_internals_t *priv = vlc_internals( p_parent );
791     INSERT_ELEM( priv->pp_children, priv->i_children, priv->i_children,
792                  p_this );
793
794     vlc_mutex_unlock( &structure_lock );
795 }
796
797
798 static void vlc_object_detach_unlocked (vlc_object_t *p_this)
799 {
800     vlc_assert_locked (&structure_lock);
801
802     if (p_this->p_parent == NULL)
803         return;
804
805     vlc_object_internals_t *priv = vlc_internals( p_this->p_parent );
806
807     int i_index, i;
808
809     /* Remove p_this's parent */
810     p_this->p_parent = NULL;
811
812     /* Remove all of p_parent's children which are p_this */
813     for( i_index = priv->i_children ; i_index-- ; )
814     {
815         if( priv->pp_children[i_index] == p_this )
816         {
817             priv->i_children--;
818             for( i = i_index ; i < priv->i_children ; i++ )
819                 priv->pp_children[i] = priv->pp_children[i+1];
820         }
821     }
822
823     if( priv->i_children )
824     {
825         priv->pp_children = (vlc_object_t **)realloc( priv->pp_children,
826                                priv->i_children * sizeof(vlc_object_t *) );
827     }
828     else
829     {
830         /* Special case - don't realloc() to zero to avoid leaking */
831         free( priv->pp_children );
832         priv->pp_children = NULL;
833     }
834 }
835
836
837 /**
838  ****************************************************************************
839  * detach object from its parent
840  *****************************************************************************
841  * This function removes all links between an object and its parent.
842  *****************************************************************************/
843 void __vlc_object_detach( vlc_object_t *p_this )
844 {
845     if( !p_this ) return;
846
847     vlc_mutex_lock( &structure_lock );
848     if( !p_this->p_parent )
849         msg_Err( p_this, "object is not attached" );
850     else
851         vlc_object_detach_unlocked( p_this );
852     vlc_mutex_unlock( &structure_lock );
853 }
854
855
856 /**
857  ****************************************************************************
858  * find a list typed objects and increment their refcount
859  *****************************************************************************
860  * This function recursively looks for a given object type. i_mode can be one
861  * of FIND_PARENT, FIND_CHILD or FIND_ANYWHERE.
862  *****************************************************************************/
863 vlc_list_t * __vlc_list_find( vlc_object_t *p_this, int i_type, int i_mode )
864 {
865     vlc_list_t *p_list;
866     int i_count = 0;
867
868     /* Look for the objects */
869     switch( i_mode & 0x000f )
870     {
871     case FIND_ANYWHERE:
872         /* Modules should probably not be object, and the module should perhaps
873          * not be shared across LibVLC instances. In the mean time, this ugly
874          * hack is brought to you by Courmisch. */
875         if (i_type == VLC_OBJECT_MODULE)
876             return vlc_list_find ((vlc_object_t *)p_module_bank,
877                                   i_type, FIND_CHILD);
878         return vlc_list_find (p_this->p_libvlc, i_type, FIND_CHILD);
879
880     case FIND_CHILD:
881         vlc_mutex_lock( &structure_lock );
882         i_count = CountChildren( p_this, i_type );
883         p_list = NewList( i_count );
884
885         /* Check allocation was successful */
886         if( p_list->i_count != i_count )
887         {
888             vlc_mutex_unlock( &structure_lock );
889             msg_Err( p_this, "list allocation failed!" );
890             p_list->i_count = 0;
891             break;
892         }
893
894         p_list->i_count = 0;
895         ListChildren( p_list, p_this, i_type );
896         vlc_mutex_unlock( &structure_lock );
897         break;
898
899     default:
900         msg_Err( p_this, "unimplemented!" );
901         p_list = NewList( 0 );
902         break;
903     }
904
905     return p_list;
906 }
907
908 /**
909  * Gets the list of children of an objects, and increment their reference
910  * count.
911  * @return a list (possibly empty) or NULL in case of error.
912  */
913 vlc_list_t *__vlc_list_children( vlc_object_t *obj )
914 {
915     vlc_list_t *l;
916     vlc_object_internals_t *priv = vlc_internals( obj );
917
918     vlc_mutex_lock( &structure_lock );
919     l = NewList( priv->i_children );
920     for (int i = 0; i < l->i_count; i++)
921     {
922         vlc_object_yield( priv->pp_children[i] );
923         l->p_values[i].p_object = priv->pp_children[i];
924     }
925     vlc_mutex_unlock( &structure_lock );
926     return l;
927 }
928
929 /*****************************************************************************
930  * DumpCommand: print the current vlc structure
931  *****************************************************************************
932  * This function prints either an ASCII tree showing the connections between
933  * vlc objects, and additional information such as their refcount, thread ID,
934  * etc. (command "tree"), or the same data as a simple list (command "list").
935  *****************************************************************************/
936 static int DumpCommand( vlc_object_t *p_this, char const *psz_cmd,
937                         vlc_value_t oldval, vlc_value_t newval, void *p_data )
938 {
939     libvlc_int_t *p_libvlc = p_this->p_libvlc;
940
941     (void)oldval; (void)p_data;
942     if( *psz_cmd == 'l' )
943     {
944         vlc_object_t *cur = VLC_OBJECT (p_libvlc);
945
946         vlc_mutex_lock( &structure_lock );
947         do
948         {
949             PrintObject (cur, "");
950             cur = vlc_internals (cur)->next;
951         }
952         while (cur != VLC_OBJECT(p_libvlc));
953         vlc_mutex_unlock( &structure_lock );
954     }
955     else
956     {
957         vlc_object_t *p_object = NULL;
958
959         if( *newval.psz_string )
960         {
961             char *end;
962             int i_id = strtol( newval.psz_string, &end, 0 );
963             if( !*end )
964                 p_object = vlc_object_get( p_libvlc, i_id );
965             else
966                 /* try using the object's name to find it */
967                 p_object = vlc_object_find_name( p_this, newval.psz_string,
968                                                  FIND_ANYWHERE );
969
970             if( !p_object )
971             {
972                 return VLC_ENOOBJ;
973             }
974         }
975
976         vlc_mutex_lock( &structure_lock );
977
978         if( *psz_cmd == 't' )
979         {
980             char psz_foo[2 * MAX_DUMPSTRUCTURE_DEPTH + 1];
981
982             if( !p_object )
983                 p_object = VLC_OBJECT(p_this->p_libvlc);
984
985             psz_foo[0] = '|';
986             DumpStructure( p_object, 0, psz_foo );
987         }
988         else if( *psz_cmd == 'v' )
989         {
990             int i;
991
992             if( !p_object )
993                 p_object = p_this->p_libvlc ? VLC_OBJECT(p_this->p_libvlc) : p_this;
994
995             PrintObject( p_object, "" );
996
997             if( !vlc_internals( p_object )->i_vars )
998                 printf( " `-o No variables\n" );
999             for( i = 0; i < vlc_internals( p_object )->i_vars; i++ )
1000             {
1001                 variable_t *p_var = vlc_internals( p_object )->p_vars + i;
1002
1003                 const char *psz_type = "unknown";
1004                 switch( p_var->i_type & VLC_VAR_TYPE )
1005                 {
1006 #define MYCASE( type, nice )                \
1007                     case VLC_VAR_ ## type:  \
1008                         psz_type = nice;    \
1009                         break;
1010                     MYCASE( VOID, "void" );
1011                     MYCASE( BOOL, "bool" );
1012                     MYCASE( INTEGER, "integer" );
1013                     MYCASE( HOTKEY, "hotkey" );
1014                     MYCASE( STRING, "string" );
1015                     MYCASE( MODULE, "module" );
1016                     MYCASE( FILE, "file" );
1017                     MYCASE( DIRECTORY, "directory" );
1018                     MYCASE( VARIABLE, "variable" );
1019                     MYCASE( FLOAT, "float" );
1020                     MYCASE( TIME, "time" );
1021                     MYCASE( ADDRESS, "address" );
1022                     MYCASE( MUTEX, "mutex" );
1023                     MYCASE( LIST, "list" );
1024 #undef MYCASE
1025                 }
1026                 printf( " %c-o \"%s\" (%s",
1027                         i + 1 == vlc_internals( p_object )->i_vars ? '`' : '|',
1028                         p_var->psz_name, psz_type );
1029                 if( p_var->psz_text )
1030                     printf( ", %s", p_var->psz_text );
1031                 printf( ")" );
1032                 if( p_var->i_type & VLC_VAR_HASCHOICE )
1033                     printf( ", has choices" );
1034                 if( p_var->i_type & VLC_VAR_ISCOMMAND )
1035                     printf( ", command" );
1036                 if( p_var->i_entries )
1037                     printf( ", %d callbacks", p_var->i_entries );
1038                 switch( p_var->i_type & 0x00f0 )
1039                 {
1040                     case VLC_VAR_VOID:
1041                     case VLC_VAR_MUTEX:
1042                         break;
1043                     case VLC_VAR_BOOL:
1044                         printf( ": %s", p_var->val.b_bool ? "true" : "false" );
1045                         break;
1046                     case VLC_VAR_INTEGER:
1047                         printf( ": %d", p_var->val.i_int );
1048                         break;
1049                     case VLC_VAR_STRING:
1050                         printf( ": \"%s\"", p_var->val.psz_string );
1051                         break;
1052                     case VLC_VAR_FLOAT:
1053                         printf( ": %f", p_var->val.f_float );
1054                         break;
1055                     case VLC_VAR_TIME:
1056                         printf( ": %"PRIi64, (int64_t)p_var->val.i_time );
1057                         break;
1058                     case VLC_VAR_ADDRESS:
1059                         printf( ": %p", p_var->val.p_address );
1060                         break;
1061                     case VLC_VAR_LIST:
1062                         printf( ": TODO" );
1063                         break;
1064                 }
1065                 printf( "\n" );
1066             }
1067         }
1068
1069         vlc_mutex_unlock( &structure_lock );
1070
1071         if( *newval.psz_string )
1072         {
1073             vlc_object_release( p_object );
1074         }
1075     }
1076
1077     return VLC_SUCCESS;
1078 }
1079
1080 /*****************************************************************************
1081  * vlc_list_release: free a list previously allocated by vlc_list_find
1082  *****************************************************************************
1083  * This function decreases the refcount of all objects in the list and
1084  * frees the list.
1085  *****************************************************************************/
1086 void vlc_list_release( vlc_list_t *p_list )
1087 {
1088     int i_index;
1089
1090     for( i_index = 0; i_index < p_list->i_count; i_index++ )
1091     {
1092         vlc_object_release( p_list->p_values[i_index].p_object );
1093     }
1094
1095     free( p_list->p_values );
1096     free( p_list );
1097 }
1098
1099 /*****************************************************************************
1100  * dump an object. (Debug function)
1101  *****************************************************************************/
1102 void __vlc_object_dump( vlc_object_t *p_this )
1103 {
1104     char psz_foo[2 * MAX_DUMPSTRUCTURE_DEPTH + 1];
1105     psz_foo[0] = '|';
1106
1107     vlc_assert_locked( &structure_lock );
1108     DumpStructure( p_this, 0, psz_foo );
1109 }
1110
1111 /* Following functions are local */
1112
1113 static vlc_object_t * FindObject( vlc_object_t *p_this, int i_type, int i_mode )
1114 {
1115     int i;
1116     vlc_object_t *p_tmp;
1117
1118     switch( i_mode & 0x000f )
1119     {
1120     case FIND_PARENT:
1121         p_tmp = p_this->p_parent;
1122         if( p_tmp )
1123         {
1124             if( p_tmp->i_object_type == i_type )
1125             {
1126                 vlc_object_yield( p_tmp );
1127                 return p_tmp;
1128             }
1129             else
1130             {
1131                 return FindObject( p_tmp, i_type, i_mode );
1132             }
1133         }
1134         break;
1135
1136     case FIND_CHILD:
1137         for( i = vlc_internals( p_this )->i_children; i--; )
1138         {
1139             p_tmp = vlc_internals( p_this )->pp_children[i];
1140             if( p_tmp->i_object_type == i_type )
1141             {
1142                 vlc_object_yield( p_tmp );
1143                 return p_tmp;
1144             }
1145             else if( vlc_internals( p_tmp )->i_children )
1146             {
1147                 p_tmp = FindObject( p_tmp, i_type, i_mode );
1148                 if( p_tmp )
1149                 {
1150                     return p_tmp;
1151                 }
1152             }
1153         }
1154         break;
1155
1156     case FIND_ANYWHERE:
1157         /* Handled in vlc_object_find */
1158         break;
1159     }
1160
1161     return NULL;
1162 }
1163
1164 static vlc_object_t * FindObjectName( vlc_object_t *p_this,
1165                                       const char *psz_name,
1166                                       int i_mode )
1167 {
1168     int i;
1169     vlc_object_t *p_tmp;
1170
1171     switch( i_mode & 0x000f )
1172     {
1173     case FIND_PARENT:
1174         p_tmp = p_this->p_parent;
1175         if( p_tmp )
1176         {
1177             if( p_tmp->psz_object_name
1178                 && !strcmp( p_tmp->psz_object_name, psz_name ) )
1179             {
1180                 vlc_object_yield( p_tmp );
1181                 return p_tmp;
1182             }
1183             else
1184             {
1185                 return FindObjectName( p_tmp, psz_name, i_mode );
1186             }
1187         }
1188         break;
1189
1190     case FIND_CHILD:
1191         for( i = vlc_internals( p_this )->i_children; i--; )
1192         {
1193             p_tmp = vlc_internals( p_this )->pp_children[i];
1194             if( p_tmp->psz_object_name
1195                 && !strcmp( p_tmp->psz_object_name, psz_name ) )
1196             {
1197                 vlc_object_yield( p_tmp );
1198                 return p_tmp;
1199             }
1200             else if( vlc_internals( p_tmp )->i_children )
1201             {
1202                 p_tmp = FindObjectName( p_tmp, psz_name, i_mode );
1203                 if( p_tmp )
1204                 {
1205                     return p_tmp;
1206                 }
1207             }
1208         }
1209         break;
1210
1211     case FIND_ANYWHERE:
1212         /* Handled in vlc_object_find */
1213         break;
1214     }
1215
1216     return NULL;
1217 }
1218
1219
1220 static void PrintObject( vlc_object_t *p_this, const char *psz_prefix )
1221 {
1222     char psz_children[20], psz_refcount[20], psz_thread[30], psz_name[50],
1223          psz_parent[20];
1224
1225     int canc = vlc_savecancel ();
1226     memset( &psz_name, 0, sizeof(psz_name) );
1227     if( p_this->psz_object_name )
1228     {
1229         snprintf( psz_name, 49, " \"%s\"", p_this->psz_object_name );
1230         if( psz_name[48] )
1231             psz_name[48] = '\"';
1232     }
1233
1234     psz_children[0] = '\0';
1235     switch( vlc_internals( p_this )->i_children )
1236     {
1237         case 0:
1238             break;
1239         case 1:
1240             strcpy( psz_children, ", 1 child" );
1241             break;
1242         default:
1243             snprintf( psz_children, 19, ", %i children",
1244                       vlc_internals( p_this )->i_children );
1245             break;
1246     }
1247
1248     psz_refcount[0] = '\0';
1249     if( vlc_internals( p_this )->i_refcount > 0 )
1250         snprintf( psz_refcount, 19, ", refcount %u",
1251                   vlc_internals( p_this )->i_refcount );
1252
1253     psz_thread[0] = '\0';
1254     if( vlc_internals( p_this )->b_thread )
1255         snprintf( psz_thread, 29, " (thread %lu)",
1256                   (unsigned long)vlc_internals( p_this )->thread_id );
1257
1258     psz_parent[0] = '\0';
1259     if( p_this->p_parent )
1260         snprintf( psz_parent, 19, ", parent %i", p_this->p_parent->i_object_id );
1261
1262     printf( " %so %.8i %s%s%s%s%s%s\n", psz_prefix,
1263             p_this->i_object_id, p_this->psz_object_type,
1264             psz_name, psz_thread, psz_refcount, psz_children,
1265             psz_parent );
1266     vlc_restorecancel (canc);
1267 }
1268
1269 static void DumpStructure( vlc_object_t *p_this, int i_level, char *psz_foo )
1270 {
1271     int i;
1272     char i_back = psz_foo[i_level];
1273     psz_foo[i_level] = '\0';
1274
1275     PrintObject( p_this, psz_foo );
1276
1277     psz_foo[i_level] = i_back;
1278
1279     if( i_level / 2 >= MAX_DUMPSTRUCTURE_DEPTH )
1280     {
1281         msg_Warn( p_this, "structure tree is too deep" );
1282         return;
1283     }
1284
1285     for( i = 0 ; i < vlc_internals( p_this )->i_children ; i++ )
1286     {
1287         if( i_level )
1288         {
1289             psz_foo[i_level-1] = ' ';
1290
1291             if( psz_foo[i_level-2] == '`' )
1292             {
1293                 psz_foo[i_level-2] = ' ';
1294             }
1295         }
1296
1297         if( i == vlc_internals( p_this )->i_children - 1 )
1298         {
1299             psz_foo[i_level] = '`';
1300         }
1301         else
1302         {
1303             psz_foo[i_level] = '|';
1304         }
1305
1306         psz_foo[i_level+1] = '-';
1307         psz_foo[i_level+2] = '\0';
1308
1309         DumpStructure( vlc_internals( p_this )->pp_children[i], i_level + 2,
1310                        psz_foo );
1311     }
1312 }
1313
1314 static vlc_list_t * NewList( int i_count )
1315 {
1316     vlc_list_t * p_list = (vlc_list_t *)malloc( sizeof( vlc_list_t ) );
1317     if( p_list == NULL )
1318     {
1319         return NULL;
1320     }
1321
1322     p_list->i_count = i_count;
1323
1324     if( i_count == 0 )
1325     {
1326         p_list->p_values = NULL;
1327         return p_list;
1328     }
1329
1330     p_list->p_values = malloc( i_count * sizeof( vlc_value_t ) );
1331     if( p_list->p_values == NULL )
1332     {
1333         p_list->i_count = 0;
1334         return p_list;
1335     }
1336
1337     return p_list;
1338 }
1339
1340 static void ListReplace( vlc_list_t *p_list, vlc_object_t *p_object,
1341                          int i_index )
1342 {
1343     if( p_list == NULL || i_index >= p_list->i_count )
1344     {
1345         return;
1346     }
1347
1348     vlc_object_yield( p_object );
1349
1350     p_list->p_values[i_index].p_object = p_object;
1351
1352     return;
1353 }
1354
1355 /*static void ListAppend( vlc_list_t *p_list, vlc_object_t *p_object )
1356 {
1357     if( p_list == NULL )
1358     {
1359         return;
1360     }
1361
1362     p_list->p_values = realloc( p_list->p_values, (p_list->i_count + 1)
1363                                 * sizeof( vlc_value_t ) );
1364     if( p_list->p_values == NULL )
1365     {
1366         p_list->i_count = 0;
1367         return;
1368     }
1369
1370     vlc_object_yield( p_object );
1371
1372     p_list->p_values[p_list->i_count].p_object = p_object;
1373     p_list->i_count++;
1374
1375     return;
1376 }*/
1377
1378 static int CountChildren( vlc_object_t *p_this, int i_type )
1379 {
1380     vlc_object_t *p_tmp;
1381     int i, i_count = 0;
1382
1383     for( i = 0; i < vlc_internals( p_this )->i_children; i++ )
1384     {
1385         p_tmp = vlc_internals( p_this )->pp_children[i];
1386
1387         if( p_tmp->i_object_type == i_type )
1388         {
1389             i_count++;
1390         }
1391         i_count += CountChildren( p_tmp, i_type );
1392     }
1393
1394     return i_count;
1395 }
1396
1397 static void ListChildren( vlc_list_t *p_list, vlc_object_t *p_this, int i_type )
1398 {
1399     vlc_object_t *p_tmp;
1400     int i;
1401
1402     for( i = 0; i < vlc_internals( p_this )->i_children; i++ )
1403     {
1404         p_tmp = vlc_internals( p_this )->pp_children[i];
1405
1406         if( p_tmp->i_object_type == i_type )
1407             ListReplace( p_list, p_tmp, p_list->i_count++ );
1408
1409         ListChildren( p_list, p_tmp, i_type );
1410     }
1411 }