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