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