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