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