c41ea19220936d596c482960b61bb1cfa79bcd7f
[vlc.git] / src / playlist / thread.c
1 /*****************************************************************************
2  * thread.c : Playlist management functions
3  *****************************************************************************
4  * Copyright © 1999-2008 VLC authors and VideoLAN
5  * $Id$
6  *
7  * Authors: Samuel Hocevar <sam@zoy.org>
8  *          Clément Stenac <zorglub@videolan.org>
9  *
10  * This program is free software; you can redistribute it and/or modify it
11  * under the terms of the GNU Lesser General Public License as published by
12  * the Free Software Foundation; either version 2.1 of the License, or
13  * (at your option) any later version.
14  *
15  * This program is distributed in the hope that it will be useful,
16  * but WITHOUT ANY WARRANTY; without even the implied warranty of
17  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18  * GNU Lesser General Public License for more details.
19  *
20  * You should have received a copy of the GNU Lesser General Public License
21  * along with this program; if not, write to the Free Software Foundation,
22  * Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
23  *****************************************************************************/
24 #ifdef HAVE_CONFIG_H
25 # include "config.h"
26 #endif
27
28 #include <assert.h>
29
30 #include <vlc_common.h>
31 #include <vlc_es.h>
32 #include <vlc_input.h>
33 #include <vlc_interface.h>
34 #include <vlc_playlist.h>
35 #include <vlc_rand.h>
36 #include "stream_output/stream_output.h"
37 #include "playlist_internal.h"
38
39 /*****************************************************************************
40  * Local prototypes
41  *****************************************************************************/
42 static void *Thread   ( void * );
43
44 /*****************************************************************************
45  * Main functions for the global thread
46  *****************************************************************************/
47
48 /**
49  * Creates the main playlist thread.
50  */
51 void playlist_Activate( playlist_t *p_playlist )
52 {
53     playlist_private_t *p_sys = pl_priv(p_playlist);
54
55     if( vlc_clone( &p_sys->thread, Thread, p_playlist,
56                    VLC_THREAD_PRIORITY_LOW ) )
57     {
58         msg_Err( p_playlist, "cannot spawn playlist thread" );
59         abort();
60     }
61 }
62
63 /**
64  * Stops the playlist forever (but do not destroy it yet).
65  * Any input is stopped.
66  * \return Nothing but waits for the playlist to be deactivated.
67  */
68 void playlist_Deactivate( playlist_t *p_playlist )
69 {
70     playlist_private_t *p_sys = pl_priv(p_playlist);
71
72     PL_LOCK;
73     /* WARNING: There is a latent bug. It is assumed that only one thread will
74      * be waiting for playlist deactivation at a time. So far, that works
75      * as playlist_Deactivate() is only ever called while closing an
76      * interface and interfaces are shut down serially by intf_DestroyAll(). */
77     if( p_sys->killed )
78     {
79         PL_UNLOCK;
80         return;
81     }
82
83     msg_Dbg( p_playlist, "deactivating the playlist" );
84     p_sys->killed = true;
85     vlc_cond_signal( &p_sys->signal );
86     PL_UNLOCK;
87
88     vlc_join( p_sys->thread, NULL );
89 }
90
91 /* */
92
93 /* Input Callback */
94 static int InputEvent( vlc_object_t *p_this, char const *psz_cmd,
95                        vlc_value_t oldval, vlc_value_t newval, void *p_data )
96 {
97     VLC_UNUSED(p_this); VLC_UNUSED(psz_cmd); VLC_UNUSED(oldval);
98     playlist_t *p_playlist = p_data;
99
100     if( newval.i_int != INPUT_EVENT_STATE &&
101         newval.i_int != INPUT_EVENT_DEAD )
102         return VLC_SUCCESS;
103
104     PL_LOCK;
105
106     /* XXX: signaling while not changing any parameter... suspicious... */
107     vlc_cond_signal( &pl_priv(p_playlist)->signal );
108
109     PL_UNLOCK;
110     return VLC_SUCCESS;
111 }
112
113 /**
114  * Synchronise the current index of the playlist
115  * to match the index of the current item.
116  *
117  * \param p_playlist the playlist structure
118  * \param p_cur the current playlist item
119  * \return nothing
120  */
121 void ResyncCurrentIndex( playlist_t *p_playlist, playlist_item_t *p_cur )
122 {
123     PL_ASSERT_LOCKED;
124
125     PL_DEBUG( "resyncing on %s", PLI_NAME( p_cur ) );
126     /* Simply resync index */
127     int i;
128     p_playlist->i_current_index = -1;
129     for( i = 0 ; i< p_playlist->current.i_size; i++ )
130     {
131         if( ARRAY_VAL( p_playlist->current, i ) == p_cur )
132         {
133             p_playlist->i_current_index = i;
134             break;
135         }
136     }
137     PL_DEBUG( "%s is at %i", PLI_NAME( p_cur ), p_playlist->i_current_index );
138 }
139
140 /**
141  * Reset the currently playing playlist.
142  *
143  * \param p_playlist the playlist structure
144  * \param p_cur the current playlist item
145  * \return nothing
146  */
147 void ResetCurrentlyPlaying( playlist_t *p_playlist,
148                                    playlist_item_t *p_cur )
149 {
150     playlist_private_t *p_sys = pl_priv(p_playlist);
151
152     PL_DEBUG( "rebuilding array of current - root %s",
153               PLI_NAME( p_sys->status.p_node ) );
154     ARRAY_RESET( p_playlist->current );
155     p_playlist->i_current_index = -1;
156     for( playlist_item_t *p_next = NULL; ; )
157     {
158         /** FIXME: this is *slow* */
159         p_next = playlist_GetNextLeaf( p_playlist,
160                                        p_sys->status.p_node,
161                                        p_next, true, false );
162         if( !p_next )
163             break;
164
165         if( p_next == p_cur )
166             p_playlist->i_current_index = p_playlist->current.i_size;
167         ARRAY_APPEND( p_playlist->current, p_next);
168     }
169     PL_DEBUG("rebuild done - %i items, index %i", p_playlist->current.i_size,
170                                                   p_playlist->i_current_index);
171
172     if( var_GetBool( p_playlist, "random" ) && ( p_playlist->current.i_size > 0 ) )
173     {
174         /* Shuffle the array */
175         for( unsigned j = p_playlist->current.i_size - 1; j > 0; j-- )
176         {
177             unsigned i = vlc_lrand48() % (j+1); /* between 0 and j */
178             playlist_item_t *p_tmp;
179             /* swap the two items */
180             p_tmp = ARRAY_VAL(p_playlist->current, i);
181             ARRAY_VAL(p_playlist->current,i) = ARRAY_VAL(p_playlist->current,j);
182             ARRAY_VAL(p_playlist->current,j) = p_tmp;
183         }
184     }
185     p_sys->b_reset_currently_playing = false;
186 }
187
188
189 /**
190  * Start the input for an item
191  *
192  * \param p_playlist the playlist object
193  * \param p_item the item to play
194  * \return nothing
195  */
196 static int PlayItem( playlist_t *p_playlist, playlist_item_t *p_item )
197 {
198     playlist_private_t *p_sys = pl_priv(p_playlist);
199     input_item_t *p_input = p_item->p_input;
200
201     PL_ASSERT_LOCKED;
202
203     msg_Dbg( p_playlist, "creating new input thread" );
204
205     p_input->i_nb_played++;
206     set_current_status_item( p_playlist, p_item );
207
208     p_sys->status.i_status = PLAYLIST_RUNNING;
209
210     assert( p_sys->p_input == NULL );
211
212     input_thread_t *p_input_thread = input_Create( p_playlist, p_input, NULL, p_sys->p_input_resource );
213     if( p_input_thread )
214     {
215         p_sys->p_input = p_input_thread;
216         var_AddCallback( p_input_thread, "intf-event", InputEvent, p_playlist );
217
218         var_SetAddress( p_playlist, "input-current", p_input_thread );
219
220         if( input_Start( p_sys->p_input ) )
221         {
222             vlc_object_release( p_input_thread );
223             p_sys->p_input = p_input_thread = NULL;
224         }
225     }
226
227     /* TODO store art policy in playlist private data */
228     char *psz_arturl = input_item_GetArtURL( p_input );
229     char *psz_name = input_item_GetName( p_input );
230     /* p_input->p_meta should not be null after a successful CreateThread */
231     bool b_has_art = !EMPTY_STR( psz_arturl );
232
233     if( !b_has_art || strncmp( psz_arturl, "attachment://", 13 ) )
234     {
235         PL_DEBUG( "requesting art for %s", psz_name );
236         libvlc_ArtRequest( p_playlist->p_libvlc, p_input, META_REQUEST_OPTION_NONE );
237     }
238     free( psz_arturl );
239     free( psz_name );
240
241     PL_UNLOCK;
242     var_TriggerCallback( p_playlist, "activity" );
243     PL_LOCK;
244
245     return VLC_SUCCESS;
246 }
247
248 /**
249  * Compute the next playlist item depending on
250  * the playlist course mode (forward, backward, random, view,...).
251  *
252  * \param p_playlist the playlist object
253  * \return nothing
254  */
255 static playlist_item_t *NextItem( playlist_t *p_playlist )
256 {
257     playlist_private_t *p_sys = pl_priv(p_playlist);
258     playlist_item_t *p_new = NULL;
259
260     /* Handle quickly a few special cases */
261     /* No items to play */
262     if( p_playlist->items.i_size == 0 )
263     {
264         msg_Info( p_playlist, "playlist is empty" );
265         return NULL;
266     }
267
268     /* Start the real work */
269     if( p_sys->request.b_request )
270     {
271         p_new = p_sys->request.p_item;
272         int i_skip = p_sys->request.i_skip;
273         PL_DEBUG( "processing request item: %s, node: %s, skip: %i",
274                         PLI_NAME( p_sys->request.p_item ),
275                         PLI_NAME( p_sys->request.p_node ), i_skip );
276
277         if( p_sys->request.p_node &&
278             p_sys->request.p_node != get_current_status_node( p_playlist ) )
279         {
280
281             set_current_status_node( p_playlist, p_sys->request.p_node );
282             p_sys->request.p_node = NULL;
283             p_sys->b_reset_currently_playing = true;
284         }
285
286         /* If we are asked for a node, go to it's first child */
287         if( i_skip == 0 && ( p_new == NULL || p_new->i_children != -1 ) )
288         {
289             i_skip++;
290             if( p_new != NULL )
291             {
292                 p_new = playlist_GetNextLeaf( p_playlist, p_new, NULL, true, false );
293                 for( int i = 0; i < p_playlist->current.i_size; i++ )
294                 {
295                     if( p_new == ARRAY_VAL( p_playlist->current, i ) )
296                     {
297                         p_playlist->i_current_index = i;
298                         i_skip = 0;
299                     }
300                 }
301             }
302         }
303
304         if( p_sys->b_reset_currently_playing )
305             /* A bit too bad to reset twice ... */
306             ResetCurrentlyPlaying( p_playlist, p_new );
307         else if( p_new )
308             ResyncCurrentIndex( p_playlist, p_new );
309         else
310             p_playlist->i_current_index = -1;
311
312         if( p_playlist->current.i_size && (i_skip > 0) )
313         {
314             if( p_playlist->i_current_index < -1 )
315                 p_playlist->i_current_index = -1;
316             for( int i = i_skip; i > 0 ; i-- )
317             {
318                 p_playlist->i_current_index++;
319                 if( p_playlist->i_current_index >= p_playlist->current.i_size )
320                 {
321                     PL_DEBUG( "looping - restarting at beginning of node" );
322                     /* reshuffle playlist when end is reached */
323                     if( var_GetBool( p_playlist, "random" ) ) {
324                         PL_DEBUG( "reshuffle playlist" );
325                         ResetCurrentlyPlaying( p_playlist,
326                                 get_current_status_item( p_playlist ) );
327                     }
328                     p_playlist->i_current_index = 0;
329                 }
330             }
331             p_new = ARRAY_VAL( p_playlist->current,
332                                p_playlist->i_current_index );
333         }
334         else if( p_playlist->current.i_size && (i_skip < 0) )
335         {
336             for( int i = i_skip; i < 0 ; i++ )
337             {
338                 p_playlist->i_current_index--;
339                 if( p_playlist->i_current_index <= -1 )
340                 {
341                     PL_DEBUG( "looping - restarting at end of node" );
342                     /* reshuffle playlist when beginning is reached */
343                     if( var_GetBool( p_playlist, "random" ) ) {
344                         PL_DEBUG( "reshuffle playlist" );
345                         ResetCurrentlyPlaying( p_playlist,
346                                 get_current_status_item( p_playlist ) );
347                     }
348                     p_playlist->i_current_index = p_playlist->current.i_size-1;
349                 }
350             }
351             p_new = ARRAY_VAL( p_playlist->current,
352                                p_playlist->i_current_index );
353         }
354         /* Clear the request */
355         p_sys->request.b_request = false;
356     }
357     /* "Automatic" item change ( next ) */
358     else
359     {
360         bool b_loop = var_GetBool( p_playlist, "loop" );
361         bool b_repeat = var_GetBool( p_playlist, "repeat" );
362         bool b_playstop = var_InheritBool( p_playlist, "play-and-stop" );
363
364         /* Repeat and play/stop */
365         if( b_repeat && get_current_status_item( p_playlist ) )
366         {
367             msg_Dbg( p_playlist,"repeating item" );
368             return get_current_status_item( p_playlist );
369         }
370         if( b_playstop )
371         {
372             msg_Dbg( p_playlist,"stopping (play and stop)" );
373             return NULL;
374         }
375
376         /* */
377         if( get_current_status_item( p_playlist ) )
378         {
379             playlist_item_t *p_parent = get_current_status_item( p_playlist );
380             while( p_parent )
381             {
382                 if( p_parent->i_flags & PLAYLIST_SKIP_FLAG )
383                 {
384                     msg_Dbg( p_playlist, "blocking item, stopping") ;
385                     return NULL;
386                 }
387                 p_parent = p_parent->p_parent;
388             }
389         }
390
391         PL_DEBUG( "changing item without a request (current %i/%i)",
392                   p_playlist->i_current_index, p_playlist->current.i_size );
393         /* Cant go to next from current item */
394         if( get_current_status_item( p_playlist ) &&
395             get_current_status_item( p_playlist )->i_flags & PLAYLIST_SKIP_FLAG )
396             return NULL;
397
398         if( p_sys->b_reset_currently_playing )
399             ResetCurrentlyPlaying( p_playlist,
400                                    get_current_status_item( p_playlist ) );
401
402         p_playlist->i_current_index++;
403         assert( p_playlist->i_current_index <= p_playlist->current.i_size );
404         if( p_playlist->i_current_index == p_playlist->current.i_size )
405         {
406             if( !b_loop || p_playlist->current.i_size == 0 )
407                 return NULL;
408             /* reshuffle after last item has been played */
409             if( var_GetBool( p_playlist, "random" ) ) {
410                 PL_DEBUG( "reshuffle playlist" );
411                 ResetCurrentlyPlaying( p_playlist,
412                                        get_current_status_item( p_playlist ) );
413             }
414             p_playlist->i_current_index = 0;
415         }
416         PL_DEBUG( "using item %i", p_playlist->i_current_index );
417         if ( p_playlist->current.i_size == 0 )
418             return NULL;
419
420         p_new = ARRAY_VAL( p_playlist->current, p_playlist->i_current_index );
421         /* The new item can't be autoselected  */
422         if( p_new != NULL && p_new->i_flags & PLAYLIST_SKIP_FLAG )
423             return NULL;
424     }
425     return p_new;
426 }
427
428 static void LoopInput( playlist_t *p_playlist )
429 {
430     playlist_private_t *p_sys = pl_priv(p_playlist);
431     input_thread_t *p_input = p_sys->p_input;
432
433     assert( p_input != NULL );
434
435     if( p_sys->request.b_request || p_sys->killed )
436     {
437         PL_DEBUG( "incoming request - stopping current input" );
438         input_Stop( p_input, true );
439     }
440
441 #warning Unsynchronized access to *p_input flags...
442     /* This input is dead. Remove it ! */
443     if( p_input->b_dead )
444     {
445         p_sys->p_input = NULL;
446         PL_DEBUG( "dead input" );
447         PL_UNLOCK;
448
449         /* WARNING: Input resource manipulation and callback deletion are
450          * incompatible with the playlist lock. */
451         if( !var_InheritBool( p_input, "sout-keep" ) )
452             input_resource_TerminateSout( p_sys->p_input_resource );
453         var_DelCallback( p_input, "intf-event", InputEvent, p_playlist );
454
455         input_Close( p_input );
456         var_TriggerCallback( p_playlist, "activity" );
457         PL_LOCK;
458         return;
459     }
460     /* This input has finished, ask it to die ! */
461     else if( p_input->b_error || p_input->b_eof )
462     {
463         PL_DEBUG( "finished input" );
464         input_Stop( p_input, false );
465     }
466
467     vlc_cond_wait( &p_sys->signal, &p_sys->lock );
468 }
469
470 static void LoopRequest( playlist_t *p_playlist, int i_status )
471 {
472     playlist_private_t *p_sys = pl_priv(p_playlist);
473     assert( !p_sys->p_input );
474
475     /* No input. Several cases
476      *  - No request, running status -> start new item
477      *  - No request, stopped status -> collect garbage
478      *  - Request, running requested -> start new item
479      *  - Request, stopped requested -> collect garbage
480     */
481     if( i_status == PLAYLIST_STOPPED )
482     {
483         p_sys->status.i_status = PLAYLIST_STOPPED;
484         vlc_cond_wait( &p_sys->signal, &p_sys->lock );
485         return;
486     }
487
488     playlist_item_t *p_item = NextItem( p_playlist );
489     if( p_item )
490     {
491         msg_Dbg( p_playlist, "starting playback of the new playlist item" );
492         ResyncCurrentIndex( p_playlist, p_item );
493         PlayItem( p_playlist, p_item );
494         return;
495     }
496
497     msg_Dbg( p_playlist, "nothing to play" );
498     p_sys->status.i_status = PLAYLIST_STOPPED;
499
500     if( var_InheritBool( p_playlist, "play-and-exit" ) )
501     {
502         msg_Info( p_playlist, "end of playlist, exiting" );
503         libvlc_Quit( p_playlist->p_libvlc );
504     }
505 }
506
507 /**
508  * Run the main control thread itself
509  */
510 static void *Thread ( void *data )
511 {
512     playlist_t *p_playlist = data;
513     playlist_private_t *p_sys = pl_priv(p_playlist);
514
515     PL_LOCK;
516     for( ;; )
517     {
518         while( p_sys->p_input != NULL )
519             LoopInput( p_playlist );
520
521         if( p_sys->killed )
522             break; /* THE END */
523
524         const int status = p_sys->request.b_request ?
525                            p_sys->request.i_status : p_sys->status.i_status;
526
527         /* Destroy any video display if the playlist is supposed to stop */
528         if( status == PLAYLIST_STOPPED
529          && input_resource_HasVout( p_sys->p_input_resource ) )
530         {
531             PL_UNLOCK; /* Mind: NO LOCKS while manipulating input resources! */
532             input_resource_TerminateVout( p_sys->p_input_resource );
533             PL_LOCK;
534             continue; /* lost lock = lost state */
535         }
536
537         LoopRequest( p_playlist, status );
538     }
539     p_sys->status.i_status = PLAYLIST_STOPPED;
540     PL_UNLOCK;
541
542     input_resource_Terminate( p_sys->p_input_resource );
543     return NULL;
544 }