]> git.sesse.net Git - vlc/blob - src/libvlc.c
1820a4b7436e77202557bc101e99524fa0824c27
[vlc] / src / libvlc.c
1 /*****************************************************************************
2  * libvlc.c: libvlc instances creation and deletion, interfaces handling
3  *****************************************************************************
4  * Copyright (C) 1998-2008 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  * Preamble
34  *****************************************************************************/
35 #ifdef HAVE_CONFIG_H
36 # include "config.h"
37 #endif
38
39 #include <vlc_common.h>
40 #include "control/libvlc_internal.h"
41 #include <vlc_input.h>
42
43 #include "modules/modules.h"
44 #include "config/configuration.h"
45 #include "interface/interface.h"
46
47 #include <errno.h>                                                 /* ENOMEM */
48 #include <stdio.h>                                              /* sprintf() */
49 #include <string.h>
50 #include <stdlib.h>                                                /* free() */
51
52 #ifndef WIN32
53 #   include <netinet/in.h>                            /* BSD: struct in_addr */
54 #endif
55
56 #ifdef HAVE_UNISTD_H
57 #   include <unistd.h>
58 #elif defined( WIN32 ) && !defined( UNDER_CE )
59 #   include <io.h>
60 #endif
61
62 #ifdef WIN32                       /* optind, getopt(), included in unistd.h */
63 #   include "extras/getopt.h"
64 #endif
65
66 #ifdef HAVE_LOCALE_H
67 #   include <locale.h>
68 #endif
69
70 #ifdef HAVE_DBUS
71 /* used for one-instance mode */
72 #   include <dbus/dbus.h>
73 #endif
74
75 #ifdef HAVE_HAL
76 #   include <hal/libhal.h>
77 #endif
78
79 #include <vlc_playlist.h>
80 #include <vlc_interface.h>
81
82 #include <vlc_aout.h>
83 #include "audio_output/aout_internal.h"
84
85 #include <vlc_vout.h>
86
87 #include <vlc_sout.h>
88 #include "stream_output/stream_output.h"
89
90 #include <vlc_charset.h>
91
92 #include "libvlc.h"
93
94 #include "playlist/playlist_internal.h"
95
96 #include <vlc_vlm.h>
97
98 #include <assert.h>
99
100 /*****************************************************************************
101  * The evil global variables. We handle them with care, don't worry.
102  *****************************************************************************/
103 static libvlc_int_t *    p_static_vlc = NULL;
104 static unsigned          i_instances = 0;
105
106 #ifndef WIN32
107 static bool b_daemon = false;
108 #endif
109
110 /*****************************************************************************
111  * vlc_gc_*.
112  *****************************************************************************/
113 void __vlc_gc_incref( gc_object_t * p_gc )
114 {
115     assert( p_gc->i_gc_refcount > 0 );
116
117     /* FIXME: atomic version needed! */
118     p_gc->i_gc_refcount ++;
119 }
120
121 void __vlc_gc_decref( gc_object_t *p_gc )
122 {
123     assert( p_gc );
124     assert( p_gc->i_gc_refcount > 0 );
125
126     /* FIXME: atomic version needed! */
127     p_gc->i_gc_refcount -- ;
128
129     if( p_gc->i_gc_refcount == 0 )
130     {
131         p_gc->pf_destructor( p_gc );
132         /* Do not use the p_gc pointer from now on ! */
133     }
134 }
135
136 void
137 __vlc_gc_init( gc_object_t * p_gc, void (*pf_destructor)( gc_object_t * ),
138                void * arg)
139 {
140     p_gc->i_gc_refcount = 1;
141     p_gc->pf_destructor = pf_destructor;
142     p_gc->p_destructor_arg = arg;
143 }
144
145 /*****************************************************************************
146  * Local prototypes
147  *****************************************************************************/
148 #if defined( ENABLE_NLS ) && (defined (__APPLE__) || defined (WIN32)) && \
149     ( defined( HAVE_GETTEXT ) || defined( HAVE_INCLUDED_GETTEXT ) )
150 static void SetLanguage   ( char const * );
151 #endif
152 static inline int LoadMessages (void);
153 static int  GetFilenames  ( libvlc_int_t *, int, const char *[] );
154 static void Help          ( libvlc_int_t *, char const *psz_help_name );
155 static void Usage         ( libvlc_int_t *, char const *psz_module_name );
156 static void ListModules   ( libvlc_int_t *, bool );
157 static void Version       ( void );
158
159 #ifdef WIN32
160 static void ShowConsole   ( bool );
161 static void PauseConsole  ( void );
162 #endif
163 static int  ConsoleWidth  ( void );
164
165 static int  VerboseCallback( vlc_object_t *, char const *,
166                              vlc_value_t, vlc_value_t, void * );
167
168 static void InitDeviceValues( libvlc_int_t * );
169
170 /**
171  * Allocate a libvlc instance, initialize global data if needed
172  * It also initializes the threading system
173  */
174 libvlc_int_t * libvlc_InternalCreate( void )
175 {
176     libvlc_int_t *p_libvlc;
177     libvlc_priv_t *priv;
178     char *psz_env = NULL;
179
180     /* vlc_threads_init *must* be the first internal call! No other call is
181      * allowed before the thread system has been initialized. */
182     if (vlc_threads_init ())
183         return NULL;
184
185     libvlc_global_data_t *p_libvlc_global = vlc_global();
186     /* Now that the thread system is initialized, we don't have much, but
187      * at least we have variables */
188     vlc_mutex_t *lock = var_AcquireMutex( "libvlc" );
189     if( i_instances == 0 )
190     {
191         /* Guess what CPU we have */
192         cpu_flags = CPUCapabilities();
193        /* The module bank will be initialized later */
194         p_libvlc_global->p_module_bank = NULL;
195     }
196
197     /* Allocate a libvlc instance object */
198     p_libvlc = vlc_custom_create( VLC_OBJECT(p_libvlc_global),
199                                   sizeof (*p_libvlc) + sizeof (libvlc_priv_t),
200                                   VLC_OBJECT_LIBVLC, "libvlc" );
201     if( p_libvlc != NULL )
202         i_instances++;
203     vlc_mutex_unlock( lock );
204
205     if( p_libvlc == NULL )
206         return NULL;
207
208     priv = libvlc_priv (p_libvlc);
209     priv->p_playlist = NULL;
210     priv->p_interaction = NULL;
211     priv->p_vlm = NULL;
212     p_libvlc->psz_object_name = strdup( "libvlc" );
213
214     /* Initialize message queue */
215     msg_Create( p_libvlc );
216
217     /* Find verbosity from VLC_VERBOSE environment variable */
218     psz_env = getenv( "VLC_VERBOSE" );
219     if( psz_env != NULL )
220         priv->i_verbose = atoi( psz_env );
221     else
222         priv->i_verbose = 3;
223 #if defined( HAVE_ISATTY ) && !defined( WIN32 )
224     priv->b_color = isatty( 2 ); /* 2 is for stderr */
225 #else
226     priv->b_color = false;
227 #endif
228
229     /* Announce who we are - Do it only for first instance ? */
230     msg_Dbg( p_libvlc, COPYRIGHT_MESSAGE );
231     msg_Dbg( p_libvlc, "libvlc was configured with %s", CONFIGURE_LINE );
232
233     /* Initialize mutexes */
234     vlc_mutex_init( &priv->timer_lock );
235     vlc_mutex_init( &priv->config_lock );
236
237     priv->threads_count = 0;
238     vlc_mutex_init (&priv->threads_lock);
239     vlc_cond_init (NULL, &priv->threads_wait);
240
241     /* Store data for the non-reentrant API */
242     p_static_vlc = p_libvlc;
243
244     return p_libvlc;
245 }
246
247 /**
248  * Initialize a libvlc instance
249  * This function initializes a previously allocated libvlc instance:
250  *  - CPU detection
251  *  - gettext initialization
252  *  - message queue, module bank and playlist initialization
253  *  - configuration and commandline parsing
254  */
255 int libvlc_InternalInit( libvlc_int_t *p_libvlc, int i_argc,
256                          const char *ppsz_argv[] )
257 {
258     libvlc_global_data_t *p_libvlc_global = vlc_global();
259     libvlc_priv_t *priv = libvlc_priv (p_libvlc);
260     char         p_capabilities[200];
261     char *       p_tmp = NULL;
262     char *       psz_modules = NULL;
263     char *       psz_parser = NULL;
264     char *       psz_control = NULL;
265     bool   b_exit = false;
266     int          i_ret = VLC_EEXIT;
267     playlist_t  *p_playlist = NULL;
268     vlc_value_t  val;
269 #if defined( ENABLE_NLS ) \
270      && ( defined( HAVE_GETTEXT ) || defined( HAVE_INCLUDED_GETTEXT ) )
271 # if defined (WIN32) || defined (__APPLE__)
272     char *       psz_language;
273 #endif
274 #endif
275
276     /* System specific initialization code */
277     system_Init( p_libvlc, &i_argc, ppsz_argv );
278
279     /* Get the executable name (similar to the basename command) */
280     if( i_argc > 0 && ppsz_argv[0][0] )
281     {
282         free( p_libvlc->psz_object_name );
283
284         const char *psz_exe = strrchr( ppsz_argv[0], '/' );
285         if( psz_exe && *(psz_exe + 1) )
286             p_libvlc->psz_object_name = strdup( psz_exe + 1 );
287         else
288             p_libvlc->psz_object_name = strdup( ppsz_argv[0] );
289     }
290
291     /*
292      * Support for gettext
293      */
294     LoadMessages ();
295
296     /* Translate "C" to the language code: "fr", "en_GB", "nl", "ru"... */
297     msg_Dbg( p_libvlc, "translation test: code is \"%s\"", _("C") );
298
299     /* Initialize the module bank and load the configuration of the
300      * main module. We need to do this at this stage to be able to display
301      * a short help if required by the user. (short help == main module
302      * options) */
303     module_InitBank( p_libvlc );
304
305     if( config_LoadCmdLine( p_libvlc, &i_argc, ppsz_argv, true ) )
306     {
307         module_EndBank( p_libvlc );
308         return VLC_EGENERIC;
309     }
310
311     /* Check for short help option */
312     if( config_GetInt( p_libvlc, "help" ) > 0 )
313     {
314         Help( p_libvlc, "help" );
315         b_exit = true;
316         i_ret = VLC_EEXITSUCCESS;
317     }
318     /* Check for version option */
319     else if( config_GetInt( p_libvlc, "version" ) > 0 )
320     {
321         Version();
322         b_exit = true;
323         i_ret = VLC_EEXITSUCCESS;
324     }
325
326     /* Set the config file stuff */
327     priv->psz_configfile = config_GetCustomConfigFile( p_libvlc );
328
329     /* Check for plugins cache options */
330     if( config_GetInt( p_libvlc, "reset-plugins-cache" ) > 0 )
331     {
332         p_libvlc_global->p_module_bank->b_cache_delete = true;
333     }
334
335     /* Will be re-done properly later on */
336     priv->i_verbose = config_GetInt( p_libvlc, "verbose" );
337
338     /* Check for daemon mode */
339 #ifndef WIN32
340     if( config_GetInt( p_libvlc, "daemon" ) > 0 )
341     {
342 #ifdef HAVE_DAEMON
343         char *psz_pidfile = NULL;
344
345         if( daemon( 1, 0) != 0 )
346         {
347             msg_Err( p_libvlc, "Unable to fork vlc to daemon mode" );
348             b_exit = true;
349         }
350         b_daemon = true;
351
352         /* lets check if we need to write the pidfile */
353         psz_pidfile = config_GetPsz( p_libvlc, "pidfile" );
354         if( psz_pidfile != NULL )
355         {
356             FILE *pidfile;
357             pid_t i_pid = getpid ();
358             msg_Dbg( p_libvlc, "PID is %d, writing it to %s",
359                                i_pid, psz_pidfile );
360             pidfile = utf8_fopen( psz_pidfile,"w" );
361             if( pidfile != NULL )
362             {
363                 utf8_fprintf( pidfile, "%d", (int)i_pid );
364                 fclose( pidfile );
365             }
366             else
367             {
368                 msg_Err( p_libvlc, "cannot open pid file for writing: %s (%m)",
369                          psz_pidfile );
370             }
371         }
372         free( psz_pidfile );
373
374 #else
375         pid_t i_pid;
376
377         if( ( i_pid = fork() ) < 0 )
378         {
379             msg_Err( p_libvlc, "unable to fork vlc to daemon mode" );
380             b_exit = true;
381         }
382         else if( i_pid )
383         {
384             /* This is the parent, exit right now */
385             msg_Dbg( p_libvlc, "closing parent process" );
386             b_exit = true;
387             i_ret = VLC_EEXITSUCCESS;
388         }
389         else
390         {
391             /* We are the child */
392             msg_Dbg( p_libvlc, "daemon spawned" );
393             close( STDIN_FILENO );
394             close( STDOUT_FILENO );
395             close( STDERR_FILENO );
396
397             b_daemon = true;
398         }
399 #endif
400     }
401 #endif
402
403     if( b_exit )
404     {
405         module_EndBank( p_libvlc );
406         return i_ret;
407     }
408
409     /* Check for translation config option */
410 #if defined( ENABLE_NLS ) \
411      && ( defined( HAVE_GETTEXT ) || defined( HAVE_INCLUDED_GETTEXT ) )
412 # if defined (WIN32) || defined (__APPLE__)
413     /* This ain't really nice to have to reload the config here but it seems
414      * the only way to do it. */
415
416     if( !config_GetInt( p_libvlc, "ignore-config" ) )
417         config_LoadConfigFile( p_libvlc, "main" );
418     config_LoadCmdLine( p_libvlc, &i_argc, ppsz_argv, true );
419
420     /* Check if the user specified a custom language */
421     psz_language = config_GetPsz( p_libvlc, "language" );
422     if( psz_language && *psz_language && strcmp( psz_language, "auto" ) )
423     {
424         bool b_cache_delete = p_libvlc_global->p_module_bank->b_cache_delete;
425
426         /* Reset the default domain */
427         SetLanguage( psz_language );
428
429         /* Translate "C" to the language code: "fr", "en_GB", "nl", "ru"... */
430         msg_Dbg( p_libvlc, "translation test: code is \"%s\"", _("C") );
431
432         module_EndBank( p_libvlc );
433         module_InitBank( p_libvlc );
434         if( !config_GetInt( p_libvlc, "ignore-config" ) )
435             config_LoadConfigFile( p_libvlc, "main" );
436         config_LoadCmdLine( p_libvlc, &i_argc, ppsz_argv, true );
437         p_libvlc_global->p_module_bank->b_cache_delete = b_cache_delete;
438     }
439     free( psz_language );
440 # endif
441 #endif
442
443     /*
444      * Load the builtins and plugins into the module_bank.
445      * We have to do it before config_Load*() because this also gets the
446      * list of configuration options exported by each module and loads their
447      * default values.
448      */
449     module_LoadBuiltins( p_libvlc );
450     module_LoadPlugins( p_libvlc );
451     if( p_libvlc->b_die )
452     {
453         b_exit = true;
454     }
455
456     msg_Dbg( p_libvlc, "module bank initialized, found %i modules",
457              vlc_internals( p_libvlc_global->p_module_bank )->i_children );
458
459     /* Check for help on modules */
460     if( (p_tmp = config_GetPsz( p_libvlc, "module" )) )
461     {
462         Help( p_libvlc, p_tmp );
463         free( p_tmp );
464         b_exit = true;
465         i_ret = VLC_EEXITSUCCESS;
466     }
467     /* Check for full help option */
468     else if( config_GetInt( p_libvlc, "full-help" ) > 0 )
469     {
470         config_PutInt( p_libvlc, "advanced", 1);
471         config_PutInt( p_libvlc, "help-verbose", 1);
472         Help( p_libvlc, "full-help" );
473         b_exit = true;
474         i_ret = VLC_EEXITSUCCESS;
475     }
476     /* Check for long help option */
477     else if( config_GetInt( p_libvlc, "longhelp" ) > 0 )
478     {
479         Help( p_libvlc, "longhelp" );
480         b_exit = true;
481         i_ret = VLC_EEXITSUCCESS;
482     }
483     /* Check for module list option */
484     else if( config_GetInt( p_libvlc, "list" ) > 0 )
485     {
486         ListModules( p_libvlc, false );
487         b_exit = true;
488         i_ret = VLC_EEXITSUCCESS;
489     }
490     else if( config_GetInt( p_libvlc, "list-verbose" ) > 0 )
491     {
492         ListModules( p_libvlc, true );
493         b_exit = true;
494         i_ret = VLC_EEXITSUCCESS;
495     }
496
497     /* Check for config file options */
498     if( !config_GetInt( p_libvlc, "ignore-config" ) )
499     {
500         if( config_GetInt( p_libvlc, "reset-config" ) > 0 )
501         {
502             config_ResetAll( p_libvlc );
503             config_LoadCmdLine( p_libvlc, &i_argc, ppsz_argv, true );
504             config_SaveConfigFile( p_libvlc, NULL );
505         }
506         if( config_GetInt( p_libvlc, "save-config" ) > 0 )
507         {
508             config_LoadConfigFile( p_libvlc, NULL );
509             config_LoadCmdLine( p_libvlc, &i_argc, ppsz_argv, true );
510             config_SaveConfigFile( p_libvlc, NULL );
511         }
512     }
513
514     if( b_exit )
515     {
516         module_EndBank( p_libvlc );
517         return i_ret;
518     }
519
520     /*
521      * Init device values
522      */
523     InitDeviceValues( p_libvlc );
524
525     /*
526      * Override default configuration with config file settings
527      */
528     if( !config_GetInt( p_libvlc, "ignore-config" ) )
529         config_LoadConfigFile( p_libvlc, NULL );
530
531     /*
532      * Override configuration with command line settings
533      */
534     if( config_LoadCmdLine( p_libvlc, &i_argc, ppsz_argv, false ) )
535     {
536 #ifdef WIN32
537         ShowConsole( false );
538         /* Pause the console because it's destroyed when we exit */
539         fprintf( stderr, "The command line options couldn't be loaded, check "
540                  "that they are valid.\n" );
541         PauseConsole();
542 #endif
543         module_EndBank( p_libvlc );
544         return VLC_EGENERIC;
545     }
546
547     /*
548      * System specific configuration
549      */
550     system_Configure( p_libvlc, &i_argc, ppsz_argv );
551
552 /* FIXME: could be replaced by using Unix sockets */
553 #ifdef HAVE_DBUS
554     dbus_threads_init_default();
555
556     if( config_GetInt( p_libvlc, "one-instance" ) > 0 )
557     {
558         /* Initialise D-Bus interface, check for other instances */
559         DBusConnection  *p_conn = NULL;
560         DBusError       dbus_error;
561
562         dbus_error_init( &dbus_error );
563
564         /* connect to the session bus */
565         p_conn = dbus_bus_get( DBUS_BUS_SESSION, &dbus_error );
566         if( !p_conn )
567         {
568             msg_Err( p_libvlc, "Failed to connect to D-Bus session daemon: %s",
569                     dbus_error.message );
570             dbus_error_free( &dbus_error );
571         }
572         else
573         {
574             /* check if VLC is available on the bus
575              * if not: D-Bus control is not enabled on the other
576              * instance and we can't pass MRLs to it */
577             DBusMessage *p_test_msg = NULL;
578             DBusMessage *p_test_reply = NULL;
579             p_test_msg =  dbus_message_new_method_call(
580                     "org.mpris.vlc", "/",
581                     "org.freedesktop.MediaPlayer", "Identity" );
582             /* block until a reply arrives */
583             p_test_reply = dbus_connection_send_with_reply_and_block(
584                     p_conn, p_test_msg, -1, &dbus_error );
585             dbus_message_unref( p_test_msg );
586             if( p_test_reply == NULL )
587             {
588                 dbus_error_free( &dbus_error );
589                 msg_Dbg( p_libvlc, "No Media Player is running. "
590                         "Continuing normally." );
591             }
592             else
593             {
594                 int i_input;
595                 DBusMessage* p_dbus_msg = NULL;
596                 DBusMessageIter dbus_args;
597                 DBusPendingCall* p_dbus_pending = NULL;
598                 dbus_bool_t b_play;
599
600                 dbus_message_unref( p_test_reply );
601                 msg_Warn( p_libvlc, "Another Media Player is running. Exiting");
602
603                 for( i_input = optind;i_input < i_argc;i_input++ )
604                 {
605                     msg_Dbg( p_libvlc, "Adds %s to the running Media Player",
606                             ppsz_argv[i_input] );
607
608                     p_dbus_msg = dbus_message_new_method_call(
609                             "org.mpris.vlc", "/TrackList",
610                             "org.freedesktop.MediaPlayer", "AddTrack" );
611
612                     if ( NULL == p_dbus_msg )
613                     {
614                         msg_Err( p_libvlc, "D-Bus problem" );
615                         system_End( p_libvlc );
616                         exit( VLC_ETIMEOUT );
617                     }
618
619                     /* append MRLs */
620                     dbus_message_iter_init_append( p_dbus_msg, &dbus_args );
621                     if ( !dbus_message_iter_append_basic( &dbus_args,
622                                 DBUS_TYPE_STRING, &ppsz_argv[i_input] ) )
623                     {
624                         dbus_message_unref( p_dbus_msg );
625                         system_End( p_libvlc );
626                         exit( VLC_ENOMEM );
627                     }
628                     b_play = TRUE;
629                     if( config_GetInt( p_libvlc, "playlist-enqueue" ) > 0 )
630                         b_play = FALSE;
631                     if ( !dbus_message_iter_append_basic( &dbus_args,
632                                 DBUS_TYPE_BOOLEAN, &b_play ) )
633                     {
634                         dbus_message_unref( p_dbus_msg );
635                         system_End( p_libvlc );
636                         exit( VLC_ENOMEM );
637                     }
638
639                     /* send message and get a handle for a reply */
640                     if ( !dbus_connection_send_with_reply ( p_conn,
641                                 p_dbus_msg, &p_dbus_pending, -1 ) )
642                     {
643                         msg_Err( p_libvlc, "D-Bus problem" );
644                         dbus_message_unref( p_dbus_msg );
645                         system_End( p_libvlc );
646                         exit( VLC_ETIMEOUT );
647                     }
648
649                     if ( NULL == p_dbus_pending )
650                     {
651                         msg_Err( p_libvlc, "D-Bus problem" );
652                         dbus_message_unref( p_dbus_msg );
653                         system_End( p_libvlc );
654                         exit( VLC_ETIMEOUT );
655                     }
656                     dbus_connection_flush( p_conn );
657                     dbus_message_unref( p_dbus_msg );
658                     /* block until we receive a reply */
659                     dbus_pending_call_block( p_dbus_pending );
660                     dbus_pending_call_unref( p_dbus_pending );
661                 } /* processes all command line MRLs */
662
663                 /* bye bye */
664                 system_End( p_libvlc );
665                 exit( VLC_SUCCESS );
666             }
667         }
668         /* we unreference the connection when we've finished with it */
669         if( p_conn ) dbus_connection_unref( p_conn );
670     }
671 #endif
672
673     /*
674      * Message queue options
675      */
676
677     var_Create( p_libvlc, "verbose", VLC_VAR_INTEGER | VLC_VAR_DOINHERIT );
678     if( config_GetInt( p_libvlc, "quiet" ) > 0 )
679     {
680         val.i_int = -1;
681         var_Set( p_libvlc, "verbose", val );
682     }
683     var_AddCallback( p_libvlc, "verbose", VerboseCallback, NULL );
684     var_Change( p_libvlc, "verbose", VLC_VAR_TRIGGER_CALLBACKS, NULL, NULL );
685
686     if( priv->b_color )
687         priv->b_color = config_GetInt( p_libvlc, "color" ) > 0;
688
689     /*
690      * Output messages that may still be in the queue
691      */
692     msg_Flush( p_libvlc );
693
694     if( !config_GetInt( p_libvlc, "fpu" ) )
695         cpu_flags &= ~CPU_CAPABILITY_FPU;
696
697 #if defined( __i386__ ) || defined( __x86_64__ )
698     if( !config_GetInt( p_libvlc, "mmx" ) )
699         cpu_flags &= ~CPU_CAPABILITY_MMX;
700     if( !config_GetInt( p_libvlc, "3dn" ) )
701         cpu_flags &= ~CPU_CAPABILITY_3DNOW;
702     if( !config_GetInt( p_libvlc, "mmxext" ) )
703         cpu_flags &= ~CPU_CAPABILITY_MMXEXT;
704     if( !config_GetInt( p_libvlc, "sse" ) )
705         cpu_flags &= ~CPU_CAPABILITY_SSE;
706     if( !config_GetInt( p_libvlc, "sse2" ) )
707         cpu_flags &= ~CPU_CAPABILITY_SSE2;
708 #endif
709 #if defined( __powerpc__ ) || defined( __ppc__ ) || defined( __ppc64__ )
710     if( !config_GetInt( p_libvlc, "altivec" ) )
711         cpu_flags &= ~CPU_CAPABILITY_ALTIVEC;
712 #endif
713
714 #define PRINT_CAPABILITY( capability, string )                              \
715     if( vlc_CPU() & capability )                                            \
716     {                                                                       \
717         strncat( p_capabilities, string " ",                                \
718                  sizeof(p_capabilities) - strlen(p_capabilities) );         \
719         p_capabilities[sizeof(p_capabilities) - 1] = '\0';                  \
720     }
721
722     p_capabilities[0] = '\0';
723     PRINT_CAPABILITY( CPU_CAPABILITY_486, "486" );
724     PRINT_CAPABILITY( CPU_CAPABILITY_586, "586" );
725     PRINT_CAPABILITY( CPU_CAPABILITY_PPRO, "Pentium Pro" );
726     PRINT_CAPABILITY( CPU_CAPABILITY_MMX, "MMX" );
727     PRINT_CAPABILITY( CPU_CAPABILITY_3DNOW, "3DNow!" );
728     PRINT_CAPABILITY( CPU_CAPABILITY_MMXEXT, "MMXEXT" );
729     PRINT_CAPABILITY( CPU_CAPABILITY_SSE, "SSE" );
730     PRINT_CAPABILITY( CPU_CAPABILITY_SSE2, "SSE2" );
731     PRINT_CAPABILITY( CPU_CAPABILITY_ALTIVEC, "AltiVec" );
732     PRINT_CAPABILITY( CPU_CAPABILITY_FPU, "FPU" );
733     msg_Dbg( p_libvlc, "CPU has capabilities %s", p_capabilities );
734
735     /*
736      * Choose the best memcpy module
737      */
738     priv->p_memcpy_module = module_Need( p_libvlc, "memcpy", "$memcpy", 0 );
739
740     priv->b_stats = config_GetInt( p_libvlc, "stats" ) > 0;
741     priv->i_timers = 0;
742     priv->pp_timers = NULL;
743
744     /* Init stats */
745     p_libvlc->p_stats = (global_stats_t *)malloc( sizeof( global_stats_t ) );
746     if( !p_libvlc->p_stats )
747     {
748         vlc_object_release( p_libvlc );
749         return VLC_ENOMEM;
750     }
751     vlc_mutex_init( &p_libvlc->p_stats->lock );
752     priv->p_stats_computer = NULL;
753
754     /* Init the array that holds every input item */
755     ARRAY_INIT( priv->input_items );
756     priv->i_last_input_id = 0;
757
758     /*
759      * Initialize hotkey handling
760      */
761     var_Create( p_libvlc, "key-pressed", VLC_VAR_INTEGER );
762     var_Create( p_libvlc, "key-action", VLC_VAR_INTEGER );
763     p_libvlc->p_hotkeys = malloc( libvlc_hotkeys_size );
764     /* Do a copy (we don't need to modify the strings) */
765     memcpy( p_libvlc->p_hotkeys, libvlc_hotkeys, libvlc_hotkeys_size );
766     var_AddCallback( p_libvlc, "key-pressed", vlc_key_to_action,
767                      p_libvlc->p_hotkeys );
768
769     /* Initialize interaction */
770     priv->p_interaction = interaction_Init( p_libvlc );
771
772     /* Initialize playlist and get commandline files */
773     playlist_ThreadCreate( p_libvlc );
774     if( !priv->p_playlist )
775     {
776         msg_Err( p_libvlc, "playlist initialization failed" );
777         if( priv->p_memcpy_module != NULL )
778         {
779             module_Unneed( p_libvlc, priv->p_memcpy_module );
780         }
781         module_EndBank( p_libvlc );
782         return VLC_EGENERIC;
783     }
784     p_playlist = priv->p_playlist;
785
786     psz_modules = config_GetPsz( p_playlist, "services-discovery" );
787     if( psz_modules && *psz_modules )
788     {
789         /* Add service discovery modules */
790         playlist_ServicesDiscoveryAdd( p_playlist, psz_modules );
791     }
792     free( psz_modules );
793
794 #ifdef ENABLE_VLM
795     /* Initialize VLM if vlm-conf is specified */
796     psz_parser = config_GetPsz( p_libvlc, "vlm-conf" );
797     if( psz_parser && *psz_parser )
798     {
799         priv->p_vlm = vlm_New( p_libvlc );
800         if( !priv->p_vlm )
801             msg_Err( p_libvlc, "VLM initialization failed" );
802     }
803     free( psz_parser );
804 #endif
805
806     /*
807      * Load background interfaces
808      */
809     psz_modules = config_GetPsz( p_libvlc, "extraintf" );
810     psz_control = config_GetPsz( p_libvlc, "control" );
811
812     if( psz_modules && *psz_modules && psz_control && *psz_control )
813     {
814         psz_modules = (char *)realloc( psz_modules, strlen( psz_modules ) +
815                                                     strlen( psz_control ) + 1 );
816         sprintf( psz_modules, "%s:%s", psz_modules, psz_control );
817     }
818     else if( psz_control && *psz_control )
819     {
820         free( psz_modules );
821         psz_modules = strdup( psz_control );
822     }
823
824     psz_parser = psz_modules;
825     while ( psz_parser && *psz_parser )
826     {
827         char *psz_module, *psz_temp;
828         psz_module = psz_parser;
829         psz_parser = strchr( psz_module, ':' );
830         if ( psz_parser )
831         {
832             *psz_parser = '\0';
833             psz_parser++;
834         }
835         psz_temp = (char *)malloc( strlen(psz_module) + sizeof(",none") );
836         if( psz_temp )
837         {
838             sprintf( psz_temp, "%s,none", psz_module );
839             libvlc_InternalAddIntf( p_libvlc, psz_temp );
840             free( psz_temp );
841         }
842     }
843     free( psz_modules );
844     free( psz_control );
845
846     /*
847      * Always load the hotkeys interface if it exists
848      */
849     libvlc_InternalAddIntf( p_libvlc, "hotkeys,none" );
850
851 #ifdef HAVE_DBUS
852     /* loads dbus control interface if in one-instance mode
853      * we do it only when playlist exists, because dbus module needs it */
854     if( config_GetInt( p_libvlc, "one-instance" ) > 0 )
855         libvlc_InternalAddIntf( p_libvlc, "dbus,none" );
856
857     /* Prevents the power management daemon from suspending the system
858      * when VLC is active */
859     if( config_GetInt( p_libvlc, "inhibit" ) > 0 )
860         libvlc_InternalAddIntf( p_libvlc, "inhibit,none" );
861 #endif
862
863     /*
864      * If needed, load the Xscreensaver interface
865      * Currently, only for X
866      */
867 #ifdef HAVE_X11_XLIB_H
868     if( config_GetInt( p_libvlc, "disable-screensaver" ) )
869     {
870         libvlc_InternalAddIntf( p_libvlc, "screensaver,none" );
871     }
872 #endif
873
874     if( config_GetInt( p_libvlc, "file-logging" ) > 0 )
875     {
876         libvlc_InternalAddIntf( p_libvlc, "logger,none" );
877     }
878 #ifdef HAVE_SYSLOG_H
879     if( config_GetInt( p_libvlc, "syslog" ) > 0 )
880     {
881         char *logmode = var_CreateGetString( p_libvlc, "logmode" );
882         var_SetString( p_libvlc, "logmode", "syslog" );
883         libvlc_InternalAddIntf( p_libvlc, "logger,none" );
884
885         if( logmode )
886         {
887             var_SetString( p_libvlc, "logmode", logmode );
888             free( logmode );
889         }
890         else
891             var_Destroy( p_libvlc, "logmode" );
892     }
893 #endif
894
895     if( config_GetInt( p_libvlc, "show-intf" ) > 0 )
896     {
897         libvlc_InternalAddIntf( p_libvlc, "showintf,none" );
898     }
899
900     if( config_GetInt( p_libvlc, "network-synchronisation") > 0 )
901     {
902         libvlc_InternalAddIntf( p_libvlc, "netsync,none" );
903     }
904
905 #ifdef WIN32
906     if( config_GetInt( p_libvlc, "prefer-system-codecs") > 0 )
907     {
908         char *psz_codecs = config_GetPsz( p_playlist, "codec" );
909         if( psz_codecs )
910         {
911             char *psz_morecodecs;
912             asprintf(&psz_morecodecs, "%s,dmo,quicktime", psz_codecs);
913             if( psz_morecodecs )
914             {
915                 config_PutPsz( p_libvlc, "codec", psz_morecodecs);
916                 free( psz_morecodecs );
917             }
918         }
919         else
920             config_PutPsz( p_libvlc, "codec", "dmo,quicktime");
921         free( psz_codecs );
922     }
923 #endif
924
925     /*
926      * FIXME: kludge to use a p_libvlc-local variable for the Mozilla plugin
927      */
928     var_Create( p_libvlc, "drawable", VLC_VAR_INTEGER );
929     var_Create( p_libvlc, "drawable-view-top", VLC_VAR_INTEGER );
930     var_Create( p_libvlc, "drawable-view-left", VLC_VAR_INTEGER );
931     var_Create( p_libvlc, "drawable-view-bottom", VLC_VAR_INTEGER );
932     var_Create( p_libvlc, "drawable-view-right", VLC_VAR_INTEGER );
933     var_Create( p_libvlc, "drawable-clip-top", VLC_VAR_INTEGER );
934     var_Create( p_libvlc, "drawable-clip-left", VLC_VAR_INTEGER );
935     var_Create( p_libvlc, "drawable-clip-bottom", VLC_VAR_INTEGER );
936     var_Create( p_libvlc, "drawable-clip-right", VLC_VAR_INTEGER );
937
938     /* Create volume callback system. */
939     var_Create( p_libvlc, "volume-change", VLC_VAR_BOOL );
940
941     /* Create a variable for showing the interface (moved from playlist). */
942     var_Create( p_libvlc, "intf-show", VLC_VAR_BOOL );
943     var_SetBool( p_libvlc, "intf-show", true );
944
945     var_Create( p_libvlc, "intf-popupmenu", VLC_VAR_BOOL );
946
947     /*
948      * Get input filenames given as commandline arguments
949      */
950     GetFilenames( p_libvlc, i_argc, ppsz_argv );
951
952     /*
953      * Get --open argument
954      */
955     var_Create( p_libvlc, "open", VLC_VAR_STRING | VLC_VAR_DOINHERIT );
956     var_Get( p_libvlc, "open", &val );
957     if ( val.psz_string != NULL && *val.psz_string )
958     {
959         playlist_t *p_playlist = pl_Yield( p_libvlc );
960         playlist_AddExt( p_playlist, val.psz_string, NULL, PLAYLIST_INSERT, 0,
961                          -1, NULL, 0, true, pl_Unlocked );
962         pl_Release( p_libvlc );
963     }
964     free( val.psz_string );
965
966     return VLC_SUCCESS;
967 }
968
969 /**
970  * Cleanup a libvlc instance. The instance is not completely deallocated
971  * \param p_libvlc the instance to clean
972  */
973 int libvlc_InternalCleanup( libvlc_int_t *p_libvlc )
974 {
975     intf_thread_t      * p_intf = NULL;
976     libvlc_priv_t      *priv = libvlc_priv (p_libvlc);
977
978     /* Ask the interfaces to stop and destroy them */
979     msg_Dbg( p_libvlc, "removing all interfaces" );
980     while( (p_intf = vlc_object_find( p_libvlc, VLC_OBJECT_INTF, FIND_CHILD )) )
981     {
982         intf_StopThread( p_intf );
983         vlc_object_detach( p_intf );
984         vlc_object_release( p_intf ); /* for intf_Create() */
985         vlc_object_release( p_intf ); /* for vlc_object_find() */
986     }
987
988 #ifdef ENABLE_VLM
989     /* Destroy VLM if created in libvlc_InternalInit */
990     if( priv->p_vlm )
991     {
992         vlm_Delete( priv->p_vlm );
993     }
994 #endif
995
996     playlist_t *p_playlist = priv->p_playlist;
997     /* Remove all services discovery */
998     msg_Dbg( p_libvlc, "removing all services discovery tasks" );
999     playlist_ServicesDiscoveryKillAll( p_playlist );
1000
1001     /* Free playlist */
1002     /* Any thread still running must not assume pl_Yield() succeeds. */
1003     msg_Dbg( p_libvlc, "removing playlist" );
1004     priv->p_playlist = NULL;
1005     vlc_object_kill( p_playlist ); /* <-- memory barrier for pl_Yield() */
1006     vlc_thread_join( p_playlist );
1007     vlc_object_release( p_playlist );
1008
1009     /* Free interaction */
1010     msg_Dbg( p_libvlc, "removing interaction" );
1011     interaction_Destroy( priv->p_interaction );
1012
1013     /* Free video outputs */
1014     msg_Dbg( p_libvlc, "removing all video outputs" );
1015     vlc_list_t *list = vlc_list_find (p_libvlc, VLC_OBJECT_VOUT, FIND_CHILD);
1016     for (int i = 0; i < list->i_count; i++)
1017         vlc_object_release (list->p_values[i].p_object);
1018     vlc_list_release (list);
1019
1020     stats_TimersDumpAll( p_libvlc );
1021     stats_TimersCleanAll( p_libvlc );
1022
1023 #ifdef ENABLE_SOUT
1024     announce_handler_t * p_announce;
1025
1026     /* Free announce handler(s?) */
1027     while( (p_announce = vlc_object_find( p_libvlc, VLC_OBJECT_ANNOUNCE,
1028                                                  FIND_CHILD ) ) )
1029     {
1030         msg_Dbg( p_libvlc, "removing announce handler" );
1031         vlc_object_detach( p_announce );
1032         vlc_object_release( p_announce );
1033         announce_HandlerDestroy( p_announce );
1034     }
1035 #endif
1036
1037     /* Make sure all threads are completed before we start looking for
1038      * reference leaks and deinitializing core LibVLC subsytems. */
1039     vlc_mutex_lock (&priv->threads_lock);
1040     while (priv->threads_count)
1041     {
1042         msg_Dbg (p_libvlc, "waiting for %u remaining threads",
1043                  priv->threads_count);
1044         vlc_cond_wait (&priv->threads_wait, &priv->threads_lock);
1045     }
1046     vlc_mutex_unlock (&priv->threads_lock);
1047
1048     bool b_clean = true;
1049     FOREACH_ARRAY( input_item_t *p_del, priv->input_items )
1050         msg_Err( p_libvlc, "input item %p has not been deleted properly: refcount %d, name %s",
1051             p_del, p_del->i_gc_refcount, p_del->psz_name ? p_del->psz_name : "(null)" );
1052         b_clean = false;
1053     FOREACH_END();
1054     assert( b_clean );
1055     ARRAY_RESET( priv->input_items );
1056
1057     msg_Dbg( p_libvlc, "removing stats" );
1058     vlc_mutex_destroy( &p_libvlc->p_stats->lock );
1059     FREENULL( p_libvlc->p_stats );
1060
1061     return VLC_SUCCESS;
1062 }
1063
1064 /**
1065  * Destroy everything.
1066  * This function requests the running threads to finish, waits for their
1067  * termination, and destroys their structure.
1068  * It stops the thread systems: no instance can run after this has run
1069  * \param p_libvlc the instance to destroy
1070  */
1071 int libvlc_InternalDestroy( libvlc_int_t *p_libvlc )
1072 {
1073     if( !p_libvlc )
1074         return VLC_EGENERIC;
1075
1076     libvlc_priv_t *priv = libvlc_priv (p_libvlc);
1077
1078 #ifndef WIN32
1079     char* psz_pidfile = NULL;
1080
1081     if( b_daemon )
1082     {
1083         psz_pidfile = config_GetPsz( p_libvlc, "pidfile" );
1084         if( psz_pidfile != NULL )
1085         {
1086             msg_Dbg( p_libvlc, "removing pid file %s", psz_pidfile );
1087             if( unlink( psz_pidfile ) == -1 )
1088             {
1089                 msg_Dbg( p_libvlc, "removing pid file %s: %m",
1090                         psz_pidfile );
1091             }
1092         }
1093         free( psz_pidfile );
1094     }
1095 #endif
1096
1097     if( priv->p_memcpy_module )
1098     {
1099         module_Unneed( p_libvlc, priv->p_memcpy_module );
1100         priv->p_memcpy_module = NULL;
1101     }
1102
1103     /* Free module bank. It is refcounted, so we call this each time  */
1104     module_EndBank( p_libvlc );
1105
1106     FREENULL( priv->psz_configfile );
1107     var_DelCallback( p_libvlc, "key-pressed", vlc_key_to_action,
1108                      p_libvlc->p_hotkeys );
1109     FREENULL( p_libvlc->p_hotkeys );
1110
1111     vlc_mutex_t *lock = var_AcquireMutex( "libvlc" );
1112     i_instances--;
1113
1114     if( i_instances == 0 )
1115     {
1116         /* System specific cleaning code */
1117         system_End( p_libvlc );
1118     }
1119     vlc_mutex_unlock( lock );
1120
1121     msg_Flush( p_libvlc );
1122     msg_Destroy( p_libvlc );
1123
1124     /* Destroy mutexes */
1125     vlc_mutex_destroy( &priv->config_lock );
1126     vlc_mutex_destroy( &priv->timer_lock );
1127     vlc_cond_destroy (&priv->threads_wait);
1128     vlc_mutex_destroy (&priv->threads_lock);
1129
1130     vlc_object_release( p_libvlc );
1131     p_libvlc = NULL;
1132
1133     /* Stop thread system: last one out please shut the door!
1134      * The number of initializations of the thread system is counted, we
1135      * can call this each time */
1136     vlc_threads_end ();
1137
1138     return VLC_SUCCESS;
1139 }
1140
1141 /**
1142  * Add an interface plugin and run it
1143  */
1144 int libvlc_InternalAddIntf( libvlc_int_t *p_libvlc, char const *psz_module )
1145 {
1146     int i_err;
1147     intf_thread_t *p_intf = NULL;
1148
1149     if( !p_libvlc )
1150         return VLC_EGENERIC;
1151
1152     if( !psz_module ) /* requesting the default interface */
1153     {
1154         char *psz_interface = config_GetPsz( p_libvlc, "intf" );
1155         if( !psz_interface || !*psz_interface ) /* "intf" has not been set */
1156         {
1157 #ifndef WIN32
1158             if( b_daemon )
1159                  /* Daemon mode hack.
1160                   * We prefer the dummy interface if none is specified. */
1161                 psz_module = "dummy";
1162             else
1163 #endif
1164                 msg_Info( p_libvlc, _("Running vlc with the default interface. Use 'cvlc' to use vlc without interface.") );
1165         }
1166         free( psz_interface );
1167     }
1168
1169     /* Try to create the interface */
1170     p_intf = intf_Create( p_libvlc, psz_module ? psz_module : "$intf" );
1171     if( p_intf == NULL )
1172     {
1173         msg_Err( p_libvlc, "interface \"%s\" initialization failed",
1174                  psz_module );
1175         return VLC_EGENERIC;
1176     }
1177
1178     /* Try to run the interface */
1179     i_err = intf_RunThread( p_intf );
1180     if( i_err )
1181     {
1182         vlc_object_detach( p_intf );
1183         vlc_object_release( p_intf );
1184         return i_err;
1185     }
1186
1187     return VLC_SUCCESS;
1188 };
1189
1190 #if defined( ENABLE_NLS ) && (defined (__APPLE__) || defined (WIN32)) && \
1191     ( defined( HAVE_GETTEXT ) || defined( HAVE_INCLUDED_GETTEXT ) )
1192 /*****************************************************************************
1193  * SetLanguage: set the interface language.
1194  *****************************************************************************
1195  * We set the LC_MESSAGES locale category for interface messages and buttons,
1196  * as well as the LC_CTYPE category for string sorting and possible wide
1197  * character support.
1198  *****************************************************************************/
1199 static void SetLanguage ( const char *psz_lang )
1200 {
1201 #ifdef __APPLE__
1202     /* I need that under Darwin, please check it doesn't disturb
1203      * other platforms. --Meuuh */
1204     setenv( "LANG", psz_lang, 1 );
1205
1206 #else
1207     /* We set LC_ALL manually because it is the only way to set
1208      * the language at runtime under eg. Windows. Beware that this
1209      * makes the environment unconsistent when libvlc is unloaded and
1210      * should probably be moved to a safer place like vlc.c. */
1211     static char psz_lcall[20];
1212     snprintf( psz_lcall, 19, "LC_ALL=%s", psz_lang );
1213     psz_lcall[19] = '\0';
1214     putenv( psz_lcall );
1215 #endif
1216
1217     setlocale( LC_ALL, psz_lang );
1218 }
1219 #endif
1220
1221
1222 static inline int LoadMessages (void)
1223 {
1224 #if defined( ENABLE_NLS ) \
1225      && ( defined( HAVE_GETTEXT ) || defined( HAVE_INCLUDED_GETTEXT ) )
1226     /* Specify where to find the locales for current domain */
1227 #if !defined( __APPLE__ ) && !defined( WIN32 ) && !defined( SYS_BEOS )
1228     static const char psz_path[] = LOCALEDIR;
1229 #else
1230     char psz_path[1024];
1231     if (snprintf (psz_path, sizeof (psz_path), "%s" DIR_SEP "%s",
1232                   config_GetDataDir(), "locale")
1233                      >= (int)sizeof (psz_path))
1234         return -1;
1235
1236 #endif
1237     if (bindtextdomain (PACKAGE_NAME, psz_path) == NULL)
1238     {
1239         fprintf (stderr, "Warning: cannot bind text domain "PACKAGE_NAME
1240                          " to directory %s\n", psz_path);
1241         return -1;
1242     }
1243
1244     /* LibVLC wants all messages in UTF-8.
1245      * Unfortunately, we cannot ask UTF-8 for strerror_r(), strsignal_r()
1246      * and other functions that are not part of our text domain.
1247      */
1248     if (bind_textdomain_codeset (PACKAGE_NAME, "UTF-8") == NULL)
1249     {
1250         fprintf (stderr, "Error: cannot set Unicode encoding for text domain "
1251                          PACKAGE_NAME"\n");
1252         // Unbinds the text domain to avoid broken encoding
1253         bindtextdomain (PACKAGE_NAME, "DOES_NOT_EXIST");
1254         return -1;
1255     }
1256
1257     /* LibVLC does NOT set the default textdomain, since it is a library.
1258      * This could otherwise break programs using LibVLC (other than VLC).
1259      * textdomain (PACKAGE_NAME);
1260      */
1261 #endif
1262     return 0;
1263 }
1264
1265 /*****************************************************************************
1266  * GetFilenames: parse command line options which are not flags
1267  *****************************************************************************
1268  * Parse command line for input files as well as their associated options.
1269  * An option always follows its associated input and begins with a ":".
1270  *****************************************************************************/
1271 static int GetFilenames( libvlc_int_t *p_vlc, int i_argc, const char *ppsz_argv[] )
1272 {
1273     int i_opt, i_options;
1274
1275     /* We assume that the remaining parameters are filenames
1276      * and their input options */
1277     for( i_opt = i_argc - 1; i_opt >= optind; i_opt-- )
1278     {
1279         i_options = 0;
1280
1281         /* Count the input options */
1282         while( *ppsz_argv[ i_opt ] == ':' && i_opt > optind )
1283         {
1284             i_options++;
1285             i_opt--;
1286         }
1287
1288         /* TODO: write an internal function of this one, to avoid
1289          *       unnecessary lookups. */
1290
1291         playlist_t *p_playlist = pl_Yield( p_vlc );
1292         playlist_AddExt( p_playlist, ppsz_argv[i_opt], NULL, PLAYLIST_INSERT,
1293                          0, -1, ( i_options ? &ppsz_argv[i_opt + 1] : NULL ),
1294                          i_options, true, pl_Unlocked );
1295         pl_Release( p_vlc );
1296     }
1297
1298     return VLC_SUCCESS;
1299 }
1300
1301 /*****************************************************************************
1302  * Help: print program help
1303  *****************************************************************************
1304  * Print a short inline help. Message interface is initialized at this stage.
1305  *****************************************************************************/
1306 static inline void print_help_on_full_help( void )
1307 {
1308     utf8_fprintf( stdout, "\n" );
1309     utf8_fprintf( stdout, "%s\n", _("To get exhaustive help, use '-H'.") );
1310 }
1311
1312 static void Help( libvlc_int_t *p_this, char const *psz_help_name )
1313 {
1314 #ifdef WIN32
1315     ShowConsole( true );
1316 #endif
1317
1318     if( psz_help_name && !strcmp( psz_help_name, "help" ) )
1319     {
1320         utf8_fprintf( stdout, vlc_usage, p_this->psz_object_name );
1321         Usage( p_this, "help" );
1322         Usage( p_this, "main" );
1323         print_help_on_full_help();
1324     }
1325     else if( psz_help_name && !strcmp( psz_help_name, "longhelp" ) )
1326     {
1327         utf8_fprintf( stdout, vlc_usage, p_this->psz_object_name );
1328         Usage( p_this, NULL );
1329         print_help_on_full_help();
1330     }
1331     else if( psz_help_name && !strcmp( psz_help_name, "full-help" ) )
1332     {
1333         utf8_fprintf( stdout, vlc_usage, p_this->psz_object_name );
1334         Usage( p_this, NULL );
1335     }
1336     else if( psz_help_name )
1337     {
1338         Usage( p_this, psz_help_name );
1339     }
1340
1341 #ifdef WIN32        /* Pause the console because it's destroyed when we exit */
1342     PauseConsole();
1343 #endif
1344 }
1345
1346 /*****************************************************************************
1347  * Usage: print module usage
1348  *****************************************************************************
1349  * Print a short inline help. Message interface is initialized at this stage.
1350  *****************************************************************************/
1351 #   define COL(x)  "\033[" #x ";1m"
1352 #   define RED     COL(31)
1353 #   define GREEN   COL(32)
1354 #   define YELLOW  COL(33)
1355 #   define BLUE    COL(34)
1356 #   define MAGENTA COL(35)
1357 #   define CYAN    COL(36)
1358 #   define WHITE   COL(0)
1359 #   define GRAY    "\033[0m"
1360 static void print_help_section( module_config_t *p_item, bool b_color, bool b_description )
1361 {
1362     if( !p_item ) return;
1363     if( b_color )
1364     {
1365         utf8_fprintf( stdout, RED"   %s:\n"GRAY,
1366                       p_item->psz_text );
1367         if( b_description && p_item->psz_longtext )
1368             utf8_fprintf( stdout, MAGENTA"   %s\n"GRAY,
1369                           p_item->psz_longtext );
1370     }
1371     else
1372     {
1373         utf8_fprintf( stdout, "   %s:\n", p_item->psz_text );
1374         if( b_description && p_item->psz_longtext )
1375             utf8_fprintf( stdout, "   %s\n", p_item->psz_longtext );
1376     }
1377 }
1378
1379 static void Usage( libvlc_int_t *p_this, char const *psz_module_name )
1380 {
1381 #define FORMAT_STRING "  %s --%s%s%s%s%s%s%s "
1382     /* short option ------'    | | | | | | |
1383      * option name ------------' | | | | | |
1384      * <bra ---------------------' | | | | |
1385      * option type or "" ----------' | | | |
1386      * ket> -------------------------' | | |
1387      * padding spaces -----------------' | |
1388      * comment --------------------------' |
1389      * comment suffix ---------------------'
1390      *
1391      * The purpose of having bra and ket is that we might i18n them as well.
1392      */
1393
1394 #define COLOR_FORMAT_STRING (WHITE"  %s --%s"YELLOW"%s%s%s%s%s%s "GRAY)
1395 #define COLOR_FORMAT_STRING_BOOL (WHITE"  %s --%s%s%s%s%s%s%s "GRAY)
1396
1397 #define LINE_START 8
1398 #define PADDING_SPACES 25
1399 #ifdef WIN32
1400 #   define OPTION_VALUE_SEP "="
1401 #else
1402 #   define OPTION_VALUE_SEP " "
1403 #endif
1404     vlc_list_t *p_list = NULL;
1405     char psz_spaces_text[PADDING_SPACES+LINE_START+1];
1406     char psz_spaces_longtext[LINE_START+3];
1407     char psz_format[sizeof(COLOR_FORMAT_STRING)];
1408     char psz_format_bool[sizeof(COLOR_FORMAT_STRING_BOOL)];
1409     char psz_buffer[10000];
1410     char psz_short[4];
1411     int i_index;
1412     int i_width = ConsoleWidth() - (PADDING_SPACES+LINE_START+1);
1413     int i_width_description = i_width + PADDING_SPACES - 1;
1414     bool b_advanced    = config_GetInt( p_this, "advanced" ) > 0;
1415     bool b_description = config_GetInt( p_this, "help-verbose" ) > 0;
1416     bool b_description_hack;
1417     bool b_color       = config_GetInt( p_this, "color" ) > 0;
1418     bool b_has_advanced = false;
1419
1420     memset( psz_spaces_text, ' ', PADDING_SPACES+LINE_START );
1421     psz_spaces_text[PADDING_SPACES+LINE_START] = '\0';
1422     memset( psz_spaces_longtext, ' ', LINE_START+2 );
1423     psz_spaces_longtext[LINE_START+2] = '\0';
1424 #ifndef WIN32
1425     if( !isatty( 1 ) )
1426 #endif
1427         b_color = false; // don't put color control codes in a .txt file
1428
1429     if( b_color )
1430     {
1431         strcpy( psz_format, COLOR_FORMAT_STRING );
1432         strcpy( psz_format_bool, COLOR_FORMAT_STRING_BOOL );
1433     }
1434     else
1435     {
1436         strcpy( psz_format, FORMAT_STRING );
1437         strcpy( psz_format_bool, FORMAT_STRING );
1438     }
1439
1440     /* List all modules */
1441     p_list = vlc_list_find( p_this, VLC_OBJECT_MODULE, FIND_ANYWHERE );
1442
1443     /* Ugly hack to make sure that the help options always come first
1444      * (part 1) */
1445     if( !psz_module_name )
1446         Usage( p_this, "help" );
1447
1448     /* Enumerate the config for each module */
1449     for( i_index = 0; i_index < p_list->i_count; i_index++ )
1450     {
1451         bool b_help_module;
1452         module_t *p_parser = (module_t *)p_list->p_values[i_index].p_object;
1453         module_config_t *p_item = NULL;
1454         module_config_t *p_section = NULL;
1455         module_config_t *p_end = p_parser->p_config + p_parser->confsize;
1456
1457         if( psz_module_name && strcmp( psz_module_name,
1458                                        p_parser->psz_object_name ) )
1459         {
1460             char *const *pp_shortcut = p_parser->pp_shortcuts;
1461             while( *pp_shortcut )
1462             {
1463                 if( !strcmp( psz_module_name, *pp_shortcut ) )
1464                     break;
1465                 pp_shortcut ++;
1466             }
1467             if( !*pp_shortcut )
1468                 continue;
1469         }
1470
1471         /* Ignore modules without config options */
1472         if( !p_parser->i_config_items )
1473         {
1474             continue;
1475         }
1476
1477         b_help_module = !strcmp( "help", p_parser->psz_object_name );
1478         /* Ugly hack to make sure that the help options always come first
1479          * (part 2) */
1480         if( !psz_module_name && b_help_module )
1481             continue;
1482
1483         /* Ignore modules with only advanced config options if requested */
1484         if( !b_advanced )
1485         {
1486             for( p_item = p_parser->p_config;
1487                  p_item < p_end;
1488                  p_item++ )
1489             {
1490                 if( (p_item->i_type & CONFIG_ITEM) &&
1491                     !p_item->b_advanced ) break;
1492             }
1493         }
1494
1495         /* Print name of module */
1496         if( strcmp( "main", p_parser->psz_object_name ) )
1497         {
1498             if( b_color )
1499                 utf8_fprintf( stdout, "\n " GREEN "%s" GRAY "\n",
1500                               p_parser->psz_longname );
1501             else
1502                 utf8_fprintf( stdout, "\n %s\n", p_parser->psz_longname );
1503         }
1504         if( p_parser->psz_help )
1505         {
1506             if( b_color )
1507                 utf8_fprintf( stdout, CYAN" %s\n"GRAY, p_parser->psz_help );
1508             else
1509                 utf8_fprintf( stdout, " %s\n", p_parser->psz_help );
1510         }
1511
1512         /* Print module options */
1513         for( p_item = p_parser->p_config;
1514              p_item < p_end;
1515              p_item++ )
1516         {
1517             char *psz_text, *psz_spaces = psz_spaces_text;
1518             const char *psz_bra = NULL, *psz_type = NULL, *psz_ket = NULL;
1519             const char *psz_suf = "", *psz_prefix = NULL;
1520             signed int i;
1521             size_t i_cur_width;
1522
1523             /* Skip removed options */
1524             if( p_item->b_removed )
1525             {
1526                 continue;
1527             }
1528             /* Skip advanced options if requested */
1529             if( p_item->b_advanced && !b_advanced )
1530             {
1531                 b_has_advanced = true;
1532                 continue;
1533             }
1534
1535             switch( p_item->i_type )
1536             {
1537             case CONFIG_HINT_CATEGORY:
1538             case CONFIG_HINT_USAGE:
1539                 if( !strcmp( "main", p_parser->psz_object_name ) )
1540                 {
1541                     if( b_color )
1542                         utf8_fprintf( stdout, GREEN "\n %s\n" GRAY,
1543                                       p_item->psz_text );
1544                     else
1545                         utf8_fprintf( stdout, "\n %s\n", p_item->psz_text );
1546                 }
1547                 if( b_description && p_item->psz_longtext )
1548                 {
1549                     if( b_color )
1550                         utf8_fprintf( stdout, CYAN " %s\n" GRAY,
1551                                       p_item->psz_longtext );
1552                     else
1553                         utf8_fprintf( stdout, " %s\n", p_item->psz_longtext );
1554                 }
1555                 break;
1556
1557             case CONFIG_HINT_SUBCATEGORY:
1558                 if( strcmp( "main", p_parser->psz_object_name ) )
1559                     break;
1560             case CONFIG_SECTION:
1561                 p_section = p_item;
1562                 break;
1563
1564             case CONFIG_ITEM_STRING:
1565             case CONFIG_ITEM_FILE:
1566             case CONFIG_ITEM_DIRECTORY:
1567             case CONFIG_ITEM_MODULE: /* We could also have "=<" here */
1568             case CONFIG_ITEM_MODULE_CAT:
1569             case CONFIG_ITEM_MODULE_LIST:
1570             case CONFIG_ITEM_MODULE_LIST_CAT:
1571             case CONFIG_ITEM_FONT:
1572             case CONFIG_ITEM_PASSWORD:
1573                 print_help_section( p_section, b_color, b_description );
1574                 p_section = NULL;
1575                 psz_bra = OPTION_VALUE_SEP "<";
1576                 psz_type = _("string");
1577                 psz_ket = ">";
1578
1579                 if( p_item->ppsz_list )
1580                 {
1581                     psz_bra = OPTION_VALUE_SEP "{";
1582                     psz_type = psz_buffer;
1583                     psz_buffer[0] = '\0';
1584                     for( i = 0; p_item->ppsz_list[i]; i++ )
1585                     {
1586                         if( i ) strcat( psz_buffer, "," );
1587                         strcat( psz_buffer, p_item->ppsz_list[i] );
1588                     }
1589                     psz_ket = "}";
1590                 }
1591                 break;
1592             case CONFIG_ITEM_INTEGER:
1593             case CONFIG_ITEM_KEY: /* FIXME: do something a bit more clever */
1594                 print_help_section( p_section, b_color, b_description );
1595                 p_section = NULL;
1596                 psz_bra = OPTION_VALUE_SEP "<";
1597                 psz_type = _("integer");
1598                 psz_ket = ">";
1599
1600                 if( p_item->min.i || p_item->max.i )
1601                 {
1602                     sprintf( psz_buffer, "%s [%i .. %i]", psz_type,
1603                              p_item->min.i, p_item->max.i );
1604                     psz_type = psz_buffer;
1605                 }
1606
1607                 if( p_item->i_list )
1608                 {
1609                     psz_bra = OPTION_VALUE_SEP "{";
1610                     psz_type = psz_buffer;
1611                     psz_buffer[0] = '\0';
1612                     for( i = 0; p_item->ppsz_list_text[i]; i++ )
1613                     {
1614                         if( i ) strcat( psz_buffer, ", " );
1615                         sprintf( psz_buffer + strlen(psz_buffer), "%i (%s)",
1616                                  p_item->pi_list[i],
1617                                  p_item->ppsz_list_text[i] );
1618                     }
1619                     psz_ket = "}";
1620                 }
1621                 break;
1622             case CONFIG_ITEM_FLOAT:
1623                 print_help_section( p_section, b_color, b_description );
1624                 p_section = NULL;
1625                 psz_bra = OPTION_VALUE_SEP "<";
1626                 psz_type = _("float");
1627                 psz_ket = ">";
1628                 if( p_item->min.f || p_item->max.f )
1629                 {
1630                     sprintf( psz_buffer, "%s [%f .. %f]", psz_type,
1631                              p_item->min.f, p_item->max.f );
1632                     psz_type = psz_buffer;
1633                 }
1634                 break;
1635             case CONFIG_ITEM_BOOL:
1636                 print_help_section( p_section, b_color, b_description );
1637                 p_section = NULL;
1638                 psz_bra = ""; psz_type = ""; psz_ket = "";
1639                 if( !b_help_module )
1640                 {
1641                     psz_suf = p_item->value.i ? _(" (default enabled)") :
1642                                                 _(" (default disabled)");
1643                 }
1644                 break;
1645             }
1646
1647             if( !psz_type )
1648             {
1649                 continue;
1650             }
1651
1652             /* Add short option if any */
1653             if( p_item->i_short )
1654             {
1655                 sprintf( psz_short, "-%c,", p_item->i_short );
1656             }
1657             else
1658             {
1659                 strcpy( psz_short, "   " );
1660             }
1661
1662             i = PADDING_SPACES - strlen( p_item->psz_name )
1663                  - strlen( psz_bra ) - strlen( psz_type )
1664                  - strlen( psz_ket ) - 1;
1665
1666             if( p_item->i_type == CONFIG_ITEM_BOOL && !b_help_module )
1667             {
1668                 psz_prefix =  ", --no-";
1669                 i -= strlen( p_item->psz_name ) + strlen( psz_prefix );
1670             }
1671
1672             if( i < 0 )
1673             {
1674                 psz_spaces[0] = '\n';
1675                 i = 0;
1676             }
1677             else
1678             {
1679                 psz_spaces[i] = '\0';
1680             }
1681
1682             if( p_item->i_type == CONFIG_ITEM_BOOL && !b_help_module )
1683             {
1684                 utf8_fprintf( stdout, psz_format_bool, psz_short, 
1685                               p_item->psz_name, psz_prefix, p_item->psz_name,
1686                               psz_bra, psz_type, psz_ket, psz_spaces );
1687             }
1688             else
1689             {
1690                 utf8_fprintf( stdout, psz_format, psz_short, p_item->psz_name,
1691                          "", "", psz_bra, psz_type, psz_ket, psz_spaces );
1692             }
1693
1694             psz_spaces[i] = ' ';
1695
1696             /* We wrap the rest of the output */
1697             sprintf( psz_buffer, "%s%s", p_item->psz_text, psz_suf );
1698             b_description_hack = b_description;
1699
1700  description:
1701             psz_text = psz_buffer;
1702             i_cur_width = b_description && !b_description_hack
1703                           ? i_width_description
1704                           : i_width;
1705             while( *psz_text )
1706             {
1707                 char *psz_parser, *psz_word;
1708                 size_t i_end = strlen( psz_text );
1709
1710                 /* If the remaining text fits in a line, print it. */
1711                 if( i_end <= i_cur_width )
1712                 {
1713                     if( b_color )
1714                     {
1715                         if( !b_description || b_description_hack )
1716                             utf8_fprintf( stdout, BLUE"%s\n"GRAY, psz_text );
1717                         else
1718                             utf8_fprintf( stdout, "%s\n", psz_text );
1719                     }
1720                     else
1721                     {
1722                         utf8_fprintf( stdout, "%s\n", psz_text );
1723                     }
1724                     break;
1725                 }
1726
1727                 /* Otherwise, eat as many words as possible */
1728                 psz_parser = psz_text;
1729                 do
1730                 {
1731                     psz_word = psz_parser;
1732                     psz_parser = strchr( psz_word, ' ' );
1733                     /* If no space was found, we reached the end of the text
1734                      * block; otherwise, we skip the space we just found. */
1735                     psz_parser = psz_parser ? psz_parser + 1
1736                                             : psz_text + i_end;
1737
1738                 } while( (size_t)(psz_parser - psz_text) <= i_cur_width );
1739
1740                 /* We cut a word in one of these cases:
1741                  *  - it's the only word in the line and it's too long.
1742                  *  - we used less than 80% of the width and the word we are
1743                  *    going to wrap is longer than 40% of the width, and even
1744                  *    if the word would have fit in the next line. */
1745                 if( psz_word == psz_text
1746              || ( (size_t)(psz_word - psz_text) < 80 * i_cur_width / 100
1747              && (size_t)(psz_parser - psz_word) > 40 * i_cur_width / 100 ) )
1748                 {
1749                     char c = psz_text[i_cur_width];
1750                     psz_text[i_cur_width] = '\0';
1751                     if( b_color )
1752                     {
1753                         if( !b_description || b_description_hack )
1754                             utf8_fprintf( stdout, BLUE"%s\n%s"GRAY,
1755                                           psz_text, psz_spaces );
1756                         else
1757                             utf8_fprintf( stdout, "%s\n%s",
1758                                           psz_text, psz_spaces );
1759                     }
1760                     else
1761                     {
1762                         utf8_fprintf( stdout, "%s\n%s", psz_text, psz_spaces );
1763                     }
1764                     psz_text += i_cur_width;
1765                     psz_text[0] = c;
1766                 }
1767                 else
1768                 {
1769                     psz_word[-1] = '\0';
1770                     if( b_color )
1771                     {
1772                         if( !b_description || b_description_hack )
1773                             utf8_fprintf( stdout, BLUE"%s\n%s"GRAY,
1774                                           psz_text, psz_spaces );
1775                         else
1776                             utf8_fprintf( stdout, "%s\n%s",
1777                                           psz_text, psz_spaces );
1778                     }
1779                     else
1780                     {
1781                         utf8_fprintf( stdout, "%s\n%s", psz_text, psz_spaces );
1782                     }
1783                     psz_text = psz_word;
1784                 }
1785             }
1786
1787             if( b_description_hack && p_item->psz_longtext )
1788             {
1789                 sprintf( psz_buffer, "%s%s", p_item->psz_longtext, psz_suf );
1790                 b_description_hack = false;
1791                 psz_spaces = psz_spaces_longtext;
1792                 utf8_fprintf( stdout, "%s", psz_spaces );
1793                 goto description;
1794             }
1795         }
1796     }
1797
1798     if( b_has_advanced ) 
1799     {
1800         if( b_color )
1801             utf8_fprintf( stdout, "\n" WHITE "%s" GRAY " %s\n", _( "Note:" ),
1802            _( "add --advanced to your command line to see advanced options."));
1803         else
1804             utf8_fprintf( stdout, "\n %s %s\n", _( "Note:" ),
1805            _( "add --advanced to your command line to see advanced options."));
1806     }
1807
1808     /* Release the module list */
1809     vlc_list_release( p_list );
1810 }
1811
1812 /*****************************************************************************
1813  * ListModules: list the available modules with their description
1814  *****************************************************************************
1815  * Print a list of all available modules (builtins and plugins) and a short
1816  * description for each one.
1817  *****************************************************************************/
1818 static void ListModules( libvlc_int_t *p_this, bool b_verbose )
1819 {
1820     vlc_list_t *p_list = NULL;
1821     module_t *p_parser = NULL;
1822     char psz_spaces[22];
1823     int i_index;
1824
1825     bool b_color = config_GetInt( p_this, "color" ) > 0;
1826
1827     memset( psz_spaces, ' ', 22 );
1828
1829 #ifdef WIN32
1830     ShowConsole( true );
1831 #endif
1832
1833     /* List all modules */
1834     p_list = vlc_list_find( p_this, VLC_OBJECT_MODULE, FIND_ANYWHERE );
1835
1836     /* Enumerate each module */
1837     for( i_index = 0; i_index < p_list->i_count; i_index++ )
1838     {
1839         int i;
1840
1841         p_parser = (module_t *)p_list->p_values[i_index].p_object ;
1842
1843         /* Nasty hack, but right now I'm too tired to think about a nice
1844          * solution */
1845         i = 22 - strlen( p_parser->psz_object_name ) - 1;
1846         if( i < 0 ) i = 0;
1847         psz_spaces[i] = 0;
1848
1849         if( b_color )
1850             utf8_fprintf( stdout, GREEN"  %s%s "WHITE"%s\n"GRAY,
1851                           p_parser->psz_object_name,
1852                           psz_spaces,
1853                           p_parser->psz_longname );
1854         else
1855             utf8_fprintf( stdout, "  %s%s %s\n",
1856                           p_parser->psz_object_name,
1857                           psz_spaces, p_parser->psz_longname );
1858
1859         if( b_verbose )
1860         {
1861             char *const *pp_shortcut = p_parser->pp_shortcuts;
1862             while( *pp_shortcut )
1863             {
1864                 if( strcmp( *pp_shortcut, p_parser->psz_object_name ) )
1865                 {
1866                     if( b_color )
1867                         utf8_fprintf( stdout, CYAN"   s %s\n"GRAY,
1868                                       *pp_shortcut );
1869                     else
1870                         utf8_fprintf( stdout, "   s %s\n",
1871                                       *pp_shortcut );
1872                 }
1873                 pp_shortcut++;
1874             }
1875             if( p_parser->psz_capability )
1876             {
1877                 if( b_color )
1878                     utf8_fprintf( stdout, MAGENTA"   c %s (%d)\n"GRAY,
1879                                   p_parser->psz_capability,
1880                                   p_parser->i_score );
1881                 else
1882                     utf8_fprintf( stdout, "   c %s (%d)\n",
1883                                   p_parser->psz_capability,
1884                                   p_parser->i_score );
1885             }
1886         }
1887
1888         psz_spaces[i] = ' ';
1889     }
1890
1891     vlc_list_release( p_list );
1892
1893 #ifdef WIN32        /* Pause the console because it's destroyed when we exit */
1894     PauseConsole();
1895 #endif
1896 }
1897
1898 /*****************************************************************************
1899  * Version: print complete program version
1900  *****************************************************************************
1901  * Print complete program version and build number.
1902  *****************************************************************************/
1903 static void Version( void )
1904 {
1905 #ifdef WIN32
1906     ShowConsole( true );
1907 #endif
1908
1909     utf8_fprintf( stdout, _("VLC version %s\n"), VLC_Version() );
1910     utf8_fprintf( stdout, _("Compiled by %s@%s.%s\n"),
1911              VLC_CompileBy(), VLC_CompileHost(), VLC_CompileDomain() );
1912     utf8_fprintf( stdout, _("Compiler: %s\n"), VLC_Compiler() );
1913     if( strcmp( VLC_Changeset(), "exported" ) )
1914         utf8_fprintf( stdout, _("Based upon Git commit [%s]\n"),
1915                  VLC_Changeset() );
1916     utf8_fprintf( stdout, LICENSE_MSG );
1917
1918 #ifdef WIN32        /* Pause the console because it's destroyed when we exit */
1919     PauseConsole();
1920 #endif
1921 }
1922
1923 /*****************************************************************************
1924  * ShowConsole: On Win32, create an output console for debug messages
1925  *****************************************************************************
1926  * This function is useful only on Win32.
1927  *****************************************************************************/
1928 #ifdef WIN32 /*  */
1929 static void ShowConsole( bool b_dofile )
1930 {
1931 #   ifndef UNDER_CE
1932     FILE *f_help = NULL;
1933
1934     if( getenv( "PWD" ) && getenv( "PS1" ) ) return; /* cygwin shell */
1935
1936     AllocConsole();
1937     /* Use the ANSI code page (e.g. Windows-1252) as expected by the LibVLC
1938      * Unicode/locale subsystem. By default, we have the obsolecent OEM code
1939      * page (e.g. CP437 or CP850). */
1940     SetConsoleOutputCP (GetACP ());
1941     SetConsoleTitle ("VLC media player version "PACKAGE_VERSION);
1942
1943     freopen( "CONOUT$", "w", stderr );
1944     freopen( "CONIN$", "r", stdin );
1945
1946     if( b_dofile && (f_help = fopen( "vlc-help.txt", "wt" )) )
1947     {
1948         fclose( f_help );
1949         freopen( "vlc-help.txt", "wt", stdout );
1950         utf8_fprintf( stderr, _("\nDumped content to vlc-help.txt file.\n") );
1951     }
1952     else freopen( "CONOUT$", "w", stdout );
1953
1954 #   endif
1955 }
1956 #endif
1957
1958 /*****************************************************************************
1959  * PauseConsole: On Win32, wait for a key press before closing the console
1960  *****************************************************************************
1961  * This function is useful only on Win32.
1962  *****************************************************************************/
1963 #ifdef WIN32 /*  */
1964 static void PauseConsole( void )
1965 {
1966 #   ifndef UNDER_CE
1967
1968     if( getenv( "PWD" ) && getenv( "PS1" ) ) return; /* cygwin shell */
1969
1970     utf8_fprintf( stderr, _("\nPress the RETURN key to continue...\n") );
1971     getchar();
1972     fclose( stdout );
1973
1974 #   endif
1975 }
1976 #endif
1977
1978 /*****************************************************************************
1979  * ConsoleWidth: Return the console width in characters
1980  *****************************************************************************
1981  * We use the stty shell command to get the console width; if this fails or
1982  * if the width is less than 80, we default to 80.
1983  *****************************************************************************/
1984 static int ConsoleWidth( void )
1985 {
1986     unsigned i_width = 80;
1987
1988 #ifndef WIN32
1989     FILE *file = popen( "stty size 2>/dev/null", "r" );
1990     if (file != NULL)
1991     {
1992         if (fscanf (file, "%*u %u", &i_width) <= 0)
1993             i_width = 80;
1994         pclose( file );
1995     }
1996 #else
1997     CONSOLE_SCREEN_BUFFER_INFO buf;
1998
1999     if (GetConsoleScreenBufferInfo (GetStdHandle (STD_OUTPUT_HANDLE), &buf))
2000         i_width = buf.dwSize.X;
2001 #endif
2002
2003     return i_width;
2004 }
2005
2006 static int VerboseCallback( vlc_object_t *p_this, const char *psz_variable,
2007                      vlc_value_t old_val, vlc_value_t new_val, void *param)
2008 {
2009     libvlc_int_t *p_libvlc = (libvlc_int_t *)p_this;
2010     (void)psz_variable;
2011     (void)old_val;
2012     (void)param;
2013
2014     if( new_val.i_int >= -1 )
2015     {
2016         libvlc_priv (p_libvlc)->i_verbose = __MIN( new_val.i_int, 2 );
2017     }
2018     return VLC_SUCCESS;
2019 }
2020
2021 /*****************************************************************************
2022  * InitDeviceValues: initialize device values
2023  *****************************************************************************
2024  * This function inits the dvd, vcd and cd-audio values
2025  *****************************************************************************/
2026 static void InitDeviceValues( libvlc_int_t *p_vlc )
2027 {
2028 #ifdef HAVE_HAL
2029     LibHalContext * ctx = NULL;
2030     int i, i_devices;
2031     char **devices = NULL;
2032     char *block_dev = NULL;
2033     dbus_bool_t b_dvd;
2034
2035     DBusConnection *p_connection = NULL;
2036     DBusError       error;
2037
2038     ctx = libhal_ctx_new();
2039     if( !ctx ) return;
2040     dbus_error_init( &error );
2041     p_connection = dbus_bus_get ( DBUS_BUS_SYSTEM, &error );
2042     if( dbus_error_is_set( &error ) || !p_connection )
2043     {
2044         libhal_ctx_free( ctx );
2045         dbus_error_free( &error );
2046         return;
2047     }
2048     libhal_ctx_set_dbus_connection( ctx, p_connection );
2049     if( libhal_ctx_init( ctx, &error ) )
2050     {
2051         if( ( devices = libhal_get_all_devices( ctx, &i_devices, NULL ) ) )
2052         {
2053             for( i = 0; i < i_devices; i++ )
2054             {
2055                 if( !libhal_device_property_exists( ctx, devices[i],
2056                                                 "storage.cdrom.dvd", NULL ) )
2057                 {
2058                     continue;
2059                 }
2060                 b_dvd = libhal_device_get_property_bool( ctx, devices[ i ],
2061                                                  "storage.cdrom.dvd", NULL  );
2062                 block_dev = libhal_device_get_property_string( ctx,
2063                                 devices[ i ], "block.device" , NULL );
2064                 if( b_dvd )
2065                 {
2066                     config_PutPsz( p_vlc, "dvd", block_dev );
2067                 }
2068
2069                 config_PutPsz( p_vlc, "vcd", block_dev );
2070                 config_PutPsz( p_vlc, "cd-audio", block_dev );
2071                 libhal_free_string( block_dev );
2072             }
2073             libhal_free_string_array( devices );
2074         }
2075         libhal_ctx_shutdown( ctx, NULL );
2076         dbus_connection_unref( p_connection );
2077         libhal_ctx_free( ctx );
2078     }
2079     else
2080     {
2081         msg_Warn( p_vlc, "Unable to get HAL device properties" );
2082     }
2083 #else
2084     (void)p_vlc;
2085 #endif /* HAVE_HAL */
2086 }