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