]> git.sesse.net Git - vlc/blob - src/libvlc.c
Load plugins and configuration as soon as possible
[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 <stdio.h>                                              /* sprintf() */
47 #include <string.h>
48 #include <stdlib.h>                                                /* free() */
49
50 #ifndef WIN32
51 #   include <netinet/in.h>                            /* BSD: struct in_addr */
52 #endif
53
54 #ifdef HAVE_UNISTD_H
55 #   include <unistd.h>
56 #elif defined( WIN32 ) && !defined( UNDER_CE )
57 #   include <io.h>
58 #endif
59
60 #include "config/vlc_getopt.h"
61
62 #ifdef HAVE_LOCALE_H
63 #   include <locale.h>
64 #endif
65
66 #ifdef HAVE_DBUS
67 /* used for one-instance mode */
68 #   include <dbus/dbus.h>
69 #endif
70
71
72 #include <vlc_media_library.h>
73 #include <vlc_playlist.h>
74 #include <vlc_interface.h>
75
76 #include <vlc_aout.h>
77 #include "audio_output/aout_internal.h"
78
79 #include <vlc_charset.h>
80 #include <vlc_fs.h>
81 #include <vlc_cpu.h>
82 #include <vlc_url.h>
83 #include <vlc_atomic.h>
84 #include <vlc_modules.h>
85
86 #include "libvlc.h"
87
88 #include "playlist/playlist_internal.h"
89
90 #include <vlc_vlm.h>
91
92 #ifdef __APPLE__
93 # include <libkern/OSAtomic.h>
94 #endif
95
96 #include <assert.h>
97
98 /*****************************************************************************
99  * The evil global variables. We handle them with care, don't worry.
100  *****************************************************************************/
101
102 #ifndef WIN32
103 static bool b_daemon = false;
104 #endif
105
106 #undef vlc_gc_init
107 #undef vlc_hold
108 #undef vlc_release
109
110 /**
111  * Atomically set the reference count to 1.
112  * @param p_gc reference counted object
113  * @param pf_destruct destruction calback
114  * @return p_gc.
115  */
116 void *vlc_gc_init (gc_object_t *p_gc, void (*pf_destruct) (gc_object_t *))
117 {
118     /* There is no point in using the GC if there is no destructor... */
119     assert (pf_destruct);
120     p_gc->pf_destructor = pf_destruct;
121
122     vlc_atomic_set (&p_gc->refs, 1);
123     return p_gc;
124 }
125
126 /**
127  * Atomically increment the reference count.
128  * @param p_gc reference counted object
129  * @return p_gc.
130  */
131 void *vlc_hold (gc_object_t * p_gc)
132 {
133     uintptr_t refs;
134
135     assert( p_gc );
136     refs = vlc_atomic_inc (&p_gc->refs);
137     assert (refs != 1); /* there had to be a reference already */
138     return p_gc;
139 }
140
141 /**
142  * Atomically decrement the reference count and, if it reaches zero, destroy.
143  * @param p_gc reference counted object.
144  */
145 void vlc_release (gc_object_t *p_gc)
146 {
147     uintptr_t refs;
148
149     assert( p_gc );
150     refs = vlc_atomic_dec (&p_gc->refs);
151     assert (refs != (uintptr_t)(-1)); /* reference underflow?! */
152     if (refs == 0)
153         p_gc->pf_destructor (p_gc);
154 }
155
156 /*****************************************************************************
157  * Local prototypes
158  *****************************************************************************/
159 #if defined( ENABLE_NLS ) && (defined (__APPLE__) || defined (WIN32)) && \
160     ( defined( HAVE_GETTEXT ) || defined( HAVE_INCLUDED_GETTEXT ) )
161 static void SetLanguage   ( char const * );
162 #endif
163 static void GetFilenames  ( libvlc_int_t *, unsigned, const char *const [] );
164 static void Help          ( libvlc_int_t *, char const *psz_help_name );
165 static void Usage         ( libvlc_int_t *, char const *psz_search );
166 static void ListModules   ( libvlc_int_t *, bool );
167 static void Version       ( void );
168
169 #ifdef WIN32
170 static void ShowConsole   ( bool );
171 static void PauseConsole  ( void );
172 #endif
173 static int  ConsoleWidth  ( void );
174
175 extern const char psz_vlc_changeset[];
176
177 /**
178  * Allocate a libvlc instance, initialize global data if needed
179  * It also initializes the threading system
180  */
181 libvlc_int_t * libvlc_InternalCreate( void )
182 {
183     libvlc_int_t *p_libvlc;
184     libvlc_priv_t *priv;
185     char *psz_env = NULL;
186
187     /* Now that the thread system is initialized, we don't have much, but
188      * at least we have variables */
189     /* Allocate a libvlc instance object */
190     p_libvlc = vlc_custom_create( (vlc_object_t *)NULL, sizeof (*priv),
191                                   "libvlc" );
192     if( p_libvlc == NULL )
193         return NULL;
194
195     priv = libvlc_priv (p_libvlc);
196     priv->p_playlist = NULL;
197     priv->p_ml = NULL;
198     priv->p_dialog_provider = NULL;
199     priv->p_vlm = NULL;
200
201     /* Find verbosity from VLC_VERBOSE environment variable */
202     psz_env = getenv( "VLC_VERBOSE" );
203     if( psz_env != NULL )
204         priv->i_verbose = atoi( psz_env );
205     else
206         priv->i_verbose = 3;
207 #if defined( HAVE_ISATTY ) && !defined( WIN32 )
208     priv->b_color = isatty( 2 ); /* 2 is for stderr */
209 #else
210     priv->b_color = false;
211 #endif
212
213     /* Initialize mutexes */
214     vlc_mutex_init( &priv->ml_lock );
215     vlc_mutex_init( &priv->timer_lock );
216     vlc_ExitInit( &priv->exit );
217
218     return p_libvlc;
219 }
220
221 /**
222  * Initialize a libvlc instance
223  * This function initializes a previously allocated libvlc instance:
224  *  - CPU detection
225  *  - gettext initialization
226  *  - message queue, module bank and playlist initialization
227  *  - configuration and commandline parsing
228  */
229 int libvlc_InternalInit( libvlc_int_t *p_libvlc, int i_argc,
230                          const char *ppsz_argv[] )
231 {
232     libvlc_priv_t *priv = libvlc_priv (p_libvlc);
233     char *       p_tmp = NULL;
234     char *       psz_modules = NULL;
235     char *       psz_parser = NULL;
236     char *       psz_control = NULL;
237     bool   b_exit = false;
238     int          i_ret = VLC_EEXIT;
239     playlist_t  *p_playlist = NULL;
240     char        *psz_val;
241 #if defined( ENABLE_NLS ) \
242      && ( defined( HAVE_GETTEXT ) || defined( HAVE_INCLUDED_GETTEXT ) )
243 # if defined (WIN32) || defined (__APPLE__)
244     char *       psz_language;
245 #endif
246 #endif
247
248     /* System specific initialization code */
249     system_Init();
250
251     /*
252      * Support for gettext
253      */
254     vlc_bindtextdomain (PACKAGE_NAME);
255
256     /* Initialize the module bank and load the configuration of the
257      * main module. We need to do this at this stage to be able to display
258      * a short help if required by the user. (short help == main module
259      * options) */
260     module_InitBank ();
261
262     /* Get command line options that affect module loading. */
263     if( config_LoadCmdLine( p_libvlc, i_argc, ppsz_argv, NULL ) )
264     {
265         module_EndBank (false);
266         return VLC_EGENERIC;
267     }
268     priv->i_verbose = var_InheritInteger( p_libvlc, "verbose" );
269
270     /* Announce who we are (TODO: only first instance?) */
271     msg_Dbg( p_libvlc, "VLC media player - %s", VERSION_MESSAGE );
272     msg_Dbg( p_libvlc, "%s", COPYRIGHT_MESSAGE );
273     msg_Dbg( p_libvlc, "revision %s", psz_vlc_changeset );
274     msg_Dbg( p_libvlc, "configured with %s", CONFIGURE_LINE );
275
276     /* Load the builtins and plugins into the module_bank.
277      * We have to do it before config_Load*() because this also gets the
278      * list of configuration options exported by each module and loads their
279      * default values. */
280     size_t module_count = module_LoadPlugins (p_libvlc);
281
282     /*
283      * Override default configuration with config file settings
284      */
285     if( !var_InheritBool( p_libvlc, "ignore-config" ) )
286     {
287         if( var_InheritBool( p_libvlc, "reset-config" ) )
288             config_SaveConfigFile( p_libvlc ); /* Save default config */
289         else
290             config_LoadConfigFile( p_libvlc );
291     }
292
293     /*
294      * Override configuration with command line settings
295      */
296     int vlc_optind;
297     if( config_LoadCmdLine( p_libvlc, i_argc, ppsz_argv, &vlc_optind ) )
298     {
299 #ifdef WIN32
300         ShowConsole( false );
301         /* Pause the console because it's destroyed when we exit */
302         fprintf( stderr, "The command line options couldn't be loaded, check "
303                  "that they are valid.\n" );
304         PauseConsole();
305 #endif
306         module_EndBank (true);
307         return VLC_EGENERIC;
308     }
309     priv->i_verbose = var_InheritInteger( p_libvlc, "verbose" );
310
311     /*xgettext: Translate "C" to the language code: "fr", "en_GB", "nl", "ru"... */
312     msg_Dbg( p_libvlc, "translation test: code is \"%s\"", _("C") );
313
314     /* Check for short help option */
315     if( var_InheritBool( p_libvlc, "help" ) )
316     {
317         Help( p_libvlc, "help" );
318         b_exit = true;
319         i_ret = VLC_EEXITSUCCESS;
320     }
321     /* Check for version option */
322     else if( var_InheritBool( p_libvlc, "version" ) )
323     {
324         Version();
325         b_exit = true;
326         i_ret = VLC_EEXITSUCCESS;
327     }
328
329     /* Check for daemon mode */
330 #if !defined( WIN32 ) && !defined( __SYMBIAN32__ )
331     if( var_InheritBool( p_libvlc, "daemon" ) )
332     {
333 #ifdef HAVE_DAEMON
334         char *psz_pidfile = NULL;
335
336         if( daemon( 1, 0) != 0 )
337         {
338             msg_Err( p_libvlc, "Unable to fork vlc to daemon mode" );
339             b_exit = true;
340         }
341         b_daemon = true;
342
343         /* lets check if we need to write the pidfile */
344         psz_pidfile = var_CreateGetNonEmptyString( p_libvlc, "pidfile" );
345         if( psz_pidfile != NULL )
346         {
347             FILE *pidfile;
348             pid_t i_pid = getpid ();
349             msg_Dbg( p_libvlc, "PID is %d, writing it to %s",
350                                i_pid, psz_pidfile );
351             pidfile = vlc_fopen( psz_pidfile,"w" );
352             if( pidfile != NULL )
353             {
354                 utf8_fprintf( pidfile, "%d", (int)i_pid );
355                 fclose( pidfile );
356             }
357             else
358             {
359                 msg_Err( p_libvlc, "cannot open pid file for writing: %s (%m)",
360                          psz_pidfile );
361             }
362         }
363         free( psz_pidfile );
364
365 #else
366         pid_t i_pid;
367
368         if( ( i_pid = fork() ) < 0 )
369         {
370             msg_Err( p_libvlc, "unable to fork vlc to daemon mode" );
371             b_exit = true;
372         }
373         else if( i_pid )
374         {
375             /* This is the parent, exit right now */
376             msg_Dbg( p_libvlc, "closing parent process" );
377             b_exit = true;
378             i_ret = VLC_EEXITSUCCESS;
379         }
380         else
381         {
382             /* We are the child */
383             msg_Dbg( p_libvlc, "daemon spawned" );
384             close( STDIN_FILENO );
385             close( STDOUT_FILENO );
386             close( STDERR_FILENO );
387
388             b_daemon = true;
389         }
390 #endif
391     }
392 #endif
393
394     if( b_exit )
395     {
396         module_EndBank (true);
397         return i_ret;
398     }
399
400     /* Check for translation config option */
401 #if defined( ENABLE_NLS ) \
402      && ( defined( HAVE_GETTEXT ) || defined( HAVE_INCLUDED_GETTEXT ) )
403 # if defined (WIN32) || defined (__APPLE__)
404     /* Check if the user specified a custom language */
405     psz_language = var_CreateGetNonEmptyString( p_libvlc, "language" );
406     if( psz_language && strcmp( psz_language, "auto" ) )
407     {
408         /* Reset the default domain */
409         SetLanguage( psz_language );
410
411         /* Translate "C" to the language code: "fr", "en_GB", "nl", "ru"... */
412         msg_Dbg( p_libvlc, "translation test: code is \"%s\"", _("C") );
413     }
414     free( psz_language );
415 # endif
416 #endif
417
418     /* Check for help on modules */
419     if( (p_tmp = var_InheritString( p_libvlc, "module" )) )
420     {
421         Help( p_libvlc, p_tmp );
422         free( p_tmp );
423         b_exit = true;
424         i_ret = VLC_EEXITSUCCESS;
425     }
426     /* Check for full help option */
427     else if( var_InheritBool( p_libvlc, "full-help" ) )
428     {
429         var_Create( p_libvlc, "advanced", VLC_VAR_BOOL );
430         var_SetBool( p_libvlc, "advanced", true );
431         var_Create( p_libvlc, "help-verbose", VLC_VAR_BOOL );
432         var_SetBool( p_libvlc, "help-verbose", true );
433         Help( p_libvlc, "full-help" );
434         b_exit = true;
435         i_ret = VLC_EEXITSUCCESS;
436     }
437     /* Check for long help option */
438     else if( var_InheritBool( p_libvlc, "longhelp" ) )
439     {
440         Help( p_libvlc, "longhelp" );
441         b_exit = true;
442         i_ret = VLC_EEXITSUCCESS;
443     }
444     /* Check for module list option */
445     else if( var_InheritBool( p_libvlc, "list" ) )
446     {
447         ListModules( p_libvlc, false );
448         b_exit = true;
449         i_ret = VLC_EEXITSUCCESS;
450     }
451     else if( var_InheritBool( p_libvlc, "list-verbose" ) )
452     {
453         ListModules( p_libvlc, true );
454         b_exit = true;
455         i_ret = VLC_EEXITSUCCESS;
456     }
457
458     if( module_count <= 1 )
459     {
460         msg_Err( p_libvlc, "No plugins found! Check your VLC installation.");
461         b_exit = true;
462         i_ret = VLC_ENOITEM;
463     }
464
465     if( b_exit )
466     {
467         module_EndBank (true);
468         return i_ret;
469     }
470
471 /* FIXME: could be replaced by using Unix sockets */
472 #ifdef HAVE_DBUS
473     dbus_threads_init_default();
474
475     if( var_InheritBool( p_libvlc, "one-instance" )
476     || ( var_InheritBool( p_libvlc, "one-instance-when-started-from-file" )
477       && var_InheritBool( p_libvlc, "started-from-file" ) ) )
478     {
479         /* Initialise D-Bus interface, check for other instances */
480         DBusConnection  *p_conn = NULL;
481         DBusError       dbus_error;
482
483         dbus_error_init( &dbus_error );
484
485         /* connect to the session bus */
486         p_conn = dbus_bus_get( DBUS_BUS_SESSION, &dbus_error );
487         if( !p_conn )
488         {
489             msg_Err( p_libvlc, "Failed to connect to D-Bus session daemon: %s",
490                     dbus_error.message );
491             dbus_error_free( &dbus_error );
492         }
493         else
494         {
495             /* check if VLC is available on the bus
496              * if not: D-Bus control is not enabled on the other
497              * instance and we can't pass MRLs to it */
498             DBusMessage *p_test_msg   = NULL;
499             DBusMessage *p_test_reply = NULL;
500
501             p_test_msg =  dbus_message_new_method_call(
502                     "org.mpris.MediaPlayer2.vlc", "/org/mpris/MediaPlayer2",
503                     "org.freedesktop.DBus.Introspectable", "Introspect" );
504
505             /* block until a reply arrives */
506             p_test_reply = dbus_connection_send_with_reply_and_block(
507                     p_conn, p_test_msg, -1, &dbus_error );
508             dbus_message_unref( p_test_msg );
509             if( p_test_reply == NULL )
510             {
511                 dbus_error_free( &dbus_error );
512                 msg_Dbg( p_libvlc, "No Media Player is running. "
513                         "Continuing normally." );
514             }
515             else
516             {
517                 int i_input;
518                 DBusMessage* p_dbus_msg = NULL;
519                 DBusMessageIter dbus_args;
520                 DBusPendingCall* p_dbus_pending = NULL;
521                 dbus_bool_t b_play;
522
523                 dbus_message_unref( p_test_reply );
524                 msg_Warn( p_libvlc, "Another Media Player is running. Exiting");
525
526                 for( i_input = vlc_optind; i_input < i_argc;i_input++ )
527                 {
528                     /* Skip input options, we can't pass them through D-Bus */
529                     if( ppsz_argv[i_input][0] == ':' )
530                     {
531                         msg_Warn( p_libvlc, "Ignoring option %s",
532                                   ppsz_argv[i_input] );
533                         continue;
534                     }
535
536                     /* We need to resolve relative paths in this instance */
537                     char *psz_mrl = make_URI( ppsz_argv[i_input], NULL );
538                     const char *psz_after_track = "/";
539
540                     if( psz_mrl == NULL )
541                         continue;
542                     msg_Dbg( p_libvlc, "Adds %s to the running Media Player",
543                              psz_mrl );
544
545                     p_dbus_msg = dbus_message_new_method_call(
546                         "org.mpris.MediaPlayer2.vlc", "/org/mpris/MediaPlayer2",
547                         "org.mpris.MediaPlayer2.TrackList", "AddTrack" );
548
549                     if ( NULL == p_dbus_msg )
550                     {
551                         msg_Err( p_libvlc, "D-Bus problem" );
552                         free( psz_mrl );
553                         system_End( );
554                         exit( 1 );
555                     }
556
557                     /* append MRLs */
558                     dbus_message_iter_init_append( p_dbus_msg, &dbus_args );
559                     if ( !dbus_message_iter_append_basic( &dbus_args,
560                                 DBUS_TYPE_STRING, &psz_mrl ) )
561                     {
562                         dbus_message_unref( p_dbus_msg );
563                         free( psz_mrl );
564                         system_End( );
565                         exit( 1 );
566                     }
567                     free( psz_mrl );
568
569                     if( !dbus_message_iter_append_basic( &dbus_args,
570                                 DBUS_TYPE_OBJECT_PATH, &psz_after_track ) )
571                     {
572                         dbus_message_unref( p_dbus_msg );
573                         system_End( );
574                         exit( 1 );
575                     }
576
577                     b_play = TRUE;
578                     if( var_InheritBool( p_libvlc, "playlist-enqueue" ) )
579                         b_play = FALSE;
580
581                     if ( !dbus_message_iter_append_basic( &dbus_args,
582                                 DBUS_TYPE_BOOLEAN, &b_play ) )
583                     {
584                         dbus_message_unref( p_dbus_msg );
585                         system_End( );
586                         exit( 1 );
587                     }
588
589                     /* send message and get a handle for a reply */
590                     if ( !dbus_connection_send_with_reply ( p_conn,
591                                 p_dbus_msg, &p_dbus_pending, -1 ) )
592                     {
593                         msg_Err( p_libvlc, "D-Bus problem" );
594                         dbus_message_unref( p_dbus_msg );
595                         system_End( );
596                         exit( 1 );
597                     }
598
599                     if ( NULL == p_dbus_pending )
600                     {
601                         msg_Err( p_libvlc, "D-Bus problem" );
602                         dbus_message_unref( p_dbus_msg );
603                         system_End( );
604                         exit( 1 );
605                     }
606                     dbus_connection_flush( p_conn );
607                     dbus_message_unref( p_dbus_msg );
608                     /* block until we receive a reply */
609                     dbus_pending_call_block( p_dbus_pending );
610                     dbus_pending_call_unref( p_dbus_pending );
611                 } /* processes all command line MRLs */
612
613                 /* bye bye */
614                 system_End( );
615                 exit( 0 );
616             }
617         }
618         /* we unreference the connection when we've finished with it */
619         if( p_conn ) dbus_connection_unref( p_conn );
620     }
621 #endif
622
623     /*
624      * Message queue options
625      */
626     /* Last chance to set the verbosity. Once we start interfaces and other
627      * threads, verbosity becomes read-only. */
628     var_Create( p_libvlc, "verbose", VLC_VAR_INTEGER | VLC_VAR_DOINHERIT );
629     if( var_InheritBool( p_libvlc, "quiet" ) )
630     {
631         var_SetInteger( p_libvlc, "verbose", -1 );
632         priv->i_verbose = -1;
633     }
634     vlc_threads_setup( p_libvlc );
635
636     if( priv->b_color )
637         priv->b_color = var_InheritBool( p_libvlc, "color" );
638
639     vlc_CPU_dump( VLC_OBJECT(p_libvlc) );
640     /*
641      * Choose the best memcpy module
642      */
643     priv->p_memcpy_module = module_need( p_libvlc, "memcpy", "$memcpy", false );
644     /* Avoid being called "memcpy":*/
645     vlc_object_set_name( p_libvlc, "main" );
646
647     priv->b_stats = var_InheritBool( p_libvlc, "stats" );
648     priv->i_timers = 0;
649     priv->pp_timers = NULL;
650
651     /*
652      * Initialize hotkey handling
653      */
654     priv->actions = vlc_InitActions( p_libvlc );
655
656     /* Create a variable for showing the fullscreen interface */
657     var_Create( p_libvlc, "intf-show", VLC_VAR_BOOL );
658     var_SetBool( p_libvlc, "intf-show", true );
659
660     /* Create a variable for showing the right click menu */
661     var_Create( p_libvlc, "intf-popupmenu", VLC_VAR_BOOL );
662
663     /* variables for signalling creation of new files */
664     var_Create( p_libvlc, "snapshot-file", VLC_VAR_STRING );
665     var_Create( p_libvlc, "record-file", VLC_VAR_STRING );
666
667     /* some default internal settings */
668     var_Create( p_libvlc, "window", VLC_VAR_STRING );
669     var_Create( p_libvlc, "user-agent", VLC_VAR_STRING );
670     var_SetString( p_libvlc, "user-agent", "(LibVLC "VERSION")" );
671
672     /* Initialize playlist and get commandline files */
673     p_playlist = playlist_Create( VLC_OBJECT(p_libvlc) );
674     if( !p_playlist )
675     {
676         msg_Err( p_libvlc, "playlist initialization failed" );
677         if( priv->p_memcpy_module != NULL )
678         {
679             module_unneed( p_libvlc, priv->p_memcpy_module );
680         }
681         module_EndBank (true);
682         return VLC_EGENERIC;
683     }
684
685     /* System specific configuration */
686     system_Configure( p_libvlc, i_argc - vlc_optind, ppsz_argv + vlc_optind );
687
688 #if defined(MEDIA_LIBRARY)
689     /* Get the ML */
690     if( var_GetBool( p_libvlc, "load-media-library-on-startup" ) )
691     {
692         priv->p_ml = ml_Create( VLC_OBJECT( p_libvlc ), NULL );
693         if( !priv->p_ml )
694         {
695             msg_Err( p_libvlc, "ML initialization failed" );
696             return VLC_EGENERIC;
697         }
698     }
699     else
700     {
701         priv->p_ml = NULL;
702     }
703 #endif
704
705     /* Add service discovery modules */
706     psz_modules = var_InheritString( p_libvlc, "services-discovery" );
707     if( psz_modules )
708     {
709         char *p = psz_modules, *m;
710         while( ( m = strsep( &p, " :," ) ) != NULL )
711             playlist_ServicesDiscoveryAdd( p_playlist, m );
712         free( psz_modules );
713     }
714
715 #ifdef ENABLE_VLM
716     /* Initialize VLM if vlm-conf is specified */
717     psz_parser = var_CreateGetNonEmptyString( p_libvlc, "vlm-conf" );
718     if( psz_parser )
719     {
720         priv->p_vlm = vlm_New( p_libvlc );
721         if( !priv->p_vlm )
722             msg_Err( p_libvlc, "VLM initialization failed" );
723     }
724     free( psz_parser );
725 #endif
726
727     /*
728      * Load background interfaces
729      */
730     psz_modules = var_CreateGetNonEmptyString( p_libvlc, "extraintf" );
731     psz_control = var_CreateGetNonEmptyString( p_libvlc, "control" );
732
733     if( psz_modules && psz_control )
734     {
735         char* psz_tmp;
736         if( asprintf( &psz_tmp, "%s:%s", psz_modules, psz_control ) != -1 )
737         {
738             free( psz_modules );
739             psz_modules = psz_tmp;
740         }
741     }
742     else if( psz_control )
743     {
744         free( psz_modules );
745         psz_modules = strdup( psz_control );
746     }
747
748     psz_parser = psz_modules;
749     while ( psz_parser && *psz_parser )
750     {
751         char *psz_module, *psz_temp;
752         psz_module = psz_parser;
753         psz_parser = strchr( psz_module, ':' );
754         if ( psz_parser )
755         {
756             *psz_parser = '\0';
757             psz_parser++;
758         }
759         if( asprintf( &psz_temp, "%s,none", psz_module ) != -1)
760         {
761             intf_Create( p_libvlc, psz_temp );
762             free( psz_temp );
763         }
764     }
765     free( psz_modules );
766     free( psz_control );
767
768     /*
769      * Always load the hotkeys interface if it exists
770      */
771     intf_Create( p_libvlc, "hotkeys,none" );
772
773 #ifdef HAVE_DBUS
774     /* loads dbus control interface if in one-instance mode
775      * we do it only when playlist exists, because dbus module needs it */
776     if( var_InheritBool( p_libvlc, "one-instance" )
777      || ( var_InheritBool( p_libvlc, "one-instance-when-started-from-file" )
778        && var_InheritBool( p_libvlc, "started-from-file" ) ) )
779         intf_Create( p_libvlc, "dbus,none" );
780
781 # if !defined (HAVE_MAEMO)
782     /* Prevents the power management daemon from suspending the system
783      * when VLC is active */
784     if( var_InheritBool( p_libvlc, "inhibit" ) > 0 )
785         intf_Create( p_libvlc, "inhibit,none" );
786 # endif
787 #endif
788
789     if( var_InheritBool( p_libvlc, "file-logging" ) &&
790         !var_InheritBool( p_libvlc, "syslog" ) )
791     {
792         intf_Create( p_libvlc, "logger,none" );
793     }
794 #ifdef HAVE_SYSLOG_H
795     if( var_InheritBool( p_libvlc, "syslog" ) )
796     {
797         char *logmode = var_CreateGetNonEmptyString( p_libvlc, "logmode" );
798         var_SetString( p_libvlc, "logmode", "syslog" );
799         intf_Create( p_libvlc, "logger,none" );
800
801         if( logmode )
802         {
803             var_SetString( p_libvlc, "logmode", logmode );
804             free( logmode );
805         }
806         var_Destroy( p_libvlc, "logmode" );
807     }
808 #endif
809
810     if( var_InheritBool( p_libvlc, "network-synchronisation") )
811     {
812         intf_Create( p_libvlc, "netsync,none" );
813     }
814
815 #ifdef __APPLE__
816     var_Create( p_libvlc, "drawable-view-top", VLC_VAR_INTEGER );
817     var_Create( p_libvlc, "drawable-view-left", VLC_VAR_INTEGER );
818     var_Create( p_libvlc, "drawable-view-bottom", VLC_VAR_INTEGER );
819     var_Create( p_libvlc, "drawable-view-right", VLC_VAR_INTEGER );
820     var_Create( p_libvlc, "drawable-clip-top", VLC_VAR_INTEGER );
821     var_Create( p_libvlc, "drawable-clip-left", VLC_VAR_INTEGER );
822     var_Create( p_libvlc, "drawable-clip-bottom", VLC_VAR_INTEGER );
823     var_Create( p_libvlc, "drawable-clip-right", VLC_VAR_INTEGER );
824     var_Create( p_libvlc, "drawable-nsobject", VLC_VAR_ADDRESS );
825 #endif
826 #ifdef WIN32
827     var_Create( p_libvlc, "drawable-hwnd", VLC_VAR_INTEGER );
828 #endif
829
830     /*
831      * Get input filenames given as commandline arguments.
832      * We assume that the remaining parameters are filenames
833      * and their input options.
834      */
835     GetFilenames( p_libvlc, i_argc - vlc_optind, ppsz_argv + vlc_optind );
836
837     /*
838      * Get --open argument
839      */
840     psz_val = var_InheritString( p_libvlc, "open" );
841     if ( psz_val != NULL )
842     {
843         playlist_AddExt( p_playlist, psz_val, NULL, PLAYLIST_INSERT, 0,
844                          -1, 0, NULL, 0, true, pl_Unlocked );
845         free( psz_val );
846     }
847
848     return VLC_SUCCESS;
849 }
850
851 /**
852  * Cleanup a libvlc instance. The instance is not completely deallocated
853  * \param p_libvlc the instance to clean
854  */
855 void libvlc_InternalCleanup( libvlc_int_t *p_libvlc )
856 {
857     libvlc_priv_t *priv = libvlc_priv (p_libvlc);
858     playlist_t    *p_playlist = libvlc_priv (p_libvlc)->p_playlist;
859
860     /* Deactivate the playlist */
861     msg_Dbg( p_libvlc, "deactivating the playlist" );
862     pl_Deactivate( p_libvlc );
863
864     /* Remove all services discovery */
865     msg_Dbg( p_libvlc, "removing all services discovery tasks" );
866     playlist_ServicesDiscoveryKillAll( p_playlist );
867
868     /* Ask the interfaces to stop and destroy them */
869     msg_Dbg( p_libvlc, "removing all interfaces" );
870     libvlc_Quit( p_libvlc );
871     intf_DestroyAll( p_libvlc );
872
873 #ifdef ENABLE_VLM
874     /* Destroy VLM if created in libvlc_InternalInit */
875     if( priv->p_vlm )
876     {
877         vlm_Delete( priv->p_vlm );
878     }
879 #endif
880
881 #if defined(MEDIA_LIBRARY)
882     media_library_t* p_ml = priv->p_ml;
883     if( p_ml )
884     {
885         ml_Destroy( VLC_OBJECT( p_ml ) );
886         vlc_object_release( p_ml );
887         libvlc_priv(p_playlist->p_libvlc)->p_ml = NULL;
888     }
889 #endif
890
891     /* Free playlist now, all threads are gone */
892     playlist_Destroy( p_playlist );
893     stats_TimersDumpAll( p_libvlc );
894     stats_TimersCleanAll( p_libvlc );
895
896     msg_Dbg( p_libvlc, "removing stats" );
897
898 #ifndef WIN32
899     char* psz_pidfile = NULL;
900
901     if( b_daemon )
902     {
903         psz_pidfile = var_CreateGetNonEmptyString( p_libvlc, "pidfile" );
904         if( psz_pidfile != NULL )
905         {
906             msg_Dbg( p_libvlc, "removing pid file %s", psz_pidfile );
907             if( unlink( psz_pidfile ) == -1 )
908             {
909                 msg_Dbg( p_libvlc, "removing pid file %s: %m",
910                         psz_pidfile );
911             }
912         }
913         free( psz_pidfile );
914     }
915 #endif
916
917     if( priv->p_memcpy_module )
918     {
919         module_unneed( p_libvlc, priv->p_memcpy_module );
920         priv->p_memcpy_module = NULL;
921     }
922
923     /* Save the configuration */
924     if( !var_InheritBool( p_libvlc, "ignore-config" ) )
925         config_AutoSaveConfigFile( VLC_OBJECT(p_libvlc) );
926
927     /* Free module bank. It is refcounted, so we call this each time  */
928     module_EndBank (true);
929
930     vlc_DeinitActions( p_libvlc, priv->actions );
931 }
932
933 /**
934  * Destroy everything.
935  * This function requests the running threads to finish, waits for their
936  * termination, and destroys their structure.
937  * It stops the thread systems: no instance can run after this has run
938  * \param p_libvlc the instance to destroy
939  */
940 void libvlc_InternalDestroy( libvlc_int_t *p_libvlc )
941 {
942     libvlc_priv_t *priv = libvlc_priv( p_libvlc );
943
944     system_End( );
945
946     /* Destroy mutexes */
947     vlc_ExitDestroy( &priv->exit );
948     vlc_mutex_destroy( &priv->timer_lock );
949     vlc_mutex_destroy( &priv->ml_lock );
950
951 #ifndef NDEBUG /* Hack to dump leaked objects tree */
952     if( vlc_internals( p_libvlc )->i_refcount > 1 )
953         while( vlc_internals( p_libvlc )->i_refcount > 0 )
954             vlc_object_release( p_libvlc );
955 #endif
956
957     assert( vlc_internals( p_libvlc )->i_refcount == 1 );
958     vlc_object_release( p_libvlc );
959 }
960
961 /**
962  * Add an interface plugin and run it
963  */
964 int libvlc_InternalAddIntf( libvlc_int_t *p_libvlc, char const *psz_module )
965 {
966     if( !p_libvlc )
967         return VLC_EGENERIC;
968
969     if( !psz_module ) /* requesting the default interface */
970     {
971         char *psz_interface = var_CreateGetNonEmptyString( p_libvlc, "intf" );
972         if( !psz_interface ) /* "intf" has not been set */
973         {
974 #ifndef WIN32
975             if( b_daemon )
976                  /* Daemon mode hack.
977                   * We prefer the dummy interface if none is specified. */
978                 psz_module = "dummy";
979             else
980 #endif
981                 msg_Info( p_libvlc, "%s",
982                           _("Running vlc with the default interface. "
983                             "Use 'cvlc' to use vlc without interface.") );
984         }
985         free( psz_interface );
986         var_Destroy( p_libvlc, "intf" );
987     }
988
989     /* Try to create the interface */
990     int ret = intf_Create( p_libvlc, psz_module ? psz_module : "$intf" );
991     if( ret )
992         msg_Err( p_libvlc, "interface \"%s\" initialization failed",
993                  psz_module ? psz_module : "default" );
994     return ret;
995 }
996
997 #if defined( ENABLE_NLS ) && (defined (__APPLE__) || defined (WIN32)) && \
998     ( defined( HAVE_GETTEXT ) || defined( HAVE_INCLUDED_GETTEXT ) )
999 /*****************************************************************************
1000  * SetLanguage: set the interface language.
1001  *****************************************************************************
1002  * We set the LC_MESSAGES locale category for interface messages and buttons,
1003  * as well as the LC_CTYPE category for string sorting and possible wide
1004  * character support.
1005  *****************************************************************************/
1006 static void SetLanguage ( const char *psz_lang )
1007 {
1008 #ifdef __APPLE__
1009     /* I need that under Darwin, please check it doesn't disturb
1010      * other platforms. --Meuuh */
1011     setenv( "LANG", psz_lang, 1 );
1012
1013 #else
1014     /* We set LC_ALL manually because it is the only way to set
1015      * the language at runtime under eg. Windows. Beware that this
1016      * makes the environment unconsistent when libvlc is unloaded and
1017      * should probably be moved to a safer place like vlc.c. */
1018     setenv( "LC_ALL", psz_lang, 1 );
1019
1020 #endif
1021
1022     setlocale( LC_ALL, psz_lang );
1023 }
1024 #endif
1025
1026 /*****************************************************************************
1027  * GetFilenames: parse command line options which are not flags
1028  *****************************************************************************
1029  * Parse command line for input files as well as their associated options.
1030  * An option always follows its associated input and begins with a ":".
1031  *****************************************************************************/
1032 static void GetFilenames( libvlc_int_t *p_vlc, unsigned n,
1033                           const char *const args[] )
1034 {
1035     while( n > 0 )
1036     {
1037         /* Count the input options */
1038         unsigned i_options = 0;
1039
1040         while( args[--n][0] == ':' )
1041         {
1042             i_options++;
1043             if( n == 0 )
1044             {
1045                 msg_Warn( p_vlc, "options %s without item", args[n] );
1046                 return; /* syntax!? */
1047             }
1048         }
1049
1050         char *mrl = make_URI( args[n], NULL );
1051         if( !mrl )
1052             continue;
1053
1054         playlist_AddExt( pl_Get( p_vlc ), mrl, NULL, PLAYLIST_INSERT,
1055                 0, -1, i_options, ( i_options ? &args[n + 1] : NULL ),
1056                 VLC_INPUT_OPTION_TRUSTED, true, pl_Unlocked );
1057         free( mrl );
1058     }
1059 }
1060
1061 /*****************************************************************************
1062  * Help: print program help
1063  *****************************************************************************
1064  * Print a short inline help. Message interface is initialized at this stage.
1065  *****************************************************************************/
1066 static inline void print_help_on_full_help( void )
1067 {
1068     utf8_fprintf( stdout, "\n" );
1069     utf8_fprintf( stdout, "%s\n", _("To get exhaustive help, use '-H'.") );
1070 }
1071
1072 static const char vlc_usage[] = N_(
1073                             "Usage: %s [options] [stream] ..."
1074                             "\nYou can specify multiple streams on the commandline. They will be enqueued in the playlist."
1075                             "\nThe first item specified will be played first."
1076                             "\n"
1077                             "\nOptions-styles:"
1078                             "\n  --option  A global option that is set for the duration of the program."
1079                             "\n   -option  A single letter version of a global --option."
1080                             "\n   :option  An option that only applies to the stream directly before it"
1081                             "\n            and that overrides previous settings."
1082                             "\n"
1083                             "\nStream MRL syntax:"
1084                             "\n  [[access][/demux]://]URL[@[title][:chapter][-[title][:chapter]]] [:option=value ...]"
1085                             "\n"
1086                             "\n  Many of the global --options can also be used as MRL specific :options."
1087                             "\n  Multiple :option=value pairs can be specified."
1088                             "\n"
1089                             "\nURL syntax:"
1090                             "\n  [file://]filename              Plain media file"
1091                             "\n  http://ip:port/file            HTTP URL"
1092                             "\n  ftp://ip:port/file             FTP URL"
1093                             "\n  mms://ip:port/file             MMS URL"
1094                             "\n  screen://                      Screen capture"
1095                             "\n  [dvd://][device][@raw_device]  DVD device"
1096                             "\n  [vcd://][device]               VCD device"
1097                             "\n  [cdda://][device]              Audio CD device"
1098                             "\n  udp://[[<source address>]@[<bind address>][:<bind port>]]"
1099                             "\n                                 UDP stream sent by a streaming server"
1100                             "\n  vlc://pause:<seconds>          Special item to pause the playlist for a certain time"
1101                             "\n  vlc://quit                     Special item to quit VLC"
1102                             "\n");
1103
1104 static void Help( libvlc_int_t *p_this, char const *psz_help_name )
1105 {
1106 #ifdef WIN32
1107     ShowConsole( true );
1108 #endif
1109
1110     if( psz_help_name && !strcmp( psz_help_name, "help" ) )
1111     {
1112         utf8_fprintf( stdout, vlc_usage, "vlc" );
1113         Usage( p_this, "=help" );
1114         Usage( p_this, "=main" );
1115         print_help_on_full_help();
1116     }
1117     else if( psz_help_name && !strcmp( psz_help_name, "longhelp" ) )
1118     {
1119         utf8_fprintf( stdout, vlc_usage, "vlc" );
1120         Usage( p_this, NULL );
1121         print_help_on_full_help();
1122     }
1123     else if( psz_help_name && !strcmp( psz_help_name, "full-help" ) )
1124     {
1125         utf8_fprintf( stdout, vlc_usage, "vlc" );
1126         Usage( p_this, NULL );
1127     }
1128     else if( psz_help_name )
1129     {
1130         Usage( p_this, psz_help_name );
1131     }
1132
1133 #ifdef WIN32        /* Pause the console because it's destroyed when we exit */
1134     PauseConsole();
1135 #endif
1136     fflush( stdout );
1137 }
1138
1139 /*****************************************************************************
1140  * Usage: print module usage
1141  *****************************************************************************
1142  * Print a short inline help. Message interface is initialized at this stage.
1143  *****************************************************************************/
1144 #   define COL(x)  "\033[" #x ";1m"
1145 #   define RED     COL(31)
1146 #   define GREEN   COL(32)
1147 #   define YELLOW  COL(33)
1148 #   define BLUE    COL(34)
1149 #   define MAGENTA COL(35)
1150 #   define CYAN    COL(36)
1151 #   define WHITE   COL(0)
1152 #   define GRAY    "\033[0m"
1153 static void
1154 print_help_section( const module_t *m, const module_config_t *p_item,
1155                     bool b_color, bool b_description )
1156 {
1157     if( !p_item ) return;
1158     if( b_color )
1159     {
1160         utf8_fprintf( stdout, RED"   %s:\n"GRAY,
1161                       module_gettext( m, p_item->psz_text ) );
1162         if( b_description && p_item->psz_longtext )
1163             utf8_fprintf( stdout, MAGENTA"   %s\n"GRAY,
1164                           module_gettext( m, p_item->psz_longtext ) );
1165     }
1166     else
1167     {
1168         utf8_fprintf( stdout, "   %s:\n",
1169                       module_gettext( m, p_item->psz_text ) );
1170         if( b_description && p_item->psz_longtext )
1171             utf8_fprintf( stdout, "   %s\n",
1172                           module_gettext(m, p_item->psz_longtext ) );
1173     }
1174 }
1175
1176 static void Usage( libvlc_int_t *p_this, char const *psz_search )
1177 {
1178 #define FORMAT_STRING "  %s --%s%s%s%s%s%s%s "
1179     /* short option ------'    | | | | | | |
1180      * option name ------------' | | | | | |
1181      * <bra ---------------------' | | | | |
1182      * option type or "" ----------' | | | |
1183      * ket> -------------------------' | | |
1184      * padding spaces -----------------' | |
1185      * comment --------------------------' |
1186      * comment suffix ---------------------'
1187      *
1188      * The purpose of having bra and ket is that we might i18n them as well.
1189      */
1190
1191 #define COLOR_FORMAT_STRING (WHITE"  %s --%s"YELLOW"%s%s%s%s%s%s "GRAY)
1192 #define COLOR_FORMAT_STRING_BOOL (WHITE"  %s --%s%s%s%s%s%s%s "GRAY)
1193
1194 #define LINE_START 8
1195 #define PADDING_SPACES 25
1196 #ifdef WIN32
1197 #   define OPTION_VALUE_SEP "="
1198 #else
1199 #   define OPTION_VALUE_SEP " "
1200 #endif
1201     char psz_spaces_text[PADDING_SPACES+LINE_START+1];
1202     char psz_spaces_longtext[LINE_START+3];
1203     char psz_format[sizeof(COLOR_FORMAT_STRING)];
1204     char psz_format_bool[sizeof(COLOR_FORMAT_STRING_BOOL)];
1205     char psz_buffer[10000];
1206     char psz_short[4];
1207     int i_width = ConsoleWidth() - (PADDING_SPACES+LINE_START+1);
1208     int i_width_description = i_width + PADDING_SPACES - 1;
1209     bool b_advanced    = var_InheritBool( p_this, "advanced" );
1210     bool b_description = var_InheritBool( p_this, "help-verbose" );
1211     bool b_description_hack;
1212     bool b_color       = var_InheritBool( p_this, "color" );
1213     bool b_has_advanced = false;
1214     bool b_found       = false;
1215     int  i_only_advanced = 0; /* Number of modules ignored because they
1216                                * only have advanced options */
1217     bool b_strict = psz_search && *psz_search == '=';
1218     if( b_strict ) psz_search++;
1219
1220     memset( psz_spaces_text, ' ', PADDING_SPACES+LINE_START );
1221     psz_spaces_text[PADDING_SPACES+LINE_START] = '\0';
1222     memset( psz_spaces_longtext, ' ', LINE_START+2 );
1223     psz_spaces_longtext[LINE_START+2] = '\0';
1224 #ifndef WIN32
1225     if( !isatty( 1 ) )
1226 #endif
1227         b_color = false; // don't put color control codes in a .txt file
1228
1229     if( b_color )
1230     {
1231         strcpy( psz_format, COLOR_FORMAT_STRING );
1232         strcpy( psz_format_bool, COLOR_FORMAT_STRING_BOOL );
1233     }
1234     else
1235     {
1236         strcpy( psz_format, FORMAT_STRING );
1237         strcpy( psz_format_bool, FORMAT_STRING );
1238     }
1239
1240     /* List all modules */
1241     module_t **list = module_list_get (NULL);
1242     if (!list)
1243         return;
1244
1245     /* Ugly hack to make sure that the help options always come first
1246      * (part 1) */
1247     if( !psz_search )
1248         Usage( p_this, "help" );
1249
1250     /* Enumerate the config for each module */
1251     for (size_t i = 0; list[i]; i++)
1252     {
1253         bool b_help_module;
1254         module_t *p_parser = list[i];
1255         module_config_t *p_item = NULL;
1256         module_config_t *p_section = NULL;
1257         module_config_t *p_end = p_parser->p_config + p_parser->confsize;
1258         const char *objname = module_get_object (p_parser);
1259
1260         if( psz_search &&
1261             ( b_strict ? strcmp( objname, psz_search )
1262                        : !strstr( objname, psz_search ) ) )
1263         {
1264             char *const *pp_shortcuts = p_parser->pp_shortcuts;
1265             unsigned i;
1266             for( i = 0; i < p_parser->i_shortcuts; i++ )
1267             {
1268                 if( b_strict ? !strcmp( psz_search, pp_shortcuts[i] )
1269                              : !!strstr( pp_shortcuts[i], psz_search ) )
1270                     break;
1271             }
1272             if( i == p_parser->i_shortcuts )
1273                 continue;
1274         }
1275
1276         /* Ignore modules without config options */
1277         if( !p_parser->i_config_items )
1278         {
1279             continue;
1280         }
1281
1282         b_help_module = !strcmp( "help", objname );
1283         /* Ugly hack to make sure that the help options always come first
1284          * (part 2) */
1285         if( !psz_search && b_help_module )
1286             continue;
1287
1288         /* Ignore modules with only advanced config options if requested */
1289         if( !b_advanced )
1290         {
1291             for( p_item = p_parser->p_config;
1292                  p_item < p_end;
1293                  p_item++ )
1294             {
1295                 if( CONFIG_ITEM(p_item->i_type) &&
1296                     !p_item->b_advanced && !p_item->b_removed ) break;
1297             }
1298
1299             if( p_item == p_end )
1300             {
1301                 i_only_advanced++;
1302                 continue;
1303             }
1304         }
1305
1306         b_found = true;
1307
1308         /* Print name of module */
1309         if( strcmp( "main", objname ) )
1310         {
1311             if( b_color )
1312                 utf8_fprintf( stdout, "\n " GREEN "%s" GRAY " (%s)\n",
1313                               module_gettext( p_parser, p_parser->psz_longname ),
1314                               objname );
1315             else
1316                 utf8_fprintf( stdout, "\n %s\n",
1317                               module_gettext(p_parser, p_parser->psz_longname ) );
1318         }
1319         if( p_parser->psz_help )
1320         {
1321             if( b_color )
1322                 utf8_fprintf( stdout, CYAN" %s\n"GRAY,
1323                               module_gettext( p_parser, p_parser->psz_help ) );
1324             else
1325                 utf8_fprintf( stdout, " %s\n",
1326                               module_gettext( p_parser, p_parser->psz_help ) );
1327         }
1328
1329         /* Print module options */
1330         for( p_item = p_parser->p_config;
1331              p_item < p_end;
1332              p_item++ )
1333         {
1334             char *psz_text, *psz_spaces = psz_spaces_text;
1335             const char *psz_bra = NULL, *psz_type = NULL, *psz_ket = NULL;
1336             const char *psz_suf = "", *psz_prefix = NULL;
1337             signed int i;
1338             size_t i_cur_width;
1339
1340             /* Skip removed options */
1341             if( p_item->b_removed )
1342             {
1343                 continue;
1344             }
1345             /* Skip advanced options if requested */
1346             if( p_item->b_advanced && !b_advanced )
1347             {
1348                 b_has_advanced = true;
1349                 continue;
1350             }
1351
1352             switch( CONFIG_CLASS(p_item->i_type) )
1353             {
1354             case 0: // hint class
1355                 switch( p_item->i_type )
1356                 {
1357                 case CONFIG_HINT_CATEGORY:
1358                 case CONFIG_HINT_USAGE:
1359                     if( !strcmp( "main", objname ) )
1360                     {
1361                         if( b_color )
1362                             utf8_fprintf( stdout, GREEN "\n %s\n" GRAY,
1363                                           module_gettext( p_parser, p_item->psz_text ) );
1364                         else
1365                             utf8_fprintf( stdout, "\n %s\n",
1366                                           module_gettext( p_parser, p_item->psz_text ) );
1367                     }
1368                     if( b_description && p_item->psz_longtext )
1369                     {
1370                         if( b_color )
1371                             utf8_fprintf( stdout, CYAN " %s\n" GRAY,
1372                                           module_gettext( p_parser, p_item->psz_longtext ) );
1373                         else
1374                             utf8_fprintf( stdout, " %s\n",
1375                                           module_gettext( p_parser, p_item->psz_longtext ) );
1376                 }
1377                 break;
1378
1379                 case CONFIG_HINT_SUBCATEGORY:
1380                     if( strcmp( "main", objname ) )
1381                         break;
1382                 case CONFIG_SECTION:
1383                     p_section = p_item;
1384                     break;
1385                 }
1386                 break;
1387
1388             case CONFIG_ITEM_STRING:
1389                 print_help_section( p_parser, p_section, b_color,
1390                                     b_description );
1391                 p_section = NULL;
1392                 psz_bra = OPTION_VALUE_SEP "<";
1393                 psz_type = _("string");
1394                 psz_ket = ">";
1395
1396                 if( p_item->ppsz_list )
1397                 {
1398                     psz_bra = OPTION_VALUE_SEP "{";
1399                     psz_type = psz_buffer;
1400                     psz_buffer[0] = '\0';
1401                     for( i = 0; p_item->ppsz_list[i]; i++ )
1402                     {
1403                         if( i ) strcat( psz_buffer, "," );
1404                         strcat( psz_buffer, p_item->ppsz_list[i] );
1405                     }
1406                     psz_ket = "}";
1407                 }
1408                 break;
1409             case CONFIG_ITEM_INTEGER:
1410                 print_help_section( p_parser, p_section, b_color,
1411                                     b_description );
1412                 p_section = NULL;
1413                 psz_bra = OPTION_VALUE_SEP "<";
1414                 psz_type = _("integer");
1415                 psz_ket = ">";
1416
1417                 if( p_item->min.i || p_item->max.i )
1418                 {
1419                     sprintf( psz_buffer, "%s [%"PRId64" .. %"PRId64"]",
1420                              psz_type, p_item->min.i, p_item->max.i );
1421                     psz_type = psz_buffer;
1422                 }
1423
1424                 if( p_item->i_list )
1425                 {
1426                     psz_bra = OPTION_VALUE_SEP "{";
1427                     psz_type = psz_buffer;
1428                     psz_buffer[0] = '\0';
1429                     for( i = 0; p_item->ppsz_list_text[i]; i++ )
1430                     {
1431                         if( i ) strcat( psz_buffer, ", " );
1432                         sprintf( psz_buffer + strlen(psz_buffer), "%i (%s)",
1433                                  p_item->pi_list[i],
1434                                  module_gettext( p_parser, p_item->ppsz_list_text[i] ) );
1435                     }
1436                     psz_ket = "}";
1437                 }
1438                 break;
1439             case CONFIG_ITEM_FLOAT:
1440                 print_help_section( p_parser, p_section, b_color,
1441                                     b_description );
1442                 p_section = NULL;
1443                 psz_bra = OPTION_VALUE_SEP "<";
1444                 psz_type = _("float");
1445                 psz_ket = ">";
1446                 if( p_item->min.f || p_item->max.f )
1447                 {
1448                     sprintf( psz_buffer, "%s [%f .. %f]", psz_type,
1449                              p_item->min.f, p_item->max.f );
1450                     psz_type = psz_buffer;
1451                 }
1452                 break;
1453             case CONFIG_ITEM_BOOL:
1454                 print_help_section( p_parser, p_section, b_color,
1455                                     b_description );
1456                 p_section = NULL;
1457                 psz_bra = ""; psz_type = ""; psz_ket = "";
1458                 if( !b_help_module )
1459                 {
1460                     psz_suf = p_item->value.i ? _(" (default enabled)") :
1461                                                 _(" (default disabled)");
1462                 }
1463                 break;
1464             }
1465
1466             if( !psz_type )
1467             {
1468                 continue;
1469             }
1470
1471             /* Add short option if any */
1472             if( p_item->i_short )
1473             {
1474                 sprintf( psz_short, "-%c,", p_item->i_short );
1475             }
1476             else
1477             {
1478                 strcpy( psz_short, "   " );
1479             }
1480
1481             i = PADDING_SPACES - strlen( p_item->psz_name )
1482                  - strlen( psz_bra ) - strlen( psz_type )
1483                  - strlen( psz_ket ) - 1;
1484
1485             if( CONFIG_CLASS(p_item->i_type) == CONFIG_ITEM_BOOL
1486              && !b_help_module )
1487             {
1488                 psz_prefix =  ", --no-";
1489                 i -= strlen( p_item->psz_name ) + strlen( psz_prefix );
1490             }
1491
1492             if( i < 0 )
1493             {
1494                 psz_spaces[0] = '\n';
1495                 i = 0;
1496             }
1497             else
1498             {
1499                 psz_spaces[i] = '\0';
1500             }
1501
1502             if( CONFIG_CLASS(p_item->i_type) == CONFIG_ITEM_BOOL
1503              && !b_help_module )
1504             {
1505                 utf8_fprintf( stdout, psz_format_bool, psz_short,
1506                               p_item->psz_name, psz_prefix, p_item->psz_name,
1507                               psz_bra, psz_type, psz_ket, psz_spaces );
1508             }
1509             else
1510             {
1511                 utf8_fprintf( stdout, psz_format, psz_short, p_item->psz_name,
1512                          "", "", psz_bra, psz_type, psz_ket, psz_spaces );
1513             }
1514
1515             psz_spaces[i] = ' ';
1516
1517             /* We wrap the rest of the output */
1518             sprintf( psz_buffer, "%s%s", module_gettext( p_parser, p_item->psz_text ),
1519                      psz_suf );
1520             b_description_hack = b_description;
1521
1522  description:
1523             psz_text = psz_buffer;
1524             i_cur_width = b_description && !b_description_hack
1525                           ? i_width_description
1526                           : i_width;
1527             if( !*psz_text ) strcpy(psz_text, " ");
1528             while( *psz_text )
1529             {
1530                 char *psz_parser, *psz_word;
1531                 size_t i_end = strlen( psz_text );
1532
1533                 /* If the remaining text fits in a line, print it. */
1534                 if( i_end <= i_cur_width )
1535                 {
1536                     if( b_color )
1537                     {
1538                         if( !b_description || b_description_hack )
1539                             utf8_fprintf( stdout, BLUE"%s\n"GRAY, psz_text );
1540                         else
1541                             utf8_fprintf( stdout, "%s\n", psz_text );
1542                     }
1543                     else
1544                     {
1545                         utf8_fprintf( stdout, "%s\n", psz_text );
1546                     }
1547                     break;
1548                 }
1549
1550                 /* Otherwise, eat as many words as possible */
1551                 psz_parser = psz_text;
1552                 do
1553                 {
1554                     psz_word = psz_parser;
1555                     psz_parser = strchr( psz_word, ' ' );
1556                     /* If no space was found, we reached the end of the text
1557                      * block; otherwise, we skip the space we just found. */
1558                     psz_parser = psz_parser ? psz_parser + 1
1559                                             : psz_text + i_end;
1560
1561                 } while( (size_t)(psz_parser - psz_text) <= i_cur_width );
1562
1563                 /* We cut a word in one of these cases:
1564                  *  - it's the only word in the line and it's too long.
1565                  *  - we used less than 80% of the width and the word we are
1566                  *    going to wrap is longer than 40% of the width, and even
1567                  *    if the word would have fit in the next line. */
1568                 if( psz_word == psz_text
1569              || ( (size_t)(psz_word - psz_text) < 80 * i_cur_width / 100
1570              && (size_t)(psz_parser - psz_word) > 40 * i_cur_width / 100 ) )
1571                 {
1572                     char c = psz_text[i_cur_width];
1573                     psz_text[i_cur_width] = '\0';
1574                     if( b_color )
1575                     {
1576                         if( !b_description || b_description_hack )
1577                             utf8_fprintf( stdout, BLUE"%s\n%s"GRAY,
1578                                           psz_text, psz_spaces );
1579                         else
1580                             utf8_fprintf( stdout, "%s\n%s",
1581                                           psz_text, psz_spaces );
1582                     }
1583                     else
1584                     {
1585                         utf8_fprintf( stdout, "%s\n%s", psz_text, psz_spaces );
1586                     }
1587                     psz_text += i_cur_width;
1588                     psz_text[0] = c;
1589                 }
1590                 else
1591                 {
1592                     psz_word[-1] = '\0';
1593                     if( b_color )
1594                     {
1595                         if( !b_description || b_description_hack )
1596                             utf8_fprintf( stdout, BLUE"%s\n%s"GRAY,
1597                                           psz_text, psz_spaces );
1598                         else
1599                             utf8_fprintf( stdout, "%s\n%s",
1600                                           psz_text, psz_spaces );
1601                     }
1602                     else
1603                     {
1604                         utf8_fprintf( stdout, "%s\n%s", psz_text, psz_spaces );
1605                     }
1606                     psz_text = psz_word;
1607                 }
1608             }
1609
1610             if( b_description_hack && p_item->psz_longtext )
1611             {
1612                 sprintf( psz_buffer, "%s%s",
1613                          module_gettext( p_parser, p_item->psz_longtext ),
1614                          psz_suf );
1615                 b_description_hack = false;
1616                 psz_spaces = psz_spaces_longtext;
1617                 utf8_fprintf( stdout, "%s", psz_spaces );
1618                 goto description;
1619             }
1620         }
1621     }
1622
1623     if( b_has_advanced )
1624     {
1625         if( b_color )
1626             utf8_fprintf( stdout, "\n" WHITE "%s" GRAY " %s\n", _( "Note:" ),
1627            _( "add --advanced to your command line to see advanced options."));
1628         else
1629             utf8_fprintf( stdout, "\n%s %s\n", _( "Note:" ),
1630            _( "add --advanced to your command line to see advanced options."));
1631     }
1632
1633     if( i_only_advanced > 0 )
1634     {
1635         if( b_color )
1636         {
1637             utf8_fprintf( stdout, "\n" WHITE "%s" GRAY " ", _( "Note:" ) );
1638             utf8_fprintf( stdout, _( "%d module(s) were not displayed because they only have advanced options.\n" ), i_only_advanced );
1639         }
1640         else
1641         {
1642             utf8_fprintf( stdout, "\n%s ", _( "Note:" ) );
1643             utf8_fprintf( stdout, _( "%d module(s) were not displayed because they only have advanced options.\n" ), i_only_advanced );
1644         }
1645     }
1646     else if( !b_found )
1647     {
1648         if( b_color )
1649             utf8_fprintf( stdout, "\n" WHITE "%s" GRAY "\n",
1650                        _( "No matching module found. Use --list or " \
1651                           "--list-verbose to list available modules." ) );
1652         else
1653             utf8_fprintf( stdout, "\n%s\n",
1654                        _( "No matching module found. Use --list or " \
1655                           "--list-verbose to list available modules." ) );
1656     }
1657
1658     /* Release the module list */
1659     module_list_free (list);
1660 }
1661
1662 /*****************************************************************************
1663  * ListModules: list the available modules with their description
1664  *****************************************************************************
1665  * Print a list of all available modules (builtins and plugins) and a short
1666  * description for each one.
1667  *****************************************************************************/
1668 static void ListModules( libvlc_int_t *p_this, bool b_verbose )
1669 {
1670     module_t *p_parser;
1671
1672     bool b_color = var_InheritBool( p_this, "color" );
1673
1674 #ifdef WIN32
1675     ShowConsole( true );
1676     b_color = false; // don't put color control codes in a .txt file
1677 #else
1678     if( !isatty( 1 ) )
1679         b_color = false;
1680 #endif
1681
1682     /* List all modules */
1683     module_t **list = module_list_get (NULL);
1684
1685     /* Enumerate each module */
1686     for (size_t j = 0; (p_parser = list[j]) != NULL; j++)
1687     {
1688         const char *objname = module_get_object (p_parser);
1689         if( b_color )
1690             utf8_fprintf( stdout, GREEN"  %-22s "WHITE"%s\n"GRAY, objname,
1691                           module_gettext( p_parser, p_parser->psz_longname ) );
1692         else
1693             utf8_fprintf( stdout, "  %-22s %s\n", objname,
1694                           module_gettext( p_parser, p_parser->psz_longname ) );
1695
1696         if( b_verbose )
1697         {
1698             char *const *pp_shortcuts = p_parser->pp_shortcuts;
1699             for( unsigned i = 0; i < p_parser->i_shortcuts; i++ )
1700             {
1701                 if( strcmp( pp_shortcuts[i], objname ) )
1702                 {
1703                     if( b_color )
1704                         utf8_fprintf( stdout, CYAN"   s %s\n"GRAY,
1705                                       pp_shortcuts[i] );
1706                     else
1707                         utf8_fprintf( stdout, "   s %s\n",
1708                                       pp_shortcuts[i] );
1709                 }
1710             }
1711             if( p_parser->psz_capability )
1712             {
1713                 if( b_color )
1714                     utf8_fprintf( stdout, MAGENTA"   c %s (%d)\n"GRAY,
1715                                   p_parser->psz_capability,
1716                                   p_parser->i_score );
1717                 else
1718                     utf8_fprintf( stdout, "   c %s (%d)\n",
1719                                   p_parser->psz_capability,
1720                                   p_parser->i_score );
1721             }
1722         }
1723     }
1724     module_list_free (list);
1725
1726 #ifdef WIN32        /* Pause the console because it's destroyed when we exit */
1727     PauseConsole();
1728 #endif
1729 }
1730
1731 /*****************************************************************************
1732  * Version: print complete program version
1733  *****************************************************************************
1734  * Print complete program version and build number.
1735  *****************************************************************************/
1736 static void Version( void )
1737 {
1738 #ifdef WIN32
1739     ShowConsole( true );
1740 #endif
1741
1742     utf8_fprintf( stdout, _("VLC version %s (%s)\n"), VERSION_MESSAGE,
1743                   psz_vlc_changeset );
1744     utf8_fprintf( stdout, _("Compiled by %s on %s (%s)\n"),
1745              VLC_CompileBy(), VLC_CompileHost(), __DATE__" "__TIME__ );
1746     utf8_fprintf( stdout, _("Compiler: %s\n"), VLC_Compiler() );
1747     utf8_fprintf( stdout, "%s", LICENSE_MSG );
1748
1749 #ifdef WIN32        /* Pause the console because it's destroyed when we exit */
1750     PauseConsole();
1751 #endif
1752 }
1753
1754 /*****************************************************************************
1755  * ShowConsole: On Win32, create an output console for debug messages
1756  *****************************************************************************
1757  * This function is useful only on Win32.
1758  *****************************************************************************/
1759 #ifdef WIN32 /*  */
1760 static void ShowConsole( bool b_dofile )
1761 {
1762 #   ifndef UNDER_CE
1763     FILE *f_help = NULL;
1764
1765     if( getenv( "PWD" ) ) return; /* Cygwin shell or Wine */
1766
1767     AllocConsole();
1768     /* Use the ANSI code page (e.g. Windows-1252) as expected by the LibVLC
1769      * Unicode/locale subsystem. By default, we have the obsolecent OEM code
1770      * page (e.g. CP437 or CP850). */
1771     SetConsoleOutputCP (GetACP ());
1772     SetConsoleTitle ("VLC media player version "PACKAGE_VERSION);
1773
1774     freopen( "CONOUT$", "w", stderr );
1775     freopen( "CONIN$", "r", stdin );
1776
1777     if( b_dofile && (f_help = fopen( "vlc-help.txt", "wt" )) )
1778     {
1779         fclose( f_help );
1780         freopen( "vlc-help.txt", "wt", stdout );
1781         utf8_fprintf( stderr, _("\nDumped content to vlc-help.txt file.\n") );
1782     }
1783     else freopen( "CONOUT$", "w", stdout );
1784
1785 #   endif
1786 }
1787 #endif
1788
1789 /*****************************************************************************
1790  * PauseConsole: On Win32, wait for a key press before closing the console
1791  *****************************************************************************
1792  * This function is useful only on Win32.
1793  *****************************************************************************/
1794 #ifdef WIN32 /*  */
1795 static void PauseConsole( void )
1796 {
1797 #   ifndef UNDER_CE
1798
1799     if( getenv( "PWD" ) ) return; /* Cygwin shell or Wine */
1800
1801     utf8_fprintf( stderr, _("\nPress the RETURN key to continue...\n") );
1802     getchar();
1803     fclose( stdout );
1804
1805 #   endif
1806 }
1807 #endif
1808
1809 /*****************************************************************************
1810  * ConsoleWidth: Return the console width in characters
1811  *****************************************************************************
1812  * We use the stty shell command to get the console width; if this fails or
1813  * if the width is less than 80, we default to 80.
1814  *****************************************************************************/
1815 static int ConsoleWidth( void )
1816 {
1817     unsigned i_width = 80;
1818
1819 #ifndef WIN32
1820     FILE *file = popen( "stty size 2>/dev/null", "r" );
1821     if (file != NULL)
1822     {
1823         if (fscanf (file, "%*u %u", &i_width) <= 0)
1824             i_width = 80;
1825         pclose( file );
1826     }
1827 #elif !defined (UNDER_CE)
1828     CONSOLE_SCREEN_BUFFER_INFO buf;
1829
1830     if (GetConsoleScreenBufferInfo (GetStdHandle (STD_OUTPUT_HANDLE), &buf))
1831         i_width = buf.dwSize.X;
1832 #endif
1833
1834     return i_width;
1835 }