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