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