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