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