]> git.sesse.net Git - vlc/blob - src/libvlc.c
f982be86405f86cb193f1ae41983f8926a927924
[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             if( asprintf(&psz_morecodecs, "%s,dmo,quicktime", psz_codecs) != -1 )
913             {
914                 config_PutPsz( p_libvlc, "codec", psz_morecodecs);
915                 free( psz_morecodecs );
916             }
917         }
918         else
919             config_PutPsz( p_libvlc, "codec", "dmo,quicktime");
920         free( psz_codecs );
921     }
922 #endif
923
924     /*
925      * FIXME: kludge to use a p_libvlc-local variable for the Mozilla plugin
926      */
927     var_Create( p_libvlc, "drawable", VLC_VAR_INTEGER );
928     var_Create( p_libvlc, "drawable-view-top", VLC_VAR_INTEGER );
929     var_Create( p_libvlc, "drawable-view-left", VLC_VAR_INTEGER );
930     var_Create( p_libvlc, "drawable-view-bottom", VLC_VAR_INTEGER );
931     var_Create( p_libvlc, "drawable-view-right", VLC_VAR_INTEGER );
932     var_Create( p_libvlc, "drawable-clip-top", VLC_VAR_INTEGER );
933     var_Create( p_libvlc, "drawable-clip-left", VLC_VAR_INTEGER );
934     var_Create( p_libvlc, "drawable-clip-bottom", VLC_VAR_INTEGER );
935     var_Create( p_libvlc, "drawable-clip-right", VLC_VAR_INTEGER );
936
937     /* Create volume callback system. */
938     var_Create( p_libvlc, "volume-change", VLC_VAR_BOOL );
939
940     /* Create a variable for showing the interface (moved from playlist). */
941     var_Create( p_libvlc, "intf-show", VLC_VAR_BOOL );
942     var_SetBool( p_libvlc, "intf-show", true );
943
944     var_Create( p_libvlc, "intf-popupmenu", VLC_VAR_BOOL );
945
946     /*
947      * Get input filenames given as commandline arguments
948      */
949     GetFilenames( p_libvlc, i_argc, ppsz_argv );
950
951     /*
952      * Get --open argument
953      */
954     var_Create( p_libvlc, "open", VLC_VAR_STRING | VLC_VAR_DOINHERIT );
955     var_Get( p_libvlc, "open", &val );
956     if ( val.psz_string != NULL && *val.psz_string )
957     {
958         playlist_t *p_playlist = pl_Yield( p_libvlc );
959         playlist_AddExt( p_playlist, val.psz_string, NULL, PLAYLIST_INSERT, 0,
960                          -1, NULL, 0, true, pl_Unlocked );
961         pl_Release( p_libvlc );
962     }
963     free( val.psz_string );
964
965     return VLC_SUCCESS;
966 }
967
968 /**
969  * Cleanup a libvlc instance. The instance is not completely deallocated
970  * \param p_libvlc the instance to clean
971  */
972 int libvlc_InternalCleanup( libvlc_int_t *p_libvlc )
973 {
974     intf_thread_t      * p_intf = NULL;
975     libvlc_priv_t      *priv = libvlc_priv (p_libvlc);
976
977     /* Ask the interfaces to stop and destroy them */
978     msg_Dbg( p_libvlc, "removing all interfaces" );
979     while( (p_intf = vlc_object_find( p_libvlc, VLC_OBJECT_INTF, FIND_CHILD )) )
980     {
981         intf_StopThread( p_intf );
982         vlc_object_detach( p_intf );
983         vlc_object_release( p_intf ); /* for intf_Create() */
984         vlc_object_release( p_intf ); /* for vlc_object_find() */
985     }
986
987 #ifdef ENABLE_VLM
988     /* Destroy VLM if created in libvlc_InternalInit */
989     if( priv->p_vlm )
990     {
991         vlm_Delete( priv->p_vlm );
992     }
993 #endif
994
995     playlist_t *p_playlist = priv->p_playlist;
996     /* Remove all services discovery */
997     msg_Dbg( p_libvlc, "removing all services discovery tasks" );
998     playlist_ServicesDiscoveryKillAll( p_playlist );
999
1000     /* Free playlist */
1001     /* Any thread still running must not assume pl_Yield() succeeds. */
1002     msg_Dbg( p_libvlc, "removing playlist" );
1003     priv->p_playlist = NULL;
1004     vlc_object_kill( p_playlist ); /* <-- memory barrier for pl_Yield() */
1005     vlc_thread_join( p_playlist );
1006     vlc_object_release( p_playlist );
1007
1008     /* Free interaction */
1009     msg_Dbg( p_libvlc, "removing interaction" );
1010     interaction_Destroy( priv->p_interaction );
1011
1012     /* Free video outputs */
1013     msg_Dbg( p_libvlc, "removing all video outputs" );
1014     vlc_list_t *list = vlc_list_find (p_libvlc, VLC_OBJECT_VOUT, FIND_CHILD);
1015     for (int i = 0; i < list->i_count; i++)
1016         vlc_object_release (list->p_values[i].p_object);
1017     vlc_list_release (list);
1018
1019     stats_TimersDumpAll( p_libvlc );
1020     stats_TimersCleanAll( p_libvlc );
1021
1022 #ifdef ENABLE_SOUT
1023     announce_handler_t * p_announce;
1024
1025     /* Free announce handler(s?) */
1026     while( (p_announce = vlc_object_find( p_libvlc, VLC_OBJECT_ANNOUNCE,
1027                                                  FIND_CHILD ) ) )
1028     {
1029         msg_Dbg( p_libvlc, "removing announce handler" );
1030         vlc_object_detach( p_announce );
1031         vlc_object_release( p_announce );
1032         announce_HandlerDestroy( p_announce );
1033     }
1034 #endif
1035
1036     /* Make sure all threads are completed before we start looking for
1037      * reference leaks and deinitializing core LibVLC subsytems. */
1038     vlc_mutex_lock (&priv->threads_lock);
1039     while (priv->threads_count)
1040     {
1041         msg_Dbg (p_libvlc, "waiting for %u remaining threads",
1042                  priv->threads_count);
1043         vlc_cond_wait (&priv->threads_wait, &priv->threads_lock);
1044     }
1045     vlc_mutex_unlock (&priv->threads_lock);
1046
1047     bool b_clean = true;
1048     FOREACH_ARRAY( input_item_t *p_del, priv->input_items )
1049         msg_Err( p_libvlc, "input item %p has not been deleted properly: refcount %d, name %s",
1050             p_del, p_del->i_gc_refcount, p_del->psz_name ? p_del->psz_name : "(null)" );
1051         b_clean = false;
1052     FOREACH_END();
1053     assert( b_clean );
1054     ARRAY_RESET( priv->input_items );
1055
1056     msg_Dbg( p_libvlc, "removing stats" );
1057     vlc_mutex_destroy( &p_libvlc->p_stats->lock );
1058     FREENULL( p_libvlc->p_stats );
1059
1060     return VLC_SUCCESS;
1061 }
1062
1063 /**
1064  * Destroy everything.
1065  * This function requests the running threads to finish, waits for their
1066  * termination, and destroys their structure.
1067  * It stops the thread systems: no instance can run after this has run
1068  * \param p_libvlc the instance to destroy
1069  */
1070 int libvlc_InternalDestroy( libvlc_int_t *p_libvlc )
1071 {
1072     if( !p_libvlc )
1073         return VLC_EGENERIC;
1074
1075     libvlc_priv_t *priv = libvlc_priv (p_libvlc);
1076
1077 #ifndef WIN32
1078     char* psz_pidfile = NULL;
1079
1080     if( b_daemon )
1081     {
1082         psz_pidfile = config_GetPsz( p_libvlc, "pidfile" );
1083         if( psz_pidfile != NULL )
1084         {
1085             msg_Dbg( p_libvlc, "removing pid file %s", psz_pidfile );
1086             if( unlink( psz_pidfile ) == -1 )
1087             {
1088                 msg_Dbg( p_libvlc, "removing pid file %s: %m",
1089                         psz_pidfile );
1090             }
1091         }
1092         free( psz_pidfile );
1093     }
1094 #endif
1095
1096     if( priv->p_memcpy_module )
1097     {
1098         module_Unneed( p_libvlc, priv->p_memcpy_module );
1099         priv->p_memcpy_module = NULL;
1100     }
1101
1102     /* Free module bank. It is refcounted, so we call this each time  */
1103     module_EndBank( p_libvlc );
1104
1105     FREENULL( priv->psz_configfile );
1106     var_DelCallback( p_libvlc, "key-pressed", vlc_key_to_action,
1107                      p_libvlc->p_hotkeys );
1108     FREENULL( p_libvlc->p_hotkeys );
1109
1110     vlc_mutex_t *lock = var_AcquireMutex( "libvlc" );
1111     i_instances--;
1112
1113     if( i_instances == 0 )
1114     {
1115         /* System specific cleaning code */
1116         system_End( p_libvlc );
1117     }
1118     vlc_mutex_unlock( lock );
1119
1120     msg_Flush( p_libvlc );
1121     msg_Destroy( p_libvlc );
1122
1123     /* Destroy mutexes */
1124     vlc_mutex_destroy( &priv->config_lock );
1125     vlc_mutex_destroy( &priv->timer_lock );
1126     vlc_cond_destroy (&priv->threads_wait);
1127     vlc_mutex_destroy (&priv->threads_lock);
1128
1129     vlc_object_release( p_libvlc );
1130     p_libvlc = NULL;
1131
1132     /* Stop thread system: last one out please shut the door!
1133      * The number of initializations of the thread system is counted, we
1134      * can call this each time */
1135     vlc_threads_end ();
1136
1137     return VLC_SUCCESS;
1138 }
1139
1140 /**
1141  * Add an interface plugin and run it
1142  */
1143 int libvlc_InternalAddIntf( libvlc_int_t *p_libvlc, char const *psz_module )
1144 {
1145     int i_err;
1146     intf_thread_t *p_intf = NULL;
1147
1148     if( !p_libvlc )
1149         return VLC_EGENERIC;
1150
1151     if( !psz_module ) /* requesting the default interface */
1152     {
1153         char *psz_interface = config_GetPsz( p_libvlc, "intf" );
1154         if( !psz_interface || !*psz_interface ) /* "intf" has not been set */
1155         {
1156 #ifndef WIN32
1157             if( b_daemon )
1158                  /* Daemon mode hack.
1159                   * We prefer the dummy interface if none is specified. */
1160                 psz_module = "dummy";
1161             else
1162 #endif
1163                 msg_Info( p_libvlc, _("Running vlc with the default interface. Use 'cvlc' to use vlc without interface.") );
1164         }
1165         free( psz_interface );
1166     }
1167
1168     /* Try to create the interface */
1169     p_intf = intf_Create( p_libvlc, psz_module ? psz_module : "$intf" );
1170     if( p_intf == NULL )
1171     {
1172         msg_Err( p_libvlc, "interface \"%s\" initialization failed",
1173                  psz_module );
1174         return VLC_EGENERIC;
1175     }
1176
1177     /* Try to run the interface */
1178     i_err = intf_RunThread( p_intf );
1179     if( i_err )
1180     {
1181         vlc_object_detach( p_intf );
1182         vlc_object_release( p_intf );
1183         return i_err;
1184     }
1185
1186     return VLC_SUCCESS;
1187 };
1188
1189 #if defined( ENABLE_NLS ) && (defined (__APPLE__) || defined (WIN32)) && \
1190     ( defined( HAVE_GETTEXT ) || defined( HAVE_INCLUDED_GETTEXT ) )
1191 /*****************************************************************************
1192  * SetLanguage: set the interface language.
1193  *****************************************************************************
1194  * We set the LC_MESSAGES locale category for interface messages and buttons,
1195  * as well as the LC_CTYPE category for string sorting and possible wide
1196  * character support.
1197  *****************************************************************************/
1198 static void SetLanguage ( const char *psz_lang )
1199 {
1200 #ifdef __APPLE__
1201     /* I need that under Darwin, please check it doesn't disturb
1202      * other platforms. --Meuuh */
1203     setenv( "LANG", psz_lang, 1 );
1204
1205 #else
1206     /* We set LC_ALL manually because it is the only way to set
1207      * the language at runtime under eg. Windows. Beware that this
1208      * makes the environment unconsistent when libvlc is unloaded and
1209      * should probably be moved to a safer place like vlc.c. */
1210     static char psz_lcall[20];
1211     snprintf( psz_lcall, 19, "LC_ALL=%s", psz_lang );
1212     psz_lcall[19] = '\0';
1213     putenv( psz_lcall );
1214 #endif
1215
1216     setlocale( LC_ALL, psz_lang );
1217 }
1218 #endif
1219
1220
1221 static inline int LoadMessages (void)
1222 {
1223 #if defined( ENABLE_NLS ) \
1224      && ( defined( HAVE_GETTEXT ) || defined( HAVE_INCLUDED_GETTEXT ) )
1225     /* Specify where to find the locales for current domain */
1226 #if !defined( __APPLE__ ) && !defined( WIN32 ) && !defined( SYS_BEOS )
1227     static const char psz_path[] = LOCALEDIR;
1228 #else
1229     char psz_path[1024];
1230     if (snprintf (psz_path, sizeof (psz_path), "%s" DIR_SEP "%s",
1231                   config_GetDataDir(), "locale")
1232                      >= (int)sizeof (psz_path))
1233         return -1;
1234
1235 #endif
1236     if (bindtextdomain (PACKAGE_NAME, psz_path) == NULL)
1237     {
1238         fprintf (stderr, "Warning: cannot bind text domain "PACKAGE_NAME
1239                          " to directory %s\n", psz_path);
1240         return -1;
1241     }
1242
1243     /* LibVLC wants all messages in UTF-8.
1244      * Unfortunately, we cannot ask UTF-8 for strerror_r(), strsignal_r()
1245      * and other functions that are not part of our text domain.
1246      */
1247     if (bind_textdomain_codeset (PACKAGE_NAME, "UTF-8") == NULL)
1248     {
1249         fprintf (stderr, "Error: cannot set Unicode encoding for text domain "
1250                          PACKAGE_NAME"\n");
1251         // Unbinds the text domain to avoid broken encoding
1252         bindtextdomain (PACKAGE_NAME, "DOES_NOT_EXIST");
1253         return -1;
1254     }
1255
1256     /* LibVLC does NOT set the default textdomain, since it is a library.
1257      * This could otherwise break programs using LibVLC (other than VLC).
1258      * textdomain (PACKAGE_NAME);
1259      */
1260 #endif
1261     return 0;
1262 }
1263
1264 /*****************************************************************************
1265  * GetFilenames: parse command line options which are not flags
1266  *****************************************************************************
1267  * Parse command line for input files as well as their associated options.
1268  * An option always follows its associated input and begins with a ":".
1269  *****************************************************************************/
1270 static int GetFilenames( libvlc_int_t *p_vlc, int i_argc, const char *ppsz_argv[] )
1271 {
1272     int i_opt, i_options;
1273
1274     /* We assume that the remaining parameters are filenames
1275      * and their input options */
1276     for( i_opt = i_argc - 1; i_opt >= optind; i_opt-- )
1277     {
1278         i_options = 0;
1279
1280         /* Count the input options */
1281         while( *ppsz_argv[ i_opt ] == ':' && i_opt > optind )
1282         {
1283             i_options++;
1284             i_opt--;
1285         }
1286
1287         /* TODO: write an internal function of this one, to avoid
1288          *       unnecessary lookups. */
1289
1290         playlist_t *p_playlist = pl_Yield( p_vlc );
1291         playlist_AddExt( p_playlist, ppsz_argv[i_opt], NULL, PLAYLIST_INSERT,
1292                          0, -1, ( i_options ? &ppsz_argv[i_opt + 1] : NULL ),
1293                          i_options, true, pl_Unlocked );
1294         pl_Release( p_vlc );
1295     }
1296
1297     return VLC_SUCCESS;
1298 }
1299
1300 /*****************************************************************************
1301  * Help: print program help
1302  *****************************************************************************
1303  * Print a short inline help. Message interface is initialized at this stage.
1304  *****************************************************************************/
1305 static inline void print_help_on_full_help( void )
1306 {
1307     utf8_fprintf( stdout, "\n" );
1308     utf8_fprintf( stdout, "%s\n", _("To get exhaustive help, use '-H'.") );
1309 }
1310
1311 static void Help( libvlc_int_t *p_this, char const *psz_help_name )
1312 {
1313 #ifdef WIN32
1314     ShowConsole( true );
1315 #endif
1316
1317     if( psz_help_name && !strcmp( psz_help_name, "help" ) )
1318     {
1319         utf8_fprintf( stdout, vlc_usage, p_this->psz_object_name );
1320         Usage( p_this, "help" );
1321         Usage( p_this, "main" );
1322         print_help_on_full_help();
1323     }
1324     else if( psz_help_name && !strcmp( psz_help_name, "longhelp" ) )
1325     {
1326         utf8_fprintf( stdout, vlc_usage, p_this->psz_object_name );
1327         Usage( p_this, NULL );
1328         print_help_on_full_help();
1329     }
1330     else if( psz_help_name && !strcmp( psz_help_name, "full-help" ) )
1331     {
1332         utf8_fprintf( stdout, vlc_usage, p_this->psz_object_name );
1333         Usage( p_this, NULL );
1334     }
1335     else if( psz_help_name )
1336     {
1337         Usage( p_this, psz_help_name );
1338     }
1339
1340 #ifdef WIN32        /* Pause the console because it's destroyed when we exit */
1341     PauseConsole();
1342 #endif
1343 }
1344
1345 /*****************************************************************************
1346  * Usage: print module usage
1347  *****************************************************************************
1348  * Print a short inline help. Message interface is initialized at this stage.
1349  *****************************************************************************/
1350 #   define COL(x)  "\033[" #x ";1m"
1351 #   define RED     COL(31)
1352 #   define GREEN   COL(32)
1353 #   define YELLOW  COL(33)
1354 #   define BLUE    COL(34)
1355 #   define MAGENTA COL(35)
1356 #   define CYAN    COL(36)
1357 #   define WHITE   COL(0)
1358 #   define GRAY    "\033[0m"
1359 static void print_help_section( module_config_t *p_item, bool b_color, bool b_description )
1360 {
1361     if( !p_item ) return;
1362     if( b_color )
1363     {
1364         utf8_fprintf( stdout, RED"   %s:\n"GRAY,
1365                       p_item->psz_text );
1366         if( b_description && p_item->psz_longtext )
1367             utf8_fprintf( stdout, MAGENTA"   %s\n"GRAY,
1368                           p_item->psz_longtext );
1369     }
1370     else
1371     {
1372         utf8_fprintf( stdout, "   %s:\n", p_item->psz_text );
1373         if( b_description && p_item->psz_longtext )
1374             utf8_fprintf( stdout, "   %s\n", p_item->psz_longtext );
1375     }
1376 }
1377
1378 static void Usage( libvlc_int_t *p_this, char const *psz_module_name )
1379 {
1380 #define FORMAT_STRING "  %s --%s%s%s%s%s%s%s "
1381     /* short option ------'    | | | | | | |
1382      * option name ------------' | | | | | |
1383      * <bra ---------------------' | | | | |
1384      * option type or "" ----------' | | | |
1385      * ket> -------------------------' | | |
1386      * padding spaces -----------------' | |
1387      * comment --------------------------' |
1388      * comment suffix ---------------------'
1389      *
1390      * The purpose of having bra and ket is that we might i18n them as well.
1391      */
1392
1393 #define COLOR_FORMAT_STRING (WHITE"  %s --%s"YELLOW"%s%s%s%s%s%s "GRAY)
1394 #define COLOR_FORMAT_STRING_BOOL (WHITE"  %s --%s%s%s%s%s%s%s "GRAY)
1395
1396 #define LINE_START 8
1397 #define PADDING_SPACES 25
1398 #ifdef WIN32
1399 #   define OPTION_VALUE_SEP "="
1400 #else
1401 #   define OPTION_VALUE_SEP " "
1402 #endif
1403     vlc_list_t *p_list = NULL;
1404     char psz_spaces_text[PADDING_SPACES+LINE_START+1];
1405     char psz_spaces_longtext[LINE_START+3];
1406     char psz_format[sizeof(COLOR_FORMAT_STRING)];
1407     char psz_format_bool[sizeof(COLOR_FORMAT_STRING_BOOL)];
1408     char psz_buffer[10000];
1409     char psz_short[4];
1410     int i_index;
1411     int i_width = ConsoleWidth() - (PADDING_SPACES+LINE_START+1);
1412     int i_width_description = i_width + PADDING_SPACES - 1;
1413     bool b_advanced    = config_GetInt( p_this, "advanced" ) > 0;
1414     bool b_description = config_GetInt( p_this, "help-verbose" ) > 0;
1415     bool b_description_hack;
1416     bool b_color       = config_GetInt( p_this, "color" ) > 0;
1417     bool b_has_advanced = false;
1418
1419     memset( psz_spaces_text, ' ', PADDING_SPACES+LINE_START );
1420     psz_spaces_text[PADDING_SPACES+LINE_START] = '\0';
1421     memset( psz_spaces_longtext, ' ', LINE_START+2 );
1422     psz_spaces_longtext[LINE_START+2] = '\0';
1423 #ifndef WIN32
1424     if( !isatty( 1 ) )
1425 #endif
1426         b_color = false; // don't put color control codes in a .txt file
1427
1428     if( b_color )
1429     {
1430         strcpy( psz_format, COLOR_FORMAT_STRING );
1431         strcpy( psz_format_bool, COLOR_FORMAT_STRING_BOOL );
1432     }
1433     else
1434     {
1435         strcpy( psz_format, FORMAT_STRING );
1436         strcpy( psz_format_bool, FORMAT_STRING );
1437     }
1438
1439     /* List all modules */
1440     p_list = vlc_list_find( p_this, VLC_OBJECT_MODULE, FIND_ANYWHERE );
1441
1442     /* Ugly hack to make sure that the help options always come first
1443      * (part 1) */
1444     if( !psz_module_name )
1445         Usage( p_this, "help" );
1446
1447     /* Enumerate the config for each module */
1448     for( i_index = 0; i_index < p_list->i_count; i_index++ )
1449     {
1450         bool b_help_module;
1451         module_t *p_parser = (module_t *)p_list->p_values[i_index].p_object;
1452         module_config_t *p_item = NULL;
1453         module_config_t *p_section = NULL;
1454         module_config_t *p_end = p_parser->p_config + p_parser->confsize;
1455
1456         if( psz_module_name && strcmp( psz_module_name,
1457                                        p_parser->psz_object_name ) )
1458         {
1459             char *const *pp_shortcut = p_parser->pp_shortcuts;
1460             while( *pp_shortcut )
1461             {
1462                 if( !strcmp( psz_module_name, *pp_shortcut ) )
1463                     break;
1464                 pp_shortcut ++;
1465             }
1466             if( !*pp_shortcut )
1467                 continue;
1468         }
1469
1470         /* Ignore modules without config options */
1471         if( !p_parser->i_config_items )
1472         {
1473             continue;
1474         }
1475
1476         b_help_module = !strcmp( "help", p_parser->psz_object_name );
1477         /* Ugly hack to make sure that the help options always come first
1478          * (part 2) */
1479         if( !psz_module_name && b_help_module )
1480             continue;
1481
1482         /* Ignore modules with only advanced config options if requested */
1483         if( !b_advanced )
1484         {
1485             for( p_item = p_parser->p_config;
1486                  p_item < p_end;
1487                  p_item++ )
1488             {
1489                 if( (p_item->i_type & CONFIG_ITEM) &&
1490                     !p_item->b_advanced ) break;
1491             }
1492         }
1493
1494         /* Print name of module */
1495         if( strcmp( "main", p_parser->psz_object_name ) )
1496         {
1497             if( b_color )
1498                 utf8_fprintf( stdout, "\n " GREEN "%s" GRAY "\n",
1499                               p_parser->psz_longname );
1500             else
1501                 utf8_fprintf( stdout, "\n %s\n", p_parser->psz_longname );
1502         }
1503         if( p_parser->psz_help )
1504         {
1505             if( b_color )
1506                 utf8_fprintf( stdout, CYAN" %s\n"GRAY, p_parser->psz_help );
1507             else
1508                 utf8_fprintf( stdout, " %s\n", p_parser->psz_help );
1509         }
1510
1511         /* Print module options */
1512         for( p_item = p_parser->p_config;
1513              p_item < p_end;
1514              p_item++ )
1515         {
1516             char *psz_text, *psz_spaces = psz_spaces_text;
1517             const char *psz_bra = NULL, *psz_type = NULL, *psz_ket = NULL;
1518             const char *psz_suf = "", *psz_prefix = NULL;
1519             signed int i;
1520             size_t i_cur_width;
1521
1522             /* Skip removed options */
1523             if( p_item->b_removed )
1524             {
1525                 continue;
1526             }
1527             /* Skip advanced options if requested */
1528             if( p_item->b_advanced && !b_advanced )
1529             {
1530                 b_has_advanced = true;
1531                 continue;
1532             }
1533
1534             switch( p_item->i_type )
1535             {
1536             case CONFIG_HINT_CATEGORY:
1537             case CONFIG_HINT_USAGE:
1538                 if( !strcmp( "main", p_parser->psz_object_name ) )
1539                 {
1540                     if( b_color )
1541                         utf8_fprintf( stdout, GREEN "\n %s\n" GRAY,
1542                                       p_item->psz_text );
1543                     else
1544                         utf8_fprintf( stdout, "\n %s\n", p_item->psz_text );
1545                 }
1546                 if( b_description && p_item->psz_longtext )
1547                 {
1548                     if( b_color )
1549                         utf8_fprintf( stdout, CYAN " %s\n" GRAY,
1550                                       p_item->psz_longtext );
1551                     else
1552                         utf8_fprintf( stdout, " %s\n", p_item->psz_longtext );
1553                 }
1554                 break;
1555
1556             case CONFIG_HINT_SUBCATEGORY:
1557                 if( strcmp( "main", p_parser->psz_object_name ) )
1558                     break;
1559             case CONFIG_SECTION:
1560                 p_section = p_item;
1561                 break;
1562
1563             case CONFIG_ITEM_STRING:
1564             case CONFIG_ITEM_FILE:
1565             case CONFIG_ITEM_DIRECTORY:
1566             case CONFIG_ITEM_MODULE: /* We could also have "=<" here */
1567             case CONFIG_ITEM_MODULE_CAT:
1568             case CONFIG_ITEM_MODULE_LIST:
1569             case CONFIG_ITEM_MODULE_LIST_CAT:
1570             case CONFIG_ITEM_FONT:
1571             case CONFIG_ITEM_PASSWORD:
1572                 print_help_section( p_section, b_color, b_description );
1573                 p_section = NULL;
1574                 psz_bra = OPTION_VALUE_SEP "<";
1575                 psz_type = _("string");
1576                 psz_ket = ">";
1577
1578                 if( p_item->ppsz_list )
1579                 {
1580                     psz_bra = OPTION_VALUE_SEP "{";
1581                     psz_type = psz_buffer;
1582                     psz_buffer[0] = '\0';
1583                     for( i = 0; p_item->ppsz_list[i]; i++ )
1584                     {
1585                         if( i ) strcat( psz_buffer, "," );
1586                         strcat( psz_buffer, p_item->ppsz_list[i] );
1587                     }
1588                     psz_ket = "}";
1589                 }
1590                 break;
1591             case CONFIG_ITEM_INTEGER:
1592             case CONFIG_ITEM_KEY: /* FIXME: do something a bit more clever */
1593                 print_help_section( p_section, b_color, b_description );
1594                 p_section = NULL;
1595                 psz_bra = OPTION_VALUE_SEP "<";
1596                 psz_type = _("integer");
1597                 psz_ket = ">";
1598
1599                 if( p_item->min.i || p_item->max.i )
1600                 {
1601                     sprintf( psz_buffer, "%s [%i .. %i]", psz_type,
1602                              p_item->min.i, p_item->max.i );
1603                     psz_type = psz_buffer;
1604                 }
1605
1606                 if( p_item->i_list )
1607                 {
1608                     psz_bra = OPTION_VALUE_SEP "{";
1609                     psz_type = psz_buffer;
1610                     psz_buffer[0] = '\0';
1611                     for( i = 0; p_item->ppsz_list_text[i]; i++ )
1612                     {
1613                         if( i ) strcat( psz_buffer, ", " );
1614                         sprintf( psz_buffer + strlen(psz_buffer), "%i (%s)",
1615                                  p_item->pi_list[i],
1616                                  p_item->ppsz_list_text[i] );
1617                     }
1618                     psz_ket = "}";
1619                 }
1620                 break;
1621             case CONFIG_ITEM_FLOAT:
1622                 print_help_section( p_section, b_color, b_description );
1623                 p_section = NULL;
1624                 psz_bra = OPTION_VALUE_SEP "<";
1625                 psz_type = _("float");
1626                 psz_ket = ">";
1627                 if( p_item->min.f || p_item->max.f )
1628                 {
1629                     sprintf( psz_buffer, "%s [%f .. %f]", psz_type,
1630                              p_item->min.f, p_item->max.f );
1631                     psz_type = psz_buffer;
1632                 }
1633                 break;
1634             case CONFIG_ITEM_BOOL:
1635                 print_help_section( p_section, b_color, b_description );
1636                 p_section = NULL;
1637                 psz_bra = ""; psz_type = ""; psz_ket = "";
1638                 if( !b_help_module )
1639                 {
1640                     psz_suf = p_item->value.i ? _(" (default enabled)") :
1641                                                 _(" (default disabled)");
1642                 }
1643                 break;
1644             }
1645
1646             if( !psz_type )
1647             {
1648                 continue;
1649             }
1650
1651             /* Add short option if any */
1652             if( p_item->i_short )
1653             {
1654                 sprintf( psz_short, "-%c,", p_item->i_short );
1655             }
1656             else
1657             {
1658                 strcpy( psz_short, "   " );
1659             }
1660
1661             i = PADDING_SPACES - strlen( p_item->psz_name )
1662                  - strlen( psz_bra ) - strlen( psz_type )
1663                  - strlen( psz_ket ) - 1;
1664
1665             if( p_item->i_type == CONFIG_ITEM_BOOL && !b_help_module )
1666             {
1667                 psz_prefix =  ", --no-";
1668                 i -= strlen( p_item->psz_name ) + strlen( psz_prefix );
1669             }
1670
1671             if( i < 0 )
1672             {
1673                 psz_spaces[0] = '\n';
1674                 i = 0;
1675             }
1676             else
1677             {
1678                 psz_spaces[i] = '\0';
1679             }
1680
1681             if( p_item->i_type == CONFIG_ITEM_BOOL && !b_help_module )
1682             {
1683                 utf8_fprintf( stdout, psz_format_bool, psz_short, 
1684                               p_item->psz_name, psz_prefix, p_item->psz_name,
1685                               psz_bra, psz_type, psz_ket, psz_spaces );
1686             }
1687             else
1688             {
1689                 utf8_fprintf( stdout, psz_format, psz_short, p_item->psz_name,
1690                          "", "", psz_bra, psz_type, psz_ket, psz_spaces );
1691             }
1692
1693             psz_spaces[i] = ' ';
1694
1695             /* We wrap the rest of the output */
1696             sprintf( psz_buffer, "%s%s", p_item->psz_text, psz_suf );
1697             b_description_hack = b_description;
1698
1699  description:
1700             psz_text = psz_buffer;
1701             i_cur_width = b_description && !b_description_hack
1702                           ? i_width_description
1703                           : i_width;
1704             while( *psz_text )
1705             {
1706                 char *psz_parser, *psz_word;
1707                 size_t i_end = strlen( psz_text );
1708
1709                 /* If the remaining text fits in a line, print it. */
1710                 if( i_end <= i_cur_width )
1711                 {
1712                     if( b_color )
1713                     {
1714                         if( !b_description || b_description_hack )
1715                             utf8_fprintf( stdout, BLUE"%s\n"GRAY, psz_text );
1716                         else
1717                             utf8_fprintf( stdout, "%s\n", psz_text );
1718                     }
1719                     else
1720                     {
1721                         utf8_fprintf( stdout, "%s\n", psz_text );
1722                     }
1723                     break;
1724                 }
1725
1726                 /* Otherwise, eat as many words as possible */
1727                 psz_parser = psz_text;
1728                 do
1729                 {
1730                     psz_word = psz_parser;
1731                     psz_parser = strchr( psz_word, ' ' );
1732                     /* If no space was found, we reached the end of the text
1733                      * block; otherwise, we skip the space we just found. */
1734                     psz_parser = psz_parser ? psz_parser + 1
1735                                             : psz_text + i_end;
1736
1737                 } while( (size_t)(psz_parser - psz_text) <= i_cur_width );
1738
1739                 /* We cut a word in one of these cases:
1740                  *  - it's the only word in the line and it's too long.
1741                  *  - we used less than 80% of the width and the word we are
1742                  *    going to wrap is longer than 40% of the width, and even
1743                  *    if the word would have fit in the next line. */
1744                 if( psz_word == psz_text
1745              || ( (size_t)(psz_word - psz_text) < 80 * i_cur_width / 100
1746              && (size_t)(psz_parser - psz_word) > 40 * i_cur_width / 100 ) )
1747                 {
1748                     char c = psz_text[i_cur_width];
1749                     psz_text[i_cur_width] = '\0';
1750                     if( b_color )
1751                     {
1752                         if( !b_description || b_description_hack )
1753                             utf8_fprintf( stdout, BLUE"%s\n%s"GRAY,
1754                                           psz_text, psz_spaces );
1755                         else
1756                             utf8_fprintf( stdout, "%s\n%s",
1757                                           psz_text, psz_spaces );
1758                     }
1759                     else
1760                     {
1761                         utf8_fprintf( stdout, "%s\n%s", psz_text, psz_spaces );
1762                     }
1763                     psz_text += i_cur_width;
1764                     psz_text[0] = c;
1765                 }
1766                 else
1767                 {
1768                     psz_word[-1] = '\0';
1769                     if( b_color )
1770                     {
1771                         if( !b_description || b_description_hack )
1772                             utf8_fprintf( stdout, BLUE"%s\n%s"GRAY,
1773                                           psz_text, psz_spaces );
1774                         else
1775                             utf8_fprintf( stdout, "%s\n%s",
1776                                           psz_text, psz_spaces );
1777                     }
1778                     else
1779                     {
1780                         utf8_fprintf( stdout, "%s\n%s", psz_text, psz_spaces );
1781                     }
1782                     psz_text = psz_word;
1783                 }
1784             }
1785
1786             if( b_description_hack && p_item->psz_longtext )
1787             {
1788                 sprintf( psz_buffer, "%s%s", p_item->psz_longtext, psz_suf );
1789                 b_description_hack = false;
1790                 psz_spaces = psz_spaces_longtext;
1791                 utf8_fprintf( stdout, "%s", psz_spaces );
1792                 goto description;
1793             }
1794         }
1795     }
1796
1797     if( b_has_advanced ) 
1798     {
1799         if( b_color )
1800             utf8_fprintf( stdout, "\n" WHITE "%s" GRAY " %s\n", _( "Note:" ),
1801            _( "add --advanced to your command line to see advanced options."));
1802         else
1803             utf8_fprintf( stdout, "\n %s %s\n", _( "Note:" ),
1804            _( "add --advanced to your command line to see advanced options."));
1805     }
1806
1807     /* Release the module list */
1808     vlc_list_release( p_list );
1809 }
1810
1811 /*****************************************************************************
1812  * ListModules: list the available modules with their description
1813  *****************************************************************************
1814  * Print a list of all available modules (builtins and plugins) and a short
1815  * description for each one.
1816  *****************************************************************************/
1817 static void ListModules( libvlc_int_t *p_this, bool b_verbose )
1818 {
1819     vlc_list_t *p_list = NULL;
1820     module_t *p_parser = NULL;
1821     char psz_spaces[22];
1822     int i_index;
1823
1824     bool b_color = config_GetInt( p_this, "color" ) > 0;
1825
1826     memset( psz_spaces, ' ', 22 );
1827
1828 #ifdef WIN32
1829     ShowConsole( true );
1830 #endif
1831
1832     /* List all modules */
1833     p_list = vlc_list_find( p_this, VLC_OBJECT_MODULE, FIND_ANYWHERE );
1834
1835     /* Enumerate each module */
1836     for( i_index = 0; i_index < p_list->i_count; i_index++ )
1837     {
1838         int i;
1839
1840         p_parser = (module_t *)p_list->p_values[i_index].p_object ;
1841
1842         /* Nasty hack, but right now I'm too tired to think about a nice
1843          * solution */
1844         i = 22 - strlen( p_parser->psz_object_name ) - 1;
1845         if( i < 0 ) i = 0;
1846         psz_spaces[i] = 0;
1847
1848         if( b_color )
1849             utf8_fprintf( stdout, GREEN"  %s%s "WHITE"%s\n"GRAY,
1850                           p_parser->psz_object_name,
1851                           psz_spaces,
1852                           p_parser->psz_longname );
1853         else
1854             utf8_fprintf( stdout, "  %s%s %s\n",
1855                           p_parser->psz_object_name,
1856                           psz_spaces, p_parser->psz_longname );
1857
1858         if( b_verbose )
1859         {
1860             char *const *pp_shortcut = p_parser->pp_shortcuts;
1861             while( *pp_shortcut )
1862             {
1863                 if( strcmp( *pp_shortcut, p_parser->psz_object_name ) )
1864                 {
1865                     if( b_color )
1866                         utf8_fprintf( stdout, CYAN"   s %s\n"GRAY,
1867                                       *pp_shortcut );
1868                     else
1869                         utf8_fprintf( stdout, "   s %s\n",
1870                                       *pp_shortcut );
1871                 }
1872                 pp_shortcut++;
1873             }
1874             if( p_parser->psz_capability )
1875             {
1876                 if( b_color )
1877                     utf8_fprintf( stdout, MAGENTA"   c %s (%d)\n"GRAY,
1878                                   p_parser->psz_capability,
1879                                   p_parser->i_score );
1880                 else
1881                     utf8_fprintf( stdout, "   c %s (%d)\n",
1882                                   p_parser->psz_capability,
1883                                   p_parser->i_score );
1884             }
1885         }
1886
1887         psz_spaces[i] = ' ';
1888     }
1889
1890     vlc_list_release( p_list );
1891
1892 #ifdef WIN32        /* Pause the console because it's destroyed when we exit */
1893     PauseConsole();
1894 #endif
1895 }
1896
1897 /*****************************************************************************
1898  * Version: print complete program version
1899  *****************************************************************************
1900  * Print complete program version and build number.
1901  *****************************************************************************/
1902 static void Version( void )
1903 {
1904 #ifdef WIN32
1905     ShowConsole( true );
1906 #endif
1907
1908     utf8_fprintf( stdout, _("VLC version %s\n"), VLC_Version() );
1909     utf8_fprintf( stdout, _("Compiled by %s@%s.%s\n"),
1910              VLC_CompileBy(), VLC_CompileHost(), VLC_CompileDomain() );
1911     utf8_fprintf( stdout, _("Compiler: %s\n"), VLC_Compiler() );
1912     if( strcmp( VLC_Changeset(), "exported" ) )
1913         utf8_fprintf( stdout, _("Based upon Git commit [%s]\n"),
1914                  VLC_Changeset() );
1915     utf8_fprintf( stdout, LICENSE_MSG );
1916
1917 #ifdef WIN32        /* Pause the console because it's destroyed when we exit */
1918     PauseConsole();
1919 #endif
1920 }
1921
1922 /*****************************************************************************
1923  * ShowConsole: On Win32, create an output console for debug messages
1924  *****************************************************************************
1925  * This function is useful only on Win32.
1926  *****************************************************************************/
1927 #ifdef WIN32 /*  */
1928 static void ShowConsole( bool b_dofile )
1929 {
1930 #   ifndef UNDER_CE
1931     FILE *f_help = NULL;
1932
1933     if( getenv( "PWD" ) && getenv( "PS1" ) ) return; /* cygwin shell */
1934
1935     AllocConsole();
1936     /* Use the ANSI code page (e.g. Windows-1252) as expected by the LibVLC
1937      * Unicode/locale subsystem. By default, we have the obsolecent OEM code
1938      * page (e.g. CP437 or CP850). */
1939     SetConsoleOutputCP (GetACP ());
1940     SetConsoleTitle ("VLC media player version "PACKAGE_VERSION);
1941
1942     freopen( "CONOUT$", "w", stderr );
1943     freopen( "CONIN$", "r", stdin );
1944
1945     if( b_dofile && (f_help = fopen( "vlc-help.txt", "wt" )) )
1946     {
1947         fclose( f_help );
1948         freopen( "vlc-help.txt", "wt", stdout );
1949         utf8_fprintf( stderr, _("\nDumped content to vlc-help.txt file.\n") );
1950     }
1951     else freopen( "CONOUT$", "w", stdout );
1952
1953 #   endif
1954 }
1955 #endif
1956
1957 /*****************************************************************************
1958  * PauseConsole: On Win32, wait for a key press before closing the console
1959  *****************************************************************************
1960  * This function is useful only on Win32.
1961  *****************************************************************************/
1962 #ifdef WIN32 /*  */
1963 static void PauseConsole( void )
1964 {
1965 #   ifndef UNDER_CE
1966
1967     if( getenv( "PWD" ) && getenv( "PS1" ) ) return; /* cygwin shell */
1968
1969     utf8_fprintf( stderr, _("\nPress the RETURN key to continue...\n") );
1970     getchar();
1971     fclose( stdout );
1972
1973 #   endif
1974 }
1975 #endif
1976
1977 /*****************************************************************************
1978  * ConsoleWidth: Return the console width in characters
1979  *****************************************************************************
1980  * We use the stty shell command to get the console width; if this fails or
1981  * if the width is less than 80, we default to 80.
1982  *****************************************************************************/
1983 static int ConsoleWidth( void )
1984 {
1985     unsigned i_width = 80;
1986
1987 #ifndef WIN32
1988     FILE *file = popen( "stty size 2>/dev/null", "r" );
1989     if (file != NULL)
1990     {
1991         if (fscanf (file, "%*u %u", &i_width) <= 0)
1992             i_width = 80;
1993         pclose( file );
1994     }
1995 #else
1996     CONSOLE_SCREEN_BUFFER_INFO buf;
1997
1998     if (GetConsoleScreenBufferInfo (GetStdHandle (STD_OUTPUT_HANDLE), &buf))
1999         i_width = buf.dwSize.X;
2000 #endif
2001
2002     return i_width;
2003 }
2004
2005 static int VerboseCallback( vlc_object_t *p_this, const char *psz_variable,
2006                      vlc_value_t old_val, vlc_value_t new_val, void *param)
2007 {
2008     libvlc_int_t *p_libvlc = (libvlc_int_t *)p_this;
2009     (void)psz_variable;
2010     (void)old_val;
2011     (void)param;
2012
2013     if( new_val.i_int >= -1 )
2014     {
2015         libvlc_priv (p_libvlc)->i_verbose = __MIN( new_val.i_int, 2 );
2016     }
2017     return VLC_SUCCESS;
2018 }
2019
2020 /*****************************************************************************
2021  * InitDeviceValues: initialize device values
2022  *****************************************************************************
2023  * This function inits the dvd, vcd and cd-audio values
2024  *****************************************************************************/
2025 static void InitDeviceValues( libvlc_int_t *p_vlc )
2026 {
2027 #ifdef HAVE_HAL
2028     LibHalContext * ctx = NULL;
2029     int i, i_devices;
2030     char **devices = NULL;
2031     char *block_dev = NULL;
2032     dbus_bool_t b_dvd;
2033
2034     DBusConnection *p_connection = NULL;
2035     DBusError       error;
2036
2037     ctx = libhal_ctx_new();
2038     if( !ctx ) return;
2039     dbus_error_init( &error );
2040     p_connection = dbus_bus_get ( DBUS_BUS_SYSTEM, &error );
2041     if( dbus_error_is_set( &error ) || !p_connection )
2042     {
2043         libhal_ctx_free( ctx );
2044         dbus_error_free( &error );
2045         return;
2046     }
2047     libhal_ctx_set_dbus_connection( ctx, p_connection );
2048     if( libhal_ctx_init( ctx, &error ) )
2049     {
2050         if( ( devices = libhal_get_all_devices( ctx, &i_devices, NULL ) ) )
2051         {
2052             for( i = 0; i < i_devices; i++ )
2053             {
2054                 if( !libhal_device_property_exists( ctx, devices[i],
2055                                                 "storage.cdrom.dvd", NULL ) )
2056                 {
2057                     continue;
2058                 }
2059                 b_dvd = libhal_device_get_property_bool( ctx, devices[ i ],
2060                                                  "storage.cdrom.dvd", NULL  );
2061                 block_dev = libhal_device_get_property_string( ctx,
2062                                 devices[ i ], "block.device" , NULL );
2063                 if( b_dvd )
2064                 {
2065                     config_PutPsz( p_vlc, "dvd", block_dev );
2066                 }
2067
2068                 config_PutPsz( p_vlc, "vcd", block_dev );
2069                 config_PutPsz( p_vlc, "cd-audio", block_dev );
2070                 libhal_free_string( block_dev );
2071             }
2072             libhal_free_string_array( devices );
2073         }
2074         libhal_ctx_shutdown( ctx, NULL );
2075         dbus_connection_unref( p_connection );
2076         libhal_ctx_free( ctx );
2077     }
2078     else
2079     {
2080         msg_Warn( p_vlc, "Unable to get HAL device properties" );
2081     }
2082 #else
2083     (void)p_vlc;
2084 #endif /* HAVE_HAL */
2085 }