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