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