]> git.sesse.net Git - vlc/blob - src/libvlc.c
single instance: append tracks as specified in MPRIS 2.2
[vlc] / src / libvlc.c
1 /*****************************************************************************
2  * libvlc.c: libvlc instances creation and deletion, interfaces handling
3  *****************************************************************************
4  * Copyright (C) 1998-2008 VLC authors and VideoLAN
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 it
14  * under the terms of the GNU Lesser General Public License as published by
15  * the Free Software Foundation; either version 2.1 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 Lesser General Public License for more details.
22  *
23  * You should have received a copy of the GNU Lesser General Public License
24  * along with this program; if not, write to the Free Software Foundation,
25  * Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
26  *****************************************************************************/
27
28 /** \file
29  * This file contains functions to create and destroy libvlc instances
30  */
31
32 /*****************************************************************************
33  * Preamble
34  *****************************************************************************/
35 #ifdef HAVE_CONFIG_H
36 # include "config.h"
37 #endif
38
39 #include <vlc_common.h>
40 #include "../lib/libvlc_internal.h"
41 #include <vlc_input.h>
42
43 #include "modules/modules.h"
44 #include "config/configuration.h"
45
46 #include <stdio.h>                                              /* sprintf() */
47 #include <string.h>
48 #include <stdlib.h>                                                /* free() */
49
50 #include "config/vlc_getopt.h"
51
52 #ifdef HAVE_LOCALE_H
53 #   include <locale.h>
54 #endif
55 #ifdef HAVE_UNISTD_H
56 #   include <unistd.h> /* isatty() */
57 #endif
58
59 #ifdef HAVE_DBUS
60 /* used for one-instance mode */
61 #   include <dbus/dbus.h>
62 #endif
63
64
65 #include <vlc_media_library.h>
66 #include <vlc_playlist.h>
67 #include <vlc_interface.h>
68
69 #include <vlc_charset.h>
70 #include <vlc_fs.h>
71 #include <vlc_cpu.h>
72 #include <vlc_url.h>
73 #include <vlc_atomic.h>
74 #include <vlc_modules.h>
75
76 #include "libvlc.h"
77
78 #include "playlist/playlist_internal.h"
79
80 #include <vlc_vlm.h>
81
82 #ifdef __APPLE__
83 # include <libkern/OSAtomic.h>
84 #endif
85
86 #include <assert.h>
87
88 /*****************************************************************************
89  * The evil global variables. We handle them with care, don't worry.
90  *****************************************************************************/
91
92 #if !defined(WIN32) && !defined(__OS2__)
93 static bool b_daemon = false;
94 #endif
95
96 #undef vlc_gc_init
97 #undef vlc_hold
98 #undef vlc_release
99
100 /**
101  * Atomically set the reference count to 1.
102  * @param p_gc reference counted object
103  * @param pf_destruct destruction calback
104  * @return p_gc.
105  */
106 void *vlc_gc_init (gc_object_t *p_gc, void (*pf_destruct) (gc_object_t *))
107 {
108     /* There is no point in using the GC if there is no destructor... */
109     assert (pf_destruct);
110     p_gc->pf_destructor = pf_destruct;
111
112     vlc_atomic_set (&p_gc->refs, 1);
113     return p_gc;
114 }
115
116 /**
117  * Atomically increment the reference count.
118  * @param p_gc reference counted object
119  * @return p_gc.
120  */
121 void *vlc_hold (gc_object_t * p_gc)
122 {
123     uintptr_t refs;
124
125     assert( p_gc );
126     refs = vlc_atomic_inc (&p_gc->refs);
127     assert (refs != 1); /* there had to be a reference already */
128     return p_gc;
129 }
130
131 /**
132  * Atomically decrement the reference count and, if it reaches zero, destroy.
133  * @param p_gc reference counted object.
134  */
135 void vlc_release (gc_object_t *p_gc)
136 {
137     uintptr_t refs;
138
139     assert( p_gc );
140     refs = vlc_atomic_dec (&p_gc->refs);
141     assert (refs != (uintptr_t)(-1)); /* reference underflow?! */
142     if (refs == 0)
143         p_gc->pf_destructor (p_gc);
144 }
145
146 /*****************************************************************************
147  * Local prototypes
148  *****************************************************************************/
149 #if defined( ENABLE_NLS ) && (defined (__APPLE__) || defined (WIN32)) && \
150     ( defined( HAVE_GETTEXT ) || defined( HAVE_INCLUDED_GETTEXT ) )
151 static void SetLanguage   ( char const * );
152 #endif
153 static void GetFilenames  ( libvlc_int_t *, unsigned, const char *const [] );
154
155 /**
156  * Allocate a libvlc instance, initialize global data if needed
157  * It also initializes the threading system
158  */
159 libvlc_int_t * libvlc_InternalCreate( void )
160 {
161     libvlc_int_t *p_libvlc;
162     libvlc_priv_t *priv;
163     char *psz_env = NULL;
164
165     /* Now that the thread system is initialized, we don't have much, but
166      * at least we have variables */
167     /* Allocate a libvlc instance object */
168     p_libvlc = vlc_custom_create( (vlc_object_t *)NULL, sizeof (*priv),
169                                   "libvlc" );
170     if( p_libvlc == NULL )
171         return NULL;
172
173     priv = libvlc_priv (p_libvlc);
174     priv->p_playlist = NULL;
175     priv->p_ml = NULL;
176     priv->p_dialog_provider = NULL;
177     priv->p_vlm = NULL;
178
179     /* Find verbosity from VLC_VERBOSE environment variable */
180     psz_env = getenv( "VLC_VERBOSE" );
181     if( psz_env != NULL )
182         priv->i_verbose = atoi( psz_env );
183     else
184         priv->i_verbose = 3;
185 #if defined( HAVE_ISATTY ) && !defined( WIN32 )
186     priv->b_color = isatty( 2 ); /* 2 is for stderr */
187 #else
188     priv->b_color = false;
189 #endif
190
191     /* Initialize mutexes */
192     vlc_mutex_init( &priv->ml_lock );
193     vlc_ExitInit( &priv->exit );
194
195     return p_libvlc;
196 }
197
198 /**
199  * Initialize a libvlc instance
200  * This function initializes a previously allocated libvlc instance:
201  *  - CPU detection
202  *  - gettext initialization
203  *  - message queue, module bank and playlist initialization
204  *  - configuration and commandline parsing
205  */
206 int libvlc_InternalInit( libvlc_int_t *p_libvlc, int i_argc,
207                          const char *ppsz_argv[] )
208 {
209     libvlc_priv_t *priv = libvlc_priv (p_libvlc);
210     char *       psz_modules = NULL;
211     char *       psz_parser = NULL;
212     char *       psz_control = NULL;
213     playlist_t  *p_playlist = NULL;
214     char        *psz_val;
215
216     /* System specific initialization code */
217     system_Init();
218
219     /* Initialize the module bank and load the configuration of the
220      * main module. We need to do this at this stage to be able to display
221      * a short help if required by the user. (short help == main module
222      * options) */
223     module_InitBank ();
224
225     /* Get command line options that affect module loading. */
226     if( config_LoadCmdLine( p_libvlc, i_argc, ppsz_argv, NULL ) )
227     {
228         module_EndBank (false);
229         return VLC_EGENERIC;
230     }
231     priv->i_verbose = var_InheritInteger( p_libvlc, "verbose" );
232
233     /* Announce who we are (TODO: only first instance?) */
234     msg_Dbg( p_libvlc, "VLC media player - %s", VERSION_MESSAGE );
235     msg_Dbg( p_libvlc, "%s", COPYRIGHT_MESSAGE );
236     msg_Dbg( p_libvlc, "revision %s", psz_vlc_changeset );
237     msg_Dbg( p_libvlc, "configured with %s", CONFIGURE_LINE );
238
239     /* Load the builtins and plugins into the module_bank.
240      * We have to do it before config_Load*() because this also gets the
241      * list of configuration options exported by each module and loads their
242      * default values. */
243     size_t module_count = module_LoadPlugins (p_libvlc);
244
245     /*
246      * Override default configuration with config file settings
247      */
248     if( !var_InheritBool( p_libvlc, "ignore-config" ) )
249     {
250         if( var_InheritBool( p_libvlc, "reset-config" ) )
251             config_SaveConfigFile( p_libvlc ); /* Save default config */
252         else
253             config_LoadConfigFile( p_libvlc );
254     }
255
256     /*
257      * Override configuration with command line settings
258      */
259     int vlc_optind;
260     if( config_LoadCmdLine( p_libvlc, i_argc, ppsz_argv, &vlc_optind ) )
261     {
262 #ifdef WIN32
263         MessageBox (NULL, TEXT("The command line options could not be parsed.\n"
264                     "Make sure they are valid."), TEXT("VLC media player"),
265                     MB_OK|MB_ICONERROR);
266 #endif
267         module_EndBank (true);
268         return VLC_EGENERIC;
269     }
270     priv->i_verbose = var_InheritInteger( p_libvlc, "verbose" );
271
272     /*
273      * Support for gettext
274      */
275 #if defined( ENABLE_NLS ) \
276      && ( defined( HAVE_GETTEXT ) || defined( HAVE_INCLUDED_GETTEXT ) )
277 # if defined (WIN32) || defined (__APPLE__)
278     /* Check if the user specified a custom language */
279     char *lang = var_InheritString (p_libvlc, "language");
280     if (lang != NULL && strcmp (lang, "auto"))
281         SetLanguage (lang);
282     free (lang);
283 # endif
284     vlc_bindtextdomain (PACKAGE_NAME);
285 #endif
286     /*xgettext: Translate "C" to the language code: "fr", "en_GB", "nl", "ru"... */
287     msg_Dbg( p_libvlc, "translation test: code is \"%s\"", _("C") );
288
289     if (config_PrintHelp (VLC_OBJECT(p_libvlc)))
290     {
291         module_EndBank (true);
292         return VLC_EEXITSUCCESS;
293     }
294
295     if( module_count <= 1 )
296     {
297         msg_Err( p_libvlc, "No plugins found! Check your VLC installation.");
298         module_EndBank (true);
299         return VLC_ENOITEM;
300     }
301
302 #ifdef HAVE_DAEMON
303     /* Check for daemon mode */
304     if( var_InheritBool( p_libvlc, "daemon" ) )
305     {
306         char *psz_pidfile = NULL;
307
308         if( daemon( 1, 0) != 0 )
309         {
310             msg_Err( p_libvlc, "Unable to fork vlc to daemon mode" );
311             module_EndBank (true);
312             return VLC_EEXIT;
313         }
314         b_daemon = true;
315
316         /* lets check if we need to write the pidfile */
317         psz_pidfile = var_CreateGetNonEmptyString( p_libvlc, "pidfile" );
318         if( psz_pidfile != NULL )
319         {
320             FILE *pidfile;
321             pid_t i_pid = getpid ();
322             msg_Dbg( p_libvlc, "PID is %d, writing it to %s",
323                                i_pid, psz_pidfile );
324             pidfile = vlc_fopen( psz_pidfile,"w" );
325             if( pidfile != NULL )
326             {
327                 utf8_fprintf( pidfile, "%d", (int)i_pid );
328                 fclose( pidfile );
329             }
330             else
331             {
332                 msg_Err( p_libvlc, "cannot open pid file for writing: %s (%m)",
333                          psz_pidfile );
334             }
335         }
336         free( psz_pidfile );
337     }
338 #endif
339
340 /* FIXME: could be replaced by using Unix sockets */
341 #ifdef HAVE_DBUS
342
343 #define MPRIS_APPEND "/org/mpris/MediaPlayer2/TrackList/Append"
344 #define MPRIS_BUS_NAME "org.mpris.MediaPlayer2.vlc"
345 #define MPRIS_OBJECT_PATH "/org/mpris/MediaPlayer2"
346 #define MPRIS_TRACKLIST_INTERFACE "org.mpris.MediaPlayer2.TrackList"
347
348     dbus_threads_init_default();
349
350     if( var_InheritBool( p_libvlc, "one-instance" )
351     || ( var_InheritBool( p_libvlc, "one-instance-when-started-from-file" )
352       && var_InheritBool( p_libvlc, "started-from-file" ) ) )
353     {
354         /* Initialise D-Bus interface, check for other instances */
355         DBusConnection  *p_conn = NULL;
356         DBusError       dbus_error;
357
358         dbus_error_init( &dbus_error );
359
360         /* connect to the session bus */
361         p_conn = dbus_bus_get( DBUS_BUS_SESSION, &dbus_error );
362         if( !p_conn )
363         {
364             msg_Err( p_libvlc, "Failed to connect to D-Bus session daemon: %s",
365                     dbus_error.message );
366             dbus_error_free( &dbus_error );
367         }
368         else
369         {
370             /* check if VLC is available on the bus
371              * if not: D-Bus control is not enabled on the other
372              * instance and we can't pass MRLs to it */
373             if( !dbus_bus_name_has_owner( p_conn, MPRIS_BUS_NAME, &dbus_error ) )
374             {
375                 if( dbus_error_is_set( &dbus_error ) )
376                 {
377                     msg_Err( p_libvlc, "D-Bus error: %s", dbus_error.message );
378                     dbus_error_free( &dbus_error );
379                 }
380                 else
381                     msg_Dbg( p_libvlc, "No Media Player is running. "
382                             "Continuing normally." );
383             }
384             else
385             {
386                 int i_input;
387                 DBusMessage* p_dbus_msg = NULL;
388                 DBusMessageIter dbus_args;
389                 DBusPendingCall* p_dbus_pending = NULL;
390                 dbus_bool_t b_play;
391
392                 msg_Warn( p_libvlc, "Another Media Player is running. Exiting");
393
394                 for( i_input = vlc_optind; i_input < i_argc;i_input++ )
395                 {
396                     /* Skip input options, we can't pass them through D-Bus */
397                     if( ppsz_argv[i_input][0] == ':' )
398                     {
399                         msg_Warn( p_libvlc, "Ignoring option %s",
400                                   ppsz_argv[i_input] );
401                         continue;
402                     }
403
404                     /* We need to resolve relative paths in this instance */
405                     char *psz_mrl = make_URI( ppsz_argv[i_input], NULL );
406                     const char *psz_after_track = MPRIS_APPEND;
407
408                     if( psz_mrl == NULL )
409                         continue;
410                     msg_Dbg( p_libvlc, "Adds %s to the running Media Player",
411                              psz_mrl );
412
413                     p_dbus_msg = dbus_message_new_method_call(
414                         MPRIS_BUS_NAME, MPRIS_OBJECT_PATH,
415                         MPRIS_TRACKLIST_INTERFACE, "AddTrack" );
416
417                     if ( NULL == p_dbus_msg )
418                     {
419                         msg_Err( p_libvlc, "D-Bus problem" );
420                         free( psz_mrl );
421                         system_End( );
422                         exit( 1 );
423                     }
424
425                     /* append MRLs */
426                     dbus_message_iter_init_append( p_dbus_msg, &dbus_args );
427                     if ( !dbus_message_iter_append_basic( &dbus_args,
428                                 DBUS_TYPE_STRING, &psz_mrl ) )
429                     {
430                         dbus_message_unref( p_dbus_msg );
431                         free( psz_mrl );
432                         system_End( );
433                         exit( 1 );
434                     }
435                     free( psz_mrl );
436
437                     if( !dbus_message_iter_append_basic( &dbus_args,
438                                 DBUS_TYPE_OBJECT_PATH, &psz_after_track ) )
439                     {
440                         dbus_message_unref( p_dbus_msg );
441                         system_End( );
442                         exit( 1 );
443                     }
444
445                     b_play = TRUE;
446                     if( var_InheritBool( p_libvlc, "playlist-enqueue" ) )
447                         b_play = FALSE;
448
449                     if ( !dbus_message_iter_append_basic( &dbus_args,
450                                 DBUS_TYPE_BOOLEAN, &b_play ) )
451                     {
452                         dbus_message_unref( p_dbus_msg );
453                         system_End( );
454                         exit( 1 );
455                     }
456
457                     /* send message and get a handle for a reply */
458                     if ( !dbus_connection_send_with_reply ( p_conn,
459                                 p_dbus_msg, &p_dbus_pending, -1 ) )
460                     {
461                         msg_Err( p_libvlc, "D-Bus problem" );
462                         dbus_message_unref( p_dbus_msg );
463                         system_End( );
464                         exit( 1 );
465                     }
466
467                     if ( NULL == p_dbus_pending )
468                     {
469                         msg_Err( p_libvlc, "D-Bus problem" );
470                         dbus_message_unref( p_dbus_msg );
471                         system_End( );
472                         exit( 1 );
473                     }
474                     dbus_connection_flush( p_conn );
475                     dbus_message_unref( p_dbus_msg );
476                     /* block until we receive a reply */
477                     dbus_pending_call_block( p_dbus_pending );
478                     dbus_pending_call_unref( p_dbus_pending );
479                 } /* processes all command line MRLs */
480
481                 /* bye bye */
482                 system_End( );
483                 exit( 0 );
484             }
485         }
486         /* we unreference the connection when we've finished with it */
487         if( p_conn ) dbus_connection_unref( p_conn );
488     }
489
490 #undef MPRIS_APPEND
491 #undef MPRIS_BUS_NAME
492 #undef MPRIS_OBJECT_PATH
493 #undef MPRIS_TRACKLIST_INTERFACE
494
495 #endif // HAVE_DBUS
496
497     /*
498      * Message queue options
499      */
500     /* Last chance to set the verbosity. Once we start interfaces and other
501      * threads, verbosity becomes read-only. */
502     var_Create( p_libvlc, "verbose", VLC_VAR_INTEGER | VLC_VAR_DOINHERIT );
503     if( var_InheritBool( p_libvlc, "quiet" ) )
504     {
505         var_SetInteger( p_libvlc, "verbose", -1 );
506         priv->i_verbose = -1;
507     }
508     vlc_threads_setup( p_libvlc );
509
510     if( priv->b_color )
511         priv->b_color = var_InheritBool( p_libvlc, "color" );
512
513     vlc_CPU_dump( VLC_OBJECT(p_libvlc) );
514     /*
515      * Choose the best memcpy module
516      */
517     priv->p_memcpy_module = module_need( p_libvlc, "memcpy", "$memcpy", false );
518     /* Avoid being called "memcpy":*/
519     vlc_object_set_name( p_libvlc, "main" );
520
521     priv->b_stats = var_InheritBool( p_libvlc, "stats" );
522
523     /*
524      * Initialize hotkey handling
525      */
526     priv->actions = vlc_InitActions( p_libvlc );
527
528     /* Create a variable for showing the fullscreen interface */
529     var_Create( p_libvlc, "intf-toggle-fscontrol", VLC_VAR_BOOL );
530     var_SetBool( p_libvlc, "intf-toggle-fscontrol", true );
531
532     /* Create a variable for the Boss Key */
533     var_Create( p_libvlc, "intf-boss", VLC_VAR_VOID );
534
535     /* Create a variable for showing the main interface */
536     var_Create( p_libvlc, "intf-show", VLC_VAR_BOOL );
537
538     /* Create a variable for showing the right click menu */
539     var_Create( p_libvlc, "intf-popupmenu", VLC_VAR_BOOL );
540
541     /* variables for signalling creation of new files */
542     var_Create( p_libvlc, "snapshot-file", VLC_VAR_STRING );
543     var_Create( p_libvlc, "record-file", VLC_VAR_STRING );
544
545     /* some default internal settings */
546     var_Create( p_libvlc, "window", VLC_VAR_STRING );
547     var_Create( p_libvlc, "user-agent", VLC_VAR_STRING );
548     var_SetString( p_libvlc, "user-agent", "(LibVLC "VERSION")" );
549
550     /* Initialize playlist and get commandline files */
551     p_playlist = playlist_Create( VLC_OBJECT(p_libvlc) );
552     if( !p_playlist )
553     {
554         msg_Err( p_libvlc, "playlist initialization failed" );
555         if( priv->p_memcpy_module != NULL )
556         {
557             module_unneed( p_libvlc, priv->p_memcpy_module );
558         }
559         module_EndBank (true);
560         return VLC_EGENERIC;
561     }
562
563     /* System specific configuration */
564     system_Configure( p_libvlc, i_argc - vlc_optind, ppsz_argv + vlc_optind );
565
566 #if defined(MEDIA_LIBRARY)
567     /* Get the ML */
568     if( var_GetBool( p_libvlc, "load-media-library-on-startup" ) )
569     {
570         priv->p_ml = ml_Create( VLC_OBJECT( p_libvlc ), NULL );
571         if( !priv->p_ml )
572         {
573             msg_Err( p_libvlc, "ML initialization failed" );
574             return VLC_EGENERIC;
575         }
576     }
577     else
578     {
579         priv->p_ml = NULL;
580     }
581 #endif
582
583     /* Add service discovery modules */
584     psz_modules = var_InheritString( p_libvlc, "services-discovery" );
585     if( psz_modules )
586     {
587         char *p = psz_modules, *m;
588         while( ( m = strsep( &p, " :," ) ) != NULL )
589             playlist_ServicesDiscoveryAdd( p_playlist, m );
590         free( psz_modules );
591     }
592
593 #ifdef ENABLE_VLM
594     /* Initialize VLM if vlm-conf is specified */
595     psz_parser = var_CreateGetNonEmptyString( p_libvlc, "vlm-conf" );
596     if( psz_parser )
597     {
598         priv->p_vlm = vlm_New( p_libvlc );
599         if( !priv->p_vlm )
600             msg_Err( p_libvlc, "VLM initialization failed" );
601     }
602     free( psz_parser );
603 #endif
604
605     /*
606      * Load background interfaces
607      */
608     psz_modules = var_CreateGetNonEmptyString( p_libvlc, "extraintf" );
609     psz_control = var_CreateGetNonEmptyString( p_libvlc, "control" );
610
611     if( psz_modules && psz_control )
612     {
613         char* psz_tmp;
614         if( asprintf( &psz_tmp, "%s:%s", psz_modules, psz_control ) != -1 )
615         {
616             free( psz_modules );
617             psz_modules = psz_tmp;
618         }
619     }
620     else if( psz_control )
621     {
622         free( psz_modules );
623         psz_modules = strdup( psz_control );
624     }
625
626     psz_parser = psz_modules;
627     while ( psz_parser && *psz_parser )
628     {
629         char *psz_module, *psz_temp;
630         psz_module = psz_parser;
631         psz_parser = strchr( psz_module, ':' );
632         if ( psz_parser )
633         {
634             *psz_parser = '\0';
635             psz_parser++;
636         }
637         if( asprintf( &psz_temp, "%s,none", psz_module ) != -1)
638         {
639             intf_Create( p_libvlc, psz_temp );
640             free( psz_temp );
641         }
642     }
643     free( psz_modules );
644     free( psz_control );
645
646     /*
647      * Always load the hotkeys interface if it exists
648      */
649     intf_Create( p_libvlc, "hotkeys,none" );
650
651     if( var_InheritBool( p_libvlc, "file-logging" )
652 #ifdef HAVE_SYSLOG_H
653         && !var_InheritBool( p_libvlc, "syslog" )
654 #endif
655         )
656     {
657         intf_Create( p_libvlc, "logger,none" );
658     }
659 #ifdef HAVE_SYSLOG_H
660     if( var_InheritBool( p_libvlc, "syslog" ) )
661     {
662         char *logmode = var_CreateGetNonEmptyString( p_libvlc, "logmode" );
663         var_SetString( p_libvlc, "logmode", "syslog" );
664         intf_Create( p_libvlc, "logger,none" );
665
666         if( logmode )
667         {
668             var_SetString( p_libvlc, "logmode", logmode );
669             free( logmode );
670         }
671         var_Destroy( p_libvlc, "logmode" );
672     }
673 #endif
674
675     if( var_InheritBool( p_libvlc, "network-synchronisation") )
676     {
677         intf_Create( p_libvlc, "netsync,none" );
678     }
679
680 #ifdef __APPLE__
681     var_Create( p_libvlc, "drawable-view-top", VLC_VAR_INTEGER );
682     var_Create( p_libvlc, "drawable-view-left", VLC_VAR_INTEGER );
683     var_Create( p_libvlc, "drawable-view-bottom", VLC_VAR_INTEGER );
684     var_Create( p_libvlc, "drawable-view-right", VLC_VAR_INTEGER );
685     var_Create( p_libvlc, "drawable-clip-top", VLC_VAR_INTEGER );
686     var_Create( p_libvlc, "drawable-clip-left", VLC_VAR_INTEGER );
687     var_Create( p_libvlc, "drawable-clip-bottom", VLC_VAR_INTEGER );
688     var_Create( p_libvlc, "drawable-clip-right", VLC_VAR_INTEGER );
689     var_Create( p_libvlc, "drawable-nsobject", VLC_VAR_ADDRESS );
690 #endif
691 #if defined (WIN32) || defined (__OS2__)
692     var_Create( p_libvlc, "drawable-hwnd", VLC_VAR_INTEGER );
693 #endif
694
695     /*
696      * Get input filenames given as commandline arguments.
697      * We assume that the remaining parameters are filenames
698      * and their input options.
699      */
700     GetFilenames( p_libvlc, i_argc - vlc_optind, ppsz_argv + vlc_optind );
701
702     /*
703      * Get --open argument
704      */
705     psz_val = var_InheritString( p_libvlc, "open" );
706     if ( psz_val != NULL )
707     {
708         playlist_AddExt( p_playlist, psz_val, NULL, PLAYLIST_INSERT, 0,
709                          -1, 0, NULL, 0, true, pl_Unlocked );
710         free( psz_val );
711     }
712
713     return VLC_SUCCESS;
714 }
715
716 /**
717  * Cleanup a libvlc instance. The instance is not completely deallocated
718  * \param p_libvlc the instance to clean
719  */
720 void libvlc_InternalCleanup( libvlc_int_t *p_libvlc )
721 {
722     libvlc_priv_t *priv = libvlc_priv (p_libvlc);
723     playlist_t    *p_playlist = libvlc_priv (p_libvlc)->p_playlist;
724
725     /* Deactivate the playlist */
726     msg_Dbg( p_libvlc, "deactivating the playlist" );
727     pl_Deactivate( p_libvlc );
728
729     /* Remove all services discovery */
730     msg_Dbg( p_libvlc, "removing all services discovery tasks" );
731     playlist_ServicesDiscoveryKillAll( p_playlist );
732
733     /* Ask the interfaces to stop and destroy them */
734     msg_Dbg( p_libvlc, "removing all interfaces" );
735     libvlc_Quit( p_libvlc );
736     intf_DestroyAll( p_libvlc );
737
738 #ifdef ENABLE_VLM
739     /* Destroy VLM if created in libvlc_InternalInit */
740     if( priv->p_vlm )
741     {
742         vlm_Delete( priv->p_vlm );
743     }
744 #endif
745
746 #if defined(MEDIA_LIBRARY)
747     media_library_t* p_ml = priv->p_ml;
748     if( p_ml )
749     {
750         ml_Destroy( VLC_OBJECT( p_ml ) );
751         vlc_object_release( p_ml );
752         libvlc_priv(p_playlist->p_libvlc)->p_ml = NULL;
753     }
754 #endif
755
756     /* Free playlist now, all threads are gone */
757     playlist_Destroy( p_playlist );
758
759     msg_Dbg( p_libvlc, "removing stats" );
760
761 #if !defined( WIN32 ) && !defined( __OS2__ )
762     char* psz_pidfile = NULL;
763
764     if( b_daemon )
765     {
766         psz_pidfile = var_CreateGetNonEmptyString( p_libvlc, "pidfile" );
767         if( psz_pidfile != NULL )
768         {
769             msg_Dbg( p_libvlc, "removing pid file %s", psz_pidfile );
770             if( unlink( psz_pidfile ) == -1 )
771             {
772                 msg_Dbg( p_libvlc, "removing pid file %s: %m",
773                         psz_pidfile );
774             }
775         }
776         free( psz_pidfile );
777     }
778 #endif
779
780     if( priv->p_memcpy_module )
781     {
782         module_unneed( p_libvlc, priv->p_memcpy_module );
783         priv->p_memcpy_module = NULL;
784     }
785
786     /* Save the configuration */
787     if( !var_InheritBool( p_libvlc, "ignore-config" ) )
788         config_AutoSaveConfigFile( VLC_OBJECT(p_libvlc) );
789
790     /* Free module bank. It is refcounted, so we call this each time  */
791     module_EndBank (true);
792
793     vlc_DeinitActions( p_libvlc, priv->actions );
794 }
795
796 /**
797  * Destroy everything.
798  * This function requests the running threads to finish, waits for their
799  * termination, and destroys their structure.
800  * It stops the thread systems: no instance can run after this has run
801  * \param p_libvlc the instance to destroy
802  */
803 void libvlc_InternalDestroy( libvlc_int_t *p_libvlc )
804 {
805     libvlc_priv_t *priv = libvlc_priv( p_libvlc );
806
807     system_End( );
808
809     /* Destroy mutexes */
810     vlc_ExitDestroy( &priv->exit );
811     vlc_mutex_destroy( &priv->ml_lock );
812
813 #ifndef NDEBUG /* Hack to dump leaked objects tree */
814     if( vlc_internals( p_libvlc )->i_refcount > 1 )
815         while( vlc_internals( p_libvlc )->i_refcount > 0 )
816             vlc_object_release( p_libvlc );
817 #endif
818
819     assert( vlc_internals( p_libvlc )->i_refcount == 1 );
820     vlc_object_release( p_libvlc );
821 }
822
823 /**
824  * Add an interface plugin and run it
825  */
826 int libvlc_InternalAddIntf( libvlc_int_t *p_libvlc, char const *psz_module )
827 {
828     if( !p_libvlc )
829         return VLC_EGENERIC;
830
831     if( !psz_module ) /* requesting the default interface */
832     {
833         char *psz_interface = var_CreateGetNonEmptyString( p_libvlc, "intf" );
834         if( !psz_interface ) /* "intf" has not been set */
835         {
836 #if !defined( WIN32 ) && !defined( __OS2__ )
837             if( b_daemon )
838                  /* Daemon mode hack.
839                   * We prefer the dummy interface if none is specified. */
840                 psz_module = "dummy";
841             else
842 #endif
843                 msg_Info( p_libvlc, "%s",
844                           _("Running vlc with the default interface. "
845                             "Use 'cvlc' to use vlc without interface.") );
846         }
847         free( psz_interface );
848         var_Destroy( p_libvlc, "intf" );
849     }
850
851     /* Try to create the interface */
852     int ret = intf_Create( p_libvlc, psz_module ? psz_module : "$intf" );
853     if( ret )
854         msg_Err( p_libvlc, "interface \"%s\" initialization failed",
855                  psz_module ? psz_module : "default" );
856     return ret;
857 }
858
859 #if defined( ENABLE_NLS ) && (defined (__APPLE__) || defined (WIN32)) && \
860     ( defined( HAVE_GETTEXT ) || defined( HAVE_INCLUDED_GETTEXT ) )
861 /*****************************************************************************
862  * SetLanguage: set the interface language.
863  *****************************************************************************
864  * We set the LC_MESSAGES locale category for interface messages and buttons,
865  * as well as the LC_CTYPE category for string sorting and possible wide
866  * character support.
867  *****************************************************************************/
868 static void SetLanguage ( const char *psz_lang )
869 {
870 #ifdef __APPLE__
871     /* I need that under Darwin, please check it doesn't disturb
872      * other platforms. --Meuuh */
873     setenv( "LANG", psz_lang, 1 );
874
875 #else
876     /* We set LC_ALL manually because it is the only way to set
877      * the language at runtime under eg. Windows. Beware that this
878      * makes the environment unconsistent when libvlc is unloaded and
879      * should probably be moved to a safer place like vlc.c. */
880     setenv( "LC_ALL", psz_lang, 1 );
881
882 #endif
883
884     setlocale( LC_ALL, psz_lang );
885 }
886 #endif
887
888 /*****************************************************************************
889  * GetFilenames: parse command line options which are not flags
890  *****************************************************************************
891  * Parse command line for input files as well as their associated options.
892  * An option always follows its associated input and begins with a ":".
893  *****************************************************************************/
894 static void GetFilenames( libvlc_int_t *p_vlc, unsigned n,
895                           const char *const args[] )
896 {
897     while( n > 0 )
898     {
899         /* Count the input options */
900         unsigned i_options = 0;
901
902         while( args[--n][0] == ':' )
903         {
904             i_options++;
905             if( n == 0 )
906             {
907                 msg_Warn( p_vlc, "options %s without item", args[n] );
908                 return; /* syntax!? */
909             }
910         }
911
912         char *mrl = make_URI( args[n], NULL );
913         if( !mrl )
914             continue;
915
916         playlist_AddExt( pl_Get( p_vlc ), mrl, NULL, PLAYLIST_INSERT,
917                 0, -1, i_options, ( i_options ? &args[n + 1] : NULL ),
918                 VLC_INPUT_OPTION_TRUSTED, true, pl_Unlocked );
919         free( mrl );
920     }
921 }