]> git.sesse.net Git - vlc/blob - src/libvlc.c
Obsolete thread-unsafe command line options for CPU capabilities
[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     PRINT_CAPABILITY( CPU_CAPABILITY_MMX, "MMX" );
681     PRINT_CAPABILITY( CPU_CAPABILITY_3DNOW, "3DNow!" );
682     PRINT_CAPABILITY( CPU_CAPABILITY_MMXEXT, "MMXEXT" );
683     PRINT_CAPABILITY( CPU_CAPABILITY_SSE, "SSE" );
684     PRINT_CAPABILITY( CPU_CAPABILITY_SSE2, "SSE2" );
685     PRINT_CAPABILITY( CPU_CAPABILITY_SSE3, "SSE3" );
686     PRINT_CAPABILITY( CPU_CAPABILITY_SSSE3, "SSSE3" );
687     PRINT_CAPABILITY( CPU_CAPABILITY_SSE4_1, "SSE4.1" );
688     PRINT_CAPABILITY( CPU_CAPABILITY_SSE4_2, "SSE4.2" );
689     PRINT_CAPABILITY( CPU_CAPABILITY_SSE4A,  "SSE4A" );
690
691 #elif defined( __powerpc__ ) || defined( __ppc__ ) || defined( __ppc64__ )
692     PRINT_CAPABILITY( CPU_CAPABILITY_ALTIVEC, "AltiVec" );
693
694 #elif defined( __arm__ )
695     PRINT_CAPABILITY( CPU_CAPABILITY_NEON, "NEONv1" );
696
697 #endif
698
699 #if HAVE_FPU
700     strncat( p_capabilities, "FPU ",
701              sizeof(p_capabilities) - strlen( p_capabilities) );
702     p_capabilities[sizeof(p_capabilities) - 1] = '\0';
703 #endif
704
705     if (p_capabilities[0])
706         msg_Dbg( p_libvlc, "CPU has capabilities %s", p_capabilities );
707
708     /*
709      * Choose the best memcpy module
710      */
711     priv->p_memcpy_module = module_need( p_libvlc, "memcpy", "$memcpy", false );
712     /* Avoid being called "memcpy":*/
713     vlc_object_set_name( p_libvlc, "main" );
714
715     priv->b_stats = var_InheritBool( p_libvlc, "stats" );
716     priv->i_timers = 0;
717     priv->pp_timers = NULL;
718
719     /*
720      * Initialize hotkey handling
721      */
722     priv->actions = vlc_InitActions( p_libvlc );
723
724     /* Create a variable for showing the fullscreen interface */
725     var_Create( p_libvlc, "intf-show", VLC_VAR_BOOL );
726     var_SetBool( p_libvlc, "intf-show", true );
727
728     /* Create a variable for showing the right click menu */
729     var_Create( p_libvlc, "intf-popupmenu", VLC_VAR_BOOL );
730
731     /* variables for signalling creation of new files */
732     var_Create( p_libvlc, "snapshot-file", VLC_VAR_STRING );
733     var_Create( p_libvlc, "record-file", VLC_VAR_STRING );
734
735     /* some default internal settings */
736     var_Create( p_libvlc, "window", VLC_VAR_STRING );
737     var_Create( p_libvlc, "user-agent", VLC_VAR_STRING );
738     var_SetString( p_libvlc, "user-agent", "(LibVLC "VERSION")" );
739
740     /* Initialize playlist and get commandline files */
741     p_playlist = playlist_Create( VLC_OBJECT(p_libvlc) );
742     if( !p_playlist )
743     {
744         msg_Err( p_libvlc, "playlist initialization failed" );
745         if( priv->p_memcpy_module != NULL )
746         {
747             module_unneed( p_libvlc, priv->p_memcpy_module );
748         }
749         module_EndBank (true);
750         return VLC_EGENERIC;
751     }
752
753     /* System specific configuration */
754     system_Configure( p_libvlc, i_argc - vlc_optind, ppsz_argv + vlc_optind );
755
756 #if defined(MEDIA_LIBRARY)
757     /* Get the ML */
758     if( var_GetBool( p_libvlc, "load-media-library-on-startup" ) )
759     {
760         priv->p_ml = ml_Create( VLC_OBJECT( p_libvlc ), NULL );
761         if( !priv->p_ml )
762         {
763             msg_Err( p_libvlc, "ML initialization failed" );
764             return VLC_EGENERIC;
765         }
766     }
767     else
768     {
769         priv->p_ml = NULL;
770     }
771 #endif
772
773     /* Add service discovery modules */
774     psz_modules = var_InheritString( p_libvlc, "services-discovery" );
775     if( psz_modules )
776     {
777         char *p = psz_modules, *m;
778         while( ( m = strsep( &p, " :," ) ) != NULL )
779             playlist_ServicesDiscoveryAdd( p_playlist, m );
780         free( psz_modules );
781     }
782
783 #ifdef ENABLE_VLM
784     /* Initialize VLM if vlm-conf is specified */
785     psz_parser = var_CreateGetNonEmptyString( p_libvlc, "vlm-conf" );
786     if( psz_parser )
787     {
788         priv->p_vlm = vlm_New( p_libvlc );
789         if( !priv->p_vlm )
790             msg_Err( p_libvlc, "VLM initialization failed" );
791     }
792     free( psz_parser );
793 #endif
794
795     /*
796      * Load background interfaces
797      */
798     psz_modules = var_CreateGetNonEmptyString( p_libvlc, "extraintf" );
799     psz_control = var_CreateGetNonEmptyString( p_libvlc, "control" );
800
801     if( psz_modules && psz_control )
802     {
803         char* psz_tmp;
804         if( asprintf( &psz_tmp, "%s:%s", psz_modules, psz_control ) != -1 )
805         {
806             free( psz_modules );
807             psz_modules = psz_tmp;
808         }
809     }
810     else if( psz_control )
811     {
812         free( psz_modules );
813         psz_modules = strdup( psz_control );
814     }
815
816     psz_parser = psz_modules;
817     while ( psz_parser && *psz_parser )
818     {
819         char *psz_module, *psz_temp;
820         psz_module = psz_parser;
821         psz_parser = strchr( psz_module, ':' );
822         if ( psz_parser )
823         {
824             *psz_parser = '\0';
825             psz_parser++;
826         }
827         if( asprintf( &psz_temp, "%s,none", psz_module ) != -1)
828         {
829             intf_Create( p_libvlc, psz_temp );
830             free( psz_temp );
831         }
832     }
833     free( psz_modules );
834     free( psz_control );
835
836     /*
837      * Always load the hotkeys interface if it exists
838      */
839     intf_Create( p_libvlc, "hotkeys,none" );
840
841 #ifdef HAVE_DBUS
842     /* loads dbus control interface if in one-instance mode
843      * we do it only when playlist exists, because dbus module needs it */
844     if( var_InheritBool( p_libvlc, "one-instance" )
845      || ( var_InheritBool( p_libvlc, "one-instance-when-started-from-file" )
846        && var_InheritBool( p_libvlc, "started-from-file" ) ) )
847         intf_Create( p_libvlc, "dbus,none" );
848
849 # if !defined (HAVE_MAEMO)
850     /* Prevents the power management daemon from suspending the system
851      * when VLC is active */
852     if( var_InheritBool( p_libvlc, "inhibit" ) > 0 )
853         intf_Create( p_libvlc, "inhibit,none" );
854 # endif
855 #endif
856
857     if( var_InheritBool( p_libvlc, "file-logging" ) &&
858         !var_InheritBool( p_libvlc, "syslog" ) )
859     {
860         intf_Create( p_libvlc, "logger,none" );
861     }
862 #ifdef HAVE_SYSLOG_H
863     if( var_InheritBool( p_libvlc, "syslog" ) )
864     {
865         char *logmode = var_CreateGetNonEmptyString( p_libvlc, "logmode" );
866         var_SetString( p_libvlc, "logmode", "syslog" );
867         intf_Create( p_libvlc, "logger,none" );
868
869         if( logmode )
870         {
871             var_SetString( p_libvlc, "logmode", logmode );
872             free( logmode );
873         }
874         var_Destroy( p_libvlc, "logmode" );
875     }
876 #endif
877
878     if( var_InheritBool( p_libvlc, "network-synchronisation") )
879     {
880         intf_Create( p_libvlc, "netsync,none" );
881     }
882
883 #ifdef __APPLE__
884     var_Create( p_libvlc, "drawable-view-top", VLC_VAR_INTEGER );
885     var_Create( p_libvlc, "drawable-view-left", VLC_VAR_INTEGER );
886     var_Create( p_libvlc, "drawable-view-bottom", VLC_VAR_INTEGER );
887     var_Create( p_libvlc, "drawable-view-right", VLC_VAR_INTEGER );
888     var_Create( p_libvlc, "drawable-clip-top", VLC_VAR_INTEGER );
889     var_Create( p_libvlc, "drawable-clip-left", VLC_VAR_INTEGER );
890     var_Create( p_libvlc, "drawable-clip-bottom", VLC_VAR_INTEGER );
891     var_Create( p_libvlc, "drawable-clip-right", VLC_VAR_INTEGER );
892     var_Create( p_libvlc, "drawable-nsobject", VLC_VAR_ADDRESS );
893 #endif
894 #ifdef WIN32
895     var_Create( p_libvlc, "drawable-hwnd", VLC_VAR_INTEGER );
896 #endif
897
898     /*
899      * Get input filenames given as commandline arguments.
900      * We assume that the remaining parameters are filenames
901      * and their input options.
902      */
903     GetFilenames( p_libvlc, i_argc - vlc_optind, ppsz_argv + vlc_optind );
904
905     /*
906      * Get --open argument
907      */
908     psz_val = var_InheritString( p_libvlc, "open" );
909     if ( psz_val != NULL )
910     {
911         playlist_AddExt( p_playlist, psz_val, NULL, PLAYLIST_INSERT, 0,
912                          -1, 0, NULL, 0, true, pl_Unlocked );
913         free( psz_val );
914     }
915
916     return VLC_SUCCESS;
917 }
918
919 /**
920  * Cleanup a libvlc instance. The instance is not completely deallocated
921  * \param p_libvlc the instance to clean
922  */
923 void libvlc_InternalCleanup( libvlc_int_t *p_libvlc )
924 {
925     libvlc_priv_t *priv = libvlc_priv (p_libvlc);
926     playlist_t    *p_playlist = libvlc_priv (p_libvlc)->p_playlist;
927
928     /* Deactivate the playlist */
929     msg_Dbg( p_libvlc, "deactivating the playlist" );
930     pl_Deactivate( p_libvlc );
931
932     /* Remove all services discovery */
933     msg_Dbg( p_libvlc, "removing all services discovery tasks" );
934     playlist_ServicesDiscoveryKillAll( p_playlist );
935
936     /* Ask the interfaces to stop and destroy them */
937     msg_Dbg( p_libvlc, "removing all interfaces" );
938     libvlc_Quit( p_libvlc );
939     intf_DestroyAll( p_libvlc );
940
941 #ifdef ENABLE_VLM
942     /* Destroy VLM if created in libvlc_InternalInit */
943     if( priv->p_vlm )
944     {
945         vlm_Delete( priv->p_vlm );
946     }
947 #endif
948
949 #if defined(MEDIA_LIBRARY)
950     media_library_t* p_ml = priv->p_ml;
951     if( p_ml )
952     {
953         ml_Destroy( VLC_OBJECT( p_ml ) );
954         vlc_object_release( p_ml );
955         libvlc_priv(p_playlist->p_libvlc)->p_ml = NULL;
956     }
957 #endif
958
959     /* Free playlist now, all threads are gone */
960     playlist_Destroy( p_playlist );
961     stats_TimersDumpAll( p_libvlc );
962     stats_TimersCleanAll( p_libvlc );
963
964     msg_Dbg( p_libvlc, "removing stats" );
965
966 #ifndef WIN32
967     char* psz_pidfile = NULL;
968
969     if( b_daemon )
970     {
971         psz_pidfile = var_CreateGetNonEmptyString( p_libvlc, "pidfile" );
972         if( psz_pidfile != NULL )
973         {
974             msg_Dbg( p_libvlc, "removing pid file %s", psz_pidfile );
975             if( unlink( psz_pidfile ) == -1 )
976             {
977                 msg_Dbg( p_libvlc, "removing pid file %s: %m",
978                         psz_pidfile );
979             }
980         }
981         free( psz_pidfile );
982     }
983 #endif
984
985     if( priv->p_memcpy_module )
986     {
987         module_unneed( p_libvlc, priv->p_memcpy_module );
988         priv->p_memcpy_module = NULL;
989     }
990
991     /* Save the configuration */
992     if( !var_InheritBool( p_libvlc, "ignore-config" ) )
993         config_AutoSaveConfigFile( VLC_OBJECT(p_libvlc) );
994
995     /* Free module bank. It is refcounted, so we call this each time  */
996     module_EndBank (true);
997
998     vlc_DeinitActions( p_libvlc, priv->actions );
999 }
1000
1001 /**
1002  * Destroy everything.
1003  * This function requests the running threads to finish, waits for their
1004  * termination, and destroys their structure.
1005  * It stops the thread systems: no instance can run after this has run
1006  * \param p_libvlc the instance to destroy
1007  */
1008 void libvlc_InternalDestroy( libvlc_int_t *p_libvlc )
1009 {
1010     libvlc_priv_t *priv = libvlc_priv( p_libvlc );
1011
1012     vlc_mutex_lock( &global_lock );
1013     i_instances--;
1014
1015     if( i_instances == 0 )
1016     {
1017         /* System specific cleaning code */
1018         system_End( );
1019     }
1020     vlc_mutex_unlock( &global_lock );
1021
1022     /* Destroy mutexes */
1023     vlc_ExitDestroy( &priv->exit );
1024     vlc_mutex_destroy( &priv->timer_lock );
1025     vlc_mutex_destroy( &priv->ml_lock );
1026
1027 #ifndef NDEBUG /* Hack to dump leaked objects tree */
1028     if( vlc_internals( p_libvlc )->i_refcount > 1 )
1029         while( vlc_internals( p_libvlc )->i_refcount > 0 )
1030             vlc_object_release( p_libvlc );
1031 #endif
1032
1033     assert( vlc_internals( p_libvlc )->i_refcount == 1 );
1034     vlc_object_release( p_libvlc );
1035 }
1036
1037 /**
1038  * Add an interface plugin and run it
1039  */
1040 int libvlc_InternalAddIntf( libvlc_int_t *p_libvlc, char const *psz_module )
1041 {
1042     if( !p_libvlc )
1043         return VLC_EGENERIC;
1044
1045     if( !psz_module ) /* requesting the default interface */
1046     {
1047         char *psz_interface = var_CreateGetNonEmptyString( p_libvlc, "intf" );
1048         if( !psz_interface ) /* "intf" has not been set */
1049         {
1050 #ifndef WIN32
1051             if( b_daemon )
1052                  /* Daemon mode hack.
1053                   * We prefer the dummy interface if none is specified. */
1054                 psz_module = "dummy";
1055             else
1056 #endif
1057                 msg_Info( p_libvlc, "%s",
1058                           _("Running vlc with the default interface. "
1059                             "Use 'cvlc' to use vlc without interface.") );
1060         }
1061         free( psz_interface );
1062         var_Destroy( p_libvlc, "intf" );
1063     }
1064
1065     /* Try to create the interface */
1066     int ret = intf_Create( p_libvlc, psz_module ? psz_module : "$intf" );
1067     if( ret )
1068         msg_Err( p_libvlc, "interface \"%s\" initialization failed",
1069                  psz_module ? psz_module : "default" );
1070     return ret;
1071 }
1072
1073 #if defined( ENABLE_NLS ) && (defined (__APPLE__) || defined (WIN32)) && \
1074     ( defined( HAVE_GETTEXT ) || defined( HAVE_INCLUDED_GETTEXT ) )
1075 /*****************************************************************************
1076  * SetLanguage: set the interface language.
1077  *****************************************************************************
1078  * We set the LC_MESSAGES locale category for interface messages and buttons,
1079  * as well as the LC_CTYPE category for string sorting and possible wide
1080  * character support.
1081  *****************************************************************************/
1082 static void SetLanguage ( const char *psz_lang )
1083 {
1084 #ifdef __APPLE__
1085     /* I need that under Darwin, please check it doesn't disturb
1086      * other platforms. --Meuuh */
1087     setenv( "LANG", psz_lang, 1 );
1088
1089 #else
1090     /* We set LC_ALL manually because it is the only way to set
1091      * the language at runtime under eg. Windows. Beware that this
1092      * makes the environment unconsistent when libvlc is unloaded and
1093      * should probably be moved to a safer place like vlc.c. */
1094     setenv( "LC_ALL", psz_lang, 1 );
1095
1096 #endif
1097
1098     setlocale( LC_ALL, psz_lang );
1099 }
1100 #endif
1101
1102 /*****************************************************************************
1103  * GetFilenames: parse command line options which are not flags
1104  *****************************************************************************
1105  * Parse command line for input files as well as their associated options.
1106  * An option always follows its associated input and begins with a ":".
1107  *****************************************************************************/
1108 static void GetFilenames( libvlc_int_t *p_vlc, unsigned n,
1109                           const char *const args[] )
1110 {
1111     while( n > 0 )
1112     {
1113         /* Count the input options */
1114         unsigned i_options = 0;
1115
1116         while( args[--n][0] == ':' )
1117         {
1118             i_options++;
1119             if( n == 0 )
1120             {
1121                 msg_Warn( p_vlc, "options %s without item", args[n] );
1122                 return; /* syntax!? */
1123             }
1124         }
1125
1126         char *mrl = make_URI( args[n], NULL );
1127         if( !mrl )
1128             continue;
1129
1130         playlist_AddExt( pl_Get( p_vlc ), mrl, NULL, PLAYLIST_INSERT,
1131                 0, -1, i_options, ( i_options ? &args[n + 1] : NULL ),
1132                 VLC_INPUT_OPTION_TRUSTED, true, pl_Unlocked );
1133         free( mrl );
1134     }
1135 }
1136
1137 /*****************************************************************************
1138  * Help: print program help
1139  *****************************************************************************
1140  * Print a short inline help. Message interface is initialized at this stage.
1141  *****************************************************************************/
1142 static inline void print_help_on_full_help( void )
1143 {
1144     utf8_fprintf( stdout, "\n" );
1145     utf8_fprintf( stdout, "%s\n", _("To get exhaustive help, use '-H'.") );
1146 }
1147
1148 static const char vlc_usage[] = N_(
1149                             "Usage: %s [options] [stream] ..."
1150                             "\nYou can specify multiple streams on the commandline. They will be enqueued in the playlist."
1151                             "\nThe first item specified will be played first."
1152                             "\n"
1153                             "\nOptions-styles:"
1154                             "\n  --option  A global option that is set for the duration of the program."
1155                             "\n   -option  A single letter version of a global --option."
1156                             "\n   :option  An option that only applies to the stream directly before it"
1157                             "\n            and that overrides previous settings."
1158                             "\n"
1159                             "\nStream MRL syntax:"
1160                             "\n  [[access][/demux]://]URL[@[title][:chapter][-[title][:chapter]]] [:option=value ...]"
1161                             "\n"
1162                             "\n  Many of the global --options can also be used as MRL specific :options."
1163                             "\n  Multiple :option=value pairs can be specified."
1164                             "\n"
1165                             "\nURL syntax:"
1166                             "\n  [file://]filename              Plain media file"
1167                             "\n  http://ip:port/file            HTTP URL"
1168                             "\n  ftp://ip:port/file             FTP URL"
1169                             "\n  mms://ip:port/file             MMS URL"
1170                             "\n  screen://                      Screen capture"
1171                             "\n  [dvd://][device][@raw_device]  DVD device"
1172                             "\n  [vcd://][device]               VCD device"
1173                             "\n  [cdda://][device]              Audio CD device"
1174                             "\n  udp://[[<source address>]@[<bind address>][:<bind port>]]"
1175                             "\n                                 UDP stream sent by a streaming server"
1176                             "\n  vlc://pause:<seconds>          Special item to pause the playlist for a certain time"
1177                             "\n  vlc://quit                     Special item to quit VLC"
1178                             "\n");
1179
1180 static void Help( libvlc_int_t *p_this, char const *psz_help_name )
1181 {
1182 #ifdef WIN32
1183     ShowConsole( true );
1184 #endif
1185
1186     if( psz_help_name && !strcmp( psz_help_name, "help" ) )
1187     {
1188         utf8_fprintf( stdout, vlc_usage, "vlc" );
1189         Usage( p_this, "=help" );
1190         Usage( p_this, "=main" );
1191         print_help_on_full_help();
1192     }
1193     else if( psz_help_name && !strcmp( psz_help_name, "longhelp" ) )
1194     {
1195         utf8_fprintf( stdout, vlc_usage, "vlc" );
1196         Usage( p_this, NULL );
1197         print_help_on_full_help();
1198     }
1199     else if( psz_help_name && !strcmp( psz_help_name, "full-help" ) )
1200     {
1201         utf8_fprintf( stdout, vlc_usage, "vlc" );
1202         Usage( p_this, NULL );
1203     }
1204     else if( psz_help_name )
1205     {
1206         Usage( p_this, psz_help_name );
1207     }
1208
1209 #ifdef WIN32        /* Pause the console because it's destroyed when we exit */
1210     PauseConsole();
1211 #endif
1212     fflush( stdout );
1213 }
1214
1215 /*****************************************************************************
1216  * Usage: print module usage
1217  *****************************************************************************
1218  * Print a short inline help. Message interface is initialized at this stage.
1219  *****************************************************************************/
1220 #   define COL(x)  "\033[" #x ";1m"
1221 #   define RED     COL(31)
1222 #   define GREEN   COL(32)
1223 #   define YELLOW  COL(33)
1224 #   define BLUE    COL(34)
1225 #   define MAGENTA COL(35)
1226 #   define CYAN    COL(36)
1227 #   define WHITE   COL(0)
1228 #   define GRAY    "\033[0m"
1229 static void
1230 print_help_section( const module_t *m, const module_config_t *p_item,
1231                     bool b_color, bool b_description )
1232 {
1233     if( !p_item ) return;
1234     if( b_color )
1235     {
1236         utf8_fprintf( stdout, RED"   %s:\n"GRAY,
1237                       module_gettext( m, p_item->psz_text ) );
1238         if( b_description && p_item->psz_longtext )
1239             utf8_fprintf( stdout, MAGENTA"   %s\n"GRAY,
1240                           module_gettext( m, p_item->psz_longtext ) );
1241     }
1242     else
1243     {
1244         utf8_fprintf( stdout, "   %s:\n",
1245                       module_gettext( m, p_item->psz_text ) );
1246         if( b_description && p_item->psz_longtext )
1247             utf8_fprintf( stdout, "   %s\n",
1248                           module_gettext(m, p_item->psz_longtext ) );
1249     }
1250 }
1251
1252 static void Usage( libvlc_int_t *p_this, char const *psz_search )
1253 {
1254 #define FORMAT_STRING "  %s --%s%s%s%s%s%s%s "
1255     /* short option ------'    | | | | | | |
1256      * option name ------------' | | | | | |
1257      * <bra ---------------------' | | | | |
1258      * option type or "" ----------' | | | |
1259      * ket> -------------------------' | | |
1260      * padding spaces -----------------' | |
1261      * comment --------------------------' |
1262      * comment suffix ---------------------'
1263      *
1264      * The purpose of having bra and ket is that we might i18n them as well.
1265      */
1266
1267 #define COLOR_FORMAT_STRING (WHITE"  %s --%s"YELLOW"%s%s%s%s%s%s "GRAY)
1268 #define COLOR_FORMAT_STRING_BOOL (WHITE"  %s --%s%s%s%s%s%s%s "GRAY)
1269
1270 #define LINE_START 8
1271 #define PADDING_SPACES 25
1272 #ifdef WIN32
1273 #   define OPTION_VALUE_SEP "="
1274 #else
1275 #   define OPTION_VALUE_SEP " "
1276 #endif
1277     char psz_spaces_text[PADDING_SPACES+LINE_START+1];
1278     char psz_spaces_longtext[LINE_START+3];
1279     char psz_format[sizeof(COLOR_FORMAT_STRING)];
1280     char psz_format_bool[sizeof(COLOR_FORMAT_STRING_BOOL)];
1281     char psz_buffer[10000];
1282     char psz_short[4];
1283     int i_width = ConsoleWidth() - (PADDING_SPACES+LINE_START+1);
1284     int i_width_description = i_width + PADDING_SPACES - 1;
1285     bool b_advanced    = var_InheritBool( p_this, "advanced" );
1286     bool b_description = var_InheritBool( p_this, "help-verbose" );
1287     bool b_description_hack;
1288     bool b_color       = var_InheritBool( p_this, "color" );
1289     bool b_has_advanced = false;
1290     bool b_found       = false;
1291     int  i_only_advanced = 0; /* Number of modules ignored because they
1292                                * only have advanced options */
1293     bool b_strict = psz_search && *psz_search == '=';
1294     if( b_strict ) psz_search++;
1295
1296     memset( psz_spaces_text, ' ', PADDING_SPACES+LINE_START );
1297     psz_spaces_text[PADDING_SPACES+LINE_START] = '\0';
1298     memset( psz_spaces_longtext, ' ', LINE_START+2 );
1299     psz_spaces_longtext[LINE_START+2] = '\0';
1300 #ifndef WIN32
1301     if( !isatty( 1 ) )
1302 #endif
1303         b_color = false; // don't put color control codes in a .txt file
1304
1305     if( b_color )
1306     {
1307         strcpy( psz_format, COLOR_FORMAT_STRING );
1308         strcpy( psz_format_bool, COLOR_FORMAT_STRING_BOOL );
1309     }
1310     else
1311     {
1312         strcpy( psz_format, FORMAT_STRING );
1313         strcpy( psz_format_bool, FORMAT_STRING );
1314     }
1315
1316     /* List all modules */
1317     module_t **list = module_list_get (NULL);
1318     if (!list)
1319         return;
1320
1321     /* Ugly hack to make sure that the help options always come first
1322      * (part 1) */
1323     if( !psz_search )
1324         Usage( p_this, "help" );
1325
1326     /* Enumerate the config for each module */
1327     for (size_t i = 0; list[i]; i++)
1328     {
1329         bool b_help_module;
1330         module_t *p_parser = list[i];
1331         module_config_t *p_item = NULL;
1332         module_config_t *p_section = NULL;
1333         module_config_t *p_end = p_parser->p_config + p_parser->confsize;
1334         const char *objname = module_get_object (p_parser);
1335
1336         if( psz_search &&
1337             ( b_strict ? strcmp( objname, psz_search )
1338                        : !strstr( objname, psz_search ) ) )
1339         {
1340             char *const *pp_shortcuts = p_parser->pp_shortcuts;
1341             unsigned i;
1342             for( i = 0; i < p_parser->i_shortcuts; i++ )
1343             {
1344                 if( b_strict ? !strcmp( psz_search, pp_shortcuts[i] )
1345                              : !!strstr( pp_shortcuts[i], psz_search ) )
1346                     break;
1347             }
1348             if( i == p_parser->i_shortcuts )
1349                 continue;
1350         }
1351
1352         /* Ignore modules without config options */
1353         if( !p_parser->i_config_items )
1354         {
1355             continue;
1356         }
1357
1358         b_help_module = !strcmp( "help", objname );
1359         /* Ugly hack to make sure that the help options always come first
1360          * (part 2) */
1361         if( !psz_search && b_help_module )
1362             continue;
1363
1364         /* Ignore modules with only advanced config options if requested */
1365         if( !b_advanced )
1366         {
1367             for( p_item = p_parser->p_config;
1368                  p_item < p_end;
1369                  p_item++ )
1370             {
1371                 if( CONFIG_ITEM(p_item->i_type) &&
1372                     !p_item->b_advanced && !p_item->b_removed ) break;
1373             }
1374
1375             if( p_item == p_end )
1376             {
1377                 i_only_advanced++;
1378                 continue;
1379             }
1380         }
1381
1382         b_found = true;
1383
1384         /* Print name of module */
1385         if( strcmp( "main", objname ) )
1386         {
1387             if( b_color )
1388                 utf8_fprintf( stdout, "\n " GREEN "%s" GRAY " (%s)\n",
1389                               module_gettext( p_parser, p_parser->psz_longname ),
1390                               objname );
1391             else
1392                 utf8_fprintf( stdout, "\n %s\n",
1393                               module_gettext(p_parser, p_parser->psz_longname ) );
1394         }
1395         if( p_parser->psz_help )
1396         {
1397             if( b_color )
1398                 utf8_fprintf( stdout, CYAN" %s\n"GRAY,
1399                               module_gettext( p_parser, p_parser->psz_help ) );
1400             else
1401                 utf8_fprintf( stdout, " %s\n",
1402                               module_gettext( p_parser, p_parser->psz_help ) );
1403         }
1404
1405         /* Print module options */
1406         for( p_item = p_parser->p_config;
1407              p_item < p_end;
1408              p_item++ )
1409         {
1410             char *psz_text, *psz_spaces = psz_spaces_text;
1411             const char *psz_bra = NULL, *psz_type = NULL, *psz_ket = NULL;
1412             const char *psz_suf = "", *psz_prefix = NULL;
1413             signed int i;
1414             size_t i_cur_width;
1415
1416             /* Skip removed options */
1417             if( p_item->b_removed )
1418             {
1419                 continue;
1420             }
1421             /* Skip advanced options if requested */
1422             if( p_item->b_advanced && !b_advanced )
1423             {
1424                 b_has_advanced = true;
1425                 continue;
1426             }
1427
1428             switch( CONFIG_CLASS(p_item->i_type) )
1429             {
1430             case 0: // hint class
1431                 switch( p_item->i_type )
1432                 {
1433                 case CONFIG_HINT_CATEGORY:
1434                 case CONFIG_HINT_USAGE:
1435                     if( !strcmp( "main", objname ) )
1436                     {
1437                         if( b_color )
1438                             utf8_fprintf( stdout, GREEN "\n %s\n" GRAY,
1439                                           module_gettext( p_parser, p_item->psz_text ) );
1440                         else
1441                             utf8_fprintf( stdout, "\n %s\n",
1442                                           module_gettext( p_parser, p_item->psz_text ) );
1443                     }
1444                     if( b_description && p_item->psz_longtext )
1445                     {
1446                         if( b_color )
1447                             utf8_fprintf( stdout, CYAN " %s\n" GRAY,
1448                                           module_gettext( p_parser, p_item->psz_longtext ) );
1449                         else
1450                             utf8_fprintf( stdout, " %s\n",
1451                                           module_gettext( p_parser, p_item->psz_longtext ) );
1452                 }
1453                 break;
1454
1455                 case CONFIG_HINT_SUBCATEGORY:
1456                     if( strcmp( "main", objname ) )
1457                         break;
1458                 case CONFIG_SECTION:
1459                     p_section = p_item;
1460                     break;
1461                 }
1462                 break;
1463
1464             case CONFIG_ITEM_STRING:
1465                 print_help_section( p_parser, p_section, b_color,
1466                                     b_description );
1467                 p_section = NULL;
1468                 psz_bra = OPTION_VALUE_SEP "<";
1469                 psz_type = _("string");
1470                 psz_ket = ">";
1471
1472                 if( p_item->ppsz_list )
1473                 {
1474                     psz_bra = OPTION_VALUE_SEP "{";
1475                     psz_type = psz_buffer;
1476                     psz_buffer[0] = '\0';
1477                     for( i = 0; p_item->ppsz_list[i]; i++ )
1478                     {
1479                         if( i ) strcat( psz_buffer, "," );
1480                         strcat( psz_buffer, p_item->ppsz_list[i] );
1481                     }
1482                     psz_ket = "}";
1483                 }
1484                 break;
1485             case CONFIG_ITEM_INTEGER:
1486                 print_help_section( p_parser, p_section, b_color,
1487                                     b_description );
1488                 p_section = NULL;
1489                 psz_bra = OPTION_VALUE_SEP "<";
1490                 psz_type = _("integer");
1491                 psz_ket = ">";
1492
1493                 if( p_item->min.i || p_item->max.i )
1494                 {
1495                     sprintf( psz_buffer, "%s [%"PRId64" .. %"PRId64"]",
1496                              psz_type, p_item->min.i, p_item->max.i );
1497                     psz_type = psz_buffer;
1498                 }
1499
1500                 if( p_item->i_list )
1501                 {
1502                     psz_bra = OPTION_VALUE_SEP "{";
1503                     psz_type = psz_buffer;
1504                     psz_buffer[0] = '\0';
1505                     for( i = 0; p_item->ppsz_list_text[i]; i++ )
1506                     {
1507                         if( i ) strcat( psz_buffer, ", " );
1508                         sprintf( psz_buffer + strlen(psz_buffer), "%i (%s)",
1509                                  p_item->pi_list[i],
1510                                  module_gettext( p_parser, p_item->ppsz_list_text[i] ) );
1511                     }
1512                     psz_ket = "}";
1513                 }
1514                 break;
1515             case CONFIG_ITEM_FLOAT:
1516                 print_help_section( p_parser, p_section, b_color,
1517                                     b_description );
1518                 p_section = NULL;
1519                 psz_bra = OPTION_VALUE_SEP "<";
1520                 psz_type = _("float");
1521                 psz_ket = ">";
1522                 if( p_item->min.f || p_item->max.f )
1523                 {
1524                     sprintf( psz_buffer, "%s [%f .. %f]", psz_type,
1525                              p_item->min.f, p_item->max.f );
1526                     psz_type = psz_buffer;
1527                 }
1528                 break;
1529             case CONFIG_ITEM_BOOL:
1530                 print_help_section( p_parser, p_section, b_color,
1531                                     b_description );
1532                 p_section = NULL;
1533                 psz_bra = ""; psz_type = ""; psz_ket = "";
1534                 if( !b_help_module )
1535                 {
1536                     psz_suf = p_item->value.i ? _(" (default enabled)") :
1537                                                 _(" (default disabled)");
1538                 }
1539                 break;
1540             }
1541
1542             if( !psz_type )
1543             {
1544                 continue;
1545             }
1546
1547             /* Add short option if any */
1548             if( p_item->i_short )
1549             {
1550                 sprintf( psz_short, "-%c,", p_item->i_short );
1551             }
1552             else
1553             {
1554                 strcpy( psz_short, "   " );
1555             }
1556
1557             i = PADDING_SPACES - strlen( p_item->psz_name )
1558                  - strlen( psz_bra ) - strlen( psz_type )
1559                  - strlen( psz_ket ) - 1;
1560
1561             if( CONFIG_CLASS(p_item->i_type) == CONFIG_ITEM_BOOL
1562              && !b_help_module )
1563             {
1564                 psz_prefix =  ", --no-";
1565                 i -= strlen( p_item->psz_name ) + strlen( psz_prefix );
1566             }
1567
1568             if( i < 0 )
1569             {
1570                 psz_spaces[0] = '\n';
1571                 i = 0;
1572             }
1573             else
1574             {
1575                 psz_spaces[i] = '\0';
1576             }
1577
1578             if( CONFIG_CLASS(p_item->i_type) == CONFIG_ITEM_BOOL
1579              && !b_help_module )
1580             {
1581                 utf8_fprintf( stdout, psz_format_bool, psz_short,
1582                               p_item->psz_name, psz_prefix, p_item->psz_name,
1583                               psz_bra, psz_type, psz_ket, psz_spaces );
1584             }
1585             else
1586             {
1587                 utf8_fprintf( stdout, psz_format, psz_short, p_item->psz_name,
1588                          "", "", psz_bra, psz_type, psz_ket, psz_spaces );
1589             }
1590
1591             psz_spaces[i] = ' ';
1592
1593             /* We wrap the rest of the output */
1594             sprintf( psz_buffer, "%s%s", module_gettext( p_parser, p_item->psz_text ),
1595                      psz_suf );
1596             b_description_hack = b_description;
1597
1598  description:
1599             psz_text = psz_buffer;
1600             i_cur_width = b_description && !b_description_hack
1601                           ? i_width_description
1602                           : i_width;
1603             if( !*psz_text ) strcpy(psz_text, " ");
1604             while( *psz_text )
1605             {
1606                 char *psz_parser, *psz_word;
1607                 size_t i_end = strlen( psz_text );
1608
1609                 /* If the remaining text fits in a line, print it. */
1610                 if( i_end <= i_cur_width )
1611                 {
1612                     if( b_color )
1613                     {
1614                         if( !b_description || b_description_hack )
1615                             utf8_fprintf( stdout, BLUE"%s\n"GRAY, psz_text );
1616                         else
1617                             utf8_fprintf( stdout, "%s\n", psz_text );
1618                     }
1619                     else
1620                     {
1621                         utf8_fprintf( stdout, "%s\n", psz_text );
1622                     }
1623                     break;
1624                 }
1625
1626                 /* Otherwise, eat as many words as possible */
1627                 psz_parser = psz_text;
1628                 do
1629                 {
1630                     psz_word = psz_parser;
1631                     psz_parser = strchr( psz_word, ' ' );
1632                     /* If no space was found, we reached the end of the text
1633                      * block; otherwise, we skip the space we just found. */
1634                     psz_parser = psz_parser ? psz_parser + 1
1635                                             : psz_text + i_end;
1636
1637                 } while( (size_t)(psz_parser - psz_text) <= i_cur_width );
1638
1639                 /* We cut a word in one of these cases:
1640                  *  - it's the only word in the line and it's too long.
1641                  *  - we used less than 80% of the width and the word we are
1642                  *    going to wrap is longer than 40% of the width, and even
1643                  *    if the word would have fit in the next line. */
1644                 if( psz_word == psz_text
1645              || ( (size_t)(psz_word - psz_text) < 80 * i_cur_width / 100
1646              && (size_t)(psz_parser - psz_word) > 40 * i_cur_width / 100 ) )
1647                 {
1648                     char c = psz_text[i_cur_width];
1649                     psz_text[i_cur_width] = '\0';
1650                     if( b_color )
1651                     {
1652                         if( !b_description || b_description_hack )
1653                             utf8_fprintf( stdout, BLUE"%s\n%s"GRAY,
1654                                           psz_text, psz_spaces );
1655                         else
1656                             utf8_fprintf( stdout, "%s\n%s",
1657                                           psz_text, psz_spaces );
1658                     }
1659                     else
1660                     {
1661                         utf8_fprintf( stdout, "%s\n%s", psz_text, psz_spaces );
1662                     }
1663                     psz_text += i_cur_width;
1664                     psz_text[0] = c;
1665                 }
1666                 else
1667                 {
1668                     psz_word[-1] = '\0';
1669                     if( b_color )
1670                     {
1671                         if( !b_description || b_description_hack )
1672                             utf8_fprintf( stdout, BLUE"%s\n%s"GRAY,
1673                                           psz_text, psz_spaces );
1674                         else
1675                             utf8_fprintf( stdout, "%s\n%s",
1676                                           psz_text, psz_spaces );
1677                     }
1678                     else
1679                     {
1680                         utf8_fprintf( stdout, "%s\n%s", psz_text, psz_spaces );
1681                     }
1682                     psz_text = psz_word;
1683                 }
1684             }
1685
1686             if( b_description_hack && p_item->psz_longtext )
1687             {
1688                 sprintf( psz_buffer, "%s%s",
1689                          module_gettext( p_parser, p_item->psz_longtext ),
1690                          psz_suf );
1691                 b_description_hack = false;
1692                 psz_spaces = psz_spaces_longtext;
1693                 utf8_fprintf( stdout, "%s", psz_spaces );
1694                 goto description;
1695             }
1696         }
1697     }
1698
1699     if( b_has_advanced )
1700     {
1701         if( b_color )
1702             utf8_fprintf( stdout, "\n" WHITE "%s" GRAY " %s\n", _( "Note:" ),
1703            _( "add --advanced to your command line to see advanced options."));
1704         else
1705             utf8_fprintf( stdout, "\n%s %s\n", _( "Note:" ),
1706            _( "add --advanced to your command line to see advanced options."));
1707     }
1708
1709     if( i_only_advanced > 0 )
1710     {
1711         if( b_color )
1712         {
1713             utf8_fprintf( stdout, "\n" WHITE "%s" GRAY " ", _( "Note:" ) );
1714             utf8_fprintf( stdout, _( "%d module(s) were not displayed because they only have advanced options.\n" ), i_only_advanced );
1715         }
1716         else
1717         {
1718             utf8_fprintf( stdout, "\n%s ", _( "Note:" ) );
1719             utf8_fprintf( stdout, _( "%d module(s) were not displayed because they only have advanced options.\n" ), i_only_advanced );
1720         }
1721     }
1722     else if( !b_found )
1723     {
1724         if( b_color )
1725             utf8_fprintf( stdout, "\n" WHITE "%s" GRAY "\n",
1726                        _( "No matching module found. Use --list or " \
1727                           "--list-verbose to list available modules." ) );
1728         else
1729             utf8_fprintf( stdout, "\n%s\n",
1730                        _( "No matching module found. Use --list or " \
1731                           "--list-verbose to list available modules." ) );
1732     }
1733
1734     /* Release the module list */
1735     module_list_free (list);
1736 }
1737
1738 /*****************************************************************************
1739  * ListModules: list the available modules with their description
1740  *****************************************************************************
1741  * Print a list of all available modules (builtins and plugins) and a short
1742  * description for each one.
1743  *****************************************************************************/
1744 static void ListModules( libvlc_int_t *p_this, bool b_verbose )
1745 {
1746     module_t *p_parser;
1747
1748     bool b_color = var_InheritBool( p_this, "color" );
1749
1750 #ifdef WIN32
1751     ShowConsole( true );
1752     b_color = false; // don't put color control codes in a .txt file
1753 #else
1754     if( !isatty( 1 ) )
1755         b_color = false;
1756 #endif
1757
1758     /* List all modules */
1759     module_t **list = module_list_get (NULL);
1760
1761     /* Enumerate each module */
1762     for (size_t j = 0; (p_parser = list[j]) != NULL; j++)
1763     {
1764         const char *objname = module_get_object (p_parser);
1765         if( b_color )
1766             utf8_fprintf( stdout, GREEN"  %-22s "WHITE"%s\n"GRAY, objname,
1767                           module_gettext( p_parser, p_parser->psz_longname ) );
1768         else
1769             utf8_fprintf( stdout, "  %-22s %s\n", objname,
1770                           module_gettext( p_parser, p_parser->psz_longname ) );
1771
1772         if( b_verbose )
1773         {
1774             char *const *pp_shortcuts = p_parser->pp_shortcuts;
1775             for( unsigned i = 0; i < p_parser->i_shortcuts; i++ )
1776             {
1777                 if( strcmp( pp_shortcuts[i], objname ) )
1778                 {
1779                     if( b_color )
1780                         utf8_fprintf( stdout, CYAN"   s %s\n"GRAY,
1781                                       pp_shortcuts[i] );
1782                     else
1783                         utf8_fprintf( stdout, "   s %s\n",
1784                                       pp_shortcuts[i] );
1785                 }
1786             }
1787             if( p_parser->psz_capability )
1788             {
1789                 if( b_color )
1790                     utf8_fprintf( stdout, MAGENTA"   c %s (%d)\n"GRAY,
1791                                   p_parser->psz_capability,
1792                                   p_parser->i_score );
1793                 else
1794                     utf8_fprintf( stdout, "   c %s (%d)\n",
1795                                   p_parser->psz_capability,
1796                                   p_parser->i_score );
1797             }
1798         }
1799     }
1800     module_list_free (list);
1801
1802 #ifdef WIN32        /* Pause the console because it's destroyed when we exit */
1803     PauseConsole();
1804 #endif
1805 }
1806
1807 /*****************************************************************************
1808  * Version: print complete program version
1809  *****************************************************************************
1810  * Print complete program version and build number.
1811  *****************************************************************************/
1812 static void Version( void )
1813 {
1814 #ifdef WIN32
1815     ShowConsole( true );
1816 #endif
1817
1818     utf8_fprintf( stdout, _("VLC version %s (%s)\n"), VERSION_MESSAGE,
1819                   psz_vlc_changeset );
1820     utf8_fprintf( stdout, _("Compiled by %s on %s (%s)\n"),
1821              VLC_CompileBy(), VLC_CompileHost(), __DATE__" "__TIME__ );
1822     utf8_fprintf( stdout, _("Compiler: %s\n"), VLC_Compiler() );
1823     utf8_fprintf( stdout, "%s", LICENSE_MSG );
1824
1825 #ifdef WIN32        /* Pause the console because it's destroyed when we exit */
1826     PauseConsole();
1827 #endif
1828 }
1829
1830 /*****************************************************************************
1831  * ShowConsole: On Win32, create an output console for debug messages
1832  *****************************************************************************
1833  * This function is useful only on Win32.
1834  *****************************************************************************/
1835 #ifdef WIN32 /*  */
1836 static void ShowConsole( bool b_dofile )
1837 {
1838 #   ifndef UNDER_CE
1839     FILE *f_help = NULL;
1840
1841     if( getenv( "PWD" ) ) return; /* Cygwin shell or Wine */
1842
1843     AllocConsole();
1844     /* Use the ANSI code page (e.g. Windows-1252) as expected by the LibVLC
1845      * Unicode/locale subsystem. By default, we have the obsolecent OEM code
1846      * page (e.g. CP437 or CP850). */
1847     SetConsoleOutputCP (GetACP ());
1848     SetConsoleTitle ("VLC media player version "PACKAGE_VERSION);
1849
1850     freopen( "CONOUT$", "w", stderr );
1851     freopen( "CONIN$", "r", stdin );
1852
1853     if( b_dofile && (f_help = fopen( "vlc-help.txt", "wt" )) )
1854     {
1855         fclose( f_help );
1856         freopen( "vlc-help.txt", "wt", stdout );
1857         utf8_fprintf( stderr, _("\nDumped content to vlc-help.txt file.\n") );
1858     }
1859     else freopen( "CONOUT$", "w", stdout );
1860
1861 #   endif
1862 }
1863 #endif
1864
1865 /*****************************************************************************
1866  * PauseConsole: On Win32, wait for a key press before closing the console
1867  *****************************************************************************
1868  * This function is useful only on Win32.
1869  *****************************************************************************/
1870 #ifdef WIN32 /*  */
1871 static void PauseConsole( void )
1872 {
1873 #   ifndef UNDER_CE
1874
1875     if( getenv( "PWD" ) ) return; /* Cygwin shell or Wine */
1876
1877     utf8_fprintf( stderr, _("\nPress the RETURN key to continue...\n") );
1878     getchar();
1879     fclose( stdout );
1880
1881 #   endif
1882 }
1883 #endif
1884
1885 /*****************************************************************************
1886  * ConsoleWidth: Return the console width in characters
1887  *****************************************************************************
1888  * We use the stty shell command to get the console width; if this fails or
1889  * if the width is less than 80, we default to 80.
1890  *****************************************************************************/
1891 static int ConsoleWidth( void )
1892 {
1893     unsigned i_width = 80;
1894
1895 #ifndef WIN32
1896     FILE *file = popen( "stty size 2>/dev/null", "r" );
1897     if (file != NULL)
1898     {
1899         if (fscanf (file, "%*u %u", &i_width) <= 0)
1900             i_width = 80;
1901         pclose( file );
1902     }
1903 #elif !defined (UNDER_CE)
1904     CONSOLE_SCREEN_BUFFER_INFO buf;
1905
1906     if (GetConsoleScreenBufferInfo (GetStdHandle (STD_OUTPUT_HANDLE), &buf))
1907         i_width = buf.dwSize.X;
1908 #endif
1909
1910     return i_width;
1911 }