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