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