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