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