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