]> git.sesse.net Git - vlc/blob - src/misc/modules.c
* src/input/control.c: added INPUT_ADD_INFO/INPUT_SET_NAME to input_Control().
[vlc] / src / misc / modules.c
1 /*****************************************************************************
2  * modules.c : Builtin and plugin modules management functions
3  *****************************************************************************
4  * Copyright (C) 2001-2004 VideoLAN
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  *
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 <vlc/vlc.h>
37
38 #ifdef HAVE_DIRENT_H
39 #   include <dirent.h>
40 #elif defined( UNDER_CE )
41 #   include <windows.h>                               /* GetFileAttributes() */
42 #else
43 #   include "../extras/dirent.h"
44 #endif
45
46 #ifdef HAVE_SYS_TYPES_H
47 #   include <sys/types.h>
48 #endif
49 #ifdef HAVE_SYS_STAT_H
50 #   include <sys/stat.h>
51 #endif
52 #ifdef HAVE_UNISTD_H
53 #   include <unistd.h>
54 #endif
55
56 #define HAVE_DYNAMIC_PLUGINS
57 #if defined(HAVE_DL_DYLD)
58 #   if defined(HAVE_MACH_O_DYLD_H)
59 #       include <mach-o/dyld.h>
60 #   endif
61 #elif defined(HAVE_DL_BEOS)
62 #   if defined(HAVE_IMAGE_H)
63 #       include <image.h>
64 #   endif
65 #elif defined(HAVE_DL_WINDOWS)
66 #   include <windows.h>
67 #elif defined(HAVE_DL_DLOPEN)
68 #   if defined(HAVE_DLFCN_H) /* Linux, BSD, Hurd */
69 #       include <dlfcn.h>
70 #   endif
71 #   if defined(HAVE_SYS_DL_H)
72 #       include <sys/dl.h>
73 #   endif
74 #elif defined(HAVE_DL_SHL_LOAD)
75 #   if defined(HAVE_DL_H)
76 #       include <dl.h>
77 #   endif
78 #else
79 #   undef HAVE_DYNAMIC_PLUGINS
80 #endif
81
82 #include "vlc_error.h"
83
84 #include "vlc_interface.h"
85 #include "intf_eject.h"
86
87 #include "stream_control.h"
88 #include "input_ext-intf.h"
89 #include "input_ext-dec.h"
90 #include "input_ext-plugins.h"
91 #include "ninput.h"
92
93 #include "vlc_playlist.h"
94
95 #include "vlc_video.h"
96 #include "video_output.h"
97 #include "vout_synchro.h"
98
99 #include "audio_output.h"
100 #include "aout_internal.h"
101
102 #include "stream_output.h"
103 #include "osd.h"
104 #include "vlc_httpd.h"
105
106 #include "iso_lang.h"
107 #include "charset.h"
108
109 #include "vlc_block.h"
110
111 #include "vlc_vlm.h"
112
113 #if defined( UNDER_CE )
114 #   define MYCHAR wchar_t
115 #else
116 #   define MYCHAR char
117 #endif
118
119 #ifdef HAVE_DYNAMIC_PLUGINS
120 #   include "modules_plugin.h"
121 #endif
122
123 #if defined( UNDER_CE )
124 #    include "modules_builtin_evc.h"
125 #elif defined( _MSC_VER )
126 #    include "modules_builtin_msvc.h"
127 #else
128 #    include "modules_builtin.h"
129 #endif
130 #include "network.h"
131
132 /*****************************************************************************
133  * Local prototypes
134  *****************************************************************************/
135 #ifdef HAVE_DYNAMIC_PLUGINS
136 static void AllocateAllPlugins   ( vlc_object_t * );
137 static void AllocatePluginDir    ( vlc_object_t *, const MYCHAR *, int );
138 static int  AllocatePluginFile   ( vlc_object_t *, MYCHAR * );
139 #endif
140 static int  AllocateBuiltinModule( vlc_object_t *, int ( * ) ( module_t * ) );
141 static int  DeleteModule ( module_t * );
142 #ifdef HAVE_DYNAMIC_PLUGINS
143 static void   DupModule        ( module_t * );
144 static void   UndupModule      ( module_t * );
145 static int    CallEntry        ( module_t * );
146 static void   CloseModule      ( module_handle_t );
147 static void * GetSymbol        ( module_handle_t, const char * );
148 #if defined(HAVE_DL_WINDOWS)
149 static char * GetWindowsError  ( void );
150 #endif
151 #endif
152
153 /*****************************************************************************
154  * module_InitBank: create the module bank.
155  *****************************************************************************
156  * This function creates a module bank structure which will be filled later
157  * on with all the modules found.
158  *****************************************************************************/
159 void __module_InitBank( vlc_object_t *p_this )
160 {
161     module_bank_t *p_bank;
162
163     p_bank = vlc_object_create( p_this, sizeof(module_bank_t) );
164     p_bank->psz_object_name = "module bank";
165
166     /*
167      * Store the symbols to be exported
168      */
169 #ifdef HAVE_DYNAMIC_PLUGINS
170     STORE_SYMBOLS( &p_bank->symbols );
171 #endif
172
173     /* Everything worked, attach the object */
174     p_this->p_libvlc->p_module_bank = p_bank;
175     vlc_object_attach( p_bank, p_this->p_libvlc );
176
177     return;
178 }
179
180 /*****************************************************************************
181  * module_ResetBank: reset the module bank.
182  *****************************************************************************
183  * This function resets the module bank by unloading all unused plugin
184  * modules.
185  *****************************************************************************/
186 void __module_ResetBank( vlc_object_t *p_this )
187 {
188     msg_Err( p_this, "FIXME: module_ResetBank unimplemented" );
189     return;
190 }
191
192 /*****************************************************************************
193  * module_EndBank: empty the module bank.
194  *****************************************************************************
195  * This function unloads all unused plugin modules and empties the module
196  * bank in case of success.
197  *****************************************************************************/
198 void __module_EndBank( vlc_object_t *p_this )
199 {
200     module_t * p_next;
201
202     vlc_object_detach( p_this->p_libvlc->p_module_bank );
203
204     while( p_this->p_libvlc->p_module_bank->i_children )
205     {
206         p_next = (module_t *)p_this->p_libvlc->p_module_bank->pp_children[0];
207
208         if( DeleteModule( p_next ) )
209         {
210             /* Module deletion failed */
211             msg_Err( p_this, "module \"%s\" can't be removed, trying harder",
212                      p_next->psz_object_name );
213
214             /* We just free the module by hand. Niahahahahaha. */
215             vlc_object_detach( p_next );
216             vlc_object_destroy( p_next );
217         }
218     }
219
220     vlc_object_destroy( p_this->p_libvlc->p_module_bank );
221
222     return;
223 }
224
225 /*****************************************************************************
226  * module_LoadMain: load the main program info into the module bank.
227  *****************************************************************************
228  * This function fills the module bank structure with the main module infos.
229  * This is very useful as it will allow us to consider the main program just
230  * as another module, and for instance the configuration options of main will
231  * be available in the module bank structure just as for every other module.
232  *****************************************************************************/
233 void __module_LoadMain( vlc_object_t *p_this )
234 {
235     AllocateBuiltinModule( p_this, vlc_entry__main );
236 }
237
238 /*****************************************************************************
239  * module_LoadBuiltins: load all modules which we built with.
240  *****************************************************************************
241  * This function fills the module bank structure with the builtin modules.
242  *****************************************************************************/
243 void __module_LoadBuiltins( vlc_object_t * p_this )
244 {
245     msg_Dbg( p_this, "checking builtin modules" );
246     ALLOCATE_ALL_BUILTINS();
247 }
248
249 /*****************************************************************************
250  * module_LoadPlugins: load all plugin modules we can find.
251  *****************************************************************************
252  * This function fills the module bank structure with the plugin modules.
253  *****************************************************************************/
254 void __module_LoadPlugins( vlc_object_t * p_this )
255 {
256 #ifdef HAVE_DYNAMIC_PLUGINS
257     msg_Dbg( p_this, "checking plugin modules" );
258     AllocateAllPlugins( p_this );
259 #endif
260 }
261
262 /*****************************************************************************
263  * module_Need: return the best module function, given a capability list.
264  *****************************************************************************
265  * This function returns the module that best fits the asked capabilities.
266  *****************************************************************************/
267 module_t * __module_Need( vlc_object_t *p_this, const char *psz_capability,
268                           const char *psz_name, vlc_bool_t b_strict )
269 {
270     typedef struct module_list_t module_list_t;
271
272     struct module_list_t
273     {
274         module_t *p_module;
275         int i_score;
276         module_list_t *p_next;
277     };
278
279     module_list_t *p_list, *p_first, *p_tmp;
280     vlc_list_t *p_all;
281
282     int i_which_module, i_index = 0;
283     vlc_bool_t b_intf = VLC_FALSE;
284
285     module_t *p_module;
286
287     int   i_shortcuts = 0;
288     char *psz_shortcuts = NULL, *psz_var = NULL;
289
290     msg_Dbg( p_this, "looking for %s module", psz_capability );
291
292     /* Deal with variables */
293     if( psz_name && psz_name[0] == '$' )
294     {
295         vlc_value_t val;
296         var_Create( p_this, psz_name + 1, VLC_VAR_MODULE | VLC_VAR_DOINHERIT );
297         var_Get( p_this, psz_name + 1, &val );
298         psz_var = val.psz_string;
299         psz_name = psz_var;
300     }
301
302     /* Count how many different shortcuts were asked for */
303     if( psz_name && *psz_name )
304     {
305         char *psz_parser, *psz_last_shortcut;
306
307         /* If the user wants none, give him none. */
308         if( !strcmp( psz_name, "none" ) )
309         {
310             if( psz_var ) free( psz_var );
311             return NULL;
312         }
313
314         i_shortcuts++;
315         psz_shortcuts = psz_last_shortcut = strdup( psz_name );
316
317         for( psz_parser = psz_shortcuts; *psz_parser; psz_parser++ )
318         {
319             if( *psz_parser == ',' )
320             {
321                  *psz_parser = '\0';
322                  i_shortcuts++;
323                  psz_last_shortcut = psz_parser + 1;
324             }
325         }
326
327         /* Check if the user wants to override the "strict" mode */
328         if( psz_last_shortcut )
329         {
330             if( !strcmp(psz_last_shortcut, "none") )
331             {
332                 b_strict = VLC_TRUE;
333                 i_shortcuts--;
334             }
335             else if( !strcmp(psz_last_shortcut, "any") )
336             {
337                 b_strict = VLC_FALSE;
338                 i_shortcuts--;
339             }
340         }
341     }
342
343     /* Sort the modules and test them */
344     p_all = vlc_list_find( p_this, VLC_OBJECT_MODULE, FIND_ANYWHERE );
345     p_list = malloc( p_all->i_count * sizeof( module_list_t ) );
346     p_first = NULL;
347
348     /* Parse the module list for capabilities and probe each of them */
349     for( i_which_module = 0; i_which_module < p_all->i_count; i_which_module++ )
350     {
351         module_t * p_submodule = NULL;
352         int i_shortcut_bonus = 0, i_submodule;
353
354         p_module = (module_t *)p_all->p_values[i_which_module].p_object;
355
356         /* Test that this module can do what we need */
357         if( strcmp( p_module->psz_capability, psz_capability ) )
358         {
359             for( i_submodule = 0;
360                  i_submodule < p_module->i_children;
361                  i_submodule++ )
362             {
363                 if( !strcmp( ((module_t*)p_module->pp_children[ i_submodule ])
364                                            ->psz_capability, psz_capability ) )
365                 {
366                     p_submodule =
367                             (module_t*)p_module->pp_children[ i_submodule ];
368                     break;
369                 }
370             }
371
372             if( p_submodule == NULL )
373             {
374                 continue;
375             }
376
377             p_module = p_submodule;
378         }
379
380         /* Test if we have the required CPU */
381         if( (p_module->i_cpu & p_this->p_libvlc->i_cpu) != p_module->i_cpu )
382         {
383             continue;
384         }
385
386         /* If we required a shortcut, check this plugin provides it. */
387         if( i_shortcuts > 0 )
388         {
389             vlc_bool_t b_trash;
390             int i_dummy, i_short = i_shortcuts;
391             char *psz_name = psz_shortcuts;
392
393             /* Let's drop modules with a 0 score (unless they are
394              * explicitly requested) */
395             b_trash = !p_module->i_score;
396
397             while( i_short > 0 )
398             {
399                 for( i_dummy = 0; p_module->pp_shortcuts[i_dummy]; i_dummy++ )
400                 {
401                     if( !strcasecmp( psz_name,
402                                      p_module->pp_shortcuts[i_dummy] ) )
403                     {
404                         /* Found it */
405                         b_trash = VLC_FALSE;
406                         i_shortcut_bonus = i_short * 10000;
407                         break;
408                     }
409                 }
410
411                 if( i_shortcut_bonus )
412                 {
413                     /* We found it... remember ? */
414                     break;
415                 }
416
417                 /* Go to the next shortcut... This is so lame! */
418                 while( *psz_name )
419                 {
420                     psz_name++;
421                 }
422                 psz_name++;
423                 i_short--;
424             }
425
426             /* If we are in "strict" mode and we couldn't
427              * find the module in the list of provided shortcuts,
428              * then kick the bastard out of here!!! */
429             if( i_short == 0 && b_strict )
430             {
431                 b_trash = VLC_TRUE;
432             }
433
434             if( b_trash )
435             {
436                 continue;
437             }
438         }
439         /* If we didn't require a shortcut, trash zero-scored plugins */
440         else if( !p_module->i_score )
441         {
442             continue;
443         }
444
445         /* Special case: test if we requested a particular intf plugin */
446         if( !i_shortcuts && p_module->psz_program
447              && !strcmp( p_module->psz_program,
448                          p_this->p_vlc->psz_object_name ) )
449         {
450             if( !b_intf )
451             {
452                 /* Remove previous non-matching plugins */
453                 i_index = 0;
454                 b_intf = VLC_TRUE;
455             }
456         }
457         else if( b_intf )
458         {
459             /* This one doesn't match */
460             continue;
461         }
462
463         /* Store this new module */
464         p_list[ i_index ].p_module = p_module;
465         p_list[ i_index ].i_score = p_module->i_score + i_shortcut_bonus;
466
467         /* Add it to the modules-to-probe list */
468         if( i_index == 0 )
469         {
470             p_list[ 0 ].p_next = NULL;
471             p_first = p_list;
472         }
473         else
474         {
475             /* Ok, so at school you learned that quicksort is quick, and
476              * bubble sort sucks raw eggs. But that's when dealing with
477              * thousands of items. Here we have barely 50. */
478             module_list_t *p_newlist = p_first;
479
480             if( p_first->i_score < p_list[ i_index ].i_score )
481             {
482                 p_list[ i_index ].p_next = p_first;
483                 p_first = &p_list[ i_index ];
484             }
485             else
486             {
487                 while( p_newlist->p_next != NULL &&
488                     p_newlist->p_next->i_score >= p_list[ i_index ].i_score )
489                 {
490                     p_newlist = p_newlist->p_next;
491                 }
492
493                 p_list[ i_index ].p_next = p_newlist->p_next;
494                 p_newlist->p_next = &p_list[ i_index ];
495             }
496         }
497
498         i_index++;
499     }
500
501     msg_Dbg( p_this, "probing %i candidate%s",
502                      i_index, i_index == 1 ? "" : "s" );
503
504     /* Lock all candidate modules */
505     p_tmp = p_first;
506     while( p_tmp != NULL )
507     {
508         vlc_object_yield( p_tmp->p_module );
509         p_tmp = p_tmp->p_next;
510     }
511
512     /* We can release the list, interesting modules were yielded */
513     vlc_list_release( p_all );
514
515     /* Parse the linked list and use the first successful module */
516     p_tmp = p_first;
517     while( p_tmp != NULL )
518     {
519         if( p_tmp->p_module->pf_activate
520              && p_tmp->p_module->pf_activate( p_this ) == VLC_SUCCESS )
521         {
522             break;
523         }
524
525         vlc_object_release( p_tmp->p_module );
526         p_tmp = p_tmp->p_next;
527     }
528
529     /* Store the locked module value */
530     if( p_tmp != NULL )
531     {
532         p_module = p_tmp->p_module;
533         p_tmp = p_tmp->p_next;
534     }
535     else
536     {
537         p_module = NULL;
538     }
539
540     /* Unlock the remaining modules */
541     while( p_tmp != NULL )
542     {
543         vlc_object_release( p_tmp->p_module );
544         p_tmp = p_tmp->p_next;
545     }
546
547     free( p_list );
548
549     if( p_module != NULL )
550     {
551         msg_Dbg( p_module, "using %s module \"%s\"",
552                  psz_capability, p_module->psz_object_name );
553     }
554     else if( p_first == NULL )
555     {
556         msg_Err( p_this, "no %s module matched \"%s\"",
557                  psz_capability, (psz_name && *psz_name) ? psz_name : "any" );
558     }
559     else if( psz_name != NULL && *psz_name )
560     {
561         msg_Warn( p_this, "no %s module matching \"%s\" could be loaded",
562                   psz_capability, (psz_name && *psz_name) ? psz_name : "any" );
563     }
564
565     if( psz_shortcuts )
566     {
567         free( psz_shortcuts );
568     }
569
570     if( psz_var )
571     {
572         free( psz_var );
573     }
574
575     /* Don't forget that the module is still locked */
576     return p_module;
577 }
578
579 /*****************************************************************************
580  * module_Unneed: decrease the usage count of a module.
581  *****************************************************************************
582  * This function must be called by the thread that called module_Need, to
583  * decrease the reference count and allow for hiding of modules.
584  *****************************************************************************/
585 void __module_Unneed( vlc_object_t * p_this, module_t * p_module )
586 {
587     /* Use the close method */
588     if( p_module->pf_deactivate )
589     {
590         p_module->pf_deactivate( p_this );
591     }
592
593     msg_Dbg( p_module, "unlocking module \"%s\"", p_module->psz_object_name );
594
595     vlc_object_release( p_module );
596
597     return;
598 }
599
600 /*****************************************************************************
601  * Following functions are local.
602  *****************************************************************************/
603
604 /*****************************************************************************
605  * AllocateAllPlugins: load all plugin modules we can find.
606  *****************************************************************************/
607 #ifdef HAVE_DYNAMIC_PLUGINS
608 static void AllocateAllPlugins( vlc_object_t *p_this )
609 {
610     /* Yes, there are two NULLs because we replace one with "plugin-path". */
611     char *          path[] = { "modules", PLUGIN_PATH, "plugins", NULL,
612                                NULL };
613
614     char **         ppsz_path = path;
615     char *          psz_fullpath;
616
617 #if defined( UNDER_CE )
618     wchar_t         psz_dir[MAX_PATH];
619 #endif
620
621     /* If the user provided a plugin path, we add it to the list */
622     path[ sizeof(path)/sizeof(char*) - 2 ] = config_GetPsz( p_this,
623                                                             "plugin-path" );
624
625     for( ; *ppsz_path != NULL ; ppsz_path++ )
626     {
627 #if defined( SYS_BEOS ) || defined( SYS_DARWIN ) \
628      || ( defined( WIN32 ) && !defined( UNDER_CE ) )
629
630         /* Handle relative as well as absolute paths */
631 #ifdef WIN32
632         if( !(*ppsz_path)[0] || (*ppsz_path)[1] != ':' )
633 #else
634         if( (*ppsz_path)[0] != '/' )
635 #endif
636         {
637             int i_dirlen = strlen( *ppsz_path );
638             i_dirlen += strlen( p_this->p_libvlc->psz_vlcpath ) + 2;
639
640             psz_fullpath = malloc( i_dirlen );
641             if( psz_fullpath == NULL )
642             {
643                 continue;
644             }
645 #ifdef WIN32
646             sprintf( psz_fullpath, "%s\\%s",
647                      p_this->p_libvlc->psz_vlcpath, *ppsz_path );
648 #else
649             sprintf( psz_fullpath, "%s/%s",
650                      p_this->p_libvlc->psz_vlcpath, *ppsz_path );
651 #endif
652         }
653         else
654 #endif
655         {
656             psz_fullpath = strdup( *ppsz_path );
657         }
658
659         msg_Dbg( p_this, "recursively browsing `%s'", psz_fullpath );
660
661         /* Don't go deeper than 5 subdirectories */
662 #if defined( UNDER_CE )
663         MultiByteToWideChar( CP_ACP, 0, psz_fullpath, -1, psz_dir, MAX_PATH );
664         AllocatePluginDir( p_this, psz_dir, 5 );
665 #else
666         AllocatePluginDir( p_this, psz_fullpath, 5 );
667 #endif
668
669         free( psz_fullpath );
670     }
671
672     /* Free plugin-path */
673     if( path[ sizeof(path)/sizeof(char*) - 2 ] )
674         free( path[ sizeof(path)/sizeof(char*) - 2 ] );
675     path[ sizeof(path)/sizeof(char*) - 2 ] = NULL;
676 }
677
678 /*****************************************************************************
679  * AllocatePluginDir: recursively parse a directory to look for plugins
680  *****************************************************************************/
681 static void AllocatePluginDir( vlc_object_t *p_this, const MYCHAR *psz_dir,
682                                int i_maxdepth )
683 {
684 #if defined( UNDER_CE ) || defined( _MSC_VER )
685 #ifdef UNDER_CE
686     MYCHAR psz_path[MAX_PATH + 256];
687 #else
688     char psz_path[MAX_PATH + 256];
689 #endif
690     WIN32_FIND_DATA finddata;
691     HANDLE handle;
692     unsigned int rc;
693 #else
694     int    i_dirlen;
695     DIR *  dir;
696     char * psz_file;
697     struct dirent * file;
698 #endif
699
700     if( p_this->p_vlc->b_die || i_maxdepth < 0 )
701     {
702         return;
703     }
704
705 #if defined( UNDER_CE ) || defined( _MSC_VER )
706     rc = GetFileAttributes( psz_dir );
707     if( !(rc & FILE_ATTRIBUTE_DIRECTORY) )
708     {
709         /* Not a directory */
710         return;
711     }
712
713     /* Parse all files in the directory */
714 #ifdef UNDER_CE
715     swprintf( psz_path, L"%s\\*.*", psz_dir );
716 #else
717     sprintf( psz_path, "%s\\*.*", psz_dir );
718 #endif
719     handle = FindFirstFile( psz_path, &finddata );
720     if( handle == INVALID_HANDLE_VALUE )
721     {
722         /* Empty directory */
723         return;
724     }
725
726     /* Parse the directory and try to load all files it contains. */
727     do
728     {
729 #ifdef UNDER_CE
730         unsigned int i_len = wcslen( finddata.cFileName );
731         swprintf( psz_path, L"%s\\%s", psz_dir, finddata.cFileName );
732 #else
733         unsigned int i_len = strlen( finddata.cFileName );
734         /* Skip ".", ".." and anything starting with "." */
735         if( !*finddata.cFileName || *finddata.cFileName == '.' )
736         {
737             if( !FindNextFile( handle, &finddata ) ) break;
738             continue;
739         }
740         sprintf( psz_path, "%s\\%s", psz_dir, finddata.cFileName );
741 #endif
742
743         if( GetFileAttributes( psz_path ) & FILE_ATTRIBUTE_DIRECTORY )
744         {
745             AllocatePluginDir( p_this, psz_path, i_maxdepth - 1 );
746         }
747         else if( i_len > strlen( LIBEXT )
748 #ifdef UNDER_CE
749                 )
750 #else
751                   /* We only load files ending with LIBEXT */
752                   && !strncasecmp( psz_path + strlen( psz_path)
753                                    - strlen( LIBEXT ),
754                                    LIBEXT, strlen( LIBEXT ) ) )
755 #endif
756         {
757             AllocatePluginFile( p_this, psz_path );
758         }
759     }
760     while( !p_this->p_vlc->b_die && FindNextFile( handle, &finddata ) );
761
762     /* Close the directory */
763     FindClose( handle );
764
765 #else
766     dir = opendir( psz_dir );
767     if( !dir )
768     {
769         return;
770     }
771
772     i_dirlen = strlen( psz_dir );
773
774     /* Parse the directory and try to load all files it contains. */
775     while( !p_this->p_vlc->b_die && (file = readdir( dir )) )
776     {
777         struct stat statbuf;
778         unsigned int i_len;
779
780         /* Skip ".", ".." and anything starting with "." */
781         if( !*file->d_name || *file->d_name == '.' )
782         {
783             continue;
784         }
785
786         i_len = strlen( file->d_name );
787         psz_file = malloc( i_dirlen + 1 + i_len + 1 );
788 #ifdef WIN32
789         sprintf( psz_file, "%s\\%s", psz_dir, file->d_name );
790 #else
791         sprintf( psz_file, "%s/%s", psz_dir, file->d_name );
792 #endif
793
794         if( !stat( psz_file, &statbuf ) && statbuf.st_mode & S_IFDIR )
795         {
796             AllocatePluginDir( p_this, psz_file, i_maxdepth - 1 );
797         }
798         else if( i_len > strlen( LIBEXT )
799                   /* We only load files ending with LIBEXT */
800                   && !strncasecmp( file->d_name + i_len - strlen( LIBEXT ),
801                                    LIBEXT, strlen( LIBEXT ) ) )
802         {
803             AllocatePluginFile( p_this, psz_file );
804         }
805
806         free( psz_file );
807     }
808
809     /* Close the directory */
810     closedir( dir );
811
812 #endif
813 }
814
815 /*****************************************************************************
816  * AllocatePluginFile: load a module into memory and initialize it.
817  *****************************************************************************
818  * This function loads a dynamically loadable module and allocates a structure
819  * for its information data. The module can then be handled by module_Need
820  * and module_Unneed. It can be removed by DeleteModule.
821  *****************************************************************************/
822 static int AllocatePluginFile( vlc_object_t * p_this, MYCHAR * psz_file )
823 {
824     module_t * p_module;
825     module_handle_t handle;
826
827     /*
828      * Try to dynamically load the module. This part is very platform-
829      * specific, and error messages should be as verbose as possible.
830      */
831
832 #if defined(HAVE_DL_DYLD)
833     NSObjectFileImage image;
834     NSObjectFileImageReturnCode ret;
835
836     ret = NSCreateObjectFileImageFromFile( psz_file, &image );
837
838     if( ret != NSObjectFileImageSuccess )
839     {
840         msg_Warn( p_this, "cannot create image from `%s'", psz_file );
841         return -1;
842     }
843
844     /* Open the dynamic module */
845     handle = NSLinkModule( image, psz_file,
846                            NSLINKMODULE_OPTION_RETURN_ON_ERROR );
847
848     if( !handle )
849     {
850         NSLinkEditErrors errors;
851         const char *psz_file, *psz_err;
852         int i_errnum;
853         NSLinkEditError( &errors, &i_errnum, &psz_file, &psz_err );
854         msg_Warn( p_this, "cannot link module `%s' (%s)", psz_file, psz_err );
855         NSDestroyObjectFileImage( image );
856         return -1;
857     }
858
859     /* Destroy our image, we won't need it */
860     NSDestroyObjectFileImage( image );
861
862 #elif defined(HAVE_DL_BEOS)
863     handle = load_add_on( psz_file );
864     if( handle < 0 )
865     {
866         msg_Warn( p_this, "cannot load module `%s'", psz_file );
867         return -1;
868     }
869
870 #elif defined(HAVE_DL_WINDOWS) && defined(UNDER_CE)
871     char psz_filename[MAX_PATH];
872     WideCharToMultiByte( CP_ACP, WC_DEFAULTCHAR, psz_file, -1,
873                          psz_filename, MAX_PATH, NULL, NULL );
874     handle = LoadLibrary( psz_filename );
875     if( handle == NULL )
876     {
877         char *psz_error = GetWindowsError();
878         msg_Warn( p_this, "cannot load module `%s' (%s)",
879                           psz_filename, psz_error );
880         free( psz_error );
881     }
882
883 #elif defined(HAVE_DL_WINDOWS) && defined(WIN32)
884     handle = LoadLibrary( psz_file );
885     if( handle == NULL )
886     {
887         char *psz_error = GetWindowsError();
888         msg_Warn( p_this, "cannot load module `%s' (%s)",
889                           psz_file, psz_error );
890         free( psz_error );
891     }
892
893 #elif defined(HAVE_DL_DLOPEN) && defined(RTLD_NOW)
894     /* static is OK, we are called atomically */
895     static vlc_bool_t b_kde = VLC_FALSE;
896
897 #   if defined(SYS_LINUX)
898     /* XXX HACK #1 - we should NOT open modules with RTLD_GLOBAL, or we
899      * are going to get namespace collisions when two modules have common
900      * public symbols, but ALSA is being a pest here. */
901     if( strstr( psz_file, "alsa_plugin" ) )
902     {
903         handle = dlopen( psz_file, RTLD_NOW | RTLD_GLOBAL );
904         if( handle == NULL )
905         {
906             msg_Warn( p_this, "cannot load module `%s' (%s)",
907                               psz_file, dlerror() );
908             return -1;
909         }
910     }
911 #   endif
912     /* XXX HACK #2 - the ugly KDE workaround. It seems that libkdewhatever
913      * causes dlopen() to segfault if libstdc++ is not loaded in the caller,
914      * so we just load libstdc++. Bwahahaha! ph34r! -- Sam. */
915     /* Update: FYI, this is Debian bug #180505, and seems to be fixed. */
916     if( !b_kde && !strstr( psz_file, "kde" ) )
917     {
918         dlopen( "libstdc++.so.6", RTLD_NOW )
919          || dlopen( "libstdc++.so.5", RTLD_NOW )
920          || dlopen( "libstdc++.so.4", RTLD_NOW )
921          || dlopen( "libstdc++.so.3", RTLD_NOW );
922         b_kde = VLC_TRUE;
923     }
924
925     handle = dlopen( psz_file, RTLD_NOW );
926     if( handle == NULL )
927     {
928         msg_Warn( p_this, "cannot load module `%s' (%s)",
929                           psz_file, dlerror() );
930         return -1;
931     }
932
933 #elif defined(HAVE_DL_DLOPEN)
934 #   if defined(DL_LAZY)
935     handle = dlopen( psz_file, DL_LAZY );
936 #   else
937     handle = dlopen( psz_file, 0 );
938 #   endif
939     if( handle == NULL )
940     {
941         msg_Warn( p_this, "cannot load module `%s' (%s)",
942                           psz_file, dlerror() );
943         return -1;
944     }
945
946 #elif defined(HAVE_DL_SHL_LOAD)
947     handle = shl_load( psz_file, BIND_IMMEDIATE | BIND_NONFATAL, NULL );
948     if( handle == NULL )
949     {
950         msg_Warn( p_this, "cannot load module `%s' (%s)",
951                           psz_file, strerror(errno) );
952         return -1;
953     }
954
955 #else
956 #   error "Something is wrong in modules.c"
957
958 #endif
959
960     /* Now that we have successfully loaded the module, we can
961      * allocate a structure for it */
962     p_module = vlc_object_create( p_this, VLC_OBJECT_MODULE );
963     if( p_module == NULL )
964     {
965         msg_Err( p_this, "out of memory" );
966         CloseModule( handle );
967         return -1;
968     }
969
970     /* We need to fill these since they may be needed by CallEntry() */
971 #ifdef UNDER_CE
972     p_module->psz_filename = psz_filename;
973 #else
974     p_module->psz_filename = psz_file;
975 #endif
976     p_module->handle = handle;
977     p_module->p_symbols = &p_this->p_libvlc->p_module_bank->symbols;
978
979     /* Initialize the module: fill p_module->psz_object_name, default config */
980     if( CallEntry( p_module ) != 0 )
981     {
982         /* We couldn't call module_init() */
983         vlc_object_destroy( p_module );
984         CloseModule( handle );
985         return -1;
986     }
987
988     DupModule( p_module );
989     p_module->psz_filename = strdup( p_module->psz_filename );
990     p_module->psz_longname = strdup( p_module->psz_longname );
991
992     /* Everything worked fine ! The module is ready to be added to the list. */
993     p_module->b_builtin = VLC_FALSE;
994
995     /* msg_Dbg( p_this, "plugin \"%s\", %s",
996                 p_module->psz_object_name, p_module->psz_longname ); */
997
998     vlc_object_attach( p_module, p_this->p_libvlc->p_module_bank );
999
1000     return 0;
1001 }
1002
1003 /*****************************************************************************
1004  * DupModule: make a plugin module standalone.
1005  *****************************************************************************
1006  * This function duplicates all strings in the module, so that the dynamic
1007  * object can be unloaded. It acts recursively on submodules.
1008  *****************************************************************************/
1009 static void DupModule( module_t *p_module )
1010 {
1011     char **pp_shortcut;
1012     int i_submodule;
1013
1014     for( pp_shortcut = p_module->pp_shortcuts ; *pp_shortcut ; pp_shortcut++ )
1015     {
1016         *pp_shortcut = strdup( *pp_shortcut );
1017     }
1018
1019     /* We strdup() these entries so that they are still valid when the
1020      * module is unloaded. */
1021     p_module->psz_object_name = strdup( p_module->psz_object_name );
1022     p_module->psz_capability = strdup( p_module->psz_capability );
1023
1024     if( p_module->psz_program != NULL )
1025     {
1026         p_module->psz_program = strdup( p_module->psz_program );
1027     }
1028
1029     for( i_submodule = 0; i_submodule < p_module->i_children; i_submodule++ )
1030     {
1031         DupModule( (module_t*)p_module->pp_children[ i_submodule ] );
1032     }
1033 }
1034
1035 /*****************************************************************************
1036  * UndupModule: free a duplicated module.
1037  *****************************************************************************
1038  * This function frees the allocations done in DupModule().
1039  *****************************************************************************/
1040 static void UndupModule( module_t *p_module )
1041 {
1042     char **pp_shortcut;
1043     int i_submodule;
1044
1045     for( i_submodule = 0; i_submodule < p_module->i_children; i_submodule++ )
1046     {
1047         UndupModule( (module_t*)p_module->pp_children[ i_submodule ] );
1048     }
1049
1050     for( pp_shortcut = p_module->pp_shortcuts ; *pp_shortcut ; pp_shortcut++ )
1051     {
1052         free( *pp_shortcut );
1053     }
1054
1055     free( p_module->psz_object_name );
1056     free( p_module->psz_capability );
1057
1058     if( p_module->psz_program != NULL )
1059     {
1060         free( p_module->psz_program );
1061     }
1062 }
1063
1064 #endif /* HAVE_DYNAMIC_PLUGINS */
1065
1066 /*****************************************************************************
1067  * AllocateBuiltinModule: initialize a builtin module.
1068  *****************************************************************************
1069  * This function registers a builtin module and allocates a structure
1070  * for its information data. The module can then be handled by module_Need
1071  * and module_Unneed. It can be removed by DeleteModule.
1072  *****************************************************************************/
1073 static int AllocateBuiltinModule( vlc_object_t * p_this,
1074                                   int ( *pf_entry ) ( module_t * ) )
1075 {
1076     module_t * p_module;
1077
1078     /* Now that we have successfully loaded the module, we can
1079      * allocate a structure for it */
1080     p_module = vlc_object_create( p_this, VLC_OBJECT_MODULE );
1081     if( p_module == NULL )
1082     {
1083         msg_Err( p_this, "out of memory" );
1084         return -1;
1085     }
1086
1087     /* Initialize the module : fill p_module->psz_object_name, etc. */
1088     if( pf_entry( p_module ) != 0 )
1089     {
1090         /* With a well-written module we shouldn't have to print an
1091          * additional error message here, but just make sure. */
1092         msg_Err( p_this, "failed calling entry point in builtin module" );
1093         vlc_object_destroy( p_module );
1094         return -1;
1095     }
1096
1097     /* Everything worked fine ! The module is ready to be added to the list. */
1098     p_module->b_builtin = VLC_TRUE;
1099
1100     /* msg_Dbg( p_this, "builtin \"%s\", %s",
1101                 p_module->psz_object_name, p_module->psz_longname ); */
1102
1103     vlc_object_attach( p_module, p_this->p_libvlc->p_module_bank );
1104
1105     return 0;
1106 }
1107
1108 /*****************************************************************************
1109  * DeleteModule: delete a module and its structure.
1110  *****************************************************************************
1111  * This function can only be called if the module isn't being used.
1112  *****************************************************************************/
1113 static int DeleteModule( module_t * p_module )
1114 {
1115     vlc_object_detach( p_module );
1116
1117     /* We free the structures that we strdup()ed in Allocate*Module(). */
1118 #ifdef HAVE_DYNAMIC_PLUGINS
1119     if( !p_module->b_builtin )
1120     {
1121         if( p_module->b_unloadable )
1122         {
1123             CloseModule( p_module->handle );
1124         }
1125         UndupModule( p_module );
1126         free( p_module->psz_filename );
1127         free( p_module->psz_longname );
1128     }
1129 #endif
1130
1131     /* Free and detach the object's children */
1132     while( p_module->i_children )
1133     {
1134         vlc_object_t *p_this = p_module->pp_children[0];
1135         vlc_object_detach( p_this );
1136         vlc_object_destroy( p_this );
1137     }
1138
1139     config_Free( p_module );
1140     vlc_object_destroy( p_module );
1141
1142     return 0;
1143 }
1144
1145 #ifdef HAVE_DYNAMIC_PLUGINS
1146 /*****************************************************************************
1147  * CallEntry: call an entry point.
1148  *****************************************************************************
1149  * This function calls a symbol given its name and a module structure. The
1150  * symbol MUST refer to a function returning int and taking a module_t* as
1151  * an argument.
1152  *****************************************************************************/
1153 static int CallEntry( module_t * p_module )
1154 {
1155     static char *psz_name = "vlc_entry" MODULE_SUFFIX;
1156     int (* pf_symbol) ( module_t * p_module );
1157
1158     /* Try to resolve the symbol */
1159     pf_symbol = (int (*)(module_t *)) GetSymbol( p_module->handle, psz_name );
1160
1161     if( pf_symbol == NULL )
1162     {
1163 #if defined(HAVE_DL_DYLD) || defined(HAVE_DL_BEOS)
1164         msg_Warn( p_module, "cannot find symbol \"%s\" in file `%s'",
1165                             psz_name, p_module->psz_filename );
1166 #elif defined(HAVE_DL_WINDOWS)
1167         char *psz_error = GetWindowsError();
1168         msg_Warn( p_module, "cannot find symbol \"%s\" in file `%s' (%s)",
1169                             psz_name, p_module->psz_filename, psz_error );
1170         free( psz_error );
1171 #elif defined(HAVE_DL_DLOPEN)
1172         msg_Warn( p_module, "cannot find symbol \"%s\" in file `%s' (%s)",
1173                             psz_name, p_module->psz_filename, dlerror() );
1174 #elif defined(HAVE_DL_SHL_LOAD)
1175         msg_Warn( p_module, "cannot find symbol \"%s\" in file `%s' (%s)",
1176                             psz_name, p_module->psz_filename, strerror(errno) );
1177 #else
1178 #   error "Something is wrong in modules.c"
1179 #endif
1180         return -1;
1181     }
1182
1183     /* We can now try to call the symbol */
1184     if( pf_symbol( p_module ) != 0 )
1185     {
1186         /* With a well-written module we shouldn't have to print an
1187          * additional error message here, but just make sure. */
1188         msg_Err( p_module, "failed calling symbol \"%s\" in file `%s'",
1189                            psz_name, p_module->psz_filename );
1190         return -1;
1191     }
1192
1193     /* Everything worked fine, we can return */
1194     return 0;
1195 }
1196
1197 /*****************************************************************************
1198  * CloseModule: unload a dynamic library
1199  *****************************************************************************
1200  * This function unloads a previously opened dynamically linked library
1201  * using a system dependant method. No return value is taken in consideration,
1202  * since some libraries sometimes refuse to close properly.
1203  *****************************************************************************/
1204 static void CloseModule( module_handle_t handle )
1205 {
1206 #if defined(HAVE_DL_DYLD)
1207     NSUnLinkModule( handle, FALSE );
1208
1209 #elif defined(HAVE_DL_BEOS)
1210     unload_add_on( handle );
1211
1212 #elif defined(HAVE_DL_WINDOWS)
1213     FreeLibrary( handle );
1214
1215 #elif defined(HAVE_DL_DLOPEN)
1216     dlclose( handle );
1217
1218 #elif defined(HAVE_DL_SHL_LOAD)
1219     shl_unload( handle );
1220
1221 #endif
1222     return;
1223 }
1224
1225 /*****************************************************************************
1226  * GetSymbol: get a symbol from a dynamic library
1227  *****************************************************************************
1228  * This function queries a loaded library for a symbol specified in a
1229  * string, and returns a pointer to it. We don't check for dlerror() or
1230  * similar functions, since we want a non-NULL symbol anyway.
1231  *****************************************************************************/
1232 static void * _module_getsymbol( module_handle_t, const char * );
1233
1234 static void * GetSymbol( module_handle_t handle, const char * psz_function )
1235 {
1236     void * p_symbol = _module_getsymbol( handle, psz_function );
1237
1238     /* MacOS X dl library expects symbols to begin with "_". So do
1239      * some other operating systems. That's really lame, but hey, what
1240      * can we do ? */
1241     if( p_symbol == NULL )
1242     {
1243         char *psz_call = malloc( strlen( psz_function ) + 2 );
1244
1245         strcpy( psz_call + 1, psz_function );
1246         psz_call[ 0 ] = '_';
1247         p_symbol = _module_getsymbol( handle, psz_call );
1248         free( psz_call );
1249     }
1250
1251     return p_symbol;
1252 }
1253
1254 static void * _module_getsymbol( module_handle_t handle,
1255                                  const char * psz_function )
1256 {
1257 #if defined(HAVE_DL_DYLD)
1258     NSSymbol sym = NSLookupSymbolInModule( handle, psz_function );
1259     return NSAddressOfSymbol( sym );
1260
1261 #elif defined(HAVE_DL_BEOS)
1262     void * p_symbol;
1263     if( B_OK == get_image_symbol( handle, psz_function,
1264                                   B_SYMBOL_TYPE_TEXT, &p_symbol ) )
1265     {
1266         return p_symbol;
1267     }
1268     else
1269     {
1270         return NULL;
1271     }
1272
1273 #elif defined(HAVE_DL_WINDOWS) && defined(UNDER_CE)
1274     wchar_t psz_real[256];
1275     MultiByteToWideChar( CP_ACP, 0, psz_function, -1, psz_real, 256 );
1276
1277     return (void *)GetProcAddress( handle, psz_real );
1278
1279 #elif defined(HAVE_DL_WINDOWS) && defined(WIN32)
1280     return (void *)GetProcAddress( handle, (MYCHAR*)psz_function );
1281
1282 #elif defined(HAVE_DL_DLOPEN)
1283     return dlsym( handle, psz_function );
1284
1285 #elif defined(HAVE_DL_SHL_LOAD)
1286     void *p_sym;
1287     shl_findsym( &handle, psz_function, TYPE_UNDEFINED, &p_sym );
1288     return p_sym;
1289
1290 #endif
1291 }
1292
1293 #if defined(HAVE_DL_WINDOWS)
1294 static char * GetWindowsError( void )
1295 {
1296 #if defined(UNDER_CE)
1297     wchar_t psz_tmp[256];
1298     char * psz_buffer = malloc( 256 );
1299 #else
1300     char * psz_tmp = malloc( 256 );
1301 #endif
1302     int i = 0, i_error = GetLastError();
1303
1304     FormatMessage( FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
1305                    NULL, i_error, MAKELANGID (LANG_NEUTRAL, SUBLANG_DEFAULT),
1306                    (LPTSTR) psz_tmp, 256, NULL );
1307
1308     /* Go to the end of the string */
1309 #if defined(UNDER_CE)
1310     while( psz_tmp[i] && psz_tmp[i] != L'\r' && psz_tmp[i] != L'\n' )
1311 #else
1312     while( psz_tmp[i] && psz_tmp[i] != '\r' && psz_tmp[i] != '\n' )
1313 #endif
1314     {
1315         i++;
1316     }
1317
1318     if( psz_tmp[i] )
1319     {
1320 #if defined(UNDER_CE)
1321         swprintf( psz_tmp + i, L" (error %i)", i_error );
1322         psz_tmp[ 255 ] = L'\0';
1323 #else
1324         snprintf( psz_tmp + i, 256 - i, " (error %i)", i_error );
1325         psz_tmp[ 255 ] = '\0';
1326 #endif
1327     }
1328
1329 #if defined(UNDER_CE)
1330     WideCharToMultiByte( CP_ACP, WC_DEFAULTCHAR, psz_tmp, -1,
1331                          psz_buffer, 256, NULL, NULL );
1332     return psz_buffer;
1333 #else
1334     return psz_tmp;
1335 #endif
1336 }
1337 #endif /* HAVE_DL_WINDOWS */
1338
1339 #endif /* HAVE_DYNAMIC_PLUGINS */