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