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