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