]> git.sesse.net Git - vlc/blob - src/libvlc-common.c
- Do not attach libvlc to the global data
[vlc] / src / libvlc-common.c
1 /*****************************************************************************
2  * libvlc-common.c: libvlc instances creation and deletion, interfaces handling
3  *****************************************************************************
4  * Copyright (C) 1998-2006 the VideoLAN team
5  * $Id$
6  *
7  * Authors: Vincent Seguin <seguin@via.ecp.fr>
8  *          Samuel Hocevar <sam@zoy.org>
9  *          Gildas Bazin <gbazin@videolan.org>
10  *          Derk-Jan Hartman <hartman at videolan dot org>
11  *          RĂ©mi Denis-Courmont <rem # videolan : org>
12  *
13  * This program is free software; you can redistribute it and/or modify
14  * it under the terms of the GNU General Public License as published by
15  * the Free Software Foundation; either version 2 of the License, or
16  * (at your option) any later version.
17  *
18  * This program is distributed in the hope that it will be useful,
19  * but WITHOUT ANY WARRANTY; without even the implied warranty of
20  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
21  * GNU General Public License for more details.
22  *
23  * You should have received a copy of the GNU General Public License
24  * along with this program; if not, write to the Free Software
25  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
26  *****************************************************************************/
27
28 /** \file
29  * This file contains functions to create and destroy libvlc instances
30  */
31
32 /*****************************************************************************
33  * Pretend we are a builtin module
34  *****************************************************************************/
35 #define MODULE_NAME main
36 #define MODULE_PATH main
37 #define __BUILTIN__
38
39 /*****************************************************************************
40  * Preamble
41  *****************************************************************************/
42 #include <vlc/vlc.h>
43 #include <libvlc_internal.h>
44 #include <vlc/input.h>
45
46 #include <errno.h>                                                 /* ENOMEM */
47 #include <stdio.h>                                              /* sprintf() */
48 #include <string.h>                                            /* strerror() */
49 #include <stdlib.h>                                                /* free() */
50
51 #ifndef WIN32
52 #   include <netinet/in.h>                            /* BSD: struct in_addr */
53 #endif
54
55 #ifdef HAVE_UNISTD_H
56 #   include <unistd.h>
57 #elif defined( WIN32 ) && !defined( UNDER_CE )
58 #   include <io.h>
59 #endif
60
61 #ifdef WIN32                       /* optind, getopt(), included in unistd.h */
62 #   include "extras/getopt.h"
63 #endif
64
65 #ifdef HAVE_LOCALE_H
66 #   include <locale.h>
67 #endif
68
69 #ifdef HAVE_HAL
70 #   include <hal/libhal.h>
71 #endif
72
73 #include "vlc_cpu.h"                                        /* CPU detection */
74 #include "os_specific.h"
75
76 #include "vlc_error.h"
77
78 #include "vlc_playlist.h"
79 #include "vlc_interface.h"
80
81 #include "audio_output.h"
82
83 #include "vlc_video.h"
84 #include "video_output.h"
85
86 #include "stream_output.h"
87 #include "charset.h"
88
89 #include "libvlc.h"
90
91 /*****************************************************************************
92  * The evil global variable. We handle it with care, don't worry.
93  *****************************************************************************/
94 static libvlc_global_data_t   libvlc_global;
95 static libvlc_global_data_t * p_libvlc_global;
96 static libvlc_int_t *    p_static_vlc;
97 static volatile unsigned int i_instances = 0;
98
99 /*****************************************************************************
100  * Local prototypes
101  *****************************************************************************/
102 void LocaleInit( vlc_object_t * );
103 void LocaleDeinit( void );
104 static void SetLanguage   ( char const * );
105 static int  GetFilenames  ( libvlc_int_t *, int, char *[] );
106 static void Help          ( libvlc_int_t *, char const *psz_help_name );
107 static void Usage         ( libvlc_int_t *, char const *psz_module_name );
108 static void ListModules   ( libvlc_int_t * );
109 static void Version       ( void );
110
111 #ifdef WIN32
112 static void ShowConsole   ( vlc_bool_t );
113 static void PauseConsole  ( void );
114 extern void __wgetmainargs(int *argc, wchar_t ***wargv, wchar_t ***wenviron,
115                            int expand_wildcards, int *startupinfo);
116 #endif
117 static int  ConsoleWidth  ( void );
118
119 static int  VerboseCallback( vlc_object_t *, char const *,
120                              vlc_value_t, vlc_value_t, void * );
121
122 static void InitDeviceValues( libvlc_int_t * );
123
124 /*****************************************************************************
125  * vlc_current_object: return the current object.
126  *****************************************************************************
127  * If i_object is non-zero, return the corresponding object. Otherwise,
128  * return the statically allocated p_vlc object.
129  *****************************************************************************/
130 libvlc_int_t * vlc_current_object( int i_object )
131 {
132     if( i_object )
133     {
134          return vlc_object_get( p_libvlc_global, i_object );
135     }
136
137     return p_static_vlc;
138 }
139
140
141 /**
142  * Allocate a libvlc instance, initialize global data if needed
143  * It also initializes the threading system
144  */
145 libvlc_int_t * libvlc_InternalCreate( void )
146 {
147     int i_ret;
148     libvlc_int_t * p_libvlc = NULL;
149     vlc_value_t lockval;
150     char *psz_env;
151
152     /* &libvlc_global never changes,
153      * so we can safely call this multiple times. */
154     p_libvlc_global = &libvlc_global;
155
156     /* vlc_threads_init *must* be the first internal call! No other call is
157      * allowed before the thread system has been initialized. */
158     i_ret = vlc_threads_init( p_libvlc_global );
159     if( i_ret < 0 ) return NULL;
160
161     /* Now that the thread system is initialized, we don't have much, but
162      * at least we have var_Create */
163     var_Create( p_libvlc_global, "libvlc", VLC_VAR_MUTEX );
164     var_Get( p_libvlc_global, "libvlc", &lockval );
165     vlc_mutex_lock( lockval.p_address );
166
167     i_instances++;
168
169     if( !libvlc_global.b_ready )
170     {
171         /* Guess what CPU we have */
172         libvlc_global.i_cpu = CPUCapabilities();
173        /* The module bank will be initialized later */
174         libvlc_global.p_module_bank = NULL;
175
176         libvlc_global.b_ready = VLC_TRUE;
177     }
178     vlc_mutex_unlock( lockval.p_address );
179     var_Destroy( p_libvlc_global, "libvlc" );
180
181     /* Allocate a libvlc instance object */
182     p_libvlc = vlc_object_create( p_libvlc_global, VLC_OBJECT_LIBVLC );
183     if( p_libvlc == NULL ) { i_instances--; return NULL; }
184     p_libvlc->thread_id = 0;
185     p_libvlc->p_playlist = NULL;
186     p_libvlc->psz_object_name = "libvlc";
187
188     /* Initialize message queue */
189     msg_Create( p_libvlc );
190     /* Announce who we are - Do it only for first instance ? */
191     msg_Dbg( p_libvlc, COPYRIGHT_MESSAGE );
192     msg_Dbg( p_libvlc, "libvlc was configured with %s", CONFIGURE_LINE );
193
194     /* Find verbosity from VLC_VERBOSE environment variable */
195     psz_env = getenv( "VLC_VERBOSE" );
196     p_libvlc->i_verbose = psz_env ? atoi( psz_env ) : -1;
197
198 #if defined( HAVE_ISATTY ) && !defined( WIN32 )
199     p_libvlc->b_color = isatty( 2 ); /* 2 is for stderr */
200 #else
201     p_libvlc->b_color = VLC_FALSE;
202 #endif
203
204     /* Initialize mutexes */
205     vlc_mutex_init( p_libvlc, &p_libvlc->config_lock );
206 #ifdef __APPLE__
207     vlc_mutex_init( p_libvlc, &p_libvlc->quicktime_lock );
208     vlc_thread_set_priority( p_libvlc, VLC_THREAD_PRIORITY_LOW );
209 #endif
210
211     /* Store data for the non-reentrant API */
212     p_static_vlc = p_libvlc;
213
214     return p_libvlc;
215 }
216
217 /**
218  * Initialize a libvlc instance
219  * This function initializes a previously allocated libvlc instance:
220  *  - CPU detection
221  *  - gettext initialization
222  *  - message queue, module bank and playlist initialization
223  *  - configuration and commandline parsing
224  */
225 int libvlc_InternalInit( libvlc_int_t *p_libvlc, int i_argc, char *ppsz_argv[] )
226 {
227     char         p_capabilities[200];
228     char *       p_tmp;
229     char *       psz_modules;
230     char *       psz_parser;
231     char *       psz_control;
232     vlc_bool_t   b_exit = VLC_FALSE;
233     int          i_ret = VLC_EEXIT;
234     module_t    *p_help_module;
235     playlist_t  *p_playlist;
236     vlc_value_t  val;
237 #if defined( ENABLE_NLS ) \
238      && ( defined( HAVE_GETTEXT ) || defined( HAVE_INCLUDED_GETTEXT ) )
239 # if defined (WIN32) || defined (__APPLE__)
240     char *       psz_language;
241 #endif
242 #endif
243
244     /* System specific initialization code */
245     system_Init( p_libvlc, &i_argc, ppsz_argv );
246
247     /* Get the executable name (similar to the basename command) */
248     if( i_argc > 0 )
249     {
250         p_libvlc->psz_object_name = p_tmp = ppsz_argv[ 0 ];
251         while( *p_tmp )
252         {
253             if( *p_tmp == '/' ) p_libvlc->psz_object_name = ++p_tmp;
254             else ++p_tmp;
255         }
256     }
257     else
258     {
259         p_libvlc->psz_object_name = "vlc";
260     }
261
262     /*
263      * Support for gettext
264      */
265     SetLanguage( "" );
266
267     /*
268      * Global iconv, must be done after setlocale()
269      * so that vlc_current_charset() works.
270      */
271     LocaleInit( (vlc_object_t *)p_libvlc );
272
273     /* Translate "C" to the language code: "fr", "en_GB", "nl", "ru"... */
274     msg_Dbg( p_libvlc, "translation test: code is \"%s\"", _("C") );
275
276     /* Initialize the module bank and load the configuration of the
277      * main module. We need to do this at this stage to be able to display
278      * a short help if required by the user. (short help == main module
279      * options) */
280     module_InitBank( p_libvlc );
281
282     /* Hack: insert the help module here */
283     p_help_module = vlc_object_create( p_libvlc, VLC_OBJECT_MODULE );
284     if( p_help_module == NULL )
285     {
286         module_EndBank( p_libvlc );
287         return VLC_EGENERIC;
288     }
289     p_help_module->psz_object_name = "help";
290     p_help_module->psz_longname = N_("Help options");
291     config_Duplicate( p_help_module, p_help_config );
292     vlc_object_attach( p_help_module, libvlc_global.p_module_bank );
293     /* End hack */
294
295     if( config_LoadCmdLine( p_libvlc, &i_argc, ppsz_argv, VLC_TRUE ) )
296     {
297         vlc_object_detach( p_help_module );
298         config_Free( p_help_module );
299         vlc_object_destroy( p_help_module );
300         module_EndBank( p_libvlc );
301         return VLC_EGENERIC;
302     }
303
304     /* Check for short help option */
305     if( config_GetInt( p_libvlc, "help" ) )
306     {
307         Help( p_libvlc, "help" );
308         b_exit = VLC_TRUE;
309         i_ret = VLC_EEXITSUCCESS;
310     }
311     /* Check for version option */
312     else if( config_GetInt( p_libvlc, "version" ) )
313     {
314         Version();
315         b_exit = VLC_TRUE;
316         i_ret = VLC_EEXITSUCCESS;
317     }
318
319     /* Set the config file stuff */
320     p_libvlc->psz_homedir = config_GetHomeDir();
321     p_libvlc->psz_userdir = config_GetUserDir();
322     if( p_libvlc->psz_userdir == NULL )
323         p_libvlc->psz_userdir = strdup(p_libvlc->psz_homedir);
324     p_libvlc->psz_configfile = config_GetPsz( p_libvlc, "config" );
325     if( p_libvlc->psz_configfile != NULL && p_libvlc->psz_configfile[0] == '~'
326          && p_libvlc->psz_configfile[1] == '/' )
327     {
328         char *psz = malloc( strlen(p_libvlc->psz_userdir)
329                              + strlen(p_libvlc->psz_configfile) );
330         /* This is incomplete : we should also support the ~cmassiot/ syntax. */
331         sprintf( psz, "%s/%s", p_libvlc->psz_userdir,
332                                p_libvlc->psz_configfile + 2 );
333         free( p_libvlc->psz_configfile );
334         p_libvlc->psz_configfile = psz;
335     }
336
337     /* Check for plugins cache options */
338     if( config_GetInt( p_libvlc, "reset-plugins-cache" ) )
339     {
340         libvlc_global.p_module_bank->b_cache_delete = VLC_TRUE;
341     }
342
343     /* Hack: remove the help module here */
344     vlc_object_detach( p_help_module );
345     /* End hack */
346
347     /* Will be re-done properly later on */
348     p_libvlc->i_verbose = config_GetInt( p_libvlc, "verbose" );
349
350     /* Check for daemon mode */
351 #ifndef WIN32
352     if( config_GetInt( p_libvlc, "daemon" ) )
353     {
354 #if HAVE_DAEMON
355         if( daemon( 1, 0) != 0 )
356         {
357             msg_Err( p_libvlc, "Unable to fork vlc to daemon mode" );
358             b_exit = VLC_TRUE;
359         }
360
361         p_libvlc->p_libvlc_global->b_daemon = VLC_TRUE;
362
363         /* lets check if we need to write the pidfile */
364         char * psz_pidfile = config_GetPsz( p_libvlc, "pidfile" );
365
366         if( psz_pidfile != NULL )
367         {
368             FILE *pidfile;
369             pid_t i_pid = getpid ();
370             msg_Dbg( p_libvlc, "PID is %d, writing it to %s",
371                                i_pid, psz_pidfile );
372             pidfile = utf8_fopen( psz_pidfile,"w" );
373             if( pidfile != NULL )
374             {
375                 utf8_fprintf( pidfile, "%d", (int)i_pid );
376                 fclose( pidfile );
377             }
378             else
379             {
380                 msg_Err( p_libvlc, "cannot open pid file for writing: %s (%s)",
381                          psz_pidfile, strerror(errno) );
382             }
383         }
384         free( psz_pidfile );
385
386 #else
387         pid_t i_pid;
388
389         if( ( i_pid = fork() ) < 0 )
390         {
391             msg_Err( p_libvlc, "unable to fork vlc to daemon mode" );
392             b_exit = VLC_TRUE;
393         }
394         else if( i_pid )
395         {
396             /* This is the parent, exit right now */
397             msg_Dbg( p_libvlc, "closing parent process" );
398             b_exit = VLC_TRUE;
399             i_ret = VLC_EEXITSUCCESS;
400         }
401         else
402         {
403             /* We are the child */
404             msg_Dbg( p_libvlc, "daemon spawned" );
405             close( STDIN_FILENO );
406             close( STDOUT_FILENO );
407             close( STDERR_FILENO );
408
409             p_libvlc->p_libvlc_global->b_daemon = VLC_TRUE;
410         }
411 #endif
412     }
413 #endif
414
415     if( b_exit )
416     {
417         config_Free( p_help_module );
418         vlc_object_destroy( p_help_module );
419         module_EndBank( p_libvlc );
420         return i_ret;
421     }
422
423     /* Check for translation config option */
424 #if defined( ENABLE_NLS ) \
425      && ( defined( HAVE_GETTEXT ) || defined( HAVE_INCLUDED_GETTEXT ) )
426 # if defined (WIN32) || defined (__APPLE__)
427     /* This ain't really nice to have to reload the config here but it seems
428      * the only way to do it. */
429     config_LoadConfigFile( p_libvlc, "main" );
430     config_LoadCmdLine( p_libvlc, &i_argc, ppsz_argv, VLC_TRUE );
431
432     /* Check if the user specified a custom language */
433     psz_language = config_GetPsz( p_libvlc, "language" );
434     if( psz_language && *psz_language && strcmp( psz_language, "auto" ) )
435     {
436         vlc_bool_t b_cache_delete = libvlc_global.p_module_bank->b_cache_delete;
437
438         /* Reset the default domain */
439         SetLanguage( psz_language );
440
441         /* Translate "C" to the language code: "fr", "en_GB", "nl", "ru"... */
442         msg_Dbg( p_libvlc, "translation test: code is \"%s\"", _("C") );
443
444         module_EndBank( p_libvlc );
445         module_InitBank( p_libvlc );
446         config_LoadConfigFile( p_libvlc, "main" );
447         config_LoadCmdLine( p_libvlc, &i_argc, ppsz_argv, VLC_TRUE );
448         libvlc_global.p_module_bank->b_cache_delete = b_cache_delete;
449     }
450     if( psz_language ) free( psz_language );
451 # endif
452 #endif
453
454     /*
455      * Load the builtins and plugins into the module_bank.
456      * We have to do it before config_Load*() because this also gets the
457      * list of configuration options exported by each module and loads their
458      * default values.
459      */
460     module_LoadBuiltins( p_libvlc );
461     module_LoadPlugins( p_libvlc );
462     if( p_libvlc->b_die )
463     {
464         b_exit = VLC_TRUE;
465     }
466
467     msg_Dbg( p_libvlc, "module bank initialized, found %i modules",
468                     libvlc_global.p_module_bank->i_children );
469
470     /* Hack: insert the help module here */
471     vlc_object_attach( p_help_module, libvlc_global.p_module_bank );
472     /* End hack */
473
474     /* Check for help on modules */
475     if( (p_tmp = config_GetPsz( p_libvlc, "module" )) )
476     {
477         Help( p_libvlc, p_tmp );
478         free( p_tmp );
479         b_exit = VLC_TRUE;
480         i_ret = VLC_EEXITSUCCESS;
481     }
482     /* Check for long help option */
483     else if( config_GetInt( p_libvlc, "longhelp" ) )
484     {
485         Help( p_libvlc, "longhelp" );
486         b_exit = VLC_TRUE;
487         i_ret = VLC_EEXITSUCCESS;
488     }
489     /* Check for module list option */
490     else if( config_GetInt( p_libvlc, "list" ) )
491     {
492         ListModules( p_libvlc );
493         b_exit = VLC_TRUE;
494         i_ret = VLC_EEXITSUCCESS;
495     }
496
497     /* Check for config file options */
498     if( config_GetInt( p_libvlc, "reset-config" ) )
499     {
500         vlc_object_detach( p_help_module );
501         config_ResetAll( p_libvlc );
502         config_LoadCmdLine( p_libvlc, &i_argc, ppsz_argv, VLC_TRUE );
503         config_SaveConfigFile( p_libvlc, NULL );
504         vlc_object_attach( p_help_module, libvlc_global.p_module_bank );
505     }
506     if( config_GetInt( p_libvlc, "save-config" ) )
507     {
508         vlc_object_detach( p_help_module );
509         config_LoadConfigFile( p_libvlc, NULL );
510         config_LoadCmdLine( p_libvlc, &i_argc, ppsz_argv, VLC_TRUE );
511         config_SaveConfigFile( p_libvlc, NULL );
512         vlc_object_attach( p_help_module, libvlc_global.p_module_bank );
513     }
514
515     /* Hack: remove the help module here */
516     vlc_object_detach( p_help_module );
517     /* End hack */
518
519     if( b_exit )
520     {
521         config_Free( p_help_module );
522         vlc_object_destroy( p_help_module );
523         module_EndBank( p_libvlc );
524         return i_ret;
525     }
526
527     /*
528      * Init device values
529      */
530     InitDeviceValues( p_libvlc );
531
532     /*
533      * Override default configuration with config file settings
534      */
535     config_LoadConfigFile( p_libvlc, NULL );
536
537     /* Hack: insert the help module here */
538     vlc_object_attach( p_help_module, libvlc_global.p_module_bank );
539     /* End hack */
540
541     /*
542      * Override configuration with command line settings
543      */
544     if( config_LoadCmdLine( p_libvlc, &i_argc, ppsz_argv, VLC_FALSE ) )
545     {
546 #ifdef WIN32
547         ShowConsole( VLC_FALSE );
548         /* Pause the console because it's destroyed when we exit */
549         fprintf( stderr, "The command line options couldn't be loaded, check "
550                  "that they are valid.\n" );
551         PauseConsole();
552 #endif
553         vlc_object_detach( p_help_module );
554         config_Free( p_help_module );
555         vlc_object_destroy( p_help_module );
556         module_EndBank( p_libvlc );
557         return VLC_EGENERIC;
558     }
559
560     /* Hack: remove the help module here */
561     vlc_object_detach( p_help_module );
562     config_Free( p_help_module );
563     vlc_object_destroy( p_help_module );
564     /* End hack */
565
566     /*
567      * System specific configuration
568      */
569     system_Configure( p_libvlc, &i_argc, ppsz_argv );
570
571     /*
572      * Message queue options
573      */
574
575     var_Create( p_libvlc, "verbose", VLC_VAR_INTEGER | VLC_VAR_DOINHERIT );
576     if( config_GetInt( p_libvlc, "quiet" ) )
577     {
578         val.i_int = -1;
579         var_Set( p_libvlc, "verbose", val );
580     }
581     var_AddCallback( p_libvlc, "verbose", VerboseCallback, NULL );
582     var_Change( p_libvlc, "verbose", VLC_VAR_TRIGGER_CALLBACKS, NULL, NULL );
583
584     p_libvlc->b_color = p_libvlc->b_color && config_GetInt( p_libvlc, "color" );
585
586     /*
587      * Output messages that may still be in the queue
588      */
589     msg_Flush( p_libvlc );
590
591     /* p_libvlc initialization. FIXME ? */
592
593     if( !config_GetInt( p_libvlc, "fpu" ) )
594         libvlc_global.i_cpu &= ~CPU_CAPABILITY_FPU;
595
596 #if defined( __i386__ ) || defined( __x86_64__ )
597     if( !config_GetInt( p_libvlc, "mmx" ) )
598         libvlc_global.i_cpu &= ~CPU_CAPABILITY_MMX;
599     if( !config_GetInt( p_libvlc, "3dn" ) )
600         libvlc_global.i_cpu &= ~CPU_CAPABILITY_3DNOW;
601     if( !config_GetInt( p_libvlc, "mmxext" ) )
602         libvlc_global.i_cpu &= ~CPU_CAPABILITY_MMXEXT;
603     if( !config_GetInt( p_libvlc, "sse" ) )
604         libvlc_global.i_cpu &= ~CPU_CAPABILITY_SSE;
605     if( !config_GetInt( p_libvlc, "sse2" ) )
606         libvlc_global.i_cpu &= ~CPU_CAPABILITY_SSE2;
607 #endif
608 #if defined( __powerpc__ ) || defined( __ppc__ ) || defined( __ppc64__ )
609     if( !config_GetInt( p_libvlc, "altivec" ) )
610         libvlc_global.i_cpu &= ~CPU_CAPABILITY_ALTIVEC;
611 #endif
612
613 #define PRINT_CAPABILITY( capability, string )                              \
614     if( libvlc_global.i_cpu & capability )                                         \
615     {                                                                       \
616         strncat( p_capabilities, string " ",                                \
617                  sizeof(p_capabilities) - strlen(p_capabilities) );         \
618         p_capabilities[sizeof(p_capabilities) - 1] = '\0';                  \
619     }
620
621     p_capabilities[0] = '\0';
622     PRINT_CAPABILITY( CPU_CAPABILITY_486, "486" );
623     PRINT_CAPABILITY( CPU_CAPABILITY_586, "586" );
624     PRINT_CAPABILITY( CPU_CAPABILITY_PPRO, "Pentium Pro" );
625     PRINT_CAPABILITY( CPU_CAPABILITY_MMX, "MMX" );
626     PRINT_CAPABILITY( CPU_CAPABILITY_3DNOW, "3DNow!" );
627     PRINT_CAPABILITY( CPU_CAPABILITY_MMXEXT, "MMXEXT" );
628     PRINT_CAPABILITY( CPU_CAPABILITY_SSE, "SSE" );
629     PRINT_CAPABILITY( CPU_CAPABILITY_SSE2, "SSE2" );
630     PRINT_CAPABILITY( CPU_CAPABILITY_ALTIVEC, "AltiVec" );
631     PRINT_CAPABILITY( CPU_CAPABILITY_FPU, "FPU" );
632     msg_Dbg( p_libvlc, "CPU has capabilities %s", p_capabilities );
633
634     /*
635      * Choose the best memcpy module
636      */
637     p_libvlc->p_memcpy_module = module_Need( p_libvlc, "memcpy", "$memcpy", 0 );
638
639     if( p_libvlc->pf_memcpy == NULL )
640     {
641         p_libvlc->pf_memcpy = memcpy;
642     }
643
644     if( p_libvlc->pf_memset == NULL )
645     {
646         p_libvlc->pf_memset = memset;
647     }
648
649     p_libvlc->b_stats = config_GetInt( p_libvlc, "stats" );
650     p_libvlc->i_timers = 0;
651     p_libvlc->pp_timers = NULL;
652     vlc_mutex_init( p_libvlc, &p_libvlc->timer_lock );
653
654     /*
655      * Initialize hotkey handling
656      */
657     var_Create( p_libvlc, "key-pressed", VLC_VAR_INTEGER );
658     p_libvlc->p_hotkeys = malloc( sizeof(p_hotkeys) );
659     /* Do a copy (we don't need to modify the strings) */
660     memcpy( p_libvlc->p_hotkeys, p_hotkeys, sizeof(p_hotkeys) );
661
662     /* Initialize playlist and get commandline files */
663     playlist_ThreadCreate( p_libvlc );
664     if( !p_libvlc->p_playlist )
665     {
666         msg_Err( p_libvlc, "playlist initialization failed" );
667         if( p_libvlc->p_memcpy_module != NULL )
668         {
669             module_Unneed( p_libvlc, p_libvlc->p_memcpy_module );
670         }
671         module_EndBank( p_libvlc );
672         return VLC_EGENERIC;
673     }
674     p_playlist = p_libvlc->p_playlist;
675
676     psz_modules = config_GetPsz( p_playlist, "services-discovery" );
677     if( psz_modules && *psz_modules )
678     {
679         /* Add service discovery modules */
680         playlist_AddSDModules( p_playlist, psz_modules );
681     }
682     if( psz_modules ) free( psz_modules );
683
684     /*
685      * Load background interfaces
686      */
687     psz_modules = config_GetPsz( p_libvlc, "extraintf" );
688     psz_control = config_GetPsz( p_libvlc, "control" );
689
690     if( psz_modules && *psz_modules && psz_control && *psz_control )
691     {
692         psz_modules = (char *)realloc( psz_modules, strlen( psz_modules ) +
693                                                     strlen( psz_control ) + 1 );
694         sprintf( psz_modules, "%s:%s", psz_modules, psz_control );
695     }
696     else if( psz_control && *psz_control )
697     {
698         if( psz_modules ) free( psz_modules );
699         psz_modules = strdup( psz_control );
700     }
701
702     psz_parser = psz_modules;
703     while ( psz_parser && *psz_parser )
704     {
705         char *psz_module, *psz_temp;
706         psz_module = psz_parser;
707         psz_parser = strchr( psz_module, ':' );
708         if ( psz_parser )
709         {
710             *psz_parser = '\0';
711             psz_parser++;
712         }
713         psz_temp = (char *)malloc( strlen(psz_module) + sizeof(",none") );
714         if( psz_temp )
715         {
716             sprintf( psz_temp, "%s,none", psz_module );
717             VLC_AddIntf( 0, psz_temp, VLC_FALSE, VLC_FALSE );
718             free( psz_temp );
719         }
720     }
721     if ( psz_modules )
722     {
723         free( psz_modules );
724     }
725
726     /*
727      * Always load the hotkeys interface if it exists
728      */
729     VLC_AddIntf( 0, "hotkeys,none", VLC_FALSE, VLC_FALSE );
730
731     /*
732      * If needed, load the Xscreensaver interface
733      * Currently, only for X
734      */
735 #ifdef HAVE_X11_XLIB_H
736     if( config_GetInt( p_libvlc, "disable-screensaver" ) == 1 )
737     {
738         VLC_AddIntf( 0, "screensaver,none", VLC_FALSE, VLC_FALSE );
739     }
740 #endif
741
742     if( config_GetInt( p_libvlc, "file-logging" ) == 1 )
743     {
744         VLC_AddIntf( 0, "logger,none", VLC_FALSE, VLC_FALSE );
745     }
746 #ifdef HAVE_SYSLOG_H
747     if( config_GetInt( p_libvlc, "syslog" ) == 1 )
748     {
749         char *psz_logmode = "logmode=syslog";
750         libvlc_InternalAddIntf( 0, "logger,none", VLC_FALSE, VLC_FALSE,
751                                 1, &psz_logmode );
752     }
753 #endif
754
755     if( config_GetInt( p_libvlc, "show-intf" ) == 1 )
756     {
757         VLC_AddIntf( 0, "showintf,none", VLC_FALSE, VLC_FALSE );
758     }
759
760     if( config_GetInt( p_libvlc, "network-synchronisation") == 1 )
761     {
762         VLC_AddIntf( 0, "netsync,none", VLC_FALSE, VLC_FALSE );
763     }
764
765     /*
766      * FIXME: kludge to use a p_libvlc-local variable for the Mozilla plugin
767      */
768     var_Create( p_libvlc, "drawable", VLC_VAR_INTEGER );
769     var_Create( p_libvlc, "drawable-view-top", VLC_VAR_INTEGER );
770     var_Create( p_libvlc, "drawable-view-left", VLC_VAR_INTEGER );
771     var_Create( p_libvlc, "drawable-view-bottom", VLC_VAR_INTEGER );
772     var_Create( p_libvlc, "drawable-view-right", VLC_VAR_INTEGER );
773     var_Create( p_libvlc, "drawable-clip-top", VLC_VAR_INTEGER );
774     var_Create( p_libvlc, "drawable-clip-left", VLC_VAR_INTEGER );
775     var_Create( p_libvlc, "drawable-clip-bottom", VLC_VAR_INTEGER );
776     var_Create( p_libvlc, "drawable-clip-right", VLC_VAR_INTEGER );
777
778     /* Create volume callback system. */
779     var_Create( p_libvlc, "volume-change", VLC_VAR_BOOL );
780
781     /*
782      * Get input filenames given as commandline arguments
783      */
784     GetFilenames( p_libvlc, i_argc, ppsz_argv );
785
786     /*
787      * Get --open argument
788      */
789     var_Create( p_libvlc, "open", VLC_VAR_STRING | VLC_VAR_DOINHERIT );
790     var_Get( p_libvlc, "open", &val );
791     if ( val.psz_string != NULL && *val.psz_string )
792     {
793         VLC_AddTarget( p_libvlc->i_object_id, val.psz_string, NULL, 0,
794                        PLAYLIST_INSERT, 0 );
795     }
796     if ( val.psz_string != NULL ) free( val.psz_string );
797
798     return VLC_SUCCESS;
799 }
800
801 /**
802  * Cleanup a libvlc instance. The instance is not completely deallocated
803  * \param p_libvlc the instance to clean
804  */
805 int libvlc_InternalCleanup( libvlc_int_t *p_libvlc )
806 {
807     intf_thread_t      * p_intf;
808     vout_thread_t      * p_vout;
809     aout_instance_t    * p_aout;
810     announce_handler_t * p_announce;
811
812     /* Ask the interfaces to stop and destroy them */
813     msg_Dbg( p_libvlc, "removing all interfaces" );
814     while( (p_intf = vlc_object_find( p_libvlc, VLC_OBJECT_INTF, FIND_CHILD )) )
815     {
816         intf_StopThread( p_intf );
817         vlc_object_detach( p_intf );
818         vlc_object_release( p_intf );
819         intf_Destroy( p_intf );
820     }
821
822     /* Free playlist */
823     msg_Dbg( p_libvlc, "removing playlist" );
824     playlist_ThreadDestroy( p_libvlc->p_playlist );
825
826     /* Free video outputs */
827     msg_Dbg( p_libvlc, "removing all video outputs" );
828     while( (p_vout = vlc_object_find( p_libvlc, VLC_OBJECT_VOUT, FIND_CHILD )) )
829     {
830         vlc_object_detach( p_vout );
831         vlc_object_release( p_vout );
832         vout_Destroy( p_vout );
833     }
834
835     /* Free audio outputs */
836     msg_Dbg( p_libvlc, "removing all audio outputs" );
837     while( (p_aout = vlc_object_find( p_libvlc, VLC_OBJECT_AOUT, FIND_CHILD )) )
838     {
839         vlc_object_detach( (vlc_object_t *)p_aout );
840         vlc_object_release( (vlc_object_t *)p_aout );
841         aout_Delete( p_aout );
842     }
843
844     stats_TimersDumpAll( p_libvlc );
845     stats_TimersClean( p_libvlc );
846
847     /* Free announce handler(s?) */
848     while( (p_announce = vlc_object_find( p_libvlc, VLC_OBJECT_ANNOUNCE,
849                                                  FIND_CHILD ) ) )
850     {
851         msg_Dbg( p_libvlc, "removing announce handler" );
852         vlc_object_detach( p_announce );
853         vlc_object_release( p_announce );
854         announce_HandlerDestroy( p_announce );
855     }
856     return VLC_SUCCESS;
857 }
858
859 /**
860  * Destroy everything.
861  * This function requests the running threads to finish, waits for their
862  * termination, and destroys their structure.
863  * It stops the thread systems: no instance can run after this has run
864  * \param p_libvlc the instance to destroy
865  * \param b_release whether we should do a release on the instance
866  */
867 int libvlc_InternalDestroy( libvlc_int_t *p_libvlc, vlc_bool_t b_release )
868 {
869     vlc_value_t lockval;
870
871     if( p_libvlc->p_memcpy_module )
872     {
873         module_Unneed( p_libvlc, p_libvlc->p_memcpy_module );
874         p_libvlc->p_memcpy_module = NULL;
875     }
876
877     /* Free module bank. It is refcounted, so we call this each time  */
878     module_EndBank( p_libvlc );
879
880     FREENULL( p_libvlc->psz_homedir );
881     FREENULL( p_libvlc->psz_userdir );
882     FREENULL( p_libvlc->psz_configfile );
883     FREENULL( p_libvlc->p_hotkeys );
884
885     var_Create( p_libvlc_global, "libvlc", VLC_VAR_MUTEX );
886     var_Get( p_libvlc_global, "libvlc", &lockval );
887     vlc_mutex_lock( lockval.p_address );
888     i_instances--;
889
890     if( i_instances == 0 )
891     {
892         /* System specific cleaning code */
893         system_End( p_libvlc );
894
895        /* Destroy global iconv */
896         LocaleDeinit();
897     }
898     vlc_mutex_unlock( lockval.p_address );
899     var_Destroy( p_libvlc_global, "libvlc" );
900
901     msg_Flush( p_libvlc );
902     msg_Destroy( p_libvlc );
903
904     /* Destroy mutexes */
905     vlc_mutex_destroy( &p_libvlc->config_lock );
906
907     if( b_release ) vlc_object_release( p_libvlc );
908     vlc_object_destroy( p_libvlc );
909
910     /* Stop thread system: last one out please shut the door!
911      * The number of initializations of the thread system is counted, we 
912      * can call this each time */
913     vlc_threads_end( p_libvlc_global );
914
915     return VLC_SUCCESS;
916 }
917
918 /**
919  * Add an interface plugin and run it
920  */
921 int libvlc_InternalAddIntf( libvlc_int_t *p_libvlc,
922                             char const *psz_module,
923                             vlc_bool_t b_block, vlc_bool_t b_play,
924                             int i_options, char **ppsz_options )
925 {
926     int i_err;
927     intf_thread_t *p_intf;
928
929 #ifndef WIN32
930     if( p_libvlc->p_libvlc_global->b_daemon && b_block && !psz_module )
931     {
932         /* Daemon mode hack.
933          * We prefer the dummy interface if none is specified. */
934         char *psz_interface = config_GetPsz( p_libvlc, "intf" );
935         if( !psz_interface || !*psz_interface ) psz_module = "dummy";
936         if( psz_interface ) free( psz_interface );
937     }
938 #endif
939
940     /* Try to create the interface */
941     p_intf = intf_Create( p_libvlc, psz_module ? psz_module : "$intf",
942                           i_options, ppsz_options );
943
944     if( p_intf == NULL )
945     {
946         msg_Err( p_libvlc, "interface \"%s\" initialization failed",
947                  psz_module );
948         return VLC_EGENERIC;
949     }
950
951     /* Interface doesn't handle play on start so do it ourselves */
952     if( !p_intf->b_play && b_play )
953         playlist_Play( p_libvlc->p_playlist );
954
955     /* Try to run the interface */
956     p_intf->b_play = b_play;
957     p_intf->b_block = b_block;
958     i_err = intf_RunThread( p_intf );
959     if( i_err )
960     {
961         vlc_object_detach( p_intf );
962         intf_Destroy( p_intf );
963         return i_err;
964     }
965     return VLC_SUCCESS;
966 };
967
968
969 /*****************************************************************************
970  * SetLanguage: set the interface language.
971  *****************************************************************************
972  * We set the LC_MESSAGES locale category for interface messages and buttons,
973  * as well as the LC_CTYPE category for string sorting and possible wide
974  * character support.
975  *****************************************************************************/
976 static void SetLanguage ( char const *psz_lang )
977 {
978 #if defined( ENABLE_NLS ) \
979      && ( defined( HAVE_GETTEXT ) || defined( HAVE_INCLUDED_GETTEXT ) )
980
981     char *          psz_path;
982 #if defined( __APPLE__ ) || defined ( WIN32 ) || defined( SYS_BEOS )
983     char            psz_tmp[1024];
984 #endif
985
986     if( psz_lang && !*psz_lang )
987     {
988 #   if defined( HAVE_LC_MESSAGES )
989         setlocale( LC_MESSAGES, psz_lang );
990 #   endif
991         setlocale( LC_CTYPE, psz_lang );
992     }
993     else if( psz_lang )
994     {
995 #ifdef __APPLE__
996         /* I need that under Darwin, please check it doesn't disturb
997          * other platforms. --Meuuh */
998         setenv( "LANG", psz_lang, 1 );
999
1000 #elif defined( SYS_BEOS ) || defined( WIN32 )
1001         /* We set LC_ALL manually because it is the only way to set
1002          * the language at runtime under eg. Windows. Beware that this
1003          * makes the environment unconsistent when libvlc is unloaded and
1004          * should probably be moved to a safer place like vlc.c. */
1005         static char psz_lcall[20];
1006         snprintf( psz_lcall, 19, "LC_ALL=%s", psz_lang );
1007         psz_lcall[19] = '\0';
1008         putenv( psz_lcall );
1009 #endif
1010
1011         setlocale( LC_ALL, psz_lang );
1012     }
1013
1014     /* Specify where to find the locales for current domain */
1015 #if !defined( __APPLE__ ) && !defined( WIN32 ) && !defined( SYS_BEOS )
1016     psz_path = LOCALEDIR;
1017 #else
1018     snprintf( psz_tmp, sizeof(psz_tmp), "%s/%s", libvlc_global.psz_vlcpath,
1019               "locale" );
1020     psz_path = psz_tmp;
1021 #endif
1022     if( !bindtextdomain( PACKAGE_NAME, psz_path ) )
1023     {
1024         fprintf( stderr, "warning: couldn't bind domain %s in directory %s\n",
1025                  PACKAGE_NAME, psz_path );
1026     }
1027
1028     /* Set the default domain */
1029     bind_textdomain_codeset( PACKAGE_NAME, "UTF-8" );
1030 #endif
1031 }
1032
1033 /*****************************************************************************
1034  * GetFilenames: parse command line options which are not flags
1035  *****************************************************************************
1036  * Parse command line for input files as well as their associated options.
1037  * An option always follows its associated input and begins with a ":".
1038  *****************************************************************************/
1039 static int GetFilenames( libvlc_int_t *p_vlc, int i_argc, char *ppsz_argv[] )
1040 {
1041     int i_opt, i_options;
1042
1043 #ifdef WIN32
1044     wchar_t **wargv, **wenvp;
1045     int si = { 0 };
1046
1047     if( GetVersion() < 0x80000000 )
1048     {
1049         /* fetch unicode argv[] for Windows NT and above */
1050         __wgetmainargs(&i_opt, &wargv, &wenvp, 0, &si);
1051     }
1052 #endif
1053
1054     /* We assume that the remaining parameters are filenames
1055      * and their input options */
1056     for( i_opt = i_argc - 1; i_opt >= optind; i_opt-- )
1057     {
1058         const char *psz_target;
1059         i_options = 0;
1060
1061         /* Count the input options */
1062         while( *ppsz_argv[ i_opt ] == ':' && i_opt > optind )
1063         {
1064             i_options++;
1065             i_opt--;
1066         }
1067
1068         /* TODO: write an internal function of this one, to avoid
1069          *       unnecessary lookups. */
1070         /* FIXME: should we convert options to UTF-8 as well ?? */
1071
1072 #ifdef WIN32
1073         if( GetVersion() < 0x80000000 )
1074         {
1075             psz_target = FromWide( wargv[ i_opt ] );
1076             VLC_AddTarget( p_vlc->i_object_id, psz_target,
1077                        (char const **)( i_options ? &ppsz_argv[i_opt + 1] :
1078                                         NULL ), i_options,
1079                        PLAYLIST_INSERT, 0 );
1080             free( psz_target );
1081         }
1082         else
1083 #endif
1084         {
1085             psz_target = FromLocale( ppsz_argv[ i_opt ] );
1086             VLC_AddTarget( p_vlc->i_object_id, psz_target,
1087                        (char const **)( i_options ? &ppsz_argv[i_opt + 1] :
1088                                         NULL ), i_options,
1089                        PLAYLIST_INSERT, 0 );
1090             LocaleFree( psz_target );
1091         }
1092     }
1093
1094     return VLC_SUCCESS;
1095 }
1096
1097 /*****************************************************************************
1098  * Help: print program help
1099  *****************************************************************************
1100  * Print a short inline help. Message interface is initialized at this stage.
1101  *****************************************************************************/
1102 static void Help( libvlc_int_t *p_this, char const *psz_help_name )
1103 {
1104 #ifdef WIN32
1105     ShowConsole( VLC_TRUE );
1106 #endif
1107
1108     if( psz_help_name && !strcmp( psz_help_name, "help" ) )
1109     {
1110         utf8_fprintf( stdout, VLC_USAGE, p_this->psz_object_name );
1111         Usage( p_this, "help" );
1112         Usage( p_this, "main" );
1113     }
1114     else if( psz_help_name && !strcmp( psz_help_name, "longhelp" ) )
1115     {
1116         utf8_fprintf( stdout, VLC_USAGE, p_this->psz_object_name );
1117         Usage( p_this, NULL );
1118     }
1119     else if( psz_help_name )
1120     {
1121         Usage( p_this, psz_help_name );
1122     }
1123
1124 #ifdef WIN32        /* Pause the console because it's destroyed when we exit */
1125     PauseConsole();
1126 #endif
1127 }
1128
1129 /*****************************************************************************
1130  * Usage: print module usage
1131  *****************************************************************************
1132  * Print a short inline help. Message interface is initialized at this stage.
1133  *****************************************************************************/
1134 static void Usage( libvlc_int_t *p_this, char const *psz_module_name )
1135 {
1136 #define FORMAT_STRING "  %s --%s%s%s%s%s%s%s "
1137     /* short option ------'    | | | | | | |
1138      * option name ------------' | | | | | |
1139      * <bra ---------------------' | | | | |
1140      * option type or "" ----------' | | | |
1141      * ket> -------------------------' | | |
1142      * padding spaces -----------------' | |
1143      * comment --------------------------' |
1144      * comment suffix ---------------------'
1145      *
1146      * The purpose of having bra and ket is that we might i18n them as well.
1147      */
1148 #define LINE_START 8
1149 #define PADDING_SPACES 25
1150     vlc_list_t *p_list;
1151     module_t *p_parser;
1152     module_config_t *p_item;
1153     char psz_spaces_text[PADDING_SPACES+LINE_START+1];
1154     char psz_spaces_longtext[LINE_START+3];
1155     char psz_format[sizeof(FORMAT_STRING)];
1156     char psz_buffer[10000];
1157     char psz_short[4];
1158     int i_index;
1159     int i_width = ConsoleWidth() - (PADDING_SPACES+LINE_START+1);
1160     vlc_bool_t b_advanced = config_GetInt( p_this, "advanced" );
1161     vlc_bool_t b_description;
1162
1163     memset( psz_spaces_text, ' ', PADDING_SPACES+LINE_START );
1164     psz_spaces_text[PADDING_SPACES+LINE_START] = '\0';
1165     memset( psz_spaces_longtext, ' ', LINE_START+2 );
1166     psz_spaces_longtext[LINE_START+2] = '\0';
1167
1168     strcpy( psz_format, FORMAT_STRING );
1169
1170     /* List all modules */
1171     p_list = vlc_list_find( p_this, VLC_OBJECT_MODULE, FIND_ANYWHERE );
1172
1173     /* Enumerate the config for each module */
1174     for( i_index = 0; i_index < p_list->i_count; i_index++ )
1175     {
1176         vlc_bool_t b_help_module;
1177
1178         p_parser = (module_t *)p_list->p_values[i_index].p_object ;
1179
1180         if( psz_module_name && strcmp( psz_module_name,
1181                                        p_parser->psz_object_name ) )
1182         {
1183             continue;
1184         }
1185
1186         /* Ignore modules without config options */
1187         if( !p_parser->i_config_items )
1188         {
1189             continue;
1190         }
1191
1192         /* Ignore modules with only advanced config options if requested */
1193         if( !b_advanced )
1194         {
1195             for( p_item = p_parser->p_config;
1196                  p_item->i_type != CONFIG_HINT_END;
1197                  p_item++ )
1198             {
1199                 if( (p_item->i_type & CONFIG_ITEM) &&
1200                     !p_item->b_advanced ) break;
1201             }
1202             if( p_item->i_type == CONFIG_HINT_END ) continue;
1203         }
1204
1205         /* Print name of module */
1206         if( strcmp( "main", p_parser->psz_object_name ) )
1207         utf8_fprintf( stdout, "\n %s\n", p_parser->psz_longname );
1208
1209         b_help_module = !strcmp( "help", p_parser->psz_object_name );
1210
1211         /* Print module options */
1212         for( p_item = p_parser->p_config;
1213              p_item->i_type != CONFIG_HINT_END;
1214              p_item++ )
1215         {
1216             char *psz_text, *psz_spaces = psz_spaces_text;
1217             char *psz_bra = NULL, *psz_type = NULL, *psz_ket = NULL;
1218             char *psz_suf = "", *psz_prefix = NULL;
1219             signed int i;
1220
1221             /* Skip deprecated options */
1222             if( p_item->psz_current )
1223             {
1224                 continue;
1225             }
1226             /* Skip advanced options if requested */
1227             if( p_item->b_advanced && !b_advanced )
1228             {
1229                 continue;
1230             }
1231
1232             switch( p_item->i_type )
1233             {
1234             case CONFIG_HINT_CATEGORY:
1235             case CONFIG_HINT_USAGE:
1236                 if( !strcmp( "main", p_parser->psz_object_name ) )
1237                 utf8_fprintf( stdout, "\n %s\n", p_item->psz_text );
1238                 break;
1239
1240             case CONFIG_ITEM_STRING:
1241             case CONFIG_ITEM_FILE:
1242             case CONFIG_ITEM_DIRECTORY:
1243             case CONFIG_ITEM_MODULE: /* We could also have "=<" here */
1244             case CONFIG_ITEM_MODULE_CAT:
1245             case CONFIG_ITEM_MODULE_LIST:
1246             case CONFIG_ITEM_MODULE_LIST_CAT:
1247                 psz_bra = " <"; psz_type = _("string"); psz_ket = ">";
1248
1249                 if( p_item->ppsz_list )
1250                 {
1251                     psz_bra = " {";
1252                     psz_type = psz_buffer;
1253                     psz_type[0] = '\0';
1254                     for( i = 0; p_item->ppsz_list[i]; i++ )
1255                     {
1256                         if( i ) strcat( psz_type, "," );
1257                         strcat( psz_type, p_item->ppsz_list[i] );
1258                     }
1259                     psz_ket = "}";
1260                 }
1261                 break;
1262             case CONFIG_ITEM_INTEGER:
1263             case CONFIG_ITEM_KEY: /* FIXME: do something a bit more clever */
1264                 psz_bra = " <"; psz_type = _("integer"); psz_ket = ">";
1265
1266                 if( p_item->i_list )
1267                 {
1268                     psz_bra = " {";
1269                     psz_type = psz_buffer;
1270                     psz_type[0] = '\0';
1271                     for( i = 0; p_item->ppsz_list_text[i]; i++ )
1272                     {
1273                         if( i ) strcat( psz_type, ", " );
1274                         sprintf( psz_type + strlen(psz_type), "%i (%s)",
1275                                  p_item->pi_list[i],
1276                                  p_item->ppsz_list_text[i] );
1277                     }
1278                     psz_ket = "}";
1279                 }
1280                 break;
1281             case CONFIG_ITEM_FLOAT:
1282                 psz_bra = " <"; psz_type = _("float"); psz_ket = ">";
1283                 break;
1284             case CONFIG_ITEM_BOOL:
1285                 psz_bra = ""; psz_type = ""; psz_ket = "";
1286                 if( !b_help_module )
1287                 {
1288                     psz_suf = p_item->i_value ? _(" (default enabled)") :
1289                                                 _(" (default disabled)");
1290                 }
1291                 break;
1292             }
1293
1294             if( !psz_type )
1295             {
1296                 continue;
1297             }
1298
1299             /* Add short option if any */
1300             if( p_item->i_short )
1301             {
1302                 sprintf( psz_short, "-%c,", p_item->i_short );
1303             }
1304             else
1305             {
1306                 strcpy( psz_short, "   " );
1307             }
1308
1309             i = PADDING_SPACES - strlen( p_item->psz_name )
1310                  - strlen( psz_bra ) - strlen( psz_type )
1311                  - strlen( psz_ket ) - 1;
1312
1313             if( p_item->i_type == CONFIG_ITEM_BOOL && !b_help_module )
1314             {
1315                 psz_prefix =  ", --no-";
1316                 i -= strlen( p_item->psz_name ) + strlen( psz_prefix );
1317             }
1318
1319             if( i < 0 )
1320             {
1321                 psz_spaces[0] = '\n';
1322                 i = 0;
1323             }
1324             else
1325             {
1326                 psz_spaces[i] = '\0';
1327             }
1328
1329             if( p_item->i_type == CONFIG_ITEM_BOOL && !b_help_module )
1330             {
1331                 utf8_fprintf( stdout, psz_format, psz_short, p_item->psz_name,
1332                          psz_prefix, p_item->psz_name, psz_bra, psz_type,
1333                          psz_ket, psz_spaces );
1334             }
1335             else
1336             {
1337                 utf8_fprintf( stdout, psz_format, psz_short, p_item->psz_name,
1338                          "", "", psz_bra, psz_type, psz_ket, psz_spaces );
1339             }
1340
1341             psz_spaces[i] = ' ';
1342
1343             /* We wrap the rest of the output */
1344             sprintf( psz_buffer, "%s%s", p_item->psz_text, psz_suf );
1345             b_description = config_GetInt( p_this, "help-verbose" );
1346
1347  description:
1348             psz_text = psz_buffer;
1349             while( *psz_text )
1350             {
1351                 char *psz_parser, *psz_word;
1352                 size_t i_end = strlen( psz_text );
1353
1354                 /* If the remaining text fits in a line, print it. */
1355                 if( i_end <= (size_t)i_width )
1356                 {
1357                     utf8_fprintf( stdout, "%s\n", psz_text );
1358                     break;
1359                 }
1360
1361                 /* Otherwise, eat as many words as possible */
1362                 psz_parser = psz_text;
1363                 do
1364                 {
1365                     psz_word = psz_parser;
1366                     psz_parser = strchr( psz_word, ' ' );
1367                     /* If no space was found, we reached the end of the text
1368                      * block; otherwise, we skip the space we just found. */
1369                     psz_parser = psz_parser ? psz_parser + 1
1370                                             : psz_text + i_end;
1371
1372                 } while( psz_parser - psz_text <= i_width );
1373
1374                 /* We cut a word in one of these cases:
1375                  *  - it's the only word in the line and it's too long.
1376                  *  - we used less than 80% of the width and the word we are
1377                  *    going to wrap is longer than 40% of the width, and even
1378                  *    if the word would have fit in the next line. */
1379                 if( psz_word == psz_text
1380                      || ( psz_word - psz_text < 80 * i_width / 100
1381                            && psz_parser - psz_word > 40 * i_width / 100 ) )
1382                 {
1383                     char c = psz_text[i_width];
1384                     psz_text[i_width] = '\0';
1385                     utf8_fprintf( stdout, "%s\n%s", psz_text, psz_spaces );
1386                     psz_text += i_width;
1387                     psz_text[0] = c;
1388                 }
1389                 else
1390                 {
1391                     psz_word[-1] = '\0';
1392                     utf8_fprintf( stdout, "%s\n%s", psz_text, psz_spaces );
1393                     psz_text = psz_word;
1394                 }
1395             }
1396
1397             if( b_description && p_item->psz_longtext )
1398             {
1399                 sprintf( psz_buffer, "%s%s", p_item->psz_longtext, psz_suf );
1400                 b_description = VLC_FALSE;
1401                 psz_spaces = psz_spaces_longtext;
1402                 utf8_fprintf( stdout, "%s", psz_spaces );
1403                 goto description;
1404             }
1405         }
1406     }
1407
1408     /* Release the module list */
1409     vlc_list_release( p_list );
1410 }
1411
1412 /*****************************************************************************
1413  * ListModules: list the available modules with their description
1414  *****************************************************************************
1415  * Print a list of all available modules (builtins and plugins) and a short
1416  * description for each one.
1417  *****************************************************************************/
1418 static void ListModules( libvlc_int_t *p_this )
1419 {
1420     vlc_list_t *p_list;
1421     module_t *p_parser;
1422     char psz_spaces[22];
1423     int i_index;
1424
1425     memset( psz_spaces, ' ', 22 );
1426
1427 #ifdef WIN32
1428     ShowConsole( VLC_TRUE );
1429 #endif
1430
1431     /* List all modules */
1432     p_list = vlc_list_find( p_this, VLC_OBJECT_MODULE, FIND_ANYWHERE );
1433
1434     /* Enumerate each module */
1435     for( i_index = 0; i_index < p_list->i_count; i_index++ )
1436     {
1437         int i;
1438
1439         p_parser = (module_t *)p_list->p_values[i_index].p_object ;
1440
1441         /* Nasty hack, but right now I'm too tired to think about a nice
1442          * solution */
1443         i = 22 - strlen( p_parser->psz_object_name ) - 1;
1444         if( i < 0 ) i = 0;
1445         psz_spaces[i] = 0;
1446
1447         utf8_fprintf( stdout, "  %s%s %s\n", p_parser->psz_object_name,
1448                          psz_spaces, p_parser->psz_longname );
1449
1450         psz_spaces[i] = ' ';
1451     }
1452
1453     vlc_list_release( p_list );
1454
1455 #ifdef WIN32        /* Pause the console because it's destroyed when we exit */
1456     PauseConsole();
1457 #endif
1458 }
1459
1460 /*****************************************************************************
1461  * Version: print complete program version
1462  *****************************************************************************
1463  * Print complete program version and build number.
1464  *****************************************************************************/
1465 static void Version( void )
1466 {
1467 #ifdef WIN32
1468     ShowConsole( VLC_TRUE );
1469 #endif
1470
1471     utf8_fprintf( stdout, _("VLC version %s\n"), VLC_Version() );
1472     utf8_fprintf( stdout, _("Compiled by %s@%s.%s\n"),
1473              VLC_CompileBy(), VLC_CompileHost(), VLC_CompileDomain() );
1474     utf8_fprintf( stdout, _("Compiler: %s\n"), VLC_Compiler() );
1475 #ifndef HAVE_SHARED_LIBVLC
1476     if( strcmp( VLC_Changeset(), "exported" ) )
1477         utf8_fprintf( stdout, _("Based upon svn changeset [%s]\n"),
1478                  VLC_Changeset() );
1479 #endif
1480     utf8_fprintf( stdout, LICENSE_MSG );
1481
1482 #ifdef WIN32        /* Pause the console because it's destroyed when we exit */
1483     PauseConsole();
1484 #endif
1485 }
1486
1487 /*****************************************************************************
1488  * ShowConsole: On Win32, create an output console for debug messages
1489  *****************************************************************************
1490  * This function is useful only on Win32.
1491  *****************************************************************************/
1492 #ifdef WIN32 /*  */
1493 static void ShowConsole( vlc_bool_t b_dofile )
1494 {
1495 #   ifndef UNDER_CE
1496     FILE *f_help;
1497
1498     if( getenv( "PWD" ) && getenv( "PS1" ) ) return; /* cygwin shell */
1499
1500     AllocConsole();
1501
1502     freopen( "CONOUT$", "w", stderr );
1503     freopen( "CONIN$", "r", stdin );
1504
1505     if( b_dofile && (f_help = fopen( "vlc-help.txt", "wt" )) )
1506     {
1507         fclose( f_help );
1508         freopen( "vlc-help.txt", "wt", stdout );
1509         utf8_fprintf( stderr, _("\nDumped content to vlc-help.txt file.\n") );
1510     }
1511
1512     else freopen( "CONOUT$", "w", stdout );
1513
1514 #   endif
1515 }
1516 #endif
1517
1518 /*****************************************************************************
1519  * PauseConsole: On Win32, wait for a key press before closing the console
1520  *****************************************************************************
1521  * This function is useful only on Win32.
1522  *****************************************************************************/
1523 #ifdef WIN32 /*  */
1524 static void PauseConsole( void )
1525 {
1526 #   ifndef UNDER_CE
1527
1528     if( getenv( "PWD" ) && getenv( "PS1" ) ) return; /* cygwin shell */
1529
1530     utf8_fprintf( stderr, _("\nPress the RETURN key to continue...\n") );
1531     getchar();
1532     fclose( stdout );
1533
1534 #   endif
1535 }
1536 #endif
1537
1538 /*****************************************************************************
1539  * ConsoleWidth: Return the console width in characters
1540  *****************************************************************************
1541  * We use the stty shell command to get the console width; if this fails or
1542  * if the width is less than 80, we default to 80.
1543  *****************************************************************************/
1544 static int ConsoleWidth( void )
1545 {
1546     int i_width = 80;
1547
1548 #ifndef WIN32
1549     char buf[20], *psz_parser;
1550     FILE *file;
1551     int i_ret;
1552
1553     file = popen( "stty size 2>/dev/null", "r" );
1554     if( file )
1555     {
1556         i_ret = fread( buf, 1, 20, file );
1557         if( i_ret > 0 )
1558         {
1559             buf[19] = '\0';
1560             psz_parser = strchr( buf, ' ' );
1561             if( psz_parser )
1562             {
1563                 i_ret = atoi( psz_parser + 1 );
1564                 if( i_ret >= 80 )
1565                 {
1566                     i_width = i_ret;
1567                 }
1568             }
1569         }
1570
1571         pclose( file );
1572     }
1573 #endif
1574
1575     return i_width;
1576 }
1577
1578 static int VerboseCallback( vlc_object_t *p_this, const char *psz_variable,
1579                      vlc_value_t old_val, vlc_value_t new_val, void *param)
1580 {
1581     libvlc_int_t *p_libvlc = (libvlc_int_t *)p_this;
1582
1583     if( new_val.i_int >= -1 )
1584     {
1585         p_libvlc->i_verbose = __MIN( new_val.i_int, 2 );
1586     }
1587     return VLC_SUCCESS;
1588 }
1589
1590 /*****************************************************************************
1591  * InitDeviceValues: initialize device values
1592  *****************************************************************************
1593  * This function inits the dvd, vcd and cd-audio values
1594  *****************************************************************************/
1595 static void InitDeviceValues( libvlc_int_t *p_vlc )
1596 {
1597 #ifdef HAVE_HAL
1598     LibHalContext * ctx;
1599     int i, i_devices;
1600     char **devices;
1601     char *block_dev;
1602     dbus_bool_t b_dvd;
1603     DBusConnection *p_connection;
1604     DBusError       error;
1605
1606 #ifdef HAVE_HAL_1
1607     ctx =  libhal_ctx_new();
1608     if( !ctx ) return;
1609     dbus_error_init( &error );
1610     p_connection = dbus_bus_get ( DBUS_BUS_SYSTEM, &error );
1611     if( dbus_error_is_set( &error ) )
1612     {
1613         dbus_error_free( &error );
1614         return;
1615     }
1616     libhal_ctx_set_dbus_connection( ctx, p_connection );
1617     if( libhal_ctx_init( ctx, &error ) )
1618 #else
1619     if( ( ctx = hal_initialize( NULL, FALSE ) ) )
1620 #endif
1621     {
1622 #ifdef HAVE_HAL_1
1623         if( ( devices = libhal_get_all_devices( ctx, &i_devices, NULL ) ) )
1624 #else
1625         if( ( devices = hal_get_all_devices( ctx, &i_devices ) ) )
1626 #endif
1627         {
1628             for( i = 0; i < i_devices; i++ )
1629             {
1630 #ifdef HAVE_HAL_1
1631                 if( !libhal_device_property_exists( ctx, devices[i],
1632                                                 "storage.cdrom.dvd", NULL ) )
1633 #else
1634                 if( !hal_device_property_exists( ctx, devices[ i ],
1635                                                 "storage.cdrom.dvd" ) )
1636 #endif
1637                 {
1638                     continue;
1639                 }
1640 #ifdef HAVE_HAL_1
1641                 b_dvd = libhal_device_get_property_bool( ctx, devices[ i ],
1642                                                  "storage.cdrom.dvd", NULL  );
1643                 block_dev = libhal_device_get_property_string( ctx,
1644                                 devices[ i ], "block.device" , NULL );
1645 #else
1646                 b_dvd = hal_device_get_property_bool( ctx, devices[ i ],
1647                                                       "storage.cdrom.dvd" );
1648                 block_dev = hal_device_get_property_string( ctx, devices[ i ],
1649                                                             "block.device" );
1650 #endif
1651                 if( b_dvd )
1652                 {
1653                     config_PutPsz( p_vlc, "dvd", block_dev );
1654                 }
1655
1656                 config_PutPsz( p_vlc, "vcd", block_dev );
1657                 config_PutPsz( p_vlc, "cd-audio", block_dev );
1658 #ifdef HAVE_HAL_1
1659                 libhal_free_string( block_dev );
1660 #else
1661                 hal_free_string( block_dev );
1662 #endif
1663             }
1664 #ifdef HAVE_HAL_1
1665             libhal_free_string_array( devices );
1666 #else
1667             hal_free_string_array( devices );
1668 #endif
1669         }
1670
1671 #ifdef HAVE_HAL_1
1672         libhal_ctx_shutdown( ctx, NULL );
1673 #else
1674         hal_shutdown( ctx );
1675 #endif
1676     }
1677     else
1678     {
1679         msg_Warn( p_vlc, "Unable to get HAL device properties" );
1680     }
1681 #endif
1682 }