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