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