]> git.sesse.net Git - vlc/blob - src/modules/modules.c
update module LIST file.
[vlc] / src / modules / modules.c
1 /*****************************************************************************
2  * modules.c : Builtin and plugin modules management functions
3  *****************************************************************************
4  * Copyright (C) 2001-2007 the VideoLAN team
5  * $Id$
6  *
7  * Authors: Sam Hocevar <sam@zoy.org>
8  *          Ethan C. Baldridge <BaldridgeE@cadmus.com>
9  *          Hans-Peter Jansen <hpj@urpla.net>
10  *          Gildas Bazin <gbazin@videolan.org>
11  *
12  * This program is free software; you can redistribute it and/or modify
13  * it under the terms of the GNU General Public License as published by
14  * the Free Software Foundation; either version 2 of the License, or
15  * (at your option) any later version.
16  *
17  * This program is distributed in the hope that it will be useful,
18  * but WITHOUT ANY WARRANTY; without even the implied warranty of
19  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20  * GNU General Public License for more details.
21  *
22  * You should have received a copy of the GNU General Public License
23  * along with this program; if not, write to the Free Software
24  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
25  *****************************************************************************/
26
27 #ifdef HAVE_CONFIG_H
28 # include "config.h"
29 #endif
30
31 #include <vlc/vlc.h>
32 #include "libvlc.h"
33
34 /* Some faulty libcs have a broken struct dirent when _FILE_OFFSET_BITS
35  * is set to 64. Don't try to be cleverer. */
36 #ifdef _FILE_OFFSET_BITS
37 #undef _FILE_OFFSET_BITS
38 #endif
39
40 #include <stdlib.h>                                      /* free(), strtol() */
41 #include <stdio.h>                                              /* sprintf() */
42 #include <string.h>                                              /* strdup() */
43 #include <assert.h>
44
45 #ifdef HAVE_DIRENT_H
46 #   include <dirent.h>
47 #endif
48
49 #ifdef HAVE_SYS_TYPES_H
50 #   include <sys/types.h>
51 #endif
52 #ifdef HAVE_SYS_STAT_H
53 #   include <sys/stat.h>
54 #endif
55 #ifdef HAVE_UNISTD_H
56 #   include <unistd.h>
57 #endif
58
59 #if !defined(HAVE_DYNAMIC_PLUGINS)
60     /* no support for plugins */
61 #elif defined(HAVE_DL_DYLD)
62 #   if defined(HAVE_MACH_O_DYLD_H)
63 #       include <mach-o/dyld.h>
64 #   endif
65 #elif defined(HAVE_DL_BEOS)
66 #   if defined(HAVE_IMAGE_H)
67 #       include <image.h>
68 #   endif
69 #elif defined(HAVE_DL_WINDOWS)
70 #   include <windows.h>
71 #elif defined(HAVE_DL_DLOPEN)
72 #   if defined(HAVE_DLFCN_H) /* Linux, BSD, Hurd */
73 #       include <dlfcn.h>
74 #   endif
75 #   if defined(HAVE_SYS_DL_H)
76 #       include <sys/dl.h>
77 #   endif
78 #elif defined(HAVE_DL_SHL_LOAD)
79 #   if defined(HAVE_DL_H)
80 #       include <dl.h>
81 #   endif
82 #endif
83
84 #include "config/configuration.h"
85
86 #include "vlc_charset.h"
87
88 #include "modules/modules.h"
89 #include "modules/builtin.h"
90
91 /*****************************************************************************
92  * Local prototypes
93  *****************************************************************************/
94 #ifdef HAVE_DYNAMIC_PLUGINS
95 static void AllocateAllPlugins  ( vlc_object_t * );
96 static void AllocatePluginDir   ( vlc_object_t *, const char *, int );
97 static int  AllocatePluginFile  ( vlc_object_t *, char *, int64_t, int64_t );
98 static module_t * AllocatePlugin( vlc_object_t *, char * );
99 #endif
100 static int  AllocateBuiltinModule( vlc_object_t *, int ( * ) ( module_t * ) );
101 static int  DeleteModule ( module_t *, vlc_bool_t );
102 #ifdef HAVE_DYNAMIC_PLUGINS
103 static void   DupModule        ( module_t * );
104 static void   UndupModule      ( module_t * );
105 #endif
106
107 /**
108  * Init bank
109  *
110  * Creates a module bank structure which will be filled later
111  * on with all the modules found.
112  * \param p_this vlc object structure
113  * \return nothing
114  */
115 void __module_InitBank( vlc_object_t *p_this )
116 {
117     module_bank_t *p_bank = NULL;
118     libvlc_global_data_t *p_libvlc_global = vlc_global();
119
120     vlc_mutex_t *lock = var_AcquireMutex( "libvlc" );
121
122     if( p_libvlc_global->p_module_bank == NULL )
123     {
124         p_bank = vlc_object_create( p_this, sizeof(module_bank_t) );
125         p_bank->psz_object_name = "module bank";
126         p_bank->i_usage = 1;
127         p_bank->i_cache = p_bank->i_loaded_cache = 0;
128         p_bank->pp_cache = p_bank->pp_loaded_cache = NULL;
129         p_bank->b_cache = p_bank->b_cache_dirty =
130         p_bank->b_cache_delete = VLC_FALSE;
131
132         /* Everything worked, attach the object */
133         p_libvlc_global->p_module_bank = p_bank;
134         vlc_object_attach( p_bank, p_libvlc_global );
135
136         /* Fills the module bank structure with the main module infos.
137          * This is very useful as it will allow us to consider the main
138          * library just as another module, and for instance the configuration
139          * options of main will be available in the module bank structure just
140          * as for every other module. */
141         AllocateBuiltinModule( p_this, vlc_entry__main );
142     }
143     else
144         p_libvlc_global->p_module_bank->i_usage++;
145
146     vlc_mutex_unlock( lock );
147 }
148
149
150 /**
151  * End bank
152  *
153  * Unloads all unused plugin modules and empties the module
154  * bank in case of success.
155  * \param p_this vlc object structure
156  * \return nothing
157  */
158 void __module_EndBank( vlc_object_t *p_this )
159 {
160     module_t * p_next = NULL;
161     libvlc_global_data_t *p_libvlc_global = vlc_global();
162
163     vlc_mutex_t *lock = var_AcquireMutex( "libvlc" );
164     if( !p_libvlc_global->p_module_bank )
165     {
166         vlc_mutex_unlock( lock );
167         return;
168     }
169     if( --p_libvlc_global->p_module_bank->i_usage )
170     {
171         vlc_mutex_unlock( lock );
172         return;
173     }
174     vlc_mutex_unlock( lock );
175
176     /* Save the configuration */
177     config_AutoSaveConfigFile( p_this );
178
179 #ifdef HAVE_DYNAMIC_PLUGINS
180 # define p_bank p_libvlc_global->p_module_bank
181     if( p_bank->b_cache ) CacheSave( p_this );
182     while( p_bank->i_loaded_cache-- )
183     {
184         if( p_bank->pp_loaded_cache[p_bank->i_loaded_cache] )
185         {
186             DeleteModule(
187                     p_bank->pp_loaded_cache[p_bank->i_loaded_cache]->p_module,
188                     p_bank->pp_loaded_cache[p_bank->i_loaded_cache]->b_used );
189             free( p_bank->pp_loaded_cache[p_bank->i_loaded_cache]->psz_file );
190             free( p_bank->pp_loaded_cache[p_bank->i_loaded_cache] );
191             p_bank->pp_loaded_cache[p_bank->i_loaded_cache] = NULL;
192         }
193     }
194     if( p_bank->pp_loaded_cache )
195     {
196         free( p_bank->pp_loaded_cache );
197         p_bank->pp_loaded_cache = NULL;
198     }
199     while( p_bank->i_cache-- )
200     {
201         free( p_bank->pp_cache[p_bank->i_cache]->psz_file );
202         free( p_bank->pp_cache[p_bank->i_cache] );
203         p_bank->pp_cache[p_bank->i_cache] = NULL;
204     }
205     if( p_bank->pp_cache )
206     {
207         free( p_bank->pp_cache );
208         p_bank->pp_cache = NULL;
209     }
210 # undef p_bank
211 #endif
212
213     vlc_object_detach( p_libvlc_global->p_module_bank );
214
215     while( p_libvlc_global->p_module_bank->i_children )
216     {
217         p_next = (module_t *)p_libvlc_global->p_module_bank->pp_children[0];
218
219         if( DeleteModule( p_next, VLC_TRUE ) )
220         {
221             /* Module deletion failed */
222             msg_Err( p_this, "module \"%s\" can't be removed, trying harder",
223                      p_next->psz_object_name );
224
225             /* We just free the module by hand. Niahahahahaha. */
226             vlc_object_detach( p_next );
227             vlc_object_release( p_next );
228         }
229     }
230
231     vlc_object_release( p_libvlc_global->p_module_bank );
232     p_libvlc_global->p_module_bank = NULL;
233 }
234
235 /**
236  * Load all modules which we built with.
237  *
238  * Fills the module bank structure with the builtin modules.
239  * \param p_this vlc object structure
240  * \return nothing
241  */
242 void __module_LoadBuiltins( vlc_object_t * p_this )
243 {
244     libvlc_global_data_t *p_libvlc_global = vlc_global();
245
246     vlc_mutex_t *lock = var_AcquireMutex( "libvlc" );
247     if( p_libvlc_global->p_module_bank->b_builtins )
248     {
249         vlc_mutex_unlock( lock );
250         return;
251     }
252     p_libvlc_global->p_module_bank->b_builtins = VLC_TRUE;
253     vlc_mutex_unlock( lock );
254
255     msg_Dbg( p_this, "checking builtin modules" );
256     ALLOCATE_ALL_BUILTINS();
257 }
258
259 /**
260  * Load all plugins
261  *
262  * Load all plugin modules we can find.
263  * Fills the module bank structure with the plugin modules.
264  * \param p_this vlc object structure
265  * \return nothing
266  */
267 void __module_LoadPlugins( vlc_object_t * p_this )
268 {
269 #ifdef HAVE_DYNAMIC_PLUGINS
270     libvlc_global_data_t *p_libvlc_global = vlc_global();
271
272     vlc_mutex_t *lock = var_AcquireMutex( "libvlc" );
273     if( p_libvlc_global->p_module_bank->b_plugins )
274     {
275         vlc_mutex_unlock( lock );
276         return;
277     }
278     p_libvlc_global->p_module_bank->b_plugins = VLC_TRUE;
279     vlc_mutex_unlock( lock );
280
281     msg_Dbg( p_this, "checking plugin modules" );
282
283     if( config_GetInt( p_this, "plugins-cache" ) )
284         p_libvlc_global->p_module_bank->b_cache = VLC_TRUE;
285
286     if( p_libvlc_global->p_module_bank->b_cache ||
287         p_libvlc_global->p_module_bank->b_cache_delete ) CacheLoad( p_this );
288
289     AllocateAllPlugins( p_this );
290 #endif
291 }
292
293 /**
294  * Checks whether a module implements a capability.
295  *
296  * \param m the module
297  * \param cap the capability to check
298  * \return TRUE if the module have the capability
299  */
300 vlc_bool_t module_IsCapable( const module_t *m, const char *cap )
301 {
302     return !strcmp( m->psz_capability, cap );
303 }
304
305 /**
306  * Get the internal name of a module
307  *
308  * \param m the module
309  * \return the module name
310  */
311 const char *module_GetObjName( const module_t *m )
312 {
313     return m->psz_object_name;
314 }
315
316 /**
317  * Get the human-friendly name of a module.
318  *
319  * \param m the module
320  * \param long_name TRUE to have the long name of the module
321  * \return the short or long name of the module
322  */
323 const char *module_GetName( const module_t *m, vlc_bool_t long_name )
324 {
325     if( long_name && ( m->psz_longname != NULL) )
326         return m->psz_longname;
327
328     return m->psz_shortname ?: m->psz_object_name;
329 }
330
331 /**
332  * Get the help for a module
333  *
334  * \param m the module
335  * \return the help
336  */
337 const char *module_GetHelp( const module_t *m )
338 {
339     return m->psz_help;
340 }
341
342 /**
343  * module Need
344  *
345  * Return the best module function, given a capability list.
346  * \param p_this the vlc object
347  * \param psz_capability list of capabilities needed
348  * \param psz_name name of the module asked
349  * \param b_strict TRUE yto use the strict mode
350  * \return the module or NULL in case of a failure
351  */
352 module_t * __module_Need( vlc_object_t *p_this, const char *psz_capability,
353                           const char *psz_name, vlc_bool_t b_strict )
354 {
355     typedef struct module_list_t module_list_t;
356
357     struct module_list_t
358     {
359         module_t *p_module;
360         int i_score;
361         vlc_bool_t b_force;
362         module_list_t *p_next;
363     };
364
365     module_list_t *p_list, *p_first, *p_tmp;
366     vlc_list_t *p_all;
367
368     int i_which_module, i_index = 0;
369
370     module_t *p_module;
371
372     int   i_shortcuts = 0;
373     char *psz_shortcuts = NULL, *psz_var = NULL, *psz_alias = NULL;
374     vlc_bool_t b_force_backup = p_this->b_force;
375
376
377     /* Deal with variables */
378     if( psz_name && psz_name[0] == '$' )
379     {
380         vlc_value_t val;
381         var_Create( p_this, psz_name + 1, VLC_VAR_MODULE | VLC_VAR_DOINHERIT );
382         var_Get( p_this, psz_name + 1, &val );
383         psz_var = val.psz_string;
384         psz_name = psz_var;
385     }
386
387     /* Count how many different shortcuts were asked for */
388     if( psz_name && *psz_name )
389     {
390         char *psz_parser, *psz_last_shortcut;
391
392         /* If the user wants none, give him none. */
393         if( !strcmp( psz_name, "none" ) )
394         {
395             free( psz_var );
396             return NULL;
397         }
398
399         i_shortcuts++;
400         psz_shortcuts = psz_last_shortcut = strdup( psz_name );
401
402         for( psz_parser = psz_shortcuts; *psz_parser; psz_parser++ )
403         {
404             if( *psz_parser == ',' )
405             {
406                  *psz_parser = '\0';
407                  i_shortcuts++;
408                  psz_last_shortcut = psz_parser + 1;
409             }
410         }
411
412         /* Check if the user wants to override the "strict" mode */
413         if( psz_last_shortcut )
414         {
415             if( !strcmp(psz_last_shortcut, "none") )
416             {
417                 b_strict = VLC_TRUE;
418                 i_shortcuts--;
419             }
420             else if( !strcmp(psz_last_shortcut, "any") )
421             {
422                 b_strict = VLC_FALSE;
423                 i_shortcuts--;
424             }
425         }
426     }
427
428     /* Sort the modules and test them */
429     p_all = vlc_list_find( p_this, VLC_OBJECT_MODULE, FIND_ANYWHERE );
430     p_list = malloc( p_all->i_count * sizeof( module_list_t ) );
431     p_first = NULL;
432     unsigned i_cpu = vlc_CPU();
433
434     /* Parse the module list for capabilities and probe each of them */
435     for( i_which_module = 0; i_which_module < p_all->i_count; i_which_module++ )
436     {
437         int i_shortcut_bonus = 0;
438
439         p_module = (module_t *)p_all->p_values[i_which_module].p_object;
440
441         /* Test that this module can do what we need */
442         if( !module_IsCapable( p_module, psz_capability ) )
443         {
444             /* Don't recurse through the sub-modules because vlc_list_find()
445              * will list them anyway. */
446             continue;
447         }
448
449         /* Test if we have the required CPU */
450         if( (p_module->i_cpu & i_cpu) != p_module->i_cpu )
451         {
452             continue;
453         }
454
455         /* If we required a shortcut, check this plugin provides it. */
456         if( i_shortcuts > 0 )
457         {
458             vlc_bool_t b_trash;
459             const char *psz_name = psz_shortcuts;
460
461             /* Let's drop modules with a <= 0 score (unless they are
462              * explicitly requested) */
463             b_trash = p_module->i_score <= 0;
464
465             for( unsigned i_short = i_shortcuts; i_short > 0; i_short-- )
466             {
467                 for( unsigned i = 0; p_module->pp_shortcuts[i]; i++ )
468                 {
469                     char *c;
470                     if( ( c = strchr( psz_name, '@' ) )
471                         ? !strncasecmp( psz_name, p_module->pp_shortcuts[i],
472                                         c-psz_name )
473                         : !strcasecmp( psz_name, p_module->pp_shortcuts[i] ) )
474                     {
475                         /* Found it */
476                         if( c && c[1] )
477                             psz_alias = c+1;
478                         i_shortcut_bonus = i_short * 10000;
479                         goto found_shortcut;
480                     }
481                 }
482
483                 /* Go to the next shortcut... This is so lame! */
484                 psz_name += strlen( psz_name ) + 1;
485             }
486
487             /* If we are in "strict" mode and we couldn't
488              * find the module in the list of provided shortcuts,
489              * then kick the bastard out of here!!! */
490             if( b_strict )
491                 continue;
492         }
493         /* If we didn't require a shortcut, trash <= 0 scored plugins */
494         else if( p_module->i_score <= 0 )
495         {
496             continue;
497         }
498
499 found_shortcut:
500
501         /* Store this new module */
502         p_list[ i_index ].p_module = p_module;
503         p_list[ i_index ].i_score = p_module->i_score + i_shortcut_bonus;
504         p_list[ i_index ].b_force = i_shortcut_bonus && b_strict;
505
506         /* Add it to the modules-to-probe list */
507         if( i_index == 0 )
508         {
509             p_list[ 0 ].p_next = NULL;
510             p_first = p_list;
511         }
512         else
513         {
514             /* Ok, so at school you learned that quicksort is quick, and
515              * bubble sort sucks raw eggs. But that's when dealing with
516              * thousands of items. Here we have barely 50. */
517             module_list_t *p_newlist = p_first;
518
519             if( p_first->i_score < p_list[ i_index ].i_score )
520             {
521                 p_list[ i_index ].p_next = p_first;
522                 p_first = &p_list[ i_index ];
523             }
524             else
525             {
526                 while( p_newlist->p_next != NULL &&
527                     p_newlist->p_next->i_score >= p_list[ i_index ].i_score )
528                 {
529                     p_newlist = p_newlist->p_next;
530                 }
531
532                 p_list[ i_index ].p_next = p_newlist->p_next;
533                 p_newlist->p_next = &p_list[ i_index ];
534             }
535         }
536
537         i_index++;
538     }
539
540     msg_Dbg( p_this, "looking for %s module: %i candidate%s", psz_capability,
541                                             i_index, i_index == 1 ? "" : "s" );
542
543     /* Lock all candidate modules */
544     p_tmp = p_first;
545     while( p_tmp != NULL )
546     {
547         vlc_object_yield( p_tmp->p_module );
548         p_tmp = p_tmp->p_next;
549     }
550
551     /* We can release the list, interesting modules were yielded */
552     vlc_list_release( p_all );
553
554     /* Parse the linked list and use the first successful module */
555     p_tmp = p_first;
556     while( p_tmp != NULL )
557     {
558 #ifdef HAVE_DYNAMIC_PLUGINS
559         /* Make sure the module is loaded in mem */
560         module_t *p_module = p_tmp->p_module;
561         if( p_module->b_submodule )
562             p_module = (module_t *)p_module->p_parent;
563
564         if( !p_module->b_builtin && !p_module->b_loaded )
565         {
566             module_t *p_new_module =
567                 AllocatePlugin( p_this, p_module->psz_filename );
568             if( p_new_module )
569             {
570                 CacheMerge( p_this, p_module, p_new_module );
571                 vlc_object_attach( p_new_module, p_module );
572                 DeleteModule( p_new_module, VLC_TRUE );
573             }
574         }
575 #endif
576
577         p_this->b_force = p_tmp->b_force;
578         if( p_tmp->p_module->pf_activate
579              && p_tmp->p_module->pf_activate( p_this ) == VLC_SUCCESS )
580         {
581             break;
582         }
583
584         vlc_object_release( p_tmp->p_module );
585         p_tmp = p_tmp->p_next;
586     }
587
588     /* Store the locked module value */
589     if( p_tmp != NULL )
590     {
591         p_module = p_tmp->p_module;
592         p_tmp = p_tmp->p_next;
593     }
594     else
595     {
596         p_module = NULL;
597     }
598
599     /* Unlock the remaining modules */
600     while( p_tmp != NULL )
601     {
602         vlc_object_release( p_tmp->p_module );
603         p_tmp = p_tmp->p_next;
604     }
605
606     free( p_list );
607     p_this->b_force = b_force_backup;
608
609     if( p_module != NULL )
610     {
611         msg_Dbg( p_this, "using %s module \"%s\"",
612                  psz_capability, p_module->psz_object_name );
613     }
614     else if( p_first == NULL )
615     {
616         if( !strcmp( psz_capability, "access_demux" ) )
617         {
618             msg_Warn( p_this, "no %s module matched \"%s\"",
619                  psz_capability, (psz_name && *psz_name) ? psz_name : "any" );
620         }
621         else
622         {
623             msg_Err( p_this, "no %s module matched \"%s\"",
624                  psz_capability, (psz_name && *psz_name) ? psz_name : "any" );
625
626             msg_StackSet( VLC_EGENERIC, "no %s module matched \"%s\"",
627                  psz_capability, (psz_name && *psz_name) ? psz_name : "any" );
628         }
629     }
630     else if( psz_name != NULL && *psz_name )
631     {
632         msg_Warn( p_this, "no %s module matching \"%s\" could be loaded",
633                   psz_capability, (psz_name && *psz_name) ? psz_name : "any" );
634     }
635     else
636         msg_StackSet( VLC_EGENERIC, "no suitable %s module", psz_capability );
637
638     if( p_module && !p_this->psz_object_name )
639     {
640         /* This assumes that p_this is the object which will be using the
641          * module. That's not always the case ... but it is in most cases.
642          */
643         p_this->psz_object_name = p_module->psz_object_name;
644     }
645
646     free( psz_shortcuts );
647     free( psz_var );
648
649     /* Don't forget that the module is still locked */
650     return p_module;
651 }
652
653 /**
654  * Module unneed
655  *
656  * This function must be called by the thread that called module_Need, to
657  * decrease the reference count and allow for hiding of modules.
658  * \param p_this vlc object structure
659  * \param p_module the module structure
660  * \return nothing
661  */
662 void __module_Unneed( vlc_object_t * p_this, module_t * p_module )
663 {
664     /* Use the close method */
665     if( p_module->pf_deactivate )
666     {
667         p_module->pf_deactivate( p_this );
668     }
669
670     msg_Dbg( p_this, "removing module \"%s\"", p_module->psz_object_name );
671
672     vlc_object_release( p_module );
673
674     return;
675 }
676
677 /**
678  * Get a pointer to a module_t given it's name.
679  *
680  * \param p_this vlc object structure
681  * \param psz_name the name of the module
682  * \return a pointer to the module or NULL in case of a failure
683  */
684 module_t *__module_Find( vlc_object_t *p_this, const char * psz_name )
685 {
686     vlc_list_t *p_list;
687     int i;
688     p_list = vlc_list_find( p_this, VLC_OBJECT_MODULE, FIND_ANYWHERE );
689     for( i = 0 ; i < p_list->i_count; i++)
690     {
691         module_t *p_module = ((module_t *) p_list->p_values[i].p_object);
692         const char *psz_module_name = p_module->psz_object_name;
693         if( psz_module_name && !strcmp( psz_module_name, psz_name ) )
694         {
695             /* We can release the list, and return yes */
696             vlc_object_yield( p_module );
697             vlc_list_release( p_list );
698             return p_module;
699         }
700     }
701     vlc_list_release( p_list );
702     return NULL;
703 }
704
705
706 /**
707  * Release a module_t pointer from module_Find().
708  *
709  * \param module the module to release
710  * \return nothing
711  */
712 void module_Put( module_t *module )
713 {
714     vlc_object_release( module );
715 }
716
717
718 /**
719  * Tell if a module exists and release it in thic case
720  *
721  * \param p_this vlc object structure
722  * \param psz_name th name of the module
723  * \return TRUE if the module exists
724  */
725 vlc_bool_t __module_Exists( vlc_object_t *p_this, const char * psz_name )
726 {
727     module_t *p_module = __module_Find( p_this, psz_name );
728     if( p_module )
729     {
730         module_Put( p_module );
731         return VLC_TRUE;
732     }
733     else
734     {
735         return VLC_FALSE;
736     }
737 }
738
739 /**
740  * GetModuleNamesForCapability
741  *
742  * Return a NULL terminated array with the names of the modules
743  * that have a certain capability.
744  * Free after uses both the string and the table.
745  * \param p_this vlc object structure
746  * \param psz_capability the capability asked
747  * \param pppsz_longname an pointer to an array of string to contain
748     the long names of the modules. If set to NULL the function don't use it.
749  * \return the NULL terminated array
750  */
751 char ** __module_GetModulesNamesForCapability( vlc_object_t *p_this,
752                                                const char *psz_capability,
753                                                char ***pppsz_longname )
754 {
755     vlc_list_t *p_list;
756     int i, j, count = 0;
757     char **psz_ret;
758
759     /* Do it in two passes : count the number of modules before */
760     p_list = vlc_list_find( p_this, VLC_OBJECT_MODULE, FIND_ANYWHERE );
761     for( i = 0 ; i < p_list->i_count; i++)
762     {
763         module_t *p_module = ((module_t *) p_list->p_values[i].p_object);
764         const char *psz_module_capability = p_module->psz_capability;
765         if( psz_module_capability && !strcmp( psz_module_capability, psz_capability ) )
766             count++;
767     }
768
769     psz_ret = malloc( sizeof(char*) * (count+1) );
770     if( pppsz_longname )
771         *pppsz_longname = malloc( sizeof(char*) * (count+1) );
772     if( !psz_ret || ( pppsz_longname && *pppsz_longname == NULL ) )
773     {
774         free( psz_ret );
775         free( *pppsz_longname );
776         *pppsz_longname = NULL;
777         vlc_list_release( p_list );
778         return NULL;
779     }
780
781     j = 0;
782     for( i = 0 ; i < p_list->i_count; i++)
783     {
784         module_t *p_module = ((module_t *) p_list->p_values[i].p_object);
785         const char *psz_module_capability = p_module->psz_capability;
786         if( psz_module_capability && !strcmp( psz_module_capability, psz_capability ) )
787         {
788             int k = -1; /* hack to handle submodules properly */
789             if( p_module->b_submodule )
790             {
791                 while( p_module->pp_shortcuts[++k] != NULL );
792                 k--;
793             }
794             psz_ret[j] = strdup( k>=0?p_module->pp_shortcuts[k]
795                                      :p_module->psz_object_name );
796             if( pppsz_longname )
797                 (*pppsz_longname)[j] = strdup( module_GetName( p_module, VLC_TRUE ) );
798             j++;
799         }
800     }
801     psz_ret[count] = NULL;
802
803     vlc_list_release( p_list );
804
805     return psz_ret;
806 }
807
808 /**
809  * Get the configuration of a module
810  *
811  * \param module the module
812  * \param psize the size of the configuration returned
813  * \return the configuration as an array
814  */
815 module_config_t *module_GetConfig( const module_t *module, unsigned *restrict psize )
816 {
817     unsigned i,j;
818     unsigned size = module->confsize;
819     module_config_t *config = malloc( size * sizeof( *config ) );
820
821     assert( psize != NULL );
822     *psize = 0;
823
824     if( !config )
825         return NULL;
826
827     for( i = 0, j = 0; i < size; i++ )
828     {
829         const module_config_t *item = module->p_config + i;
830         if( item->b_internal /* internal option */
831          || item->b_unsaveable /* non-modifiable option */
832          || item->b_removed /* removed option */ )
833             continue;
834
835         memcpy( config + j, item, sizeof( *config ) );
836         j++;
837     }
838     *psize = j;
839
840     return config;
841 }
842
843 /**
844  * Release the configuration
845  *
846  * \param the configuration
847  * \return nothing
848  */
849 void module_PutConfig( module_config_t *config )
850 {
851     free( config );
852 }
853
854 /*****************************************************************************
855  * Following functions are local.
856  *****************************************************************************/
857
858  /*****************************************************************************
859  * copy_next_paths_token: from a PATH_SEP_CHAR (a ':' or a ';') separated paths
860  * return first path.
861  *****************************************************************************/
862 static char * copy_next_paths_token( char * paths, char ** remaining_paths )
863 {
864     char * path;
865     int i;
866     bool escaped = false;
867
868     assert( paths );
869
870     /* Alloc a buffer to store the path */
871     path = malloc( strlen( paths ) + 1 );
872     if( !path ) return NULL;
873
874     /* Look for PATH_SEP_CHAR (a ':' or a ';') */
875     for( i = 0; paths[i]; i++ ) {
876         /* Take care of \\ and \: or \; escapement */
877         if( escaped ) {
878             escaped = false;
879             path[i] = paths[i];
880         }
881         else if( paths[i] == '\\' )
882             escaped = true;
883         else if( paths[i] == PATH_SEP_CHAR )
884             break;
885         else
886             path[i] = paths[i];
887     }
888     path[i] = 0;
889
890     /* Return the remaining paths */
891     if( remaining_paths ) {
892         *remaining_paths = paths[i] ? &paths[i]+1 : NULL;
893     }
894
895     return path;
896 }
897
898 /*****************************************************************************
899  * AllocateAllPlugins: load all plugin modules we can find.
900  *****************************************************************************/
901 #ifdef HAVE_DYNAMIC_PLUGINS
902 static void AllocateAllPlugins( vlc_object_t *p_this )
903 {
904     char *paths, *path, *paths_iter;
905     char * extra_path;
906
907     /* Contruct the special search path for system that have a relocatable
908      * executable. Set it to <vlc path>/modules and <vlc path>/plugins. */
909 #if defined( WIN32 ) || defined( UNDER_CE ) || defined( __APPLE__ ) || defined( SYS_BEOS )
910     if( asprintf( &extra_path,
911                     "%s" DIR_SEP "modules" PATH_SEP
912                     "%s" DIR_SEP "plugins"
913                     "%s",
914                     vlc_global()->psz_vlcpath,
915                     vlc_global()->psz_vlcpath,
916 # if defined( WIN32 ) || defined( UNDER_CE )
917                     "" ) < 0 )
918 # else
919                     PATH_SEP PLUGIN_PATH ) < 0 )
920 # endif
921
922     {
923         msg_Err( p_this, "Not enough memory" );
924         return;
925     }
926 #else
927     extra_path = strdup( PLUGIN_PATH );
928 #endif
929
930     /* If the user provided a plugin path, we add it to the list */
931     char * userpaths = config_GetPsz( p_this, "plugin-path" );
932
933     if( asprintf( &paths, "modules" PATH_SEP "%s" PATH_SEP "plugins%s%s",
934                     extra_path,
935                     userpaths ? PATH_SEP : "",
936                     userpaths ? userpaths : "" ) < 0 )
937     {
938         msg_Err( p_this, "Not enough memory" );
939         free( userpaths );
940         free( extra_path );
941         return;
942     }
943
944     /* Free plugin-path and extra path */
945     free( userpaths );
946     free( extra_path );
947
948     msg_Dbg( p_this, "We will be looking for modules in `%s'", paths );
949
950     for( paths_iter = paths; paths_iter; )
951     {
952         path = copy_next_paths_token( paths_iter, &paths_iter );
953         if( !path )
954         {
955             msg_Err( p_this, "Not enough memory" );
956             return;
957         }
958
959         msg_Dbg( p_this, "recursively browsing `%s'", path );
960
961         /* Don't go deeper than 5 subdirectories */
962         AllocatePluginDir( p_this, path, 5 );
963
964         free( path );
965     }
966
967     free( paths );
968 }
969
970 /*****************************************************************************
971  * AllocatePluginDir: recursively parse a directory to look for plugins
972  *****************************************************************************/
973 static void AllocatePluginDir( vlc_object_t *p_this, const char *psz_dir,
974                                int i_maxdepth )
975 {
976 /* FIXME: Needs to be ported to wide char on ALL Windows builds */
977 #ifdef WIN32
978 # undef opendir
979 # undef closedir
980 # undef readdir
981 #endif
982 #if defined( UNDER_CE ) || defined( _MSC_VER )
983 #ifdef UNDER_CE
984     wchar_t psz_wpath[MAX_PATH + 256];
985     wchar_t psz_wdir[MAX_PATH];
986 #endif
987     char psz_path[MAX_PATH + 256];
988     WIN32_FIND_DATA finddata;
989     HANDLE handle;
990     int rc;
991 #else
992     int    i_dirlen;
993     DIR *  dir;
994     struct dirent * file;
995 #endif
996     char * psz_file;
997
998     if( p_this->p_libvlc->b_die || i_maxdepth < 0 )
999     {
1000         return;
1001     }
1002
1003 #if defined( UNDER_CE ) || defined( _MSC_VER )
1004 #ifdef UNDER_CE
1005     MultiByteToWideChar( CP_ACP, 0, psz_dir, -1, psz_wdir, MAX_PATH );
1006
1007     rc = GetFileAttributes( psz_wdir );
1008     if( rc<0 || !(rc&FILE_ATTRIBUTE_DIRECTORY) ) return; /* Not a directory */
1009
1010     /* Parse all files in the directory */
1011     swprintf( psz_wpath, L"%ls\\*", psz_wdir );
1012 #else
1013     rc = GetFileAttributes( psz_dir );
1014     if( rc<0 || !(rc&FILE_ATTRIBUTE_DIRECTORY) ) return; /* Not a directory */
1015 #endif
1016
1017     /* Parse all files in the directory */
1018     sprintf( psz_path, "%s\\*", psz_dir );
1019
1020 #ifdef UNDER_CE
1021     handle = FindFirstFile( psz_wpath, &finddata );
1022 #else
1023     handle = FindFirstFile( psz_path, &finddata );
1024 #endif
1025     if( handle == INVALID_HANDLE_VALUE )
1026     {
1027         /* Empty directory */
1028         return;
1029     }
1030
1031     /* Parse the directory and try to load all files it contains. */
1032     do
1033     {
1034 #ifdef UNDER_CE
1035         unsigned int i_len = wcslen( finddata.cFileName );
1036         swprintf( psz_wpath, L"%ls\\%ls", psz_wdir, finddata.cFileName );
1037         sprintf( psz_path, "%s\\%ls", psz_dir, finddata.cFileName );
1038 #else
1039         unsigned int i_len = strlen( finddata.cFileName );
1040         sprintf( psz_path, "%s\\%s", psz_dir, finddata.cFileName );
1041 #endif
1042
1043         /* Skip ".", ".." */
1044         if( !*finddata.cFileName || !strcmp( finddata.cFileName, "." )
1045          || !strcmp( finddata.cFileName, ".." ) )
1046         {
1047             if( !FindNextFile( handle, &finddata ) ) break;
1048             continue;
1049         }
1050
1051 #ifdef UNDER_CE
1052         if( GetFileAttributes( psz_wpath ) & FILE_ATTRIBUTE_DIRECTORY )
1053 #else
1054         if( GetFileAttributes( psz_path ) & FILE_ATTRIBUTE_DIRECTORY )
1055 #endif
1056         {
1057             AllocatePluginDir( p_this, psz_path, i_maxdepth - 1 );
1058         }
1059         else if( i_len > strlen( LIBEXT )
1060                   /* We only load files ending with LIBEXT */
1061                   && !strncasecmp( psz_path + strlen( psz_path)
1062                                    - strlen( LIBEXT ),
1063                                    LIBEXT, strlen( LIBEXT ) ) )
1064         {
1065             WIN32_FILE_ATTRIBUTE_DATA attrbuf;
1066             int64_t i_time = 0, i_size = 0;
1067
1068 #ifdef UNDER_CE
1069             if( GetFileAttributesEx( psz_wpath, GetFileExInfoStandard,
1070                                      &attrbuf ) )
1071 #else
1072             if( GetFileAttributesEx( psz_path, GetFileExInfoStandard,
1073                                      &attrbuf ) )
1074 #endif
1075             {
1076                 i_time = attrbuf.ftLastWriteTime.dwHighDateTime;
1077                 i_time <<= 32;
1078                 i_time |= attrbuf.ftLastWriteTime.dwLowDateTime;
1079                 i_size = attrbuf.nFileSizeHigh;
1080                 i_size <<= 32;
1081                 i_size |= attrbuf.nFileSizeLow;
1082             }
1083             psz_file = psz_path;
1084
1085             AllocatePluginFile( p_this, psz_file, i_time, i_size );
1086         }
1087     }
1088     while( !p_this->p_libvlc->b_die && FindNextFile( handle, &finddata ) );
1089
1090     /* Close the directory */
1091     FindClose( handle );
1092
1093 #else
1094     dir = opendir( psz_dir );
1095     if( !dir )
1096     {
1097         return;
1098     }
1099
1100     i_dirlen = strlen( psz_dir );
1101
1102     /* Parse the directory and try to load all files it contains. */
1103     while( !p_this->p_libvlc->b_die && ( file = readdir( dir ) ) )
1104     {
1105         struct stat statbuf;
1106         unsigned int i_len;
1107         int i_stat;
1108
1109         /* Skip ".", ".." */
1110         if( !*file->d_name || !strcmp( file->d_name, "." )
1111          || !strcmp( file->d_name, ".." ) )
1112         {
1113             continue;
1114         }
1115
1116         i_len = strlen( file->d_name );
1117         psz_file = malloc( i_dirlen + 1 + i_len + 1 );
1118         sprintf( psz_file, "%s"DIR_SEP"%s", psz_dir, file->d_name );
1119
1120         i_stat = stat( psz_file, &statbuf );
1121         if( !i_stat && statbuf.st_mode & S_IFDIR )
1122         {
1123             AllocatePluginDir( p_this, psz_file, i_maxdepth - 1 );
1124         }
1125         else if( i_len > strlen( LIBEXT )
1126                   /* We only load files ending with LIBEXT */
1127                   && !strncasecmp( file->d_name + i_len - strlen( LIBEXT ),
1128                                    LIBEXT, strlen( LIBEXT ) ) )
1129         {
1130             int64_t i_time = 0, i_size = 0;
1131
1132             if( !i_stat )
1133             {
1134                 i_time = statbuf.st_mtime;
1135                 i_size = statbuf.st_size;
1136             }
1137
1138             AllocatePluginFile( p_this, psz_file, i_time, i_size );
1139         }
1140
1141         free( psz_file );
1142     }
1143
1144     /* Close the directory */
1145     closedir( dir );
1146
1147 #endif
1148 }
1149
1150 /*****************************************************************************
1151  * AllocatePluginFile: load a module into memory and initialize it.
1152  *****************************************************************************
1153  * This function loads a dynamically loadable module and allocates a structure
1154  * for its information data. The module can then be handled by module_Need
1155  * and module_Unneed. It can be removed by DeleteModule.
1156  *****************************************************************************/
1157 static int AllocatePluginFile( vlc_object_t * p_this, char * psz_file,
1158                                int64_t i_file_time, int64_t i_file_size )
1159 {
1160     module_t * p_module = NULL;
1161     module_cache_t *p_cache_entry = NULL;
1162
1163     /*
1164      * Check our plugins cache first then load plugin if needed
1165      */
1166     p_cache_entry =
1167         CacheFind( psz_file, i_file_time, i_file_size );
1168
1169     if( !p_cache_entry )
1170     {
1171         p_module = AllocatePlugin( p_this, psz_file );
1172     }
1173     else
1174     {
1175         /* If junk dll, don't try to load it */
1176         if( p_cache_entry->b_junk )
1177         {
1178             p_module = NULL;
1179         }
1180         else
1181         {
1182             module_config_t *p_item = NULL, *p_end = NULL;
1183
1184             p_module = p_cache_entry->p_module;
1185             p_module->b_loaded = VLC_FALSE;
1186
1187             /* For now we force loading if the module's config contains
1188              * callbacks or actions.
1189              * Could be optimized by adding an API call.*/
1190             for( p_item = p_module->p_config, p_end = p_item + p_module->confsize;
1191                  p_item < p_end; p_item++ )
1192             {
1193                 if( p_item->pf_callback || p_item->i_action )
1194                 {
1195                     p_module = AllocatePlugin( p_this, psz_file );
1196                     break;
1197                 }
1198             }
1199             if( p_module == p_cache_entry->p_module )
1200                 p_cache_entry->b_used = VLC_TRUE;
1201         }
1202     }
1203
1204     if( p_module )
1205     {
1206         libvlc_global_data_t *p_libvlc_global = vlc_global();
1207
1208         /* Everything worked fine !
1209          * The module is ready to be added to the list. */
1210         p_module->b_builtin = VLC_FALSE;
1211
1212         /* msg_Dbg( p_this, "plugin \"%s\", %s",
1213                     p_module->psz_object_name, p_module->psz_longname ); */
1214
1215         vlc_object_attach( p_module, p_libvlc_global->p_module_bank );
1216
1217         if( !p_libvlc_global->p_module_bank->b_cache )
1218             return 0;
1219
1220 #define p_bank p_libvlc_global->p_module_bank
1221         /* Add entry to cache */
1222         p_bank->pp_cache =
1223             realloc( p_bank->pp_cache, (p_bank->i_cache + 1) * sizeof(void *) );
1224         p_bank->pp_cache[p_bank->i_cache] = malloc( sizeof(module_cache_t) );
1225         if( !p_bank->pp_cache[p_bank->i_cache] )
1226             return -1;
1227         p_bank->pp_cache[p_bank->i_cache]->psz_file = strdup( psz_file );
1228         p_bank->pp_cache[p_bank->i_cache]->i_time = i_file_time;
1229         p_bank->pp_cache[p_bank->i_cache]->i_size = i_file_size;
1230         p_bank->pp_cache[p_bank->i_cache]->b_junk = p_module ? 0 : 1;
1231         p_bank->pp_cache[p_bank->i_cache]->b_used = VLC_TRUE;
1232         p_bank->pp_cache[p_bank->i_cache]->p_module = p_module;
1233         p_bank->i_cache++;
1234     }
1235
1236     return p_module ? 0 : -1;
1237 }
1238
1239 /*****************************************************************************
1240  * AllocatePlugin: load a module into memory and initialize it.
1241  *****************************************************************************
1242  * This function loads a dynamically loadable module and allocates a structure
1243  * for its information data. The module can then be handled by module_Need
1244  * and module_Unneed. It can be removed by DeleteModule.
1245  *****************************************************************************/
1246 static module_t * AllocatePlugin( vlc_object_t * p_this, char * psz_file )
1247 {
1248     module_t * p_module = NULL;
1249     module_handle_t handle;
1250
1251     if( module_Load( p_this, psz_file, &handle ) )
1252         return NULL;
1253
1254     /* Now that we have successfully loaded the module, we can
1255      * allocate a structure for it */
1256     p_module = vlc_module_create( p_this );
1257     if( p_module == NULL )
1258     {
1259         msg_Err( p_this, "out of memory" );
1260         module_Unload( handle );
1261         return NULL;
1262     }
1263
1264     /* We need to fill these since they may be needed by module_Call() */
1265     p_module->psz_filename = psz_file;
1266     p_module->handle = handle;
1267     p_module->b_loaded = VLC_TRUE;
1268
1269     /* Initialize the module: fill p_module, default config */
1270     if( module_Call( p_module ) != 0 )
1271     {
1272         /* We couldn't call module_init() */
1273         vlc_object_release( p_module );
1274         module_Unload( handle );
1275         return NULL;
1276     }
1277
1278     DupModule( p_module );
1279     p_module->psz_filename = strdup( p_module->psz_filename );
1280
1281     /* Everything worked fine ! The module is ready to be added to the list. */
1282     p_module->b_builtin = VLC_FALSE;
1283
1284     return p_module;
1285 }
1286
1287 /*****************************************************************************
1288  * DupModule: make a plugin module standalone.
1289  *****************************************************************************
1290  * This function duplicates all strings in the module, so that the dynamic
1291  * object can be unloaded. It acts recursively on submodules.
1292  *****************************************************************************/
1293 static void DupModule( module_t *p_module )
1294 {
1295     const char **pp_shortcut;
1296     int i_submodule;
1297
1298     for( pp_shortcut = p_module->pp_shortcuts ; *pp_shortcut ; pp_shortcut++ )
1299     {
1300         *pp_shortcut = strdup( *pp_shortcut );
1301     }
1302
1303     /* We strdup() these entries so that they are still valid when the
1304      * module is unloaded. */
1305     p_module->psz_object_name = strdup( p_module->psz_object_name );
1306     p_module->psz_capability = strdup( p_module->psz_capability );
1307     p_module->psz_shortname = p_module->psz_shortname ?
1308                                  strdup( p_module->psz_shortname ) : NULL;
1309     p_module->psz_longname = strdup( p_module->psz_longname );
1310     p_module->psz_help = p_module->psz_help ? strdup( p_module->psz_help )
1311                                             : NULL;
1312
1313     for( i_submodule = 0; i_submodule < p_module->i_children; i_submodule++ )
1314     {
1315         DupModule( (module_t*)p_module->pp_children[ i_submodule ] );
1316     }
1317 }
1318
1319 /*****************************************************************************
1320  * UndupModule: free a duplicated module.
1321  *****************************************************************************
1322  * This function frees the allocations done in DupModule().
1323  *****************************************************************************/
1324 static void UndupModule( module_t *p_module )
1325 {
1326     const char **pp_shortcut;
1327     int i_submodule;
1328
1329     for( i_submodule = 0; i_submodule < p_module->i_children; i_submodule++ )
1330     {
1331         UndupModule( (module_t*)p_module->pp_children[ i_submodule ] );
1332     }
1333
1334     for( pp_shortcut = p_module->pp_shortcuts ; *pp_shortcut ; pp_shortcut++ )
1335     {
1336         free( (void*)*pp_shortcut );
1337     }
1338
1339     free( (void*)p_module->psz_object_name );
1340     free( p_module->psz_capability );
1341     free( (void*)p_module->psz_shortname );
1342     free( (void*)p_module->psz_longname );
1343     free( (void*)p_module->psz_help );
1344 }
1345
1346 #endif /* HAVE_DYNAMIC_PLUGINS */
1347
1348 /*****************************************************************************
1349  * AllocateBuiltinModule: initialize a builtin module.
1350  *****************************************************************************
1351  * This function registers a builtin module and allocates a structure
1352  * for its information data. The module can then be handled by module_Need
1353  * and module_Unneed. It can be removed by DeleteModule.
1354  *****************************************************************************/
1355 static int AllocateBuiltinModule( vlc_object_t * p_this,
1356                                   int ( *pf_entry ) ( module_t * ) )
1357 {
1358     module_t * p_module;
1359
1360     /* Now that we have successfully loaded the module, we can
1361      * allocate a structure for it */
1362     p_module = vlc_module_create( p_this );
1363     if( p_module == NULL )
1364     {
1365         msg_Err( p_this, "out of memory" );
1366         return -1;
1367     }
1368
1369     /* Initialize the module : fill p_module->psz_object_name, etc. */
1370     if( pf_entry( p_module ) != 0 )
1371     {
1372         /* With a well-written module we shouldn't have to print an
1373          * additional error message here, but just make sure. */
1374         msg_Err( p_this, "failed calling entry point in builtin module" );
1375         vlc_object_release( p_module );
1376         return -1;
1377     }
1378
1379     /* Everything worked fine ! The module is ready to be added to the list. */
1380     p_module->b_builtin = VLC_TRUE;
1381
1382     /* msg_Dbg( p_this, "builtin \"%s\", %s",
1383                 p_module->psz_object_name, p_module->psz_longname ); */
1384
1385     vlc_object_attach( p_module, vlc_global()->p_module_bank );
1386
1387     return 0;
1388 }
1389
1390 /*****************************************************************************
1391  * DeleteModule: delete a module and its structure.
1392  *****************************************************************************
1393  * This function can only be called if the module isn't being used.
1394  *****************************************************************************/
1395 static int DeleteModule( module_t * p_module, vlc_bool_t b_detach )
1396 {
1397     if( !p_module ) return VLC_EGENERIC;
1398     if( b_detach )
1399         vlc_object_detach( p_module );
1400
1401     /* We free the structures that we strdup()ed in Allocate*Module(). */
1402 #ifdef HAVE_DYNAMIC_PLUGINS
1403     if( !p_module->b_builtin )
1404     {
1405         if( p_module->b_loaded && p_module->b_unloadable )
1406         {
1407             module_Unload( p_module->handle );
1408         }
1409         UndupModule( p_module );
1410         free( p_module->psz_filename );
1411     }
1412 #endif
1413
1414     /* Free and detach the object's children */
1415     while( p_module->i_children )
1416     {
1417         vlc_object_t *p_this = p_module->pp_children[0];
1418         vlc_object_detach( p_this );
1419         vlc_object_release( p_this );
1420     }
1421
1422     config_Free( p_module );
1423     vlc_object_release( p_module );
1424     p_module = NULL;
1425     return 0;
1426 }