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