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