]> git.sesse.net Git - vlc/blob - src/misc/objects.c
77abc036fff2f7724622e2da93486007d40c9d8e
[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( int i_id )
590 {
591     libvlc_global_data_t *p_libvlc_global = vlc_global();
592     vlc_object_t *obj = NULL;
593 #ifndef NDEBUG
594     int canc = vlc_savecancel ();
595     fprintf (stderr, "Use of deprecated vlc_object_get(%d)\n", i_id);
596     vlc_restorecancel (canc);
597 #endif
598     vlc_mutex_lock( &structure_lock );
599
600     for( obj = vlc_internals (p_libvlc_global)->next;
601          obj != VLC_OBJECT (p_libvlc_global);
602          obj = vlc_internals (obj)->next )
603     {
604         if( obj->i_object_id == i_id )
605         {
606             vlc_object_yield( obj );
607             goto out;
608         }
609     }
610     obj = NULL;
611 #ifndef NDEBUG
612     fprintf (stderr, "Object %d does not exist\n", i_id);
613 #endif
614 out:
615     vlc_mutex_unlock( &structure_lock );
616     return obj;
617 }
618
619 /**
620  ****************************************************************************
621  * find a typed object and increment its refcount
622  *****************************************************************************
623  * This function recursively looks for a given object type. i_mode can be one
624  * of FIND_PARENT, FIND_CHILD or FIND_ANYWHERE.
625  *****************************************************************************/
626 void * __vlc_object_find( vlc_object_t *p_this, int i_type, int i_mode )
627 {
628     vlc_object_t *p_found;
629
630     /* If we are of the requested type ourselves, don't look further */
631     if( !(i_mode & FIND_STRICT) && p_this->i_object_type == i_type )
632     {
633         vlc_object_yield( p_this );
634         return p_this;
635     }
636
637     /* Otherwise, recursively look for the object */
638     if ((i_mode & 0x000f) == FIND_ANYWHERE)
639     {
640 #ifndef NDEBUG
641         if (i_type == VLC_OBJECT_PLAYLIST)
642             msg_Err (p_this, "using vlc_object_find(VLC_OBJECT_PLAYLIST) "
643                      "instead of pl_Yield()");
644 #endif
645         return vlc_object_find (p_this->p_libvlc, i_type,
646                                 (i_mode & ~0x000f)|FIND_CHILD);
647     }
648
649     vlc_mutex_lock( &structure_lock );
650     p_found = FindObject( p_this, i_type, i_mode );
651     vlc_mutex_unlock( &structure_lock );
652     return p_found;
653 }
654
655 /**
656  ****************************************************************************
657  * find a named object and increment its refcount
658  *****************************************************************************
659  * This function recursively looks for a given object name. i_mode can be one
660  * of FIND_PARENT, FIND_CHILD or FIND_ANYWHERE.
661  *****************************************************************************/
662 void * __vlc_object_find_name( vlc_object_t *p_this, const char *psz_name,
663                                int i_mode )
664 {
665     vlc_object_t *p_found;
666
667     /* If have the requested name ourselves, don't look further */
668     if( !(i_mode & FIND_STRICT)
669         && p_this->psz_object_name
670         && !strcmp( p_this->psz_object_name, psz_name ) )
671     {
672         vlc_object_yield( p_this );
673         return p_this;
674     }
675
676     vlc_mutex_lock( &structure_lock );
677
678     /* Otherwise, recursively look for the object */
679     if( (i_mode & 0x000f) == FIND_ANYWHERE )
680     {
681         vlc_object_t *p_root = p_this;
682
683         /* Find the root */
684         while( p_root->p_parent != NULL &&
685                p_root != VLC_OBJECT( p_this->p_libvlc ) )
686         {
687             p_root = p_root->p_parent;
688         }
689
690         p_found = FindObjectName( p_root, psz_name,
691                                  (i_mode & ~0x000f)|FIND_CHILD );
692         if( p_found == NULL && p_root != VLC_OBJECT( p_this->p_libvlc ) )
693         {
694             p_found = FindObjectName( VLC_OBJECT( p_this->p_libvlc ),
695                                       psz_name, (i_mode & ~0x000f)|FIND_CHILD );
696         }
697     }
698     else
699     {
700         p_found = FindObjectName( p_this, psz_name, i_mode );
701     }
702
703     vlc_mutex_unlock( &structure_lock );
704
705     return p_found;
706 }
707
708 /**
709  * Increment an object reference counter.
710  */
711 void __vlc_object_yield( vlc_object_t *p_this )
712 {
713     vlc_object_internals_t *internals = vlc_internals( p_this );
714
715     vlc_spin_lock( &internals->ref_spin );
716     /* Avoid obvious freed object uses */
717     assert( internals->i_refcount > 0 );
718     /* Increment the counter */
719     internals->i_refcount++;
720     vlc_spin_unlock( &internals->ref_spin );
721 }
722
723 /*****************************************************************************
724  * Decrement an object refcount
725  * And destroy the object if its refcount reach zero.
726  *****************************************************************************/
727 void __vlc_object_release( vlc_object_t *p_this )
728 {
729     vlc_object_internals_t *internals = vlc_internals( p_this );
730     bool b_should_destroy;
731
732     vlc_spin_lock( &internals->ref_spin );
733     assert( internals->i_refcount > 0 );
734
735     if( internals->i_refcount > 1 )
736     {
737         /* Fast path */
738         /* There are still other references to the object */
739         internals->i_refcount--;
740         vlc_spin_unlock( &internals->ref_spin );
741         return;
742     }
743     vlc_spin_unlock( &internals->ref_spin );
744
745     /* Slow path */
746     /* Remember that we cannot hold the spin while waiting on the mutex */
747     vlc_mutex_lock( &structure_lock );
748     /* Take the spin again. Note that another thread may have yielded the
749      * object in the (very short) mean time. */
750     vlc_spin_lock( &internals->ref_spin );
751     b_should_destroy = --internals->i_refcount == 0;
752     vlc_spin_unlock( &internals->ref_spin );
753
754     if( b_should_destroy )
755     {
756         /* Remove the object from object list
757          * so that it cannot be encountered by vlc_object_get() */
758         vlc_internals (internals->next)->prev = internals->prev;
759         vlc_internals (internals->prev)->next = internals->next;
760
761         /* Detach from parent to protect against FIND_CHILDREN */
762         vlc_object_detach_unlocked (p_this);
763         /* Detach from children to protect against FIND_PARENT */
764         for (int i = 0; i < internals->i_children; i++)
765             internals->pp_children[i]->p_parent = NULL;
766     }
767
768     vlc_mutex_unlock( &structure_lock );
769
770     if( b_should_destroy )
771     {
772         int canc;
773
774         free( internals->pp_children );
775         internals->pp_children = NULL;
776         internals->i_children = 0;
777         canc = vlc_savecancel ();
778         vlc_object_destroy( p_this );
779         vlc_restorecancel (canc);
780     }
781 }
782
783 /**
784  ****************************************************************************
785  * attach object to a parent object
786  *****************************************************************************
787  * This function sets p_this as a child of p_parent, and p_parent as a parent
788  * of p_this. This link can be undone using vlc_object_detach.
789  *****************************************************************************/
790 void __vlc_object_attach( vlc_object_t *p_this, vlc_object_t *p_parent )
791 {
792     if( !p_this ) return;
793
794     vlc_mutex_lock( &structure_lock );
795
796     /* Attach the parent to its child */
797     assert (!p_this->p_parent);
798     p_this->p_parent = p_parent;
799
800     /* Attach the child to its parent */
801     vlc_object_internals_t *priv = vlc_internals( p_parent );
802     INSERT_ELEM( priv->pp_children, priv->i_children, priv->i_children,
803                  p_this );
804
805     vlc_mutex_unlock( &structure_lock );
806 }
807
808
809 static void vlc_object_detach_unlocked (vlc_object_t *p_this)
810 {
811     vlc_assert_locked (&structure_lock);
812
813     if (p_this->p_parent == NULL)
814         return;
815
816     vlc_object_internals_t *priv = vlc_internals( p_this->p_parent );
817
818     int i_index, i;
819
820     /* Remove p_this's parent */
821     p_this->p_parent = NULL;
822
823     /* Remove all of p_parent's children which are p_this */
824     for( i_index = priv->i_children ; i_index-- ; )
825     {
826         if( priv->pp_children[i_index] == p_this )
827         {
828             priv->i_children--;
829             for( i = i_index ; i < priv->i_children ; i++ )
830                 priv->pp_children[i] = priv->pp_children[i+1];
831         }
832     }
833
834     if( priv->i_children )
835     {
836         priv->pp_children = (vlc_object_t **)realloc( priv->pp_children,
837                                priv->i_children * sizeof(vlc_object_t *) );
838     }
839     else
840     {
841         /* Special case - don't realloc() to zero to avoid leaking */
842         free( priv->pp_children );
843         priv->pp_children = NULL;
844     }
845 }
846
847
848 /**
849  ****************************************************************************
850  * detach object from its parent
851  *****************************************************************************
852  * This function removes all links between an object and its parent.
853  *****************************************************************************/
854 void __vlc_object_detach( vlc_object_t *p_this )
855 {
856     if( !p_this ) return;
857
858     vlc_mutex_lock( &structure_lock );
859     if( !p_this->p_parent )
860         msg_Err( p_this, "object is not attached" );
861     else
862         vlc_object_detach_unlocked( p_this );
863     vlc_mutex_unlock( &structure_lock );
864 }
865
866
867 /**
868  ****************************************************************************
869  * find a list typed objects and increment their refcount
870  *****************************************************************************
871  * This function recursively looks for a given object type. i_mode can be one
872  * of FIND_PARENT, FIND_CHILD or FIND_ANYWHERE.
873  *****************************************************************************/
874 vlc_list_t * __vlc_list_find( vlc_object_t *p_this, int i_type, int i_mode )
875 {
876     vlc_list_t *p_list;
877     int i_count = 0;
878
879     /* Look for the objects */
880     switch( i_mode & 0x000f )
881     {
882     case FIND_ANYWHERE:
883         /* Modules should probably not be object, and the module should perhaps
884          * not be shared across LibVLC instances. In the mean time, this ugly
885          * hack is brought to you by Courmisch. */
886         if (i_type == VLC_OBJECT_MODULE)
887             return vlc_list_find ((vlc_object_t *)vlc_global ()->p_module_bank,
888                                   i_type, FIND_CHILD);
889         return vlc_list_find (p_this->p_libvlc, i_type, FIND_CHILD);
890
891     case FIND_CHILD:
892         vlc_mutex_lock( &structure_lock );
893         i_count = CountChildren( p_this, i_type );
894         p_list = NewList( i_count );
895
896         /* Check allocation was successful */
897         if( p_list->i_count != i_count )
898         {
899             vlc_mutex_unlock( &structure_lock );
900             msg_Err( p_this, "list allocation failed!" );
901             p_list->i_count = 0;
902             break;
903         }
904
905         p_list->i_count = 0;
906         ListChildren( p_list, p_this, i_type );
907         vlc_mutex_unlock( &structure_lock );
908         break;
909
910     default:
911         msg_Err( p_this, "unimplemented!" );
912         p_list = NewList( 0 );
913         break;
914     }
915
916     return p_list;
917 }
918
919 /**
920  * Gets the list of children of an objects, and increment their reference
921  * count.
922  * @return a list (possibly empty) or NULL in case of error.
923  */
924 vlc_list_t *__vlc_list_children( vlc_object_t *obj )
925 {
926     vlc_list_t *l;
927     vlc_object_internals_t *priv = vlc_internals( obj );
928
929     vlc_mutex_lock( &structure_lock );
930     l = NewList( priv->i_children );
931     for (int i = 0; i < l->i_count; i++)
932     {
933         vlc_object_yield( priv->pp_children[i] );
934         l->p_values[i].p_object = priv->pp_children[i];
935     }
936     vlc_mutex_unlock( &structure_lock );
937     return l;
938 }
939
940 /*****************************************************************************
941  * DumpCommand: print the current vlc structure
942  *****************************************************************************
943  * This function prints either an ASCII tree showing the connections between
944  * vlc objects, and additional information such as their refcount, thread ID,
945  * etc. (command "tree"), or the same data as a simple list (command "list").
946  *****************************************************************************/
947 static int DumpCommand( vlc_object_t *p_this, char const *psz_cmd,
948                         vlc_value_t oldval, vlc_value_t newval, void *p_data )
949 {
950     (void)oldval; (void)p_data;
951     if( *psz_cmd == 'l' )
952     {
953         vlc_object_t *root = VLC_OBJECT (vlc_global ()), *cur = root;
954
955         vlc_mutex_lock( &structure_lock );
956         do
957         {
958             PrintObject (cur, "");
959             cur = vlc_internals (cur)->next;
960         }
961         while (cur != root);
962         vlc_mutex_unlock( &structure_lock );
963     }
964     else
965     {
966         vlc_object_t *p_object = NULL;
967
968         if( *newval.psz_string )
969         {
970             char *end;
971             int i_id = strtol( newval.psz_string, &end, 0 );
972             if( end != newval.psz_string )
973                 p_object = vlc_object_get( i_id );
974             else
975                 /* try using the object's name to find it */
976                 p_object = vlc_object_find_name( p_this, newval.psz_string,
977                                                  FIND_ANYWHERE );
978
979             if( !p_object )
980             {
981                 return VLC_ENOOBJ;
982             }
983         }
984
985         vlc_mutex_lock( &structure_lock );
986
987         if( *psz_cmd == 't' )
988         {
989             char psz_foo[2 * MAX_DUMPSTRUCTURE_DEPTH + 1];
990
991             if( !p_object )
992                 p_object = p_this->p_libvlc ? VLC_OBJECT(p_this->p_libvlc) : p_this;
993
994             psz_foo[0] = '|';
995             DumpStructure( p_object, 0, psz_foo );
996         }
997         else if( *psz_cmd == 'v' )
998         {
999             int i;
1000
1001             if( !p_object )
1002                 p_object = p_this->p_libvlc ? VLC_OBJECT(p_this->p_libvlc) : p_this;
1003
1004             PrintObject( p_object, "" );
1005
1006             if( !vlc_internals( p_object )->i_vars )
1007                 printf( " `-o No variables\n" );
1008             for( i = 0; i < vlc_internals( p_object )->i_vars; i++ )
1009             {
1010                 variable_t *p_var = vlc_internals( p_object )->p_vars + i;
1011
1012                 const char *psz_type = "unknown";
1013                 switch( p_var->i_type & VLC_VAR_TYPE )
1014                 {
1015 #define MYCASE( type, nice )                \
1016                     case VLC_VAR_ ## type:  \
1017                         psz_type = nice;    \
1018                         break;
1019                     MYCASE( VOID, "void" );
1020                     MYCASE( BOOL, "bool" );
1021                     MYCASE( INTEGER, "integer" );
1022                     MYCASE( HOTKEY, "hotkey" );
1023                     MYCASE( STRING, "string" );
1024                     MYCASE( MODULE, "module" );
1025                     MYCASE( FILE, "file" );
1026                     MYCASE( DIRECTORY, "directory" );
1027                     MYCASE( VARIABLE, "variable" );
1028                     MYCASE( FLOAT, "float" );
1029                     MYCASE( TIME, "time" );
1030                     MYCASE( ADDRESS, "address" );
1031                     MYCASE( MUTEX, "mutex" );
1032                     MYCASE( LIST, "list" );
1033 #undef MYCASE
1034                 }
1035                 printf( " %c-o \"%s\" (%s",
1036                         i + 1 == vlc_internals( p_object )->i_vars ? '`' : '|',
1037                         p_var->psz_name, psz_type );
1038                 if( p_var->psz_text )
1039                     printf( ", %s", p_var->psz_text );
1040                 printf( ")" );
1041                 if( p_var->i_type & VLC_VAR_HASCHOICE )
1042                     printf( ", has choices" );
1043                 if( p_var->i_type & VLC_VAR_ISCOMMAND )
1044                     printf( ", command" );
1045                 if( p_var->i_entries )
1046                     printf( ", %d callbacks", p_var->i_entries );
1047                 switch( p_var->i_type & 0x00f0 )
1048                 {
1049                     case VLC_VAR_VOID:
1050                     case VLC_VAR_MUTEX:
1051                         break;
1052                     case VLC_VAR_BOOL:
1053                         printf( ": %s", p_var->val.b_bool ? "true" : "false" );
1054                         break;
1055                     case VLC_VAR_INTEGER:
1056                         printf( ": %d", p_var->val.i_int );
1057                         break;
1058                     case VLC_VAR_STRING:
1059                         printf( ": \"%s\"", p_var->val.psz_string );
1060                         break;
1061                     case VLC_VAR_FLOAT:
1062                         printf( ": %f", p_var->val.f_float );
1063                         break;
1064                     case VLC_VAR_TIME:
1065                         printf( ": %"PRIi64, (int64_t)p_var->val.i_time );
1066                         break;
1067                     case VLC_VAR_ADDRESS:
1068                         printf( ": %p", p_var->val.p_address );
1069                         break;
1070                     case VLC_VAR_LIST:
1071                         printf( ": TODO" );
1072                         break;
1073                 }
1074                 printf( "\n" );
1075             }
1076         }
1077
1078         vlc_mutex_unlock( &structure_lock );
1079
1080         if( *newval.psz_string )
1081         {
1082             vlc_object_release( p_object );
1083         }
1084     }
1085
1086     return VLC_SUCCESS;
1087 }
1088
1089 /*****************************************************************************
1090  * vlc_list_release: free a list previously allocated by vlc_list_find
1091  *****************************************************************************
1092  * This function decreases the refcount of all objects in the list and
1093  * frees the list.
1094  *****************************************************************************/
1095 void vlc_list_release( vlc_list_t *p_list )
1096 {
1097     int i_index;
1098
1099     for( i_index = 0; i_index < p_list->i_count; i_index++ )
1100     {
1101         vlc_object_release( p_list->p_values[i_index].p_object );
1102     }
1103
1104     free( p_list->p_values );
1105     free( p_list );
1106 }
1107
1108 /*****************************************************************************
1109  * dump an object. (Debug function)
1110  *****************************************************************************/
1111 void __vlc_object_dump( vlc_object_t *p_this )
1112 {
1113     vlc_mutex_lock( &structure_lock );
1114     char psz_foo[2 * MAX_DUMPSTRUCTURE_DEPTH + 1];
1115     psz_foo[0] = '|';
1116     DumpStructure( p_this, 0, psz_foo );
1117     vlc_mutex_unlock( &structure_lock );
1118 }
1119
1120 /* Following functions are local */
1121
1122 static vlc_object_t * FindObject( vlc_object_t *p_this, int i_type, int i_mode )
1123 {
1124     int i;
1125     vlc_object_t *p_tmp;
1126
1127     switch( i_mode & 0x000f )
1128     {
1129     case FIND_PARENT:
1130         p_tmp = p_this->p_parent;
1131         if( p_tmp )
1132         {
1133             if( p_tmp->i_object_type == i_type )
1134             {
1135                 vlc_object_yield( p_tmp );
1136                 return p_tmp;
1137             }
1138             else
1139             {
1140                 return FindObject( p_tmp, i_type, i_mode );
1141             }
1142         }
1143         break;
1144
1145     case FIND_CHILD:
1146         for( i = vlc_internals( p_this )->i_children; i--; )
1147         {
1148             p_tmp = vlc_internals( p_this )->pp_children[i];
1149             if( p_tmp->i_object_type == i_type )
1150             {
1151                 vlc_object_yield( p_tmp );
1152                 return p_tmp;
1153             }
1154             else if( vlc_internals( p_tmp )->i_children )
1155             {
1156                 p_tmp = FindObject( p_tmp, i_type, i_mode );
1157                 if( p_tmp )
1158                 {
1159                     return p_tmp;
1160                 }
1161             }
1162         }
1163         break;
1164
1165     case FIND_ANYWHERE:
1166         /* Handled in vlc_object_find */
1167         break;
1168     }
1169
1170     return NULL;
1171 }
1172
1173 static vlc_object_t * FindObjectName( vlc_object_t *p_this,
1174                                       const char *psz_name,
1175                                       int i_mode )
1176 {
1177     int i;
1178     vlc_object_t *p_tmp;
1179
1180     switch( i_mode & 0x000f )
1181     {
1182     case FIND_PARENT:
1183         p_tmp = p_this->p_parent;
1184         if( p_tmp )
1185         {
1186             if( p_tmp->psz_object_name
1187                 && !strcmp( p_tmp->psz_object_name, psz_name ) )
1188             {
1189                 vlc_object_yield( p_tmp );
1190                 return p_tmp;
1191             }
1192             else
1193             {
1194                 return FindObjectName( p_tmp, psz_name, i_mode );
1195             }
1196         }
1197         break;
1198
1199     case FIND_CHILD:
1200         for( i = vlc_internals( p_this )->i_children; i--; )
1201         {
1202             p_tmp = vlc_internals( p_this )->pp_children[i];
1203             if( p_tmp->psz_object_name
1204                 && !strcmp( p_tmp->psz_object_name, psz_name ) )
1205             {
1206                 vlc_object_yield( p_tmp );
1207                 return p_tmp;
1208             }
1209             else if( vlc_internals( p_tmp )->i_children )
1210             {
1211                 p_tmp = FindObjectName( p_tmp, psz_name, i_mode );
1212                 if( p_tmp )
1213                 {
1214                     return p_tmp;
1215                 }
1216             }
1217         }
1218         break;
1219
1220     case FIND_ANYWHERE:
1221         /* Handled in vlc_object_find */
1222         break;
1223     }
1224
1225     return NULL;
1226 }
1227
1228
1229 static void PrintObject( vlc_object_t *p_this, const char *psz_prefix )
1230 {
1231     char psz_children[20], psz_refcount[20], psz_thread[30], psz_name[50],
1232          psz_parent[20];
1233
1234     int canc = vlc_savecancel ();
1235     memset( &psz_name, 0, sizeof(psz_name) );
1236     if( p_this->psz_object_name )
1237     {
1238         snprintf( psz_name, 49, " \"%s\"", p_this->psz_object_name );
1239         if( psz_name[48] )
1240             psz_name[48] = '\"';
1241     }
1242
1243     psz_children[0] = '\0';
1244     switch( vlc_internals( p_this )->i_children )
1245     {
1246         case 0:
1247             break;
1248         case 1:
1249             strcpy( psz_children, ", 1 child" );
1250             break;
1251         default:
1252             snprintf( psz_children, 19, ", %i children",
1253                       vlc_internals( p_this )->i_children );
1254             break;
1255     }
1256
1257     psz_refcount[0] = '\0';
1258     if( vlc_internals( p_this )->i_refcount > 0 )
1259         snprintf( psz_refcount, 19, ", refcount %u",
1260                   vlc_internals( p_this )->i_refcount );
1261
1262     psz_thread[0] = '\0';
1263     if( vlc_internals( p_this )->b_thread )
1264         snprintf( psz_thread, 29, " (thread %lu)",
1265                   (unsigned long)vlc_internals( p_this )->thread_id );
1266
1267     psz_parent[0] = '\0';
1268     if( p_this->p_parent )
1269         snprintf( psz_parent, 19, ", parent %i", p_this->p_parent->i_object_id );
1270
1271     printf( " %so %.8i %s%s%s%s%s%s\n", psz_prefix,
1272             p_this->i_object_id, p_this->psz_object_type,
1273             psz_name, psz_thread, psz_refcount, psz_children,
1274             psz_parent );
1275     vlc_restorecancel (canc);
1276 }
1277
1278 static void DumpStructure( vlc_object_t *p_this, int i_level, char *psz_foo )
1279 {
1280     int i;
1281     char i_back = psz_foo[i_level];
1282     psz_foo[i_level] = '\0';
1283
1284     PrintObject( p_this, psz_foo );
1285
1286     psz_foo[i_level] = i_back;
1287
1288     if( i_level / 2 >= MAX_DUMPSTRUCTURE_DEPTH )
1289     {
1290         msg_Warn( p_this, "structure tree is too deep" );
1291         return;
1292     }
1293
1294     for( i = 0 ; i < vlc_internals( p_this )->i_children ; i++ )
1295     {
1296         if( i_level )
1297         {
1298             psz_foo[i_level-1] = ' ';
1299
1300             if( psz_foo[i_level-2] == '`' )
1301             {
1302                 psz_foo[i_level-2] = ' ';
1303             }
1304         }
1305
1306         if( i == vlc_internals( p_this )->i_children - 1 )
1307         {
1308             psz_foo[i_level] = '`';
1309         }
1310         else
1311         {
1312             psz_foo[i_level] = '|';
1313         }
1314
1315         psz_foo[i_level+1] = '-';
1316         psz_foo[i_level+2] = '\0';
1317
1318         DumpStructure( vlc_internals( p_this )->pp_children[i], i_level + 2,
1319                        psz_foo );
1320     }
1321 }
1322
1323 static vlc_list_t * NewList( int i_count )
1324 {
1325     vlc_list_t * p_list = (vlc_list_t *)malloc( sizeof( vlc_list_t ) );
1326     if( p_list == NULL )
1327     {
1328         return NULL;
1329     }
1330
1331     p_list->i_count = i_count;
1332
1333     if( i_count == 0 )
1334     {
1335         p_list->p_values = NULL;
1336         return p_list;
1337     }
1338
1339     p_list->p_values = malloc( i_count * sizeof( vlc_value_t ) );
1340     if( p_list->p_values == NULL )
1341     {
1342         p_list->i_count = 0;
1343         return p_list;
1344     }
1345
1346     return p_list;
1347 }
1348
1349 static void ListReplace( vlc_list_t *p_list, vlc_object_t *p_object,
1350                          int i_index )
1351 {
1352     if( p_list == NULL || i_index >= p_list->i_count )
1353     {
1354         return;
1355     }
1356
1357     vlc_object_yield( p_object );
1358
1359     p_list->p_values[i_index].p_object = p_object;
1360
1361     return;
1362 }
1363
1364 /*static void ListAppend( vlc_list_t *p_list, vlc_object_t *p_object )
1365 {
1366     if( p_list == NULL )
1367     {
1368         return;
1369     }
1370
1371     p_list->p_values = realloc( p_list->p_values, (p_list->i_count + 1)
1372                                 * sizeof( vlc_value_t ) );
1373     if( p_list->p_values == NULL )
1374     {
1375         p_list->i_count = 0;
1376         return;
1377     }
1378
1379     vlc_object_yield( p_object );
1380
1381     p_list->p_values[p_list->i_count].p_object = p_object;
1382     p_list->i_count++;
1383
1384     return;
1385 }*/
1386
1387 static int CountChildren( vlc_object_t *p_this, int i_type )
1388 {
1389     vlc_object_t *p_tmp;
1390     int i, i_count = 0;
1391
1392     for( i = 0; i < vlc_internals( p_this )->i_children; i++ )
1393     {
1394         p_tmp = vlc_internals( p_this )->pp_children[i];
1395
1396         if( p_tmp->i_object_type == i_type )
1397         {
1398             i_count++;
1399         }
1400         i_count += CountChildren( p_tmp, i_type );
1401     }
1402
1403     return i_count;
1404 }
1405
1406 static void ListChildren( vlc_list_t *p_list, vlc_object_t *p_this, int i_type )
1407 {
1408     vlc_object_t *p_tmp;
1409     int i;
1410
1411     for( i = 0; i < vlc_internals( p_this )->i_children; i++ )
1412     {
1413         p_tmp = vlc_internals( p_this )->pp_children[i];
1414
1415         if( p_tmp->i_object_type == i_type )
1416             ListReplace( p_list, p_tmp, p_list->i_count++ );
1417
1418         ListChildren( p_list, p_tmp, i_type );
1419     }
1420 }