5d1c60f4361bec770eaade93a9244978daeed25d
[vlc.git] / src / playlist / thread.c
1 /*****************************************************************************
2  * thread.c : Playlist management functions
3  *****************************************************************************
4  * Copyright © 1999-2008 the VideoLAN team
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
11  * it under the terms of the GNU General Public License as published by
12  * the Free Software Foundation; either version 2 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 General Public License for more details.
19  *
20  * You should have received a copy of the GNU General Public License
21  * along with this program; if not, write to the Free Software
22  * Foundation, 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 <vlc_common.h>
29 #include <vlc_es.h>
30 #include <vlc_input.h>
31 #include <vlc_interface.h>
32 #include <vlc_playlist.h>
33 #include "stream_output/stream_output.h"
34 #include "playlist_internal.h"
35
36 /*****************************************************************************
37  * Local prototypes
38  *****************************************************************************/
39 static void *Thread   ( void * );
40
41 /*****************************************************************************
42  * Main functions for the global thread
43  *****************************************************************************/
44
45 /**
46  * Create the main playlist threads.
47  * Additionally to the playlist, this thread controls :
48  *    - Statistics
49  *    - VLM
50  * \param p_parent
51  * \return an object with a started thread
52  */
53 void playlist_Activate( playlist_t *p_playlist )
54 {
55     /* */
56     playlist_private_t *p_sys = pl_priv(p_playlist);
57
58     /* Fetcher */
59     p_sys->p_fetcher = playlist_fetcher_New( p_playlist );
60     if( !p_sys->p_fetcher )
61         msg_Err( p_playlist, "cannot create playlist fetcher" );
62
63     /* Preparse */
64     p_sys->p_preparser = playlist_preparser_New( p_playlist, p_sys->p_fetcher );
65     if( !p_sys->p_preparser )
66         msg_Err( p_playlist, "cannot create playlist preparser" );
67
68     /* Start the playlist thread */
69     if( vlc_clone( &p_sys->thread, Thread, p_playlist,
70                    VLC_THREAD_PRIORITY_LOW ) )
71     {
72         msg_Err( p_playlist, "cannot spawn playlist thread" );
73     }
74     msg_Dbg( p_playlist, "Activated" );
75 }
76
77 void playlist_Deactivate( playlist_t *p_playlist )
78 {
79     /* */
80     playlist_private_t *p_sys = pl_priv(p_playlist);
81
82     msg_Dbg( p_playlist, "Deactivate" );
83
84     vlc_object_kill( p_playlist );
85     PL_LOCK;
86     vlc_cond_signal( &p_sys->signal );
87     PL_UNLOCK;
88
89     vlc_join( p_sys->thread, NULL );
90     assert( !p_sys->p_input );
91
92     PL_LOCK;
93     playlist_preparser_t *p_preparser = p_sys->p_preparser;
94     playlist_fetcher_t *p_fetcher = p_sys->p_fetcher;
95
96     p_sys->p_preparser = NULL;
97     p_sys->p_fetcher = NULL;
98     PL_UNLOCK;
99
100     if( p_preparser )
101         playlist_preparser_Delete( p_preparser );
102     if( p_fetcher )
103         playlist_fetcher_Delete( p_fetcher );
104
105     /* release input ressources */
106     if( p_sys->p_input_ressource )
107         input_ressource_Delete( p_sys->p_input_ressource );
108     p_sys->p_input_ressource = NULL;
109
110     /* */
111     playlist_MLDump( p_playlist );
112
113     PL_LOCK;
114
115     /* Release the current node */
116     set_current_status_node( p_playlist, NULL );
117
118     /* Release the current item */
119     set_current_status_item( p_playlist, NULL );
120
121     PL_UNLOCK;
122
123     msg_Dbg( p_playlist, "Deactivated" );
124 }
125
126 /* */
127
128 /* Input Callback */
129 static int InputEvent( vlc_object_t *p_this, char const *psz_cmd,
130                        vlc_value_t oldval, vlc_value_t newval, void *p_data )
131 {
132     VLC_UNUSED(p_this); VLC_UNUSED(psz_cmd); VLC_UNUSED(oldval);
133     playlist_t *p_playlist = p_data;
134
135     if( newval.i_int != INPUT_EVENT_STATE &&
136         newval.i_int != INPUT_EVENT_DEAD )
137         return VLC_SUCCESS;
138
139     PL_LOCK;
140
141     /* XXX: signaling while not changing any parameter... suspicious... */
142     vlc_cond_signal( &pl_priv(p_playlist)->signal );
143
144     PL_UNLOCK;
145     return VLC_SUCCESS;
146 }
147
148 static void UpdateActivity( playlist_t *p_playlist, int i_delta )
149 {
150     PL_ASSERT_LOCKED;
151
152     const int i_activity = var_GetInteger( p_playlist, "activity" ) ;
153     var_SetInteger( p_playlist, "activity", i_activity + i_delta );
154 }
155
156 /**
157  * Synchronise the current index of the playlist
158  * to match the index of the current item.
159  *
160  * \param p_playlist the playlist structure
161  * \param p_cur the current playlist item
162  * \return nothing
163  */
164 static void ResyncCurrentIndex( playlist_t *p_playlist, playlist_item_t *p_cur )
165 {
166     PL_ASSERT_LOCKED;
167
168     PL_DEBUG( "resyncing on %s", PLI_NAME( p_cur ) );
169     /* Simply resync index */
170     int i;
171     p_playlist->i_current_index = -1;
172     for( i = 0 ; i< p_playlist->current.i_size; i++ )
173     {
174         if( ARRAY_VAL( p_playlist->current, i ) == p_cur )
175         {
176             p_playlist->i_current_index = i;
177             break;
178         }
179     }
180     PL_DEBUG( "%s is at %i", PLI_NAME( p_cur ), p_playlist->i_current_index );
181 }
182
183 static void ResetCurrentlyPlaying( playlist_t *p_playlist,
184                                    playlist_item_t *p_cur )
185 {
186     playlist_private_t *p_sys = pl_priv(p_playlist);
187
188     stats_TimerStart( p_playlist, "Items array build",
189                       STATS_TIMER_PLAYLIST_BUILD );
190     PL_DEBUG( "rebuilding array of current - root %s",
191               PLI_NAME( p_sys->status.p_node ) );
192     ARRAY_RESET( p_playlist->current );
193     p_playlist->i_current_index = -1;
194     for( playlist_item_t *p_next = NULL; ; )
195     {
196         /** FIXME: this is *slow* */
197         p_next = playlist_GetNextLeaf( p_playlist,
198                                        p_sys->status.p_node,
199                                        p_next, true, false );
200         if( !p_next )
201             break;
202
203         if( p_next == p_cur )
204             p_playlist->i_current_index = p_playlist->current.i_size;
205         ARRAY_APPEND( p_playlist->current, p_next);
206     }
207     PL_DEBUG("rebuild done - %i items, index %i", p_playlist->current.i_size,
208                                                   p_playlist->i_current_index);
209
210     if( var_GetBool( p_playlist, "random" ) )
211     {
212         /* Shuffle the array */
213         srand( (unsigned int)mdate() );
214         for( int j = p_playlist->current.i_size - 1; j > 0; j-- )
215         {
216             int i = rand() % (j+1); /* between 0 and j */
217             playlist_item_t *p_tmp;
218             /* swap the two items */
219             p_tmp = ARRAY_VAL(p_playlist->current, i);
220             ARRAY_VAL(p_playlist->current,i) = ARRAY_VAL(p_playlist->current,j);
221             ARRAY_VAL(p_playlist->current,j) = p_tmp;
222         }
223     }
224     p_sys->b_reset_currently_playing = false;
225     stats_TimerStop( p_playlist, STATS_TIMER_PLAYLIST_BUILD );
226 }
227
228
229 /**
230  * Start the input for an item
231  *
232  * \param p_playlist the playlist object
233  * \param p_item the item to play
234  * \return nothing
235  */
236 static int PlayItem( playlist_t *p_playlist, playlist_item_t *p_item )
237 {
238     playlist_private_t *p_sys = pl_priv(p_playlist);
239     input_item_t *p_input = p_item->p_input;
240
241     PL_ASSERT_LOCKED;
242
243     msg_Dbg( p_playlist, "creating new input thread" );
244
245     p_input->i_nb_played++;
246     set_current_status_item( p_playlist, p_item );
247
248     p_sys->status.i_status = PLAYLIST_RUNNING;
249
250     UpdateActivity( p_playlist, DEFAULT_INPUT_ACTIVITY );
251
252     assert( p_sys->p_input == NULL );
253
254     input_thread_t *p_input_thread =
255         input_CreateThreadExtended( p_playlist, p_input, NULL, p_sys->p_input_ressource );
256
257     if( p_input_thread )
258     {
259         p_sys->p_input = p_input_thread;
260
261         var_AddCallback( p_input_thread, "intf-event", InputEvent, p_playlist );
262     }
263
264     p_sys->p_input_ressource = NULL;
265
266     char *psz_uri = input_item_GetURI( p_item->p_input );
267     if( psz_uri && ( !strncmp( psz_uri, "directory:", 10 ) ||
268                      !strncmp( psz_uri, "vlc:", 4 ) ) )
269     {
270         free( psz_uri );
271         return VLC_SUCCESS;
272     }
273     free( psz_uri );
274
275     /* TODO store art policy in playlist private data */
276     if( var_GetInteger( p_playlist, "album-art" ) == ALBUM_ART_WHEN_PLAYED )
277     {
278         bool b_has_art;
279
280         char *psz_arturl, *psz_name;
281         psz_arturl = input_item_GetArtURL( p_input );
282         psz_name = input_item_GetName( p_input );
283
284         /* p_input->p_meta should not be null after a successfull CreateThread */
285         b_has_art = !EMPTY_STR( psz_arturl );
286
287         if( !b_has_art || strncmp( psz_arturl, "attachment://", 13 ) )
288         {
289             PL_DEBUG( "requesting art for %s", psz_name );
290             playlist_AskForArtEnqueue( p_playlist, p_input, pl_Locked );
291         }
292         free( psz_arturl );
293         free( psz_name );
294     }
295
296     PL_UNLOCK;
297     var_SetInteger( p_playlist, "item-current", p_input->i_id );
298     PL_LOCK;
299
300     return VLC_SUCCESS;
301 }
302
303 /**
304  * Compute the next playlist item depending on
305  * the playlist course mode (forward, backward, random, view,...).
306  *
307  * \param p_playlist the playlist object
308  * \return nothing
309  */
310 static playlist_item_t *NextItem( playlist_t *p_playlist )
311 {
312     playlist_private_t *p_sys = pl_priv(p_playlist);
313     playlist_item_t *p_new = NULL;
314
315     /* Handle quickly a few special cases */
316     /* No items to play */
317     if( p_playlist->items.i_size == 0 )
318     {
319         msg_Info( p_playlist, "playlist is empty" );
320         return NULL;
321     }
322
323     /* Start the real work */
324     if( p_sys->request.b_request )
325     {
326         p_new = p_sys->request.p_item;
327         int i_skip = p_sys->request.i_skip;
328         PL_DEBUG( "processing request item %s node %s skip %i",
329                         PLI_NAME( p_sys->request.p_item ),
330                         PLI_NAME( p_sys->request.p_node ), i_skip );
331
332         if( p_sys->request.p_node &&
333             p_sys->request.p_node != get_current_status_node( p_playlist ) )
334         {
335
336             set_current_status_node( p_playlist, p_sys->request.p_node );
337             p_sys->request.p_node = NULL;
338             p_sys->b_reset_currently_playing = true;
339         }
340
341         /* If we are asked for a node, go to it's first child */
342         if( i_skip == 0 && ( p_new == NULL || p_new->i_children != -1 ) )
343         {
344             i_skip++;
345             if( p_new != NULL )
346             {
347                 p_new = playlist_GetNextLeaf( p_playlist, p_new, NULL, true, false );
348                 for( int i = 0; i < p_playlist->current.i_size; i++ )
349                 {
350                     if( p_new == ARRAY_VAL( p_playlist->current, i ) )
351                     {
352                         p_playlist->i_current_index = i;
353                         i_skip = 0;
354                     }
355                 }
356             }
357         }
358
359         if( p_sys->b_reset_currently_playing )
360             /* A bit too bad to reset twice ... */
361             ResetCurrentlyPlaying( p_playlist, p_new );
362         else if( p_new )
363             ResyncCurrentIndex( p_playlist, p_new );
364         else
365             p_playlist->i_current_index = -1;
366
367         if( p_playlist->current.i_size && (i_skip > 0) )
368         {
369             if( p_playlist->i_current_index < -1 )
370                 p_playlist->i_current_index = -1;
371             for( int i = i_skip; i > 0 ; i-- )
372             {
373                 p_playlist->i_current_index++;
374                 if( p_playlist->i_current_index >= p_playlist->current.i_size )
375                 {
376                     PL_DEBUG( "looping - restarting at beginning of node" );
377                     p_playlist->i_current_index = 0;
378                 }
379             }
380             p_new = ARRAY_VAL( p_playlist->current,
381                                p_playlist->i_current_index );
382         }
383         else if( p_playlist->current.i_size && (i_skip < 0) )
384         {
385             for( int i = i_skip; i < 0 ; i++ )
386             {
387                 p_playlist->i_current_index--;
388                 if( p_playlist->i_current_index <= -1 )
389                 {
390                     PL_DEBUG( "looping - restarting at end of node" );
391                     p_playlist->i_current_index = p_playlist->current.i_size-1;
392                 }
393             }
394             p_new = ARRAY_VAL( p_playlist->current,
395                                p_playlist->i_current_index );
396         }
397         /* Clear the request */
398         p_sys->request.b_request = false;
399     }
400     /* "Automatic" item change ( next ) */
401     else
402     {
403         bool b_loop = var_GetBool( p_playlist, "loop" );
404         bool b_repeat = var_GetBool( p_playlist, "repeat" );
405         bool b_playstop = var_GetBool( p_playlist, "play-and-stop" );
406
407         /* Repeat and play/stop */
408         if( b_repeat && get_current_status_item( p_playlist ) )
409         {
410             msg_Dbg( p_playlist,"repeating item" );
411             return get_current_status_item( p_playlist );
412         }
413         if( b_playstop )
414         {
415             msg_Dbg( p_playlist,"stopping (play and stop)" );
416             return NULL;
417         }
418
419         /* */
420         if( get_current_status_item( p_playlist ) )
421         {
422             playlist_item_t *p_parent = get_current_status_item( p_playlist );
423             while( p_parent )
424             {
425                 if( p_parent->i_flags & PLAYLIST_SKIP_FLAG )
426                 {
427                     msg_Dbg( p_playlist, "blocking item, stopping") ;
428                     return NULL;
429                 }
430                 p_parent = p_parent->p_parent;
431             }
432         }
433
434         PL_DEBUG( "changing item without a request (current %i/%i)",
435                   p_playlist->i_current_index, p_playlist->current.i_size );
436         /* Cant go to next from current item */
437         if( get_current_status_item( p_playlist ) &&
438             get_current_status_item( p_playlist )->i_flags & PLAYLIST_SKIP_FLAG )
439             return NULL;
440
441         if( p_sys->b_reset_currently_playing )
442             ResetCurrentlyPlaying( p_playlist,
443                                    get_current_status_item( p_playlist ) );
444
445         p_playlist->i_current_index++;
446         assert( p_playlist->i_current_index <= p_playlist->current.i_size );
447         if( p_playlist->i_current_index == p_playlist->current.i_size )
448         {
449             if( !b_loop || p_playlist->current.i_size == 0 )
450                 return NULL;
451             p_playlist->i_current_index = 0;
452         }
453         PL_DEBUG( "using item %i", p_playlist->i_current_index );
454         if ( p_playlist->current.i_size == 0 )
455             return NULL;
456
457         p_new = ARRAY_VAL( p_playlist->current, p_playlist->i_current_index );
458         /* The new item can't be autoselected  */
459         if( p_new != NULL && p_new->i_flags & PLAYLIST_SKIP_FLAG )
460             return NULL;
461     }
462     return p_new;
463 }
464
465 static int LoopInput( playlist_t *p_playlist )
466 {
467     playlist_private_t *p_sys = pl_priv(p_playlist);
468     input_thread_t *p_input = p_sys->p_input;
469
470     if( !p_input )
471         return VLC_EGENERIC;
472
473     if( ( p_sys->request.b_request || !vlc_object_alive( p_playlist ) ) && !p_input->b_die )
474     {
475         PL_DEBUG( "incoming request - stopping current input" );
476         input_StopThread( p_input );
477     }
478
479     /* This input is dead. Remove it ! */
480     if( p_input->b_dead )
481     {
482         PL_DEBUG( "dead input" );
483
484         assert( p_sys->p_input_ressource == NULL );
485
486         p_sys->p_input_ressource = input_DetachRessource( p_input );
487
488         PL_UNLOCK;
489         /* We can unlock as we return VLC_EGENERIC (no event will be lost) */
490
491         /* input_ressource_t must be manipulated without playlist lock */
492         if( !var_CreateGetBool( p_input, "sout-keep" ) )
493             input_ressource_TerminateSout( p_sys->p_input_ressource );
494
495         /* The DelCallback must be issued without playlist lock */
496         var_DelCallback( p_input, "intf-event", InputEvent, p_playlist );
497
498         PL_LOCK;
499
500         p_sys->p_input = NULL;
501         vlc_thread_join( p_input );
502         vlc_object_release( p_input );
503
504         UpdateActivity( p_playlist, -DEFAULT_INPUT_ACTIVITY );
505
506         return VLC_EGENERIC;
507     }
508     /* This input is dying, let it do */
509     else if( p_input->b_die )
510     {
511         PL_DEBUG( "dying input" );
512     }
513     /* This input has finished, ask it to die ! */
514     else if( p_input->b_error || p_input->b_eof )
515     {
516         PL_DEBUG( "finished input" );
517         input_StopThread( p_input );
518     }
519     return VLC_SUCCESS;
520 }
521
522 static void LoopRequest( playlist_t *p_playlist )
523 {
524     playlist_private_t *p_sys = pl_priv(p_playlist);
525     assert( !p_sys->p_input );
526
527     /* No input. Several cases
528      *  - No request, running status -> start new item
529      *  - No request, stopped status -> collect garbage
530      *  - Request, running requested -> start new item
531      *  - Request, stopped requested -> collect garbage
532     */
533     const int i_status = p_sys->request.b_request ?
534                          p_sys->request.i_status : p_sys->status.i_status;
535
536     if( i_status == PLAYLIST_STOPPED || !vlc_object_alive( p_playlist ) )
537     {
538         p_sys->status.i_status = PLAYLIST_STOPPED;
539
540         if( p_sys->p_input_ressource &&
541             input_ressource_HasVout( p_sys->p_input_ressource ) )
542         {
543             /* XXX We can unlock if we don't issue the wait as we will be
544              * call again without anything else done between the calls */
545             PL_UNLOCK;
546
547             /* input_ressource_t must be manipulated without playlist lock */
548             input_ressource_TerminateVout( p_sys->p_input_ressource );
549
550             PL_LOCK;
551         }
552         else
553         {
554             if( vlc_object_alive( p_playlist ) )
555                 vlc_cond_wait( &pl_priv(p_playlist)->signal,
556                                &vlc_internals(p_playlist)->lock );
557         }
558         return;
559     }
560
561     playlist_item_t *p_item = NextItem( p_playlist );
562     if( p_item )
563     {
564         msg_Dbg( p_playlist, "starting new item" );
565         PlayItem( p_playlist, p_item );
566         return;
567     }
568
569     msg_Dbg( p_playlist, "nothing to play" );
570     p_sys->status.i_status = PLAYLIST_STOPPED;
571
572     if( var_GetBool( p_playlist, "play-and-exit" ) )
573     {
574         msg_Info( p_playlist, "end of playlist, exiting" );
575         libvlc_Quit( p_playlist->p_libvlc );
576     }
577 }
578
579 /**
580  * Run the main control thread itself
581  */
582 static void *Thread ( void *data )
583 {
584     playlist_t *p_playlist = data;
585     playlist_private_t *p_sys = pl_priv(p_playlist);
586
587     vlc_object_lock( p_playlist );
588     while( vlc_object_alive( p_playlist ) || p_sys->p_input )
589     {
590         /* FIXME: what's that ! */
591         if( p_sys->b_reset_currently_playing &&
592             mdate() - p_sys->last_rebuild_date > 30000 ) // 30 ms
593         {
594             ResetCurrentlyPlaying( p_playlist,
595                                    get_current_status_item( p_playlist ) );
596             p_sys->last_rebuild_date = mdate();
597         }
598
599         /* If there is an input, check that it doesn't need to die. */
600         while( !LoopInput( p_playlist ) )
601             vlc_cond_wait( &pl_priv(p_playlist)->signal,
602                            &vlc_internals(p_playlist)->lock );
603
604         LoopRequest( p_playlist );
605     }
606     vlc_object_unlock( p_playlist );
607
608     return NULL;
609 }
610