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