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