]> git.sesse.net Git - vlc/blob - src/libvlc.c
playlist: create instance only when needed
[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 #include "playlist/preparser.h"
46
47 #include <stdio.h>                                              /* sprintf() */
48 #include <string.h>
49 #include <stdlib.h>                                                /* free() */
50 #include <errno.h>
51
52 #include "config/vlc_getopt.h"
53
54 #ifdef HAVE_DBUS
55 /* used for one-instance mode */
56 #   include <dbus/dbus.h>
57 #endif
58
59
60 #include <vlc_playlist.h>
61 #include <vlc_interface.h>
62
63 #include <vlc_charset.h>
64 #include <vlc_fs.h>
65 #include <vlc_cpu.h>
66 #include <vlc_url.h>
67 #include <vlc_modules.h>
68
69 #include "libvlc.h"
70 #include "playlist/playlist_internal.h"
71 #include "misc/variables.h"
72
73 #include <vlc_vlm.h>
74
75 #ifdef __APPLE__
76 # include <libkern/OSAtomic.h>
77 #endif
78
79 #include <assert.h>
80
81 /*****************************************************************************
82  * Local prototypes
83  *****************************************************************************/
84 static void GetFilenames  ( libvlc_int_t *, unsigned, const char *const [] );
85
86 /**
87  * Allocate a libvlc instance, initialize global data if needed
88  * It also initializes the threading system
89  */
90 libvlc_int_t * libvlc_InternalCreate( void )
91 {
92     libvlc_int_t *p_libvlc;
93     libvlc_priv_t *priv;
94
95     /* Now that the thread system is initialized, we don't have much, but
96      * at least we have variables */
97     /* Allocate a libvlc instance object */
98     p_libvlc = vlc_custom_create( (vlc_object_t *)NULL, sizeof (*priv),
99                                   "libvlc" );
100     if( p_libvlc == NULL )
101         return NULL;
102
103     priv = libvlc_priv (p_libvlc);
104     priv->playlist = NULL;
105     priv->p_dialog_provider = NULL;
106     priv->p_vlm = NULL;
107
108     vlc_ExitInit( &priv->exit );
109
110     return p_libvlc;
111 }
112
113 /**
114  * Initialize a libvlc instance
115  * This function initializes a previously allocated libvlc instance:
116  *  - CPU detection
117  *  - gettext initialization
118  *  - message queue, module bank and playlist initialization
119  *  - configuration and commandline parsing
120  */
121 int libvlc_InternalInit( libvlc_int_t *p_libvlc, int i_argc,
122                          const char *ppsz_argv[] )
123 {
124     libvlc_priv_t *priv = libvlc_priv (p_libvlc);
125     char *       psz_modules = NULL;
126     char *       psz_parser = NULL;
127     char *       psz_control = NULL;
128     char        *psz_val;
129
130     /* System specific initialization code */
131     system_Init();
132
133     /* Initialize the module bank and load the configuration of the
134      * core module. We need to do this at this stage to be able to display
135      * a short help if required by the user. (short help == core module
136      * options) */
137     module_InitBank ();
138
139     /* Get command line options that affect module loading. */
140     if( config_LoadCmdLine( p_libvlc, i_argc, ppsz_argv, NULL ) )
141     {
142         module_EndBank (false);
143         return VLC_EGENERIC;
144     }
145
146     vlc_LogInit (p_libvlc);
147     vlc_threads_setup (p_libvlc);
148
149     /* Load the builtins and plugins into the module_bank.
150      * We have to do it before config_Load*() because this also gets the
151      * list of configuration options exported by each module and loads their
152      * default values. */
153     size_t module_count = module_LoadPlugins (p_libvlc);
154
155     /*
156      * Override default configuration with config file settings
157      */
158     if( !var_InheritBool( p_libvlc, "ignore-config" ) )
159     {
160         if( var_InheritBool( p_libvlc, "reset-config" ) )
161             config_SaveConfigFile( p_libvlc ); /* Save default config */
162         else
163             config_LoadConfigFile( p_libvlc );
164     }
165
166     /*
167      * Override configuration with command line settings
168      */
169     int vlc_optind;
170     if( config_LoadCmdLine( p_libvlc, i_argc, ppsz_argv, &vlc_optind ) )
171     {
172         module_EndBank (true);
173         vlc_LogDeinit (p_libvlc);
174         return VLC_EGENERIC;
175     }
176
177     /*
178      * Support for gettext
179      */
180 #if defined( ENABLE_NLS ) \
181      && ( defined( HAVE_GETTEXT ) || defined( HAVE_INCLUDED_GETTEXT ) )
182     vlc_bindtextdomain (PACKAGE_NAME);
183 #endif
184     /*xgettext: Translate "C" to the language code: "fr", "en_GB", "nl", "ru"... */
185     msg_Dbg( p_libvlc, "translation test: code is \"%s\"", _("C") );
186
187     if (config_PrintHelp (VLC_OBJECT(p_libvlc)))
188     {
189         module_EndBank (true);
190         exit(0);
191     }
192
193     if( module_count <= 1 )
194     {
195         msg_Err( p_libvlc, "No plugins found! Check your VLC installation.");
196         module_EndBank (true);
197         vlc_LogDeinit (p_libvlc);
198         return VLC_ENOMOD;
199     }
200
201 #ifdef HAVE_DAEMON
202     /* Check for daemon mode */
203     if( var_InheritBool( p_libvlc, "daemon" ) )
204     {
205         if( daemon( 1, 0) != 0 )
206         {
207             msg_Err( p_libvlc, "Unable to fork vlc to daemon mode" );
208             module_EndBank (true);
209             vlc_LogDeinit (p_libvlc);
210             return VLC_ENOMEM;
211         }
212
213         /* lets check if we need to write the pidfile */
214         char *pidfile = var_InheritString( p_libvlc, "pidfile" );
215         if( pidfile != NULL )
216         {
217             FILE *stream = vlc_fopen( pidfile, "w" );
218             if( stream != NULL )
219             {
220                 fprintf( stream, "%d", (int)getpid() );
221                 fclose( stream );
222                 msg_Dbg( p_libvlc, "written PID file %s", pidfile );
223             }
224             else
225                 msg_Err( p_libvlc, "cannot write PID file %s: %s",
226                          pidfile, vlc_strerror_c(errno) );
227             free( pidfile );
228         }
229     }
230     else
231     {
232         var_Create( p_libvlc, "pidfile", VLC_VAR_STRING );
233         var_SetString( p_libvlc, "pidfile", "" );
234     }
235 #endif
236
237 /* FIXME: could be replaced by using Unix sockets */
238 #ifdef HAVE_DBUS
239
240 #define MPRIS_APPEND "/org/mpris/MediaPlayer2/TrackList/Append"
241 #define MPRIS_BUS_NAME "org.mpris.MediaPlayer2.vlc"
242 #define MPRIS_OBJECT_PATH "/org/mpris/MediaPlayer2"
243 #define MPRIS_TRACKLIST_INTERFACE "org.mpris.MediaPlayer2.TrackList"
244
245     if( var_InheritBool( p_libvlc, "one-instance" )
246     || ( var_InheritBool( p_libvlc, "one-instance-when-started-from-file" )
247       && var_InheritBool( p_libvlc, "started-from-file" ) ) )
248     {
249         for( int i = vlc_optind; i < i_argc; i++ )
250             if( ppsz_argv[i][0] == ':' )
251             {
252                 msg_Err( p_libvlc, "item option %s incompatible with single instance",
253                          ppsz_argv[i] );
254                 goto dbus_out;
255             }
256
257         /* Initialise D-Bus interface, check for other instances */
258         dbus_threads_init_default();
259
260         DBusError err;
261         dbus_error_init( &err );
262
263         /* connect to the session bus */
264         DBusConnection  *conn = dbus_bus_get( DBUS_BUS_SESSION, &err );
265         if( conn == NULL )
266         {
267             msg_Err( p_libvlc, "Failed to connect to D-Bus session daemon: %s",
268                     err.message );
269             dbus_error_free( &err );
270             goto dbus_out;
271         }
272
273         /* check if VLC is available on the bus
274          * if not: D-Bus control is not enabled on the other
275          * instance and we can't pass MRLs to it */
276         /* FIXME: This check is totally brain-dead and buggy. */
277         if( !dbus_bus_name_has_owner( conn, MPRIS_BUS_NAME, &err ) )
278         {
279             dbus_connection_unref( conn );
280             if( dbus_error_is_set( &err ) )
281             {
282                 msg_Err( p_libvlc, "D-Bus error: %s", err.message );
283             }
284             else
285                 msg_Dbg( p_libvlc, "No media player running. Continuing normally." );
286             dbus_error_free( &err );
287             goto dbus_out;
288         }
289
290         const dbus_bool_t play = !var_InheritBool( p_libvlc, "playlist-enqueue" );
291
292         msg_Warn( p_libvlc, "media player running. Exiting...");
293         for( int i = vlc_optind; i < i_argc; i++ )
294         {
295             DBusMessage *msg = dbus_message_new_method_call(
296                MPRIS_BUS_NAME, MPRIS_OBJECT_PATH, MPRIS_TRACKLIST_INTERFACE, "AddTrack" );
297             if( unlikely(msg == NULL) )
298                 continue;
299
300             /* We need to resolve relative paths in this instance */
301             char *mrl;
302             if( strstr( ppsz_argv[i], "://" ) )
303                 mrl = strdup( ppsz_argv[i] );
304             else
305                 mrl = vlc_path2uri( ppsz_argv[i], NULL );
306             if( mrl == NULL )
307             {
308                 dbus_message_unref( msg );
309                 continue;
310             }
311
312             const char *after_track = MPRIS_APPEND;
313
314             /* append MRLs */
315             if( !dbus_message_append_args( msg, DBUS_TYPE_STRING, &mrl,
316                                                 DBUS_TYPE_OBJECT_PATH, &after_track,
317                                                 DBUS_TYPE_BOOLEAN, &play,
318                                                 DBUS_TYPE_INVALID ) )
319             {
320                  dbus_message_unref( msg );
321                  msg = NULL;
322                  free( mrl );
323                  continue;
324             }
325
326             msg_Dbg( p_libvlc, "Adds %s to the running media player", mrl );
327             free( mrl );
328
329             /* send message and get a handle for a reply */
330             DBusMessage *reply = dbus_connection_send_with_reply_and_block( conn, msg, -1,
331                                                                             &err );
332             dbus_message_unref( msg );
333             if( reply == NULL )
334             {
335                 msg_Err( p_libvlc, "D-Bus error: %s", err.message );
336                 continue;
337             }
338             dbus_message_unref( reply );
339         }
340         /* we unreference the connection when we've finished with it */
341         dbus_connection_unref( conn );
342         exit( 1 );
343     }
344 #undef MPRIS_APPEND
345 #undef MPRIS_BUS_NAME
346 #undef MPRIS_OBJECT_PATH
347 #undef MPRIS_TRACKLIST_INTERFACE
348 dbus_out:
349 #endif // HAVE_DBUS
350
351     vlc_CPU_dump( VLC_OBJECT(p_libvlc) );
352
353     priv->b_stats = var_InheritBool( p_libvlc, "stats" );
354
355     /*
356      * Initialize hotkey handling
357      */
358     priv->actions = vlc_InitActions( p_libvlc );
359
360     /*
361      * Meta data handling
362      */
363     priv->parser = playlist_preparser_New(VLC_OBJECT(p_libvlc));
364
365     /* Create a variable for showing the fullscreen interface */
366     var_Create( p_libvlc, "intf-toggle-fscontrol", VLC_VAR_BOOL );
367     var_SetBool( p_libvlc, "intf-toggle-fscontrol", true );
368
369     /* Create a variable for the Boss Key */
370     var_Create( p_libvlc, "intf-boss", VLC_VAR_VOID );
371
372     /* Create a variable for showing the main interface */
373     var_Create( p_libvlc, "intf-show", VLC_VAR_BOOL );
374
375     /* Create a variable for showing the right click menu */
376     var_Create( p_libvlc, "intf-popupmenu", VLC_VAR_BOOL );
377
378     /* variables for signalling creation of new files */
379     var_Create( p_libvlc, "snapshot-file", VLC_VAR_STRING );
380     var_Create( p_libvlc, "record-file", VLC_VAR_STRING );
381
382     /* some default internal settings */
383     var_Create( p_libvlc, "window", VLC_VAR_STRING );
384     /* NOTE: Because the playlist and interfaces start before this function
385      * returns control to the application (DESIGN BUG!), all these variables
386      * must be created (in place of libvlc_new()) and set to VLC defaults
387      * (in place of VLC main()) *here*. */
388     var_Create( p_libvlc, "user-agent", VLC_VAR_STRING );
389     var_SetString( p_libvlc, "user-agent",
390                    "VLC media player (LibVLC "VERSION")" );
391     var_Create( p_libvlc, "http-user-agent", VLC_VAR_STRING );
392     var_SetString( p_libvlc, "http-user-agent",
393                    "VLC/"PACKAGE_VERSION" LibVLC/"PACKAGE_VERSION );
394     var_Create( p_libvlc, "app-icon-name", VLC_VAR_STRING );
395     var_SetString( p_libvlc, "app-icon-name", PACKAGE_NAME );
396     var_Create( p_libvlc, "app-id", VLC_VAR_STRING );
397     var_SetString( p_libvlc, "app-id", "org.VideoLAN.VLC" );
398     var_Create( p_libvlc, "app-version", VLC_VAR_STRING );
399     var_SetString( p_libvlc, "app-version", PACKAGE_VERSION );
400
401     /* System specific configuration */
402     system_Configure( p_libvlc, i_argc - vlc_optind, ppsz_argv + vlc_optind );
403
404 #ifdef ENABLE_VLM
405     /* Initialize VLM if vlm-conf is specified */
406     psz_parser = var_CreateGetNonEmptyString( p_libvlc, "vlm-conf" );
407     if( psz_parser )
408     {
409         priv->p_vlm = vlm_New( p_libvlc );
410         if( !priv->p_vlm )
411             msg_Err( p_libvlc, "VLM initialization failed" );
412     }
413     free( psz_parser );
414 #endif
415
416     /*
417      * Load background interfaces
418      */
419     psz_modules = var_CreateGetNonEmptyString( p_libvlc, "extraintf" );
420     psz_control = var_CreateGetNonEmptyString( p_libvlc, "control" );
421
422     if( psz_modules && psz_control )
423     {
424         char* psz_tmp;
425         if( asprintf( &psz_tmp, "%s:%s", psz_modules, psz_control ) != -1 )
426         {
427             free( psz_modules );
428             psz_modules = psz_tmp;
429         }
430     }
431     else if( psz_control )
432     {
433         free( psz_modules );
434         psz_modules = strdup( psz_control );
435     }
436
437     psz_parser = psz_modules;
438     while ( psz_parser && *psz_parser )
439     {
440         char *psz_module, *psz_temp;
441         psz_module = psz_parser;
442         psz_parser = strchr( psz_module, ':' );
443         if ( psz_parser )
444         {
445             *psz_parser = '\0';
446             psz_parser++;
447         }
448         if( asprintf( &psz_temp, "%s,none", psz_module ) != -1)
449         {
450             libvlc_InternalAddIntf( p_libvlc, psz_temp );
451             free( psz_temp );
452         }
453     }
454     free( psz_modules );
455     free( psz_control );
456
457 #ifdef HAVE_SYSLOG_H
458     if( var_InheritBool( p_libvlc, "syslog" ) )
459     {
460         char *logmode = var_CreateGetNonEmptyString( p_libvlc, "logmode" );
461         var_SetString( p_libvlc, "logmode", "syslog" );
462         libvlc_InternalAddIntf( p_libvlc, "logger,none" );
463
464         if( logmode )
465         {
466             var_SetString( p_libvlc, "logmode", logmode );
467             free( logmode );
468         }
469         var_Destroy( p_libvlc, "logmode" );
470     }
471     else
472 #endif
473     if( var_InheritBool( p_libvlc, "file-logging" ) )
474         libvlc_InternalAddIntf( p_libvlc, "logger,none" );
475
476     if( var_InheritBool( p_libvlc, "network-synchronisation") )
477         libvlc_InternalAddIntf( p_libvlc, "netsync,none" );
478
479 #ifdef __APPLE__
480     var_Create( p_libvlc, "drawable-view-top", VLC_VAR_INTEGER );
481     var_Create( p_libvlc, "drawable-view-left", VLC_VAR_INTEGER );
482     var_Create( p_libvlc, "drawable-view-bottom", VLC_VAR_INTEGER );
483     var_Create( p_libvlc, "drawable-view-right", VLC_VAR_INTEGER );
484     var_Create( p_libvlc, "drawable-clip-top", VLC_VAR_INTEGER );
485     var_Create( p_libvlc, "drawable-clip-left", VLC_VAR_INTEGER );
486     var_Create( p_libvlc, "drawable-clip-bottom", VLC_VAR_INTEGER );
487     var_Create( p_libvlc, "drawable-clip-right", VLC_VAR_INTEGER );
488     var_Create( p_libvlc, "drawable-nsobject", VLC_VAR_ADDRESS );
489 #endif
490 #if defined (_WIN32) || defined (__OS2__)
491     var_Create( p_libvlc, "drawable-hwnd", VLC_VAR_INTEGER );
492 #endif
493
494     /*
495      * Get input filenames given as commandline arguments.
496      * We assume that the remaining parameters are filenames
497      * and their input options.
498      */
499     GetFilenames( p_libvlc, i_argc - vlc_optind, ppsz_argv + vlc_optind );
500
501     /*
502      * Get --open argument
503      */
504     psz_val = var_InheritString( p_libvlc, "open" );
505     if ( psz_val != NULL )
506     {
507         intf_InsertItem( p_libvlc, psz_val, 0, NULL, 0 );
508         free( psz_val );
509     }
510
511     return VLC_SUCCESS;
512 }
513
514 /**
515  * Cleanup a libvlc instance. The instance is not completely deallocated
516  * \param p_libvlc the instance to clean
517  */
518 void libvlc_InternalCleanup( libvlc_int_t *p_libvlc )
519 {
520     libvlc_priv_t *priv = libvlc_priv (p_libvlc);
521
522     /* Ask the interfaces to stop and destroy them */
523     msg_Dbg( p_libvlc, "removing all interfaces" );
524     libvlc_Quit( p_libvlc );
525     intf_DestroyAll( p_libvlc );
526
527 #ifdef ENABLE_VLM
528     /* Destroy VLM if created in libvlc_InternalInit */
529     if( priv->p_vlm )
530     {
531         vlm_Delete( priv->p_vlm );
532     }
533 #endif
534
535 #if !defined( _WIN32 ) && !defined( __OS2__ )
536     char *pidfile = var_InheritString( p_libvlc, "pidfile" );
537     if( pidfile != NULL )
538     {
539         msg_Dbg( p_libvlc, "removing PID file %s", pidfile );
540         if( unlink( pidfile ) )
541             msg_Warn( p_libvlc, "cannot remove PID file %s: %s",
542                       pidfile, vlc_strerror_c(errno) );
543         free( pidfile );
544     }
545 #endif
546
547     if (priv->parser != NULL)
548         playlist_preparser_Delete(priv->parser);
549
550     vlc_DeinitActions( p_libvlc, priv->actions );
551
552     /* Save the configuration */
553     if( !var_InheritBool( p_libvlc, "ignore-config" ) )
554         config_AutoSaveConfigFile( VLC_OBJECT(p_libvlc) );
555
556     /* Free module bank. It is refcounted, so we call this each time  */
557     module_EndBank (true);
558     vlc_LogDeinit (p_libvlc);
559 #if defined(_WIN32) || defined(__OS2__)
560     system_End( );
561 #endif
562 }
563
564 /**
565  * Destroy everything.
566  * This function requests the running threads to finish, waits for their
567  * termination, and destroys their structure.
568  * It stops the thread systems: no instance can run after this has run
569  * \param p_libvlc the instance to destroy
570  */
571 void libvlc_InternalDestroy( libvlc_int_t *p_libvlc )
572 {
573     libvlc_priv_t *priv = libvlc_priv( p_libvlc );
574
575     vlc_ExitDestroy( &priv->exit );
576
577     assert( atomic_load(&(vlc_internals(p_libvlc)->refs)) == 1 );
578     vlc_object_release( p_libvlc );
579 }
580
581 /*****************************************************************************
582  * GetFilenames: parse command line options which are not flags
583  *****************************************************************************
584  * Parse command line for input files as well as their associated options.
585  * An option always follows its associated input and begins with a ":".
586  *****************************************************************************/
587 static void GetFilenames( libvlc_int_t *p_vlc, unsigned n,
588                           const char *const args[] )
589 {
590     while( n > 0 )
591     {
592         /* Count the input options */
593         unsigned i_options = 0;
594
595         while( args[--n][0] == ':' )
596         {
597             i_options++;
598             if( n == 0 )
599             {
600                 msg_Warn( p_vlc, "options %s without item", args[n] );
601                 return; /* syntax!? */
602             }
603         }
604
605         char *mrl = NULL;
606         if( strstr( args[n], "://" ) == NULL )
607         {
608             mrl = vlc_path2uri( args[n], NULL );
609             if( !mrl )
610                 continue;
611         }
612
613         intf_InsertItem( p_vlc, (mrl != NULL) ? mrl : args[n], i_options,
614                          ( i_options ? &args[n + 1] : NULL ),
615                          VLC_INPUT_OPTION_TRUSTED );
616         free( mrl );
617     }
618 }
619
620 /**
621  * Requests extraction of the meta data for an input item (a.k.a. preparsing).
622  * The actual extraction is asynchronous.
623  */
624 int libvlc_MetaRequest(libvlc_int_t *libvlc, input_item_t *item)
625 {
626     libvlc_priv_t *priv = libvlc_priv(libvlc);
627
628     if (unlikely(priv->parser == NULL))
629         return VLC_ENOMEM;
630
631     playlist_preparser_Push(priv->parser, item);
632     return VLC_SUCCESS;
633 }
634
635 /**
636  * Requests retrieving/downloading art for an input item.
637  * The retrieval is performed asynchronously.
638  */
639 int libvlc_ArtRequest(libvlc_int_t *libvlc, input_item_t *item)
640 {
641     libvlc_priv_t *priv = libvlc_priv(libvlc);
642
643     if (unlikely(priv->parser == NULL))
644         return VLC_ENOMEM;
645
646     playlist_preparser_fetcher_Push(priv->parser, item);
647     return VLC_SUCCESS;
648 }