Added ossohelper from panucci'
[jamaendo] / jamaui / player.py
1 # Implements playback controls
2 # Gstreamer stuff mostly snibbed from Panucci
3 #
4 # This file is part of Panucci.
5 # Copyright (c) 2008-2009 The Panucci Audiobook and Podcast Player Project
6 #
7 # Panucci is free software: you can redistribute it and/or modify
8 # it under the terms of the GNU General Public License as published by
9 # the Free Software Foundation, either version 3 of the License, or
10 # (at your option) any later version.
11 #
12 # Panucci is distributed in the hope that it will be useful,
13 # but WITHOUT ANY WARRANTY; without even the implied warranty of
14 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 # GNU General Public License for more details.
16 #
17 # You should have received a copy of the GNU General Public License
18 # along with Panucci.  If not, see <http://www.gnu.org/licenses/>.
19 #
20
21 import logging
22 import pygst
23 pygst.require('0.10')
24 import gst
25 import util
26 import dbus
27 import dbus.service
28
29 log = logging.getLogger(__name__)
30
31 class _Player(object):
32     """Defines the internal player interface"""
33     def __init__(self):
34         pass
35     def play_url(self, filetype, uri):
36         raise NotImplemented
37     def playing(self):
38         raise NotImplemented
39     def play_pause_toggle(self):
40         self.pause() if self.playing() else self.play()
41     def play(self):
42         raise NotImplemented
43     def pause(self):
44         raise NotImplemented
45     def stop(self):
46         raise NotImplemented
47     def set_eos_callback(self, cb):
48         raise NotImplemented
49
50 class GStreamer(_Player):
51     """Wraps GStreamer"""
52     STATES = { gst.STATE_NULL    : 'stopped',
53                gst.STATE_PAUSED  : 'paused',
54                gst.STATE_PLAYING : 'playing' }
55
56     def __init__(self):
57         _Player.__init__(self)
58         self.time_format = gst.Format(gst.FORMAT_TIME)
59         self.player = None
60         self.filesrc = None
61         self.filesrc_property = None
62         self.volume_control = None
63         self.volume_multiplier = 1
64         self.volume_property = None
65         self.eos_callback = lambda: self.stop()
66
67     def play_url(self, filetype, uri):
68         if None in (filetype, uri):
69             self.player = None
70             return False
71
72         log.debug("Setting up for %s : %s", filetype, uri)
73
74         # On maemo use software decoding to workaround some bugs their gst:
75         # 1. Weird volume bugs in playbin when playing ogg or wma files
76         # 2. When seeking the DSPs sometimes lie about the real position info
77         if util.platform == 'maemo':
78             if not self._maemo_setup_hardware_player(filetype):
79                 self._maemo_setup_software_player()
80                 log.debug( 'Using software decoding (maemo)' )
81             else:
82                 log.debug( 'Using hardware decoding (maemo)' )
83         else:
84             # This is for *ahem* "normal" versions of gstreamer
85             self._setup_playbin_player()
86             log.debug( 'Using playbin (non-maemo)' )
87
88         self._set_uri_to_be_played(uri)
89
90         bus = self.player.get_bus()
91         bus.add_signal_watch()
92         bus.connect('message', self._on_message)
93
94         self._set_volume_level( 1 )
95
96         self.play()
97         return True
98
99     def get_state(self):
100         if self.player:
101             state = self.player.get_state()[1]
102             return self.STATES.get(state, 'none')
103         return 'none'
104
105     def playing(self):
106         return self.get_state() == 'playing'
107
108     def play(self):
109         if self.player:
110             log.debug("playing")
111             self.player.set_state(gst.STATE_PLAYING)
112
113     def pause(self):
114         if self.player:
115             self.player.set_state(gst.STATE_PAUSED)
116
117     def stop(self):
118         if self.player:
119             self.player.set_state(gst.STATE_NULL)
120             self.player = None
121
122     def _maemo_setup_hardware_player( self, filetype ):
123         """ Setup a hardware player for mp3 or aac audio using
124         dspaacsink or dspmp3sink """
125
126         if filetype in [ 'mp3', 'aac', 'mp4', 'm4a' ]:
127             self.player = gst.element_factory_make('playbin', 'player')
128             self.filesrc = self.player
129             self.filesrc_property = 'uri'
130             self.volume_control = self.player
131             self.volume_multiplier = 10.
132             self.volume_property = 'volume'
133             return True
134         else:
135             return False
136
137     def _maemo_setup_software_player( self ):
138         """
139         Setup a software decoding player for maemo, this is the only choice
140         for decoding wma and ogg or if audio is to be piped to a bluetooth
141         headset (this is because the audio must first be decoded only to be
142         re-encoded using sbcenc.
143         """
144
145         self.player = gst.Pipeline('player')
146         src = gst.element_factory_make('gnomevfssrc', 'src')
147         decoder = gst.element_factory_make('decodebin', 'decoder')
148         convert = gst.element_factory_make('audioconvert', 'convert')
149         resample = gst.element_factory_make('audioresample', 'resample')
150         sink = gst.element_factory_make('dsppcmsink', 'sink')
151
152         self.filesrc = src # pointer to the main source element
153         self.filesrc_property = 'location'
154         self.volume_control = sink
155         self.volume_multiplier = 1
156         self.volume_property = 'fvolume'
157
158         # Add the various elements to the player pipeline
159         self.player.add( src, decoder, convert, resample, sink )
160
161         # Link what can be linked now, the decoder->convert happens later
162         gst.element_link_many( src, decoder )
163         gst.element_link_many( convert, resample, sink )
164
165         # We can't link the two halves of the pipeline until it comes
166         # time to start playing, this singal lets us know when it's time.
167         # This is because the output from decoder can't be determined until
168         # decoder knows what it's decoding.
169         decoder.connect('pad-added',
170                         self._on_decoder_pad_added,
171                         convert.get_pad('sink') )
172
173     def _setup_playbin_player( self ):
174         """ This is for situations where we have a normal (read: non-maemo)
175         version of gstreamer like on a regular linux distro. """
176         self.player = gst.element_factory_make('playbin2', 'player')
177         self.filesrc = self.player
178         self.filesrc_property = 'uri'
179         self.volume_control = self.player
180         self.volume_multiplier = 1.
181         self.volume_property = 'volume'
182
183     def _on_decoder_pad_added(self, decoder, src_pad, sink_pad):
184         # link the decoder's new "src_pad" to "sink_pad"
185         src_pad.link( sink_pad )
186
187     def _get_volume_level(self):
188         if self.volume_control is not None:
189             vol = self.volume_control.get_property( self.volume_property )
190             return  vol / float(self.volume_multiplier)
191
192     def _set_volume_level(self, value):
193         assert  0 <= value <= 1
194
195         if self.volume_control is not None:
196             vol = value * self.volume_multiplier
197             self.volume_control.set_property( self.volume_property, vol )
198
199     def _set_uri_to_be_played(self, uri):
200         # Sets the right property depending on the platform of self.filesrc
201         if self.player is not None:
202             self.filesrc.set_property(self.filesrc_property, uri)
203
204     def _on_message(self, bus, message):
205         t = message.type
206
207         if t == gst.MESSAGE_EOS:
208             self.eos_callback()
209
210         elif t == gst.MESSAGE_ERROR:
211             err, debug = message.parse_error()
212             log.critical( 'Error: %s %s', err, debug )
213             self.stop()
214
215     def set_eos_callback(self, cb):
216         self.eos_callback = cb
217
218 if util.platform == 'maemo':
219     class OssoPlayer(_Player):
220         """
221         A player which uses osso-media-player for playback (Maemo-specific)
222         """
223
224         SERVICE_NAME         = "com.nokia.osso_media_server"
225         OBJECT_PATH          = "/com/nokia/osso_media_server"
226         AUDIO_INTERFACE_NAME = "com.nokia.osso_media_server.music"
227
228         def __init__(self):
229             self._on_eos = lambda: self.stop()
230             self._state = 'none'
231             self._audio = self._init_dbus()
232             self._init_signals()
233
234         def play_url(self, filetype, uri):
235             self._audio.play_media(uri)
236
237         def playing(self):
238             return self._state == 'playing'
239
240         def play_pause_toggle(self):
241             self.pause() if self.playing() else self.play()
242
243         def play(self):
244             self._audio.play()
245
246         def pause(self):
247             if self.playing():
248                 self._audio.pause()
249
250         def stop(self):
251             self._audio.stop()
252
253         def set_eos_callback(self, cb):
254             self._on_eos = cb
255
256
257         def _init_dbus(self):
258             session_bus = dbus.SessionBus()
259             oms_object = session_bus.get_object(self.SERVICE_NAME,
260                                                 self.OBJECT_PATH,
261                                                 introspect = False,
262                                                 follow_name_owner_changes = True)
263             return dbus.Interface(oms_object, self.AUDIO_INTERFACE_NAME)
264
265         def _init_signals(self):
266             error_signals = {
267                 "no_media_selected":            "No media selected",
268                 "file_not_found":               "File not found",
269                 "type_not_found":               "Type not found",
270                 "unsupported_type":             "Unsupported type",
271                 "gstreamer":                    "GStreamer Error",
272                 "dsp":                          "DSP Error",
273                 "device_unavailable":           "Device Unavailable",
274                 "corrupted_file":               "Corrupted File",
275                 "out_of_memory":                "Out of Memory",
276                 "audio_codec_not_supported":    "Audio codec not supported"
277             }
278
279             # Connect status signals
280             self._audio.connect_to_signal( "state_changed",
281                                                 self._on_state_changed )
282             self._audio.connect_to_signal( "end_of_stream",
283                                                 lambda x: self._call_eos() )
284
285             # Connect error signals
286             for error, msg in error_signals.iteritems():
287                 self._audio.connect_to_signal(error, lambda *x: self._error(msg))
288
289         def _error(self, msg):
290             log.error(msg)
291
292         def _call_eos(self):
293             self._on_eos()
294
295         def _on_state_changed(self, state):
296             states = ("playing", "paused", "stopped")
297             self.__state = state if state in states else 'none'
298
299     PlayerBackend = OssoPlayer
300 else:
301     PlayerBackend = GStreamer
302
303 class Playlist(object):
304     class Entry(object):
305         def __init__(self, data):
306             if isinstance(data, dict):
307                 self.id = data['id']
308                 self.name = data['name']
309                 self.numalbum = int(data['numalbum'])
310                 self.url = data['mp3']
311                 self.type = 'mp3'
312             elif isinstance(data, basestring): # assume URI
313                 self.id = 0
314                 self.name = ''
315                 self.numalbum = 0
316                 self.url = data
317                 self.type = 'mp3'
318         def __str__(self):
319             return "{%s}" % (", ".join([str(self.name), str(self.numalbum), str(self.url)]))
320
321     def __init__(self, items = []):
322         if items is None:
323             items = []
324         self.items = [Playlist.Entry(item) for item in items]
325         self.current = -1
326
327     def add(self, item):
328         self.items.append(Playlist.Entry(item))
329
330     def next(self):
331         if self.has_next():
332             self.current = self.current + 1
333             return self.items[self.current]
334         return None
335
336     def has_next(self):
337         return self.current < (len(self.items)-1)
338
339 class Player(Playlist):
340     def __init__(self):
341         self.backend = PlayerBackend()
342         self.backend.set_eos_callback(self._on_eos)
343         self.playlist = None
344
345     def play(self, playlist = None):
346         if playlist:
347             self.playlist = playlist
348         if self.playlist is not None:
349             if self.playlist.has_next():
350                 entry = self.playlist.next()
351                 log.debug("playing %s", entry)
352                 self.backend.play_url(entry.type, entry.url)
353
354     def pause(self):
355         self.backend.pause()
356
357     def stop(self):
358         self.backend.stop()
359
360     def playing(self):
361         return self.backend.playing()
362
363     def next(self):
364         if self.playlist.has_next():
365             self.stop()
366             self.play()
367         else:
368             self.stop()
369
370     def prev(self):
371         pass
372
373     def _on_eos(self):
374         log.debug("EOS!")
375         self.next()