Debian Codegraph @

xl/player/queue.py

raw
1 # Copyright (C) 2008-2010 Adam Olsen
2 #
3 # This program is free software; you can redistribute it and/or modify
4 # it under the terms of the GNU General Public License as published by
5 # the Free Software Foundation; either version 2, or (at your option)
6 # any later version.
7 #
8 # This program is distributed in the hope that it will be useful,
9 # but WITHOUT ANY WARRANTY; without even the implied warranty of
10 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 # GNU General Public License for more details.
12 #
13 # You should have received a copy of the GNU General Public License
14 # along with this program; if not, write to the Free Software
15 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
16 #
17 #
18 # The developers of the Exaile media player hereby grant permission
19 # for non-GPL compatible GStreamer and Exaile plugins to be used and
20 # distributed together with GStreamer and Exaile. This permission is
21 # above and beyond the permissions granted by the GPL license by which
22 # Exaile is covered. If you modify this code, you may extend this
23 # exception to your version of the code, but you are not obligated to
24 # do so. If you do not wish to do so, delete this exception statement
25 # from your version.
26
27 import logging
28 import pickle
29
30 from xl import common, event, playlist, settings
31
32 logger = logging.getLogger(__name__)
33
34
35 class PlayQueue(playlist.Playlist):
36 """
37 Manages the queue of songs to be played
38
39 The content of the queue are processed before processing
40 the content of the assigned playlist.
41
42 When the remove_item_when_played option is enabled, the queue
43 removes items from itself as they are played.
44
45 When not enabled, the queue acts like a regular playlist, and
46 moves the position as tracks are played.
47
48 In this mode, when a new track is queued, the position is set
49 to play that track, and play will continue with that track
50 until the queue is exhausted, and then the assigned playlist
51 will be continued.
52
53 TODO: Queue needs to be threadsafe!
54 """
55
56 def __init__(self, player, name, location=None):
57 playlist.Playlist.__init__(self, name=name)
58
59 self.__queue_has_tracks_val = False
60 self.__current_playlist = self # this should never be None
61 self.last_playlist = None
62 self.player = player
63
64 # hack for making docs work
65 if player is not None:
66 player.queue = self
67
68 if location is not None:
69 self.load_from_location(location)
70
71 event.add_callback(self._on_option_set, '%s_option_set' % name)
72
73 self.__opt_remove_item_when_played = '%s/remove_item_when_played' % name
74 self.__opt_remove_item_after_played = '%s/remove_item_after_played' % name
75 self.__opt_disable_new_track_when_playing = (
76 '%s/disable_new_track_when_playing' % name
77 )
78 self.__opt_enqueue_begins_playback = '%s/enqueue_begins_playback' % name
79
80 self._on_option_set(None, settings, self.__opt_remove_item_when_played)
81 self._on_option_set(None, settings, self.__opt_remove_item_after_played)
82 self._on_option_set(None, settings, self.__opt_disable_new_track_when_playing)
83
84 def _on_option_set(self, evtype, settings, option):
85 if option in (
86 self.__opt_remove_item_when_played,
87 self.__opt_remove_item_after_played,
88 ):
89 # The remove_item_when_played and remove_item_after_played options are
90 # related to each other, but we're going to store them here as
91 # __remove_item_before_playback and __remove_item_after_playback so
92 # that you don't have to check both options
93
94 when_played = settings.get_option(self.__opt_remove_item_when_played, True)
95 after_played = settings.get_option(
96 self.__opt_remove_item_after_played, False
97 )
98
99 before_played = False
100 if when_played:
101 if not after_played:
102 before_played = True
103 else:
104 after_played = False
105
106 self.__remove_item_before_playback = before_played
107 self.__remove_item_after_playback = after_played
108 self.__queue_removes_items = before_played or after_played
109
110 if len(self):
111 self.__queue_has_tracks = True
112 elif option == self.__opt_disable_new_track_when_playing:
113 self.__disable_new_track_when_playing = settings.get_option(option, False)
114
115 def set_current_playlist(self, playlist):
116 """
117 Sets the playlist to be processed in the queue
118
119 :param playlist: the playlist to process
120 :type playlist: :class:`xl.playlist.Playlist`
121
122 .. note:: The following :doc:`events </xl/event>` will be emitted by this method:
123
124 * `queue_current_playlist_changed`: indicates that the queue playlist has been changed
125 """
126 if playlist is self.__current_playlist:
127 return
128 elif playlist is None:
129 playlist = self
130
131 if playlist is self:
132 self.__queue_has_tracks = True
133
134 self.__current_playlist = playlist
135 event.log_event('queue_current_playlist_changed', self, playlist)
136
137 #: The playlist currently processed in the queue
138 current_playlist = property(
139 lambda self: self.__current_playlist, set_current_playlist
140 )
141
142 def get_next(self):
143 """
144 Retrieves the next track that will be played. Does not
145 actually set the position. When you call next(), it should
146 return the same track.
147
148 This exists to support retrieving a track before it actually
149 needs to be played, such as for pre-buffering.
150
151 :returns: the next track to be played
152 :rtype: :class:`xl.trax.Track` or None
153 """
154
155 if self.__queue_has_tracks:
156 if self.__remove_item_before_playback:
157 # item was previously removed, so always point at the head
158 if len(self):
159 return self[0]
160 elif self.__remove_item_after_playback:
161 # special case: this function isn't supposed to adjust the position but
162 # if this is the last track then we won't be called again, so just
163 # remove it now instead of removing it in next()
164 if len(self) == 1:
165 self.pop(0)
166 elif len(self) > 1:
167 # if item is the head, return next, otherwise return the head
168 if self.current_position == 0:
169 return self[1]
170 else:
171 return self[0]
172 else:
173 # if queue isn't removing items, it's just a normal playlist
174 next = playlist.Playlist.get_next(self)
175 if next is not None:
176 return next
177 if self.current_playlist is not self:
178 return self.current_playlist.get_next()
179 elif self.last_playlist is not None:
180 return self.last_playlist.get_next()
181 else:
182 return None
183
184 def next(self, autoplay=True, track=None):
185 """
186 Goes to the next track, either in the queue, or in the current
187 playlist. If a track is passed in, that track is played
188
189 :param autoplay: play the track in addition to returning it
190 :type autoplay: bool
191 :param track: if passed, play this track
192 :type track: :class:`xl.trax.Track`
193
194 .. note:: The following :doc:`events </xl/event>` will be emitted by this method:
195
196 * `playback_playlist_end`: indicates that the end of the queue has been reached
197 """
198 if track is None:
199 if self.__queue_has_tracks:
200 if self.__remove_item_before_playback:
201 # next track is always the head
202 try:
203 track = self.pop(0)
204 self.current_position = 0
205 except IndexError:
206 pass
207 elif self.__remove_item_after_playback:
208 # next track is always the head
209 current_position = self.current_position
210 if current_position != -1:
211 self.pop(current_position)
212 self.current_position = -1
213 if len(self):
214 track = self[0]
215 self.current_position = 0
216 else:
217 # next track is always normal playlist behavior
218 track = super().next()
219
220 # reached the end of the internal queue, don't repeat and switch back to last playlist
221 if track is None:
222 self.__queue_has_tracks = False
223 self.current_playlist = self.last_playlist
224 else:
225 # otherwise set current playlist to queue and store last playlist
226 if self.current_playlist is not self:
227 self.last_playlist = self.current_playlist
228 self.current_playlist = self
229
230 if track is None and self.current_playlist is not self:
231 track = self.current_playlist.next()
232
233 if autoplay:
234 self.player.play(track)
235
236 if not track:
237 event.log_event("playback_playlist_end", self, self.current_playlist)
238 return track
239
240 def prev(self):
241 """
242 Goes to the previous track
243 """
244 track = None
245 if self.player.current:
246 if self.player.get_time() < 5:
247 if self.__queue_has_tracks and not self.__queue_removes_items:
248 position = self.current_position - 1
249 if position < 0:
250 position = 0 if len(self) else -1
251 self.current_position = position
252 track = self.current
253 elif self.current_playlist is not self:
254 track = self.current_playlist.prev()
255
256 if track is None:
257 track = self.player.current
258 else:
259 track = self.current
260
261 self.player.play(track)
262 return track
263
264 def get_current(self):
265 """
266 Gets the current track
267
268 :returns: the current track
269 :type: :class:`xl.trax.Track`
270 """
271 if self.player.current and self.current_position > 0:
272 current = self.player.current
273 else:
274 current = playlist.Playlist.get_current(self)
275 if current is None and self.current_playlist is not self:
276 current = self.current_playlist.get_current()
277 return current
278
279 def is_play_enabled(self):
280 ''':returns: True when calling play() will have no effect'''
281 return not (self.player.is_playing() and self.__disable_new_track_when_playing)
282
283 def play(self, track=None):
284 """
285 Starts queue processing with the given
286 track preceding the queue content
287
288 :param track: the track to play
289 :type track: :class:`xl.trax.Track`
290 """
291 if self.player.is_playing():
292 if not track or self.__disable_new_track_when_playing:
293 return
294 if not track:
295 track = self.current
296 if track:
297 self.player.play(track)
298 if self.__remove_item_before_playback:
299 try:
300 del self[self.index(track)]
301 except ValueError:
302 pass
303 else:
304 self.next()
305
306 def queue_length(self):
307 """
308 Returns the number of tracks left to play in the queue's
309 internal playlist.
310 """
311 if self.__remove_item_before_playback:
312 return len(self)
313 else:
314 if not self.__queue_has_tracks:
315 return -1
316 else:
317 return len(self) - (self.current_position + 1)
318
319 def __set_queue_has_tracks(self, value):
320 if value != self.__queue_has_tracks_val:
321 oldpos = self.current_position
322 self.__queue_has_tracks_val = value
323 event.log_event(
324 "playlist_current_position_changed",
325 self,
326 (self.current_position, oldpos),
327 )
328
329 # Internal value indicating whether the internal queue has tracks left to play
330 __queue_has_tracks = property(
331 lambda self: self.__queue_has_tracks_val, __set_queue_has_tracks
332 )
333
334 def __setitem__(self, i, value):
335 """
336 Overrides the playlist.Playlist list API.
337
338 Allows us to ensure that when a track is added to an empty queue,
339 we play it. Or not, depending on what the user wants.
340 """
341 old_len = playlist.Playlist.__len__(self)
342 playlist.Playlist.__setitem__(self, i, value)
343
344 # if nothing is queued, queue this track up
345 if self.current_position == -1:
346 if isinstance(i, slice):
347 self.current_position = i.indices(len(self))[0] - 1
348 else:
349 self.current_position = i - 1
350
351 self.__queue_has_tracks = True
352
353 if (
354 old_len == 0
355 and settings.get_option('queue/enqueue_begins_playback', True)
356 and old_len < playlist.Playlist.__len__(self)
357 ):
358 self.play()
359
360 def _save_player_state(self, location):
361 state = {}
362 state['state'] = self.player.get_state()
363 state['position'] = self.player.get_time()
364
365 with open(location, 'wb') as f:
366 pickle.dump(state, f, protocol=2)
367
368 @common.threaded
369 def _restore_player_state(self, location):
370 if not settings.get_option("%s/resume_playback" % self.player._name, True):
371 return
372
373 try:
374 with open(location, 'rb') as f:
375 state = pickle.load(f)
376 except Exception:
377 return
378
379 for req in ['state', 'position']:
380 if req not in state:
381 return
382
383 self._do_restore_player_state(state)
384
385 @common.idle_add()
386 def _do_restore_player_state(self, state):
387 if state['state'] in ['playing', 'paused']:
388 start_at = None
389 if state['position'] is not None:
390 start_at = state['position']
391
392 paused = state['state'] == 'paused' or settings.get_option(
393 "%s/resume_paused" % self.player._name, False
394 )
395
396 self.player.play(
397 self.current_playlist.get_current(), start_at=start_at, paused=paused
398 )