]> git.sesse.net Git - vlc/blob - src/misc/modules.c
99f08701e981356732a42b424e30540e306ef975
[vlc] / src / misc / modules.c
1 /*****************************************************************************
2  * modules.c : Built-in and plugin modules management functions
3  *****************************************************************************
4  * Copyright (C) 2001 VideoLAN
5  * $Id: modules.c,v 1.55 2002/03/01 00:33:18 massiot 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 <videolan/vlc.h>
37
38 #if !defined( _MSC_VER )
39 #include <dirent.h>
40 #endif
41
42 #if defined(HAVE_DLFCN_H)                                /* Linux, BSD, Hurd */
43 #   include <dlfcn.h>                        /* dlopen(), dlsym(), dlclose() */
44 #   define HAVE_DYNAMIC_PLUGINS
45 #elif defined(HAVE_IMAGE_H)                                          /* BeOS */
46 #   include <image.h>
47 #   define HAVE_DYNAMIC_PLUGINS
48 #elif defined(WIN32) && defined( __MINGW32__ )
49 #   define HAVE_DYNAMIC_PLUGINS
50 #else
51 #   undef HAVE_DYNAMIC_PLUGINS
52 #endif
53
54
55 #include "netutils.h"
56
57 #include "interface.h"
58 #include "intf_playlist.h"
59 #include "intf_eject.h"
60
61 #include "stream_control.h"
62 #include "input_ext-intf.h"
63 #include "input_ext-dec.h"
64 #include "input_ext-plugins.h"
65
66 #include "video.h"
67 #include "video_output.h"
68
69 #include "audio_output.h"
70
71 #include "iso_lang.h"
72
73 #ifdef HAVE_DYNAMIC_PLUGINS
74 #   include "modules_plugin.h"
75 #endif
76 #include "modules_builtin.h"
77
78 /*****************************************************************************
79  * Local prototypes
80  *****************************************************************************/
81 #ifdef HAVE_DYNAMIC_PLUGINS
82 static void AllocateAllPlugins   ( void );
83 static int  AllocatePluginModule ( char * );
84 #endif
85 static int  AllocateBuiltinModule( int ( * ) ( module_t * ),
86                                    int ( * ) ( module_t * ),
87                                    int ( * ) ( module_t * ) );
88 static int  DeleteModule ( module_t * );
89 static int  LockModule   ( module_t * );
90 static int  UnlockModule ( module_t * );
91 #ifdef HAVE_DYNAMIC_PLUGINS
92 static int  HideModule   ( module_t * );
93 static int  CallSymbol   ( module_t *, char * );
94 #endif
95
96 #ifdef HAVE_DYNAMIC_PLUGINS
97 static module_symbols_t symbols;
98 #endif
99
100 /*****************************************************************************
101  * module_InitBank: create the module bank.
102  *****************************************************************************
103  * This function creates a module bank structure which will be filled later
104  * on with all the modules found.
105  *****************************************************************************/
106 void module_InitBank( void )
107 {
108     p_module_bank->first = NULL;
109     p_module_bank->i_count = 0;
110     vlc_mutex_init( &p_module_bank->lock );
111
112     /*
113      * Store the symbols to be exported
114      */
115 #ifdef HAVE_DYNAMIC_PLUGINS
116     STORE_SYMBOLS( &symbols );
117 #endif
118
119     return;
120 }
121
122 /*****************************************************************************
123  * module_LoadMain: load the main program info into the module bank.
124  *****************************************************************************
125  * This function fills the module bank structure with the main module infos.
126  * This is very useful as it will allow us to consider the main program just
127  * as another module, and for instance the configuration options of main will
128  * be available in the module bank structure just as for every other module.
129  *****************************************************************************/
130 void module_LoadMain( void )
131 {
132     AllocateBuiltinModule( InitModule__MODULE_main,
133                            ActivateModule__MODULE_main,
134                            DeactivateModule__MODULE_main );
135 }
136
137 /*****************************************************************************
138  * module_LoadBuiltins: load all modules which we built with.
139  *****************************************************************************
140  * This function fills the module bank structure with the built-in modules.
141  *****************************************************************************/
142 void module_LoadBuiltins( void )
143 {
144     intf_WarnMsg( 2, "module: checking built-in modules" );
145     ALLOCATE_ALL_BUILTINS();
146 }
147
148 /*****************************************************************************
149  * module_LoadPlugins: load all plugin modules we can find.
150  *****************************************************************************
151  * This function fills the module bank structure with the plugin modules.
152  *****************************************************************************/
153 void module_LoadPlugins( void )
154 {
155 #ifdef HAVE_DYNAMIC_PLUGINS
156     intf_WarnMsg( 2, "module: checking plugin modules" );
157     AllocateAllPlugins();
158 #endif
159 }
160
161 /*****************************************************************************
162  * module_EndBank: empty the module bank.
163  *****************************************************************************
164  * This function unloads all unused plugin modules and empties the module
165  * bank in case of success.
166  *****************************************************************************/
167 void module_EndBank( void )
168 {
169     module_t * p_next;
170
171     while( p_module_bank->first != NULL )
172     {
173         if( DeleteModule( p_module_bank->first ) )
174         {
175             /* Module deletion failed */
176             intf_ErrMsg( "module error: `%s' can't be removed, trying harder",
177                          p_module_bank->first->psz_name );
178
179             /* We just free the module by hand. Niahahahahaha. */
180             p_next = p_module_bank->first->next;
181             free(p_module_bank->first);
182             p_module_bank->first = p_next;
183         }
184     }
185
186     /* Destroy the lock */
187     vlc_mutex_destroy( &p_module_bank->lock );
188
189     return;
190 }
191
192 /*****************************************************************************
193  * module_ResetBank: reset the module bank.
194  *****************************************************************************
195  * This function resets the module bank by unloading all unused plugin
196  * modules.
197  *****************************************************************************/
198 void module_ResetBank( void )
199 {
200     intf_ErrMsg( "FIXME: module_ResetBank unimplemented" );
201     return;
202 }
203
204 /*****************************************************************************
205  * module_ManageBank: manage the module bank.
206  *****************************************************************************
207  * This function parses the module bank and hides modules that have been
208  * unused for a while.
209  *****************************************************************************/
210 void module_ManageBank( void )
211 {
212 #ifdef HAVE_DYNAMIC_PLUGINS
213     module_t * p_module;
214
215     /* We take the global lock */
216     vlc_mutex_lock( &p_module_bank->lock );
217
218     /* Parse the module list to see if any modules need to be unloaded */
219     for( p_module = p_module_bank->first ;
220          p_module != NULL ;
221          p_module = p_module->next )
222     {
223         /* If the module is unused and if it is a plugin module... */
224         if( p_module->i_usage == 0 && !p_module->b_builtin )
225         {
226             if( p_module->i_unused_delay < MODULE_HIDE_DELAY )
227             {
228                 p_module->i_unused_delay++;
229             }
230             else
231             {
232                 intf_WarnMsg( 3, "module: hiding unused plugin module `%s'",
233                               p_module->psz_name );
234                 HideModule( p_module );
235
236                 /* Break here, so that we only hide one module at a time */
237                 break;
238             }
239         }
240     }
241
242     /* We release the global lock */
243     vlc_mutex_unlock( &p_module_bank->lock );
244 #endif /* HAVE_DYNAMIC_PLUGINS */
245
246     return;
247 }
248
249 /*****************************************************************************
250  * module_Need: return the best module function, given a capability list.
251  *****************************************************************************
252  * This function returns the module that best fits the asked capabilities.
253  *****************************************************************************/
254 module_t * module_Need( int i_capability, char *psz_name, void *p_data )
255 {
256     typedef struct module_list_s
257     {
258         struct module_s *p_module;
259         struct module_list_s* p_next;
260     } module_list_t;
261     struct module_list_s *p_list, *p_first;
262
263     int i_ret, i_index = 0;
264
265     module_t *p_module;
266     char     *psz_realname = NULL;
267
268     /* We take the global lock */
269     vlc_mutex_lock( &p_module_bank->lock );
270
271     if( psz_name != NULL && *psz_name )
272     {
273         /* A module name was requested. */
274         psz_realname = strdup( psz_name );
275         if( psz_realname )
276         {
277             char *p;
278             p = strchr( psz_realname, ':' );
279             if( p )
280             {
281                 *p = '\0';
282             }
283             psz_name = psz_realname;
284         }
285     }
286
287     /* Sort the modules and test them */
288     p_list = malloc( p_module_bank->i_count * sizeof( module_list_t ) );
289     p_first = NULL;
290
291     /* Parse the module list for capabilities and probe each of them */
292     for( p_module = p_module_bank->first ;
293          p_module != NULL ;
294          p_module = p_module->next )
295     {
296         /* Test that this module can do everything we need */
297         if( !(p_module->i_capabilities & ( 1 << i_capability )) )
298         {
299             continue;
300         }
301
302         /* Test if we have the required CPU */
303         if( (p_module->i_cpu_capabilities & p_main->i_cpu_capabilities)
304               != p_module->i_cpu_capabilities )
305         {
306             continue;
307         }
308
309         /* Test if this plugin exports the required shortcut */
310         if( psz_name != NULL && *psz_name )
311         {
312             boolean_t b_ok = 0;
313             int i_dummy;
314
315             for( i_dummy = 0;
316                  !b_ok && p_module->pp_shortcuts[i_dummy];
317                  i_dummy++ )
318             {
319                 b_ok = !strcmp( psz_name, p_module->pp_shortcuts[i_dummy] );
320             }
321
322             if( !b_ok )
323             {
324                 continue;
325             }
326         }
327
328         /* Test if we requested a particular intf plugin */
329 #if 0
330         if( i_capability == MODULE_CAPABILITY_INTF
331              && p_module->psz_program != NULL
332              && strcmp( p_module->psz_program, p_main->psz_arg0 ) )
333         {
334             continue;
335         }
336 #endif
337
338         /* Store this new module */
339         p_list[ i_index ].p_module = p_module;
340
341         /* Lock it */
342         LockModule( p_module );
343
344         if( i_index == 0 )
345         {
346             p_list[ i_index ].p_next = NULL;
347             p_first = p_list;
348         }
349         else
350         {
351             /* Ok, so at school you learned that quicksort is quick, and
352              * bubble sort sucks raw eggs. But that's when dealing with
353              * thousands of items. Here we have barely 50. */
354             struct module_list_s *p_newlist = p_first;
355
356             if( p_first->p_module->pi_score[i_capability]
357                  < p_module->pi_score[i_capability] )
358             {
359                 p_list[ i_index ].p_next = p_first;
360                 p_first = &p_list[ i_index ];
361             }
362             else
363             {
364                 while( p_newlist->p_next != NULL
365                         && p_newlist->p_next->p_module->pi_score[i_capability]
366                             >= p_module->pi_score[i_capability] )
367                 {
368                     p_newlist = p_newlist->p_next;
369                 }
370
371                 p_list[ i_index ].p_next = p_newlist->p_next;
372                 p_newlist->p_next = &p_list[ i_index ];
373             }
374         }
375
376         i_index++;
377     }
378
379     /* We can release the global lock, module refcount were incremented */
380     vlc_mutex_unlock( &p_module_bank->lock );
381
382     /* Parse the linked list and use the first successful module */
383     while( p_first != NULL )
384     {
385         /* Test the requested capability */
386         switch( i_capability )
387         {
388             case MODULE_CAPABILITY_ACCESS:
389                 i_ret = p_first->p_module->p_functions->access.functions.
390                               access.pf_open( (struct input_thread_s *)p_data );
391                 break;
392
393             case MODULE_CAPABILITY_DEMUX:
394                 i_ret = p_first->p_module->p_functions->demux.functions.
395                               demux.pf_init( (struct input_thread_s *)p_data );
396                 break;
397
398             case MODULE_CAPABILITY_NETWORK:
399                 i_ret = p_first->p_module->p_functions->network.functions.
400                               network.pf_open( (struct network_socket_s *)p_data );
401                 break;
402
403             case MODULE_CAPABILITY_DECODER:
404                 i_ret = p_first->p_module->p_functions->dec.functions.
405                               dec.pf_probe( (u8 *)p_data );
406                 break;
407
408             case MODULE_CAPABILITY_INTF:
409                 i_ret = p_first->p_module->p_functions->intf.functions.
410                               intf.pf_open( (struct intf_thread_s *)p_data );
411                 break;
412
413             case MODULE_CAPABILITY_AOUT:
414                 i_ret = p_first->p_module->p_functions->aout.functions.
415                               aout.pf_open( (struct aout_thread_s *)p_data );
416                 break;
417
418             case MODULE_CAPABILITY_VOUT:
419                 i_ret = p_first->p_module->p_functions->vout.functions.
420                               vout.pf_create( (struct vout_thread_s *)p_data );
421                 break;
422
423             case MODULE_CAPABILITY_CHROMA:
424                 i_ret = p_first->p_module->p_functions->chroma.functions.
425                               chroma.pf_init( (struct vout_thread_s *)p_data );
426                 break;
427
428             case MODULE_CAPABILITY_IDCT:
429             case MODULE_CAPABILITY_IMDCT:
430             case MODULE_CAPABILITY_MOTION:
431             case MODULE_CAPABILITY_DOWNMIX:
432             case MODULE_CAPABILITY_MEMCPY:
433                 /* This one always works */
434                 i_ret = 0;
435                 break;
436
437             default:
438                 intf_ErrMsg( "module error: unknown module type %i",
439                              i_capability );
440                 i_ret = -1;
441                 break;
442         }
443
444         /* If the high score was broken, we have a new champion */
445         if( i_ret == 0 )
446         {
447             break;
448         }
449         else
450         {
451             UnlockModule( p_first->p_module );
452         }
453
454         p_first = p_first->p_next;
455     }
456
457     /* Store the locked module value */
458     if( p_first != NULL )
459     {
460         p_module = p_first->p_module;
461         p_first = p_first->p_next;
462     }
463     else
464     {
465         p_module = NULL;
466     }
467
468     /* Unlock the remaining modules */
469     while( p_first != NULL )
470     {
471         UnlockModule( p_first->p_module );
472         p_first = p_first->p_next;
473     }
474
475     free( p_list );
476
477     if( p_module != NULL )
478     {
479         intf_WarnMsg( 1, "module: locking %s module `%s'",
480                          GetCapabilityName( i_capability ),
481                          p_module->psz_name );
482     }
483     else if( psz_name != NULL && *psz_name )
484     {
485         intf_ErrMsg( "module error: requested %s module `%s' unavailable",
486                      GetCapabilityName( i_capability ), psz_name );
487     }
488
489     if( psz_realname )
490     {
491         free( psz_realname );
492     }
493
494     /* Don't forget that the module is still locked */
495     return( p_module );
496 }
497
498 /*****************************************************************************
499  * module_Unneed: decrease the usage count of a module.
500  *****************************************************************************
501  * This function must be called by the thread that called module_Need, to
502  * decrease the reference count and allow for hiding of modules.
503  *****************************************************************************/
504 void module_Unneed( module_t * p_module )
505 {
506     /* We take the global lock */
507     vlc_mutex_lock( &p_module_bank->lock );
508
509     /* Just unlock the module - we can't do anything if it fails,
510      * so there is no need to check the return value. */
511     UnlockModule( p_module );
512
513     intf_WarnMsg( 1, "module: unlocking module `%s'", p_module->psz_name );
514
515     /* We release the global lock */
516     vlc_mutex_unlock( &p_module_bank->lock );
517
518     return;
519 }
520
521 /*****************************************************************************
522  * Following functions are local.
523  *****************************************************************************/
524
525 /*****************************************************************************
526  * AllocateAllPlugins: load all plugin modules we can find.
527  *****************************************************************************/
528 #ifdef HAVE_DYNAMIC_PLUGINS
529 static void AllocateAllPlugins( void )
530 {
531     static char * path[] = { ".", "plugins", PLUGIN_PATH, NULL, NULL };
532
533     char **         ppsz_path = path;
534     char *          psz_fullpath;
535     char *          psz_file;
536 #if defined( SYS_BEOS ) || defined( SYS_DARWIN )
537     char *          psz_vlcpath = system_GetProgramPath();
538     int             i_vlclen = strlen( psz_vlcpath );
539     boolean_t       b_notinroot;
540 #endif
541     DIR *           dir;
542     struct dirent * file;
543
544     for( ; *ppsz_path != NULL ; ppsz_path++ )
545     {
546         /* Store strlen(*ppsz_path) for later use. */
547         int i_dirlen = strlen( *ppsz_path );
548
549 #if defined( SYS_BEOS ) || defined( SYS_DARWIN )
550         b_notinroot = 0;
551         /* Under BeOS, we need to add beos_GetProgramPath() to access
552          * files under the current directory */
553         if( ( i_dirlen > 1 ) && strncmp( *ppsz_path, "/", 1 ) )
554         {
555             i_dirlen += i_vlclen + 2;
556             b_notinroot = 1;
557
558             psz_fullpath = malloc( i_dirlen );
559             if( psz_fullpath == NULL )
560             {
561                 continue;
562             }
563             sprintf( psz_fullpath, "%s/%s", psz_vlcpath, *ppsz_path );
564         }
565         else
566 #endif
567         {
568             psz_fullpath = *ppsz_path;
569         }
570
571         intf_WarnMsg( 1, "module: browsing `%s'", psz_fullpath );
572
573         if( (dir = opendir( psz_fullpath )) )
574         {
575             /* Parse the directory and try to load all files it contains. */
576             while( (file = readdir( dir )) )
577             {
578                 int i_filelen = strlen( file->d_name );
579
580                 /* We only load files ending with ".so" */
581                 if( i_filelen > 3
582                         && !strncmp( file->d_name + i_filelen - 3, ".so", 3 ) )
583                 {
584                     psz_file = malloc( i_dirlen + i_filelen + 2 );
585                     if( psz_file == NULL )
586                     {
587                         continue;
588                     }
589                     sprintf( psz_file, "%s/%s", psz_fullpath, file->d_name );
590
591                     /* We created a nice filename -- now we just try to load
592                      * it as a plugin module. */
593                     AllocatePluginModule( psz_file );
594
595                     /* We don't care if the allocation succeeded */
596                     free( psz_file );
597                 }
598             }
599
600             /* Close the directory if successfully opened */
601             closedir( dir );
602         }
603
604 #if defined( SYS_BEOS ) || defined( SYS_DARWIN )
605         if( b_notinroot )
606         {
607             free( psz_fullpath );
608         }
609 #endif
610     }
611 }
612
613 /*****************************************************************************
614  * AllocatePluginModule: load a module into memory and initialize it.
615  *****************************************************************************
616  * This function loads a dynamically loadable module and allocates a structure
617  * for its information data. The module can then be handled by module_Need,
618  * module_Unneed and HideModule. It can be removed by DeleteModule.
619  *****************************************************************************/
620 static int AllocatePluginModule( char * psz_filename )
621 {
622     char **pp_shortcut;
623     module_t * p_module, * p_othermodule;
624     module_handle_t handle;
625
626     /* Try to dynamically load the module. */
627     if( module_load( psz_filename, &handle ) )
628     {
629         /* The plugin module couldn't be opened */
630         intf_WarnMsg( 1, "module warning: cannot open %s (%s)",
631                          psz_filename, module_error() );
632         return( -1 );
633     }
634
635     /* Now that we have successfully loaded the module, we can
636      * allocate a structure for it */ 
637     p_module = malloc( sizeof( module_t ) );
638     if( p_module == NULL )
639     {
640         intf_ErrMsg( "module error: can't allocate p_module" );
641         module_unload( handle );
642         return( -1 );
643     }
644
645     /* We need to fill these since they may be needed by CallSymbol() */
646     p_module->is.plugin.psz_filename = psz_filename;
647     p_module->is.plugin.handle = handle;
648     p_module->p_symbols = &symbols;
649
650     /* Initialize the module : fill p_module->psz_name, default config, etc. */
651     if( CallSymbol( p_module, "InitModule" MODULE_SUFFIX ) != 0 )
652     {
653         /* We couldn't call InitModule() */
654         free( p_module );
655         module_unload( handle );
656         return( -1 );
657     }
658
659     /* Check that we don't already have a module with this name */
660     for( p_othermodule = p_module_bank->first ;
661          p_othermodule != NULL ;
662          p_othermodule = p_othermodule->next )
663     {
664         if( !strcmp( p_othermodule->psz_name, p_module->psz_name ) )
665         {
666             intf_WarnMsg( 5, "module warning: cannot load %s, a module named "
667                              "`%s' already exists",
668                              psz_filename, p_module->psz_name );
669             free( p_module );
670             module_unload( handle );
671             return( -1 );
672         }
673     }
674
675     /* Activate the module : fill the capability structure, etc. */
676     if( CallSymbol( p_module, "ActivateModule" MODULE_SUFFIX ) != 0 )
677     {
678         /* We couldn't call ActivateModule() */
679         free( p_module );
680         module_unload( handle );
681         return( -1 );
682     }
683
684     for( pp_shortcut = p_module->pp_shortcuts ; *pp_shortcut ; pp_shortcut++ )
685     {
686         *pp_shortcut = strdup( *pp_shortcut );
687     }
688
689     /* We strdup() these entries so that they are still valid when the
690      * module is unloaded. */
691     p_module->is.plugin.psz_filename =
692             strdup( p_module->is.plugin.psz_filename );
693     p_module->psz_name = strdup( p_module->psz_name );
694     p_module->psz_longname = strdup( p_module->psz_longname );
695
696     if( p_module->is.plugin.psz_filename == NULL 
697             || p_module->psz_name == NULL
698             || p_module->psz_longname == NULL )
699     {
700         intf_ErrMsg( "module error: can't duplicate strings" );
701
702         free( p_module->is.plugin.psz_filename );
703         free( p_module->psz_name );
704         free( p_module->psz_longname );
705         free( p_module->psz_program );
706
707         free( p_module );
708         module_unload( handle );
709         return( -1 );
710     }
711
712     if( p_module->psz_program != NULL )
713     {
714         p_module->psz_program = strdup( p_module->psz_program );
715     }
716
717     /* Everything worked fine ! The module is ready to be added to the list. */
718     p_module->i_usage = 0;
719     p_module->i_unused_delay = 0;
720
721     p_module->b_builtin = 0;
722
723     /* Link module into the linked list */
724     if( p_module_bank->first != NULL )
725     {
726         p_module_bank->first->prev = p_module;
727     }
728     p_module->next = p_module_bank->first;
729     p_module->prev = NULL;
730     p_module_bank->first = p_module;
731     p_module_bank->i_count++;
732
733     /* Immediate message so that a slow module doesn't make the user wait */
734     intf_WarnMsg( 2, "module: new plugin module `%s', %s",
735                      p_module->psz_name, p_module->psz_longname );
736
737     return( 0 );
738 }
739 #endif /* HAVE_DYNAMIC_PLUGINS */
740
741 /*****************************************************************************
742  * AllocateBuiltinModule: initialize a built-in module.
743  *****************************************************************************
744  * This function registers a built-in module and allocates a structure
745  * for its information data. The module can then be handled by module_Need,
746  * module_Unneed and HideModule. It can be removed by DeleteModule.
747  *****************************************************************************/
748 static int AllocateBuiltinModule( int ( *pf_init ) ( module_t * ),
749                                   int ( *pf_activate ) ( module_t * ),
750                                   int ( *pf_deactivate ) ( module_t * ) )
751 {
752     module_t * p_module, * p_othermodule;
753
754     /* Now that we have successfully loaded the module, we can
755      * allocate a structure for it */ 
756     p_module = malloc( sizeof( module_t ) );
757     if( p_module == NULL )
758     {
759         intf_ErrMsg( "module error: can't allocate p_module" );
760         return( -1 );
761     }
762
763     /* Initialize the module : fill p_module->psz_name, etc. */
764     if( pf_init( p_module ) != 0 )
765     {
766         /* With a well-written module we shouldn't have to print an
767          * additional error message here, but just make sure. */
768         intf_ErrMsg( "module error: failed calling init in builtin module" );
769         free( p_module );
770         return( -1 );
771     }
772
773     /* Check that we don't already have a module with this name */
774     for( p_othermodule = p_module_bank->first ;
775          p_othermodule != NULL ;
776          p_othermodule = p_othermodule->next )
777     {
778         if( !strcmp( p_othermodule->psz_name, p_module->psz_name ) )
779         {
780             intf_WarnMsg( 5, "module warning: cannot load builtin `%s', a "
781                              "module named `%s' already exists",
782                              p_module->psz_name, p_module->psz_name );
783             free( p_module );
784             return( -1 );
785         }
786     }
787
788     if( pf_activate( p_module ) != 0 )
789     {
790         /* With a well-written module we shouldn't have to print an
791          * additional error message here, but just make sure. */
792         intf_ErrMsg( "module error: failed calling activate "
793                      "in builtin module" );
794         free( p_module );
795         return( -1 );
796     }
797
798     /* Everything worked fine ! The module is ready to be added to the list. */
799     p_module->i_usage = 0;
800     p_module->i_unused_delay = 0;
801
802     p_module->b_builtin = 1;
803     p_module->is.builtin.pf_deactivate = pf_deactivate;
804
805     /* Link module into the linked list */
806     if( p_module_bank->first != NULL )
807     {
808         p_module_bank->first->prev = p_module;
809     }
810     p_module->next = p_module_bank->first;
811     p_module->prev = NULL;
812     p_module_bank->first = p_module;
813     p_module_bank->i_count++;
814
815     /* Immediate message so that a slow module doesn't make the user wait */
816     intf_WarnMsg( 2, "module: new builtin module `%s', %s",
817                      p_module->psz_name, p_module->psz_longname );
818
819     return( 0 );
820 }
821
822 /*****************************************************************************
823  * DeleteModule: delete a module and its structure.
824  *****************************************************************************
825  * This function can only be called if i_usage <= 0.
826  *****************************************************************************/
827 static int DeleteModule( module_t * p_module )
828 {
829     /* If the module is not in use but is still in memory, we first have
830      * to hide it and remove it from memory before we can free the
831      * data structure. */
832     if( p_module->b_builtin )
833     {
834         if( p_module->i_usage != 0 )
835         {
836             intf_ErrMsg( "module error: trying to free builtin module `%s' with"
837                          " usage %i", p_module->psz_name, p_module->i_usage );
838             return( -1 );
839         }
840         else
841         {
842             /* We deactivate the module now. */
843             p_module->is.builtin.pf_deactivate( p_module );
844         }
845     }
846 #ifdef HAVE_DYNAMIC_PLUGINS
847     else
848     {
849         if( p_module->i_usage >= 1 )
850         {
851             intf_ErrMsg( "module error: trying to free module `%s' which is"
852                          " still in use", p_module->psz_name );
853             return( -1 );
854         }
855
856         /* Two possibilities here: i_usage == -1 and the module is already
857          * unloaded, we can continue, or i_usage == 0, and we have to hide
858          * the module before going on. */
859         if( p_module->i_usage == 0 )
860         {
861             if( HideModule( p_module ) != 0 )
862             {
863                 return( -1 );
864             }
865         }
866     }
867 #endif
868
869     /* Unlink the module from the linked list. */
870     if( p_module->prev != NULL )
871     {
872         p_module->prev->next = p_module->next;
873     }
874     else
875     {
876         p_module_bank->first = p_module->next;
877     }
878
879     if( p_module->next != NULL )
880     {
881         p_module->next->prev = p_module->prev;
882     }
883
884     p_module_bank->i_count--;
885
886     /* We free the structures that we strdup()ed in Allocate*Module(). */
887 #ifdef HAVE_DYNAMIC_PLUGINS
888     if( !p_module->b_builtin )
889     {
890         char **pp_shortcut = p_module->pp_shortcuts;
891
892         for( ; *pp_shortcut ; pp_shortcut++ )
893         {
894             free( *pp_shortcut );
895         }
896
897         free( p_module->is.plugin.psz_filename );
898         free( p_module->psz_name );
899         free( p_module->psz_longname );
900         free( p_module->psz_program );
901     }
902 #endif
903
904     free( p_module );
905
906     return( 0 );
907 }
908
909 /*****************************************************************************
910  * LockModule: increase the usage count of a module and load it if needed.
911  *****************************************************************************
912  * This function has to be called before a thread starts using a module. If
913  * the module is already loaded, we just increase its usage count. If it isn't
914  * loaded, we have to dynamically open it and initialize it.
915  * If you successfully call LockModule() at any moment, be careful to call
916  * UnlockModule() when you don't need it anymore.
917  *****************************************************************************/
918 static int LockModule( module_t * p_module )
919 {
920     if( p_module->i_usage >= 0 )
921     {
922         /* This module is already loaded and activated, we can return */
923         p_module->i_usage++;
924         return( 0 );
925     }
926
927     if( p_module->b_builtin )
928     {
929         /* A built-in module should always have a refcount >= 0 ! */
930         intf_ErrMsg( "module error: built-in module `%s' has refcount %i",
931                      p_module->psz_name, p_module->i_usage );
932         return( -1 );
933     }
934
935 #ifdef HAVE_DYNAMIC_PLUGINS
936     if( p_module->i_usage != -1 )
937     {
938         /* This shouldn't happen. Ever. We have serious problems here. */
939         intf_ErrMsg( "module error: plugin module `%s' has refcount %i",
940                      p_module->psz_name, p_module->i_usage );
941         return( -1 );
942     }
943
944     /* i_usage == -1, which means that the module isn't in memory */
945     if( module_load( p_module->is.plugin.psz_filename,
946                      &p_module->is.plugin.handle ) )
947     {
948         /* The plugin module couldn't be opened */
949         intf_ErrMsg( "module error: cannot open %s (%s)",
950                      p_module->is.plugin.psz_filename, module_error() );
951         return( -1 );
952     }
953
954     /* FIXME: what to do if the guy modified the plugin while it was
955      * unloaded ? It makes XMMS crash nastily, perhaps we should try
956      * to be a bit more clever here. */
957
958     /* Activate the module : fill the capability structure, etc. */
959     if( CallSymbol( p_module, "ActivateModule" MODULE_SUFFIX ) != 0 )
960     {
961         /* We couldn't call ActivateModule() -- looks nasty, but
962          * we can't do much about it. Just try to unload module. */
963         module_unload( p_module->is.plugin.handle );
964         p_module->i_usage = -1;
965         return( -1 );
966     }
967
968     /* Everything worked fine ! The module is ready to be used */
969     p_module->i_usage = 1;
970 #endif /* HAVE_DYNAMIC_PLUGINS */
971
972     return( 0 );
973 }
974
975 /*****************************************************************************
976  * UnlockModule: decrease the usage count of a module.
977  *****************************************************************************
978  * We decrease the usage count of a module so that we know when a module
979  * becomes unused and can be hidden.
980  *****************************************************************************/
981 static int UnlockModule( module_t * p_module )
982 {
983     if( p_module->i_usage <= 0 )
984     {
985         /* This shouldn't happen. Ever. We have serious problems here. */
986         intf_ErrMsg( "module error: trying to call module_Unneed() on `%s'"
987                      " which isn't even in use", p_module->psz_name );
988         return( -1 );
989     }
990
991     /* This module is still in use, we can return */
992     p_module->i_usage--;
993     p_module->i_unused_delay = 0;
994
995     return( 0 );
996 }
997
998 #ifdef HAVE_DYNAMIC_PLUGINS
999 /*****************************************************************************
1000  * HideModule: remove a module from memory but keep its structure.
1001  *****************************************************************************
1002  * This function can only be called if i_usage == 0. It will make a call
1003  * to the module's inner DeactivateModule() symbol, and then unload it
1004  * from memory. A call to module_Need() will automagically load it again.
1005  *****************************************************************************/
1006 static int HideModule( module_t * p_module )
1007 {
1008     if( p_module->b_builtin )
1009     {
1010         /* A built-in module should never be hidden. */
1011         intf_ErrMsg( "module error: trying to hide built-in module `%s'",
1012                      p_module->psz_name );
1013         return( -1 );
1014     }
1015
1016     if( p_module->i_usage >= 1 )
1017     {
1018         intf_ErrMsg( "module error: trying to hide module `%s' which is still"
1019                      " in use", p_module->psz_name );
1020         return( -1 );
1021     }
1022
1023     if( p_module->i_usage <= -1 )
1024     {
1025         intf_ErrMsg( "module error: trying to hide module `%s' which is already"
1026                      " hidden", p_module->psz_name );
1027         return( -1 );
1028     }
1029
1030     /* Deactivate the module : free the capability structure, etc. */
1031     if( CallSymbol( p_module, "DeactivateModule" MODULE_SUFFIX ) != 0 )
1032     {
1033         /* We couldn't call DeactivateModule() -- looks nasty, but
1034          * we can't do much about it. Just try to unload module anyway. */
1035         module_unload( p_module->is.plugin.handle );
1036         p_module->i_usage = -1;
1037         return( -1 );
1038     }
1039
1040     /* Everything worked fine, we can safely unload the module. */
1041     module_unload( p_module->is.plugin.handle );
1042     p_module->i_usage = -1;
1043
1044     return( 0 );
1045 }
1046
1047 /*****************************************************************************
1048  * CallSymbol: calls a module symbol.
1049  *****************************************************************************
1050  * This function calls a symbol given its name and a module structure. The
1051  * symbol MUST refer to a function returning int and taking a module_t* as
1052  * an argument.
1053  *****************************************************************************/
1054 static int CallSymbol( module_t * p_module, char * psz_name )
1055 {
1056     int (* pf_symbol) ( module_t * p_module );
1057
1058     /* Try to resolve the symbol */
1059     pf_symbol = module_getsymbol( p_module->is.plugin.handle, psz_name );
1060
1061     if( pf_symbol == NULL )
1062     {
1063         /* We couldn't load the symbol */
1064         intf_WarnMsg( 1, "module warning: "
1065                          "cannot find symbol %s in module %s (%s)",
1066                          psz_name, p_module->is.plugin.psz_filename,
1067                          module_error() );
1068         return( -1 );
1069     }
1070
1071     /* We can now try to call the symbol */
1072     if( pf_symbol( p_module ) != 0 )
1073     {
1074         /* With a well-written module we shouldn't have to print an
1075          * additional error message here, but just make sure. */
1076         intf_ErrMsg( "module error: failed calling symbol %s in module %s",
1077                      psz_name, p_module->is.plugin.psz_filename );
1078         return( -1 );
1079     }
1080
1081     /* Everything worked fine, we can return */
1082     return( 0 );
1083 }
1084 #endif /* HAVE_DYNAMIC_PLUGINS */
1085