]> git.sesse.net Git - vlc/blob - src/misc/modules.c
* ./src/misc/objects.c: implemented vlc_list_find() which works like
[vlc] / src / misc / modules.c
1 /*****************************************************************************
2  * modules.c : Builtin and plugin modules management functions
3  *****************************************************************************
4  * Copyright (C) 2001 VideoLAN
5  * $Id: modules.c,v 1.86 2002/08/14 17:06:53 sam Exp $
6  *
7  * Authors: Samuel Hocevar <sam@zoy.org>
8  *          Ethan C. Baldridge <BaldridgeE@cadmus.com>
9  *          Hans-Peter Jansen <hpj@urpla.net>
10  *
11  * This program is free software; you can redistribute it and/or modify
12  * it under the terms of the GNU General Public License as published by
13  * the Free Software Foundation; either version 2 of the License, or
14  * (at your option) any later version.
15  *
16  * This program is distributed in the hope that it will be useful,
17  * but WITHOUT ANY WARRANTY; without even the implied warranty of
18  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
19  * GNU General Public License for more details.
20  *
21  * You should have received a copy of the GNU General Public License
22  * along with this program; if not, write to the Free Software
23  * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111, USA.
24  *****************************************************************************/
25
26 /* Some faulty libcs have a broken struct dirent when _FILE_OFFSET_BITS
27  * is set to 64. Don't try to be cleverer. */
28 #ifdef _FILE_OFFSET_BITS
29 #undef _FILE_OFFSET_BITS
30 #endif
31
32 #include <stdlib.h>                                      /* free(), strtol() */
33 #include <stdio.h>                                              /* sprintf() */
34 #include <string.h>                                              /* strdup() */
35
36 #include <vlc/vlc.h>
37
38 #include <dirent.h>
39 #include <sys/types.h>
40 #include <sys/stat.h>
41 #ifdef HAVE_UNISTD_H
42 #   include <unistd.h>
43 #endif
44
45 #if defined(HAVE_DLFCN_H)                                /* Linux, BSD, Hurd */
46 #   include <dlfcn.h>                        /* dlopen(), dlsym(), dlclose() */
47 #   define HAVE_DYNAMIC_PLUGINS
48 #elif defined(HAVE_IMAGE_H)                                          /* BeOS */
49 #   include <image.h>
50 #   define HAVE_DYNAMIC_PLUGINS
51 #elif defined(WIN32)
52 #   define HAVE_DYNAMIC_PLUGINS
53 #else
54 #   undef HAVE_DYNAMIC_PLUGINS
55 #endif
56
57
58 #include "netutils.h"
59
60 #include "interface.h"
61 #include "vlc_playlist.h"
62 #include "intf_eject.h"
63
64 #include "stream_control.h"
65 #include "input_ext-intf.h"
66 #include "input_ext-dec.h"
67 #include "input_ext-plugins.h"
68
69 #include "video.h"
70 #include "video_output.h"
71
72 #include "audio_output.h"
73 #include "aout_internal.h"
74
75 #include "stream_output.h"
76
77 #include "iso_lang.h"
78
79 #ifdef HAVE_DYNAMIC_PLUGINS
80 #   include "modules_plugin.h"
81 #endif
82
83 #if !defined( _MSC_VER )
84 #    include "modules_builtin.h"
85 #else
86 #    include "modules_builtin_msvc.h"
87 #endif
88
89 /*****************************************************************************
90  * Local prototypes
91  *****************************************************************************/
92 #ifdef HAVE_DYNAMIC_PLUGINS
93 static void AllocateAllPlugins   ( vlc_object_t * );
94 static void AllocatePluginDir    ( vlc_object_t *, const char *, int );
95 static int  AllocatePluginFile   ( vlc_object_t *, char * );
96 #endif
97 static int  AllocateBuiltinModule( vlc_object_t *, int ( * ) ( module_t * ) );
98 static int  DeleteModule ( module_t * );
99 static int  LockModule   ( module_t * );
100 static int  UnlockModule ( module_t * );
101 #ifdef HAVE_DYNAMIC_PLUGINS
102 static int  HideModule   ( module_t * );
103 static void DupModule    ( module_t * );
104 static void UndupModule  ( module_t * );
105 static int  CallEntry    ( module_t * );
106 #endif
107
108 /*****************************************************************************
109  * module_InitBank: create the module bank.
110  *****************************************************************************
111  * This function creates a module bank structure which will be filled later
112  * on with all the modules found.
113  *****************************************************************************/
114 void __module_InitBank( vlc_object_t *p_this )
115 {
116     module_bank_t *p_bank;
117
118     p_bank = vlc_object_create( p_this, sizeof(module_bank_t) );
119     p_bank->psz_object_name = "module bank";
120
121     p_bank->first = NULL;
122     p_bank->i_count = 0;
123     vlc_mutex_init( p_this, &p_bank->lock );
124
125     /*
126      * Store the symbols to be exported
127      */
128 #ifdef HAVE_DYNAMIC_PLUGINS
129     STORE_SYMBOLS( &p_bank->symbols );
130 #endif
131
132     /* Everything worked, attach the object */
133     p_this->p_vlc->p_module_bank = p_bank;
134     vlc_object_attach( p_bank, p_this->p_vlc );
135
136     return;
137 }
138
139 /*****************************************************************************
140  * module_ResetBank: reset the module bank.
141  *****************************************************************************
142  * This function resets the module bank by unloading all unused plugin
143  * modules.
144  *****************************************************************************/
145 void __module_ResetBank( vlc_object_t *p_this )
146 {
147     msg_Err( p_this, "FIXME: module_ResetBank unimplemented" );
148     return;
149 }
150
151 /*****************************************************************************
152  * module_EndBank: empty the module bank.
153  *****************************************************************************
154  * This function unloads all unused plugin modules and empties the module
155  * bank in case of success.
156  *****************************************************************************/
157 void __module_EndBank( vlc_object_t *p_this )
158 {
159     module_t * p_next;
160
161     vlc_object_detach( p_this->p_vlc->p_module_bank );
162
163     while( p_this->p_vlc->p_module_bank->first != NULL )
164     {
165         if( DeleteModule( p_this->p_vlc->p_module_bank->first ) )
166         {
167             /* Module deletion failed */
168             msg_Err( p_this, "module \"%s\" can't be removed, trying harder",
169                      p_this->p_vlc->p_module_bank->first->psz_object_name );
170
171             /* We just free the module by hand. Niahahahahaha. */
172             p_next = p_this->p_vlc->p_module_bank->first->next;
173             vlc_object_detach( p_this->p_vlc->p_module_bank->first );
174             vlc_object_destroy( p_this->p_vlc->p_module_bank->first );
175             p_this->p_vlc->p_module_bank->first = p_next;
176         }
177     }
178
179     /* Destroy the lock */
180     vlc_mutex_destroy( &p_this->p_vlc->p_module_bank->lock );
181
182     vlc_object_destroy( p_this->p_vlc->p_module_bank );
183
184     return;
185 }
186
187 /*****************************************************************************
188  * module_LoadMain: load the main program info into the module bank.
189  *****************************************************************************
190  * This function fills the module bank structure with the main module infos.
191  * This is very useful as it will allow us to consider the main program just
192  * as another module, and for instance the configuration options of main will
193  * be available in the module bank structure just as for every other module.
194  *****************************************************************************/
195 void __module_LoadMain( vlc_object_t *p_this )
196 {
197     AllocateBuiltinModule( p_this, vlc_entry__main );
198 }
199
200 /*****************************************************************************
201  * module_LoadBuiltins: load all modules which we built with.
202  *****************************************************************************
203  * This function fills the module bank structure with the builtin modules.
204  *****************************************************************************/
205 void __module_LoadBuiltins( vlc_object_t * p_this )
206 {
207     msg_Dbg( p_this, "checking builtin modules" );
208     ALLOCATE_ALL_BUILTINS();
209 }
210
211 /*****************************************************************************
212  * module_LoadPlugins: load all plugin modules we can find.
213  *****************************************************************************
214  * This function fills the module bank structure with the plugin modules.
215  *****************************************************************************/
216 void __module_LoadPlugins( vlc_object_t * p_this )
217 {
218 #ifdef HAVE_DYNAMIC_PLUGINS
219     msg_Dbg( p_this, "checking plugin modules" );
220     AllocateAllPlugins( p_this );
221 #endif
222 }
223
224 /*****************************************************************************
225  * module_ManageBank: manage the module bank.
226  *****************************************************************************
227  * This function parses the module bank and hides modules that have been
228  * unused for a while.
229  *****************************************************************************/
230 void __module_ManageBank( vlc_object_t *p_this )
231 {
232 #ifdef HAVE_DYNAMIC_PLUGINS
233     module_t * p_module;
234
235     /* We take the global lock */
236     vlc_mutex_lock( &p_this->p_vlc->p_module_bank->lock );
237
238     /* Parse the module list to see if any modules need to be unloaded */
239     for( p_module = p_this->p_vlc->p_module_bank->first ;
240          p_module != NULL ;
241          p_module = p_module->next )
242     {
243         /* If the module is unused and if it is a plugin module... */
244         if( p_module->i_usage == 0 && !p_module->b_builtin )
245         {
246             if( p_module->i_unused_delay < MODULE_HIDE_DELAY )
247             {
248                 p_module->i_unused_delay++;
249             }
250             else
251             {
252                 msg_Dbg( p_this, "hiding unused plugin module \"%s\"",
253                                  p_module->psz_object_name );
254                 HideModule( p_module );
255
256                 /* Break here, so that we only hide one module at a time */
257                 break;
258             }
259         }
260     }
261
262     /* We release the global lock */
263     vlc_mutex_unlock( &p_this->p_vlc->p_module_bank->lock );
264 #endif /* HAVE_DYNAMIC_PLUGINS */
265
266     return;
267 }
268
269 /*****************************************************************************
270  * module_Need: return the best module function, given a capability list.
271  *****************************************************************************
272  * This function returns the module that best fits the asked capabilities.
273  *****************************************************************************/
274 module_t * __module_Need( vlc_object_t *p_this, const char *psz_capability,
275                           const char *psz_name )
276 {
277     typedef struct module_list_t module_list_t;
278
279     struct module_list_t
280     {
281         module_t *p_module;
282         int i_score;
283         module_list_t *p_next;
284     };
285
286     module_list_t *p_list, *p_first, *p_tmp;
287
288     int i_index = 0;
289     vlc_bool_t b_intf = VLC_FALSE;
290
291     module_t *p_module;
292
293     int   i_shortcuts = 0;
294     char *psz_shortcuts = NULL, *psz_var = NULL;
295
296     msg_Dbg( p_this, "looking for %s module", psz_capability );
297
298     /* Deal with variables */
299     if( psz_name && psz_name[0] == '$' )
300     {
301         psz_var = config_GetPsz( p_this, psz_name + 1 );
302         psz_name = psz_var;
303     }
304
305     /* Count how many different shortcuts were asked for */
306     if( psz_name && *psz_name )
307     {
308         char *psz_parser;
309
310         /* If the user wants none, give him none. */
311         if( !strcmp( psz_name, "none" ) )
312         {
313             if( psz_var ) free( psz_var );
314             return NULL;
315         }
316
317         i_shortcuts++;
318         psz_shortcuts = strdup( psz_name );
319
320         for( psz_parser = psz_shortcuts; *psz_parser; psz_parser++ )
321         {
322             if( *psz_parser == ',' )
323             {
324                  *psz_parser = '\0';
325                  i_shortcuts++;
326             }
327         }
328     }
329
330     /* We take the global lock */
331     vlc_mutex_lock( &p_this->p_vlc->p_module_bank->lock );
332
333     /* Sort the modules and test them */
334     p_list = malloc( p_this->p_vlc->p_module_bank->i_count
335                       * sizeof( module_list_t ) );
336     p_first = NULL;
337
338     /* Parse the module list for capabilities and probe each of them */
339     for( p_module = p_this->p_vlc->p_module_bank->first ;
340          p_module != NULL ;
341          p_module = p_module->next )
342     {
343         module_t * p_submodule = NULL;
344         int i_shortcut_bonus = 0, i_submodule;
345
346         /* Test that this module can do what we need */
347         if( strcmp( p_module->psz_capability, psz_capability ) )
348         {
349             for( i_submodule = 0;
350                  i_submodule < p_module->i_children;
351                  i_submodule++ )
352             {
353                 if( !strcmp( ((module_t*)p_module->pp_children[ i_submodule ])
354                                            ->psz_capability, psz_capability ) )
355                 {
356                     p_submodule =
357                             (module_t*)p_module->pp_children[ i_submodule ];
358                     p_submodule->next = p_module->next;
359                     break;
360                 }
361             }
362
363             if( p_submodule == NULL )
364             {
365                 continue;
366             }
367
368             p_module = p_submodule;
369         }
370
371         /* Test if we have the required CPU */
372         if( (p_module->i_cpu & p_this->p_vlc->i_cpu) != p_module->i_cpu )
373         {
374             continue;
375         }
376
377         /* If we required a shortcut, check this plugin provides it. */
378         if( i_shortcuts )
379         {
380             vlc_bool_t b_trash = VLC_TRUE;
381             int i_dummy, i_short = i_shortcuts;
382             char *psz_name = psz_shortcuts;
383
384             while( i_short )
385             {
386                 for( i_dummy = 0;
387                      b_trash && p_module->pp_shortcuts[i_dummy];
388                      i_dummy++ )
389                 {
390                     b_trash = ( strcmp(psz_name, "any") || !p_module->i_score )
391                         && strcmp( psz_name, p_module->pp_shortcuts[i_dummy] );
392                 }
393
394                 if( !b_trash )
395                 {
396                     i_shortcut_bonus = i_short * 10000;
397                     break;
398                 }
399
400                 /* Go to the next shortcut... This is so lame! */
401                 while( *psz_name )
402                 {
403                     psz_name++;
404                 }
405                 psz_name++;
406                 i_short--;
407             }
408
409             if( b_trash )
410             {
411                 continue;
412             }
413         }
414         /* If we didn't require a shortcut, trash zero-scored plugins */
415         else if( !p_module->i_score )
416         {
417             continue;
418         }
419
420         /* Special case: test if we requested a particular intf plugin */
421         if( p_module->psz_program
422              && !strcmp( p_module->psz_program,
423                          p_this->p_vlc->psz_object_name ) )
424         {
425             if( !b_intf ) 
426             {
427                 /* Remove previous non-matching plugins */
428                 i_index = 0;
429                 b_intf = VLC_TRUE;
430             }
431         }
432         else if( b_intf )
433         {
434             /* This one doesn't match */
435             continue;
436         }
437
438         /* Store this new module */
439         p_list[ i_index ].p_module = p_module;
440         p_list[ i_index ].i_score = p_module->i_score + i_shortcut_bonus;
441
442         /* Add it to the modules-to-probe list */
443         if( i_index == 0 )
444         {
445             p_list[ 0 ].p_next = NULL;
446             p_first = p_list;
447         }
448         else
449         {
450             /* Ok, so at school you learned that quicksort is quick, and
451              * bubble sort sucks raw eggs. But that's when dealing with
452              * thousands of items. Here we have barely 50. */
453             module_list_t *p_newlist = p_first;
454
455             if( p_first->i_score < p_list[ i_index ].i_score )
456             {
457                 p_list[ i_index ].p_next = p_first;
458                 p_first = &p_list[ i_index ];
459             }
460             else
461             {
462                 while( p_newlist->p_next != NULL &&
463                     p_newlist->p_next->i_score >= p_list[ i_index ].i_score )
464                 {
465                     p_newlist = p_newlist->p_next;
466                 }
467
468                 p_list[ i_index ].p_next = p_newlist->p_next;
469                 p_newlist->p_next = &p_list[ i_index ];
470             }
471         }
472
473         i_index++;
474     }
475
476     msg_Dbg( p_this, "probing %i candidate%s",
477                      i_index, i_index == 1 ? "" : "s" );
478
479     /* Lock all selected modules */
480     p_tmp = p_first;
481     while( p_tmp != NULL )
482     {
483         LockModule( p_tmp->p_module );
484         p_tmp = p_tmp->p_next;
485     }
486
487     /* We can release the global lock, module refcounts were incremented */
488     vlc_mutex_unlock( &p_this->p_vlc->p_module_bank->lock );
489
490     /* Parse the linked list and use the first successful module */
491     p_tmp = p_first;
492     while( p_tmp != NULL )
493     {
494         if( p_tmp->p_module->pf_activate
495              && p_tmp->p_module->pf_activate( p_this ) == VLC_SUCCESS )
496         {
497             break;
498         }
499
500         UnlockModule( p_tmp->p_module );
501         p_tmp = p_tmp->p_next;
502     }
503
504     /* Store the locked module value */
505     if( p_tmp != NULL )
506     {
507         p_module = p_tmp->p_module;
508         p_tmp = p_tmp->p_next;
509     }
510     else
511     {
512         p_module = NULL;
513     }
514
515     /* Unlock the remaining modules */
516     while( p_tmp != NULL )
517     {
518         UnlockModule( p_tmp->p_module );
519         p_tmp = p_tmp->p_next;
520     }
521
522     free( p_list );
523
524     if( p_module != NULL )
525     {
526         msg_Info( p_module, "using %s module \"%s\"",
527                   psz_capability, p_module->psz_object_name );
528     }
529     else if( p_first == NULL )
530     {
531         msg_Err( p_this, "no %s module matched \"%s\"",
532                  psz_capability, (psz_name && *psz_name) ? psz_name : "any" );
533     }
534     else if( psz_name != NULL && *psz_name )
535     {
536         msg_Err( p_this, "no %s module matching \"%s\" could be loaded",
537                  psz_capability, (psz_name && *psz_name) ? psz_name : "any" );
538     }
539
540     if( psz_shortcuts )
541     {
542         free( psz_shortcuts );
543     }
544
545     if( psz_var )
546     {
547         free( psz_var );
548     }
549
550     /* Don't forget that the module is still locked */
551     return p_module;
552 }
553
554 /*****************************************************************************
555  * module_Unneed: decrease the usage count of a module.
556  *****************************************************************************
557  * This function must be called by the thread that called module_Need, to
558  * decrease the reference count and allow for hiding of modules.
559  *****************************************************************************/
560 void __module_Unneed( vlc_object_t * p_this, module_t * p_module )
561 {
562     /* Use the close method */
563     if( p_module->pf_deactivate )
564     {
565         p_module->pf_deactivate( p_this );
566     }
567
568     /* We take the global lock */
569     vlc_mutex_lock( &p_module->p_vlc->p_module_bank->lock );
570
571     /* Just unlock the module - we can't do anything if it fails,
572      * so there is no need to check the return value. */
573     UnlockModule( p_module );
574
575     msg_Info( p_module, "unlocking module \"%s\"", p_module->psz_object_name );
576
577     /* We release the global lock */
578     vlc_mutex_unlock( &p_module->p_vlc->p_module_bank->lock );
579
580     return;
581 }
582
583 /*****************************************************************************
584  * Following functions are local.
585  *****************************************************************************/
586
587 /*****************************************************************************
588  * AllocateAllPlugins: load all plugin modules we can find.
589  *****************************************************************************/
590 #ifdef HAVE_DYNAMIC_PLUGINS
591 static void AllocateAllPlugins( vlc_object_t *p_this )
592 {
593     /* Yes, there are two NULLs because we replace one with "plugin-path". */
594     char *          path[] = { "modules", PLUGIN_PATH, NULL, NULL };
595
596     char **         ppsz_path = path;
597     char *          psz_fullpath;
598 #if defined( SYS_BEOS ) || defined( SYS_DARWIN )
599     char *          psz_vlcpath = system_GetProgramPath();
600     int             i_vlclen = strlen( psz_vlcpath );
601     vlc_bool_t      b_notinroot;
602 #endif
603
604     /* If the user provided a plugin path, we add it to the list */
605     path[ sizeof(path)/sizeof(char*) - 2 ] = config_GetPsz( p_this,
606                                                             "plugin-path" );
607
608     for( ; *ppsz_path != NULL ; ppsz_path++ )
609     {
610 #if defined( SYS_BEOS ) || defined( SYS_DARWIN )
611         /* Store strlen(*ppsz_path) for later use. */
612         int i_dirlen = strlen( *ppsz_path );
613
614         b_notinroot = VLC_FALSE;
615         /* Under BeOS, we need to add beos_GetProgramPath() to access
616          * files under the current directory */
617         if( ( i_dirlen > 1 ) && strncmp( *ppsz_path, "/", 1 ) )
618         {
619             i_dirlen += i_vlclen + 2;
620             b_notinroot = VLC_TRUE;
621
622             psz_fullpath = malloc( i_dirlen );
623             if( psz_fullpath == NULL )
624             {
625                 continue;
626             }
627             sprintf( psz_fullpath, "%s/%s", psz_vlcpath, *ppsz_path );
628         }
629         else
630 #endif
631         {
632             psz_fullpath = *ppsz_path;
633         }
634
635         msg_Dbg( p_this, "recursively browsing `%s'", psz_fullpath );
636
637         /* Don't go deeper than 5 subdirectories */
638         AllocatePluginDir( p_this, psz_fullpath, 5 );
639
640 #if defined( SYS_BEOS ) || defined( SYS_DARWIN )
641         if( b_notinroot )
642         {
643             free( psz_fullpath );
644         }
645 #endif
646     }
647 }
648
649 /*****************************************************************************
650  * AllocatePluginDir: recursively parse a directory to look for plugins
651  *****************************************************************************/
652 static void AllocatePluginDir( vlc_object_t *p_this, const char *psz_dir,
653                                int i_maxdepth )
654 {
655 #define PLUGIN_EXT ".so"
656     int    i_dirlen;
657     DIR *  dir;
658     char * psz_file;
659
660     struct dirent * file;
661
662     if( i_maxdepth < 0 )
663     {
664         return;
665     }
666
667     dir = opendir( psz_dir );
668
669     if( !dir )
670     {
671         return;
672     }
673
674     i_dirlen = strlen( psz_dir );
675
676     /* Parse the directory and try to load all files it contains. */
677     while( (file = readdir( dir )) )
678     {
679         struct stat statbuf;
680         int i_len = strlen( file->d_name );
681
682         /* Skip ".", ".." and anything starting with "." */
683         if( !*file->d_name || *file->d_name == '.' )
684         {
685             continue;
686         }
687
688         psz_file = malloc( i_dirlen + 1 /* / */ + i_len + 1 /* \0 */ );
689         sprintf( psz_file, "%s/%s", psz_dir, file->d_name );
690
691         if( !stat( psz_file, &statbuf ) && statbuf.st_mode & S_IFDIR )
692         {
693             AllocatePluginDir( p_this, psz_file, i_maxdepth - 1 );
694         }
695         else if( i_len > strlen( PLUGIN_EXT )
696                   /* We only load files ending with ".so" */
697                   && !strncmp( file->d_name + i_len - strlen( PLUGIN_EXT ),
698                                PLUGIN_EXT, strlen( PLUGIN_EXT ) ) )
699         {
700             AllocatePluginFile( p_this, psz_file );
701         }
702
703         free( psz_file );
704     }
705
706     /* Close the directory */
707     closedir( dir );
708 }
709
710 /*****************************************************************************
711  * AllocatePluginFile: load a module into memory and initialize it.
712  *****************************************************************************
713  * This function loads a dynamically loadable module and allocates a structure
714  * for its information data. The module can then be handled by module_Need,
715  * module_Unneed and HideModule. It can be removed by DeleteModule.
716  *****************************************************************************/
717 static int AllocatePluginFile( vlc_object_t * p_this, char * psz_file )
718 {
719     module_t * p_module;
720     module_handle_t handle;
721
722     /* Try to dynamically load the module. */
723     if( module_load( psz_file, &handle ) )
724     {
725         char psz_buffer[256];
726
727         /* The plugin module couldn't be opened */
728         msg_Warn( p_this, "cannot open `%s' (%s)",
729                   psz_file, module_error( psz_buffer ) );
730         return -1;
731     }
732
733     /* Now that we have successfully loaded the module, we can
734      * allocate a structure for it */ 
735     p_module = vlc_object_create( p_this, VLC_OBJECT_MODULE );
736     if( p_module == NULL )
737     {
738         msg_Err( p_this, "out of memory" );
739         module_unload( handle );
740         return -1;
741     }
742
743     /* We need to fill these since they may be needed by CallEntry() */
744     p_module->psz_filename = psz_file;
745     p_module->handle = handle;
746     p_module->p_symbols = &p_this->p_vlc->p_module_bank->symbols;
747
748     /* Initialize the module: fill p_module->psz_object_name, default config */
749     if( CallEntry( p_module ) != 0 )
750     {
751         /* We couldn't call module_init() */
752         msg_Err( p_this, "failed calling entry point in `%s'", psz_file );
753         vlc_object_destroy( p_module );
754         module_unload( handle );
755         return -1;
756     }
757
758     DupModule( p_module );
759     p_module->psz_filename = strdup( p_module->psz_filename );
760     p_module->psz_longname = strdup( p_module->psz_longname );
761
762     /* Everything worked fine ! The module is ready to be added to the list. */
763     p_module->i_usage = 0;
764     p_module->i_unused_delay = 0;
765
766     p_module->b_builtin = VLC_FALSE;
767
768     /* Link module into the linked list */
769     if( p_this->p_vlc->p_module_bank->first != NULL )
770     {
771         p_this->p_vlc->p_module_bank->first->prev = p_module;
772     }
773     p_module->next = p_this->p_vlc->p_module_bank->first;
774     p_module->prev = NULL;
775     p_this->p_vlc->p_module_bank->first = p_module;
776     p_this->p_vlc->p_module_bank->i_count++;
777
778     /* msg_Dbg( p_this, "plugin \"%s\", %s",
779                 p_module->psz_object_name, p_module->psz_longname ); */
780
781     vlc_object_attach( p_module, p_this->p_vlc->p_module_bank );
782
783     return 0;
784 }
785
786 /*****************************************************************************
787  * DupModule: make a plugin module standalone.
788  *****************************************************************************
789  * This function duplicates all strings in the module, so that the dynamic
790  * object can be unloaded. It acts recursively on submodules.
791  *****************************************************************************/
792 static void DupModule( module_t *p_module )
793 {
794     char **pp_shortcut;
795     int i_submodule;
796
797     for( pp_shortcut = p_module->pp_shortcuts ; *pp_shortcut ; pp_shortcut++ )
798     {
799         *pp_shortcut = strdup( *pp_shortcut );
800     }
801
802     /* We strdup() these entries so that they are still valid when the
803      * module is unloaded. */
804     p_module->psz_object_name = strdup( p_module->psz_object_name );
805     p_module->psz_capability = strdup( p_module->psz_capability );
806
807     if( p_module->psz_program != NULL )
808     {
809         p_module->psz_program = strdup( p_module->psz_program );
810     }
811
812     for( i_submodule = 0; i_submodule < p_module->i_children; i_submodule++ )
813     {
814         DupModule( (module_t*)p_module->pp_children[ i_submodule ] );
815     }
816 }
817
818 /*****************************************************************************
819  * UndupModule: free a duplicated module.
820  *****************************************************************************
821  * This function frees the allocations done in DupModule().
822  *****************************************************************************/
823 static void UndupModule( module_t *p_module )
824 {
825     char **pp_shortcut;
826     int i_submodule;
827
828     for( i_submodule = 0; i_submodule < p_module->i_children; i_submodule++ )
829     {
830         UndupModule( (module_t*)p_module->pp_children[ i_submodule ] );
831     }
832
833     for( pp_shortcut = p_module->pp_shortcuts ; *pp_shortcut ; pp_shortcut++ )
834     {
835         free( *pp_shortcut );
836     }
837
838     free( p_module->psz_object_name );
839     free( p_module->psz_capability );
840
841     if( p_module->psz_program != NULL )
842     {
843         free( p_module->psz_program );
844     }
845 }
846
847 #endif /* HAVE_DYNAMIC_PLUGINS */
848
849 /*****************************************************************************
850  * AllocateBuiltinModule: initialize a builtin module.
851  *****************************************************************************
852  * This function registers a builtin module and allocates a structure
853  * for its information data. The module can then be handled by module_Need,
854  * module_Unneed and HideModule. It can be removed by DeleteModule.
855  *****************************************************************************/
856 static int AllocateBuiltinModule( vlc_object_t * p_this,
857                                   int ( *pf_entry ) ( module_t * ) )
858 {
859     module_t * p_module;
860
861     /* Now that we have successfully loaded the module, we can
862      * allocate a structure for it */ 
863     p_module = vlc_object_create( p_this, VLC_OBJECT_MODULE );
864     if( p_module == NULL )
865     {
866         msg_Err( p_this, "out of memory" );
867         return -1;
868     }
869
870     /* Initialize the module : fill p_module->psz_object_name, etc. */
871     if( pf_entry( p_module ) != 0 )
872     {
873         /* With a well-written module we shouldn't have to print an
874          * additional error message here, but just make sure. */
875         msg_Err( p_this, "failed calling entry point in builtin module" );
876         vlc_object_destroy( p_module );
877         return -1;
878     }
879
880     /* Everything worked fine ! The module is ready to be added to the list. */
881     p_module->i_usage = 0;
882     p_module->i_unused_delay = 0;
883
884     p_module->b_builtin = VLC_TRUE;
885
886     /* Link module into the linked list */
887     if( p_this->p_vlc->p_module_bank->first != NULL )
888     {
889         p_this->p_vlc->p_module_bank->first->prev = p_module;
890     }
891     p_module->next = p_this->p_vlc->p_module_bank->first;
892     p_module->prev = NULL;
893     p_this->p_vlc->p_module_bank->first = p_module;
894     p_this->p_vlc->p_module_bank->i_count++;
895
896     /* msg_Dbg( p_this, "builtin \"%s\", %s",
897                 p_module->psz_object_name, p_module->psz_longname ); */
898
899     vlc_object_attach( p_module, p_this->p_vlc->p_module_bank );
900
901     return 0;
902 }
903
904 /*****************************************************************************
905  * DeleteModule: delete a module and its structure.
906  *****************************************************************************
907  * This function can only be called if i_usage <= 0.
908  *****************************************************************************/
909 static int DeleteModule( module_t * p_module )
910 {
911     /* If the module is not in use but is still in memory, we first have
912      * to hide it and remove it from memory before we can free the
913      * data structure. */
914     if( p_module->b_builtin )
915     {
916         if( p_module->i_usage != 0 )
917         {
918             msg_Err( p_module, "trying to free builtin module \"%s\" with "
919                      "usage %i", p_module->psz_object_name, p_module->i_usage );
920             return -1;
921         }
922     }
923 #ifdef HAVE_DYNAMIC_PLUGINS
924     else
925     {
926         if( p_module->i_usage >= 1 )
927         {
928             msg_Err( p_module, "trying to free module \"%s\" which is "
929                                "still in use", p_module->psz_object_name );
930             return -1;
931         }
932
933         /* Two possibilities here: i_usage == -1 and the module is already
934          * unloaded, we can continue, or i_usage == 0, and we have to hide
935          * the module before going on. */
936         if( p_module->i_usage == 0 )
937         {
938             if( HideModule( p_module ) != 0 )
939             {
940                 return -1;
941             }
942         }
943     }
944 #endif
945
946     vlc_object_detach( p_module );
947
948     /* Unlink the module from the linked list. */
949     if( p_module->prev != NULL )
950     {
951         p_module->prev->next = p_module->next;
952     }
953     else
954     {
955         p_module->p_vlc->p_module_bank->first = p_module->next;
956     }
957
958     if( p_module->next != NULL )
959     {
960         p_module->next->prev = p_module->prev;
961     }
962
963     p_module->p_vlc->p_module_bank->i_count--;
964
965     /* We free the structures that we strdup()ed in Allocate*Module(). */
966 #ifdef HAVE_DYNAMIC_PLUGINS
967     if( !p_module->b_builtin )
968     {
969         UndupModule( p_module );
970         free( p_module->psz_filename );
971         free( p_module->psz_longname );
972     }
973 #endif
974
975     /* Free and detach the object's children */
976     while( p_module->i_children )
977     {
978         vlc_object_t *p_this = p_module->pp_children[0];
979         vlc_object_detach( p_this );
980         vlc_object_destroy( p_this );
981     }
982
983     config_Free( p_module );
984     vlc_object_destroy( p_module );
985
986     return 0;
987 }
988
989 /*****************************************************************************
990  * LockModule: increase the usage count of a module and load it if needed.
991  *****************************************************************************
992  * This function has to be called before a thread starts using a module. If
993  * the module is already loaded, we just increase its usage count. If it isn't
994  * loaded, we have to dynamically open it and initialize it.
995  * If you successfully call LockModule() at any moment, be careful to call
996  * UnlockModule() when you don't need it anymore.
997  *****************************************************************************/
998 static int LockModule( module_t * p_module )
999 {
1000     if( p_module->i_usage >= 0 )
1001     {
1002         /* This module is already loaded and activated, we can return */
1003         p_module->i_usage++;
1004         return 0;
1005     }
1006
1007     if( p_module->b_builtin )
1008     {
1009         /* A builtin module should always have a refcount >= 0 ! */
1010         msg_Err( p_module, "builtin module \"%s\" has refcount %i",
1011                            p_module->psz_object_name, p_module->i_usage );
1012         return -1;
1013     }
1014
1015 #ifdef HAVE_DYNAMIC_PLUGINS
1016     if( p_module->i_usage != -1 )
1017     {
1018         /* This shouldn't happen. Ever. We have serious problems here. */
1019         msg_Err( p_module, "plugin module \"%s\" has refcount %i",
1020                            p_module->psz_object_name, p_module->i_usage );
1021         return -1;
1022     }
1023
1024     /* i_usage == -1, which means that the module isn't in memory */
1025     if( module_load( p_module->psz_filename, &p_module->handle ) )
1026     {
1027         char psz_buffer[256];
1028
1029         /* The plugin module couldn't be opened */
1030         msg_Err( p_module, "cannot open `%s' (%s)",
1031                  p_module->psz_filename, module_error(psz_buffer) );
1032         return -1;
1033     }
1034
1035     /* FIXME: what to do if the guy modified the plugin while it was
1036      * unloaded ? It makes XMMS crash nastily, perhaps we should try
1037      * to be a bit more clever here. */
1038
1039     /* Everything worked fine ! The module is ready to be used */
1040     p_module->i_usage = 1;
1041 #endif /* HAVE_DYNAMIC_PLUGINS */
1042
1043     return 0;
1044 }
1045
1046 /*****************************************************************************
1047  * UnlockModule: decrease the usage count of a module.
1048  *****************************************************************************
1049  * We decrease the usage count of a module so that we know when a module
1050  * becomes unused and can be hidden.
1051  *****************************************************************************/
1052 static int UnlockModule( module_t * p_module )
1053 {
1054     if( p_module->i_usage <= 0 )
1055     {
1056         /* This shouldn't happen. Ever. We have serious problems here. */
1057         msg_Err( p_module, "trying to call module_Unneed() on \"%s\" "
1058                            "which is not in use", p_module->psz_object_name );
1059         return -1;
1060     }
1061
1062     /* This module is still in use, we can return */
1063     p_module->i_usage--;
1064     p_module->i_unused_delay = 0;
1065
1066     return 0;
1067 }
1068
1069 #ifdef HAVE_DYNAMIC_PLUGINS
1070 /*****************************************************************************
1071  * HideModule: remove a module from memory but keep its structure.
1072  *****************************************************************************
1073  * This function can only be called if i_usage == 0. It will make a call
1074  * to the module's inner module_deactivate() symbol, and then unload it
1075  * from memory. A call to module_Need() will automagically load it again.
1076  *****************************************************************************/
1077 static int HideModule( module_t * p_module )
1078 {
1079     if( p_module->b_builtin )
1080     {
1081         /* A builtin module should never be hidden. */
1082         msg_Err( p_module, "trying to hide builtin module \"%s\"",
1083                            p_module->psz_object_name );
1084         return -1;
1085     }
1086
1087     if( p_module->i_usage >= 1 )
1088     {
1089         msg_Err( p_module, "trying to hide module \"%s\" which is still "
1090                            "in use", p_module->psz_object_name );
1091         return -1;
1092     }
1093
1094     if( p_module->i_usage <= -1 )
1095     {
1096         msg_Err( p_module, "trying to hide module \"%s\" which is already "
1097                            "hidden", p_module->psz_object_name );
1098         return -1;
1099     }
1100
1101     /* Everything worked fine, we can safely unload the module. */
1102     module_unload( p_module->handle );
1103     p_module->i_usage = -1;
1104
1105     return 0;
1106 }
1107
1108 /*****************************************************************************
1109  * CallEntry: call an entry point.
1110  *****************************************************************************
1111  * This function calls a symbol given its name and a module structure. The
1112  * symbol MUST refer to a function returning int and taking a module_t* as
1113  * an argument.
1114  *****************************************************************************/
1115 static int CallEntry( module_t * p_module )
1116 {
1117     static char *psz_name = "vlc_entry" MODULE_SUFFIX;
1118     int (* pf_symbol) ( module_t * p_module );
1119
1120     /* Try to resolve the symbol */
1121     pf_symbol = (int (*)(module_t *)) module_getsymbol( p_module->handle, 
1122                                                         psz_name );
1123
1124     if( pf_symbol == NULL )
1125     {
1126         char psz_buffer[256];
1127
1128         /* We couldn't load the symbol */
1129         msg_Warn( p_module, "cannot find symbol \"%s\" in file `%s' (%s)",
1130                             psz_name, p_module->psz_filename,
1131                             module_error( psz_buffer ) );
1132         return -1;
1133     }
1134
1135     /* We can now try to call the symbol */
1136     if( pf_symbol( p_module ) != 0 )
1137     {
1138         /* With a well-written module we shouldn't have to print an
1139          * additional error message here, but just make sure. */
1140         msg_Err( p_module, "failed calling symbol \"%s\" in file `%s'",
1141                            psz_name, p_module->psz_filename );
1142         return -1;
1143     }
1144
1145     /* Everything worked fine, we can return */
1146     return 0;
1147 }
1148 #endif /* HAVE_DYNAMIC_PLUGINS */
1149