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