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