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