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