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