1 # Implements playback controls
2 # Gstreamer stuff mostly snibbed from Panucci
4 # This file is part of Panucci.
5 # Copyright (c) 2008-2009 The Panucci Audiobook and Podcast Player Project
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.
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.
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/>.
29 log = logging.getLogger(__name__)
31 class _Player(object):
32 """Defines the internal player interface"""
35 def play_url(self, filetype, uri):
39 def play_pause_toggle(self):
40 self.pause() if self.playing() else self.play()
47 def set_eos_callback(self, cb):
50 class GStreamer(_Player):
52 STATES = { gst.STATE_NULL : 'stopped',
53 gst.STATE_PAUSED : 'paused',
54 gst.STATE_PLAYING : 'playing' }
57 _Player.__init__(self)
58 self.time_format = gst.Format(gst.FORMAT_TIME)
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()
67 def play_url(self, filetype, uri):
68 if None in (filetype, uri):
72 log.debug("Setting up for %s : %s", filetype, uri)
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)' )
82 log.debug( 'Using hardware decoding (maemo)' )
84 # This is for *ahem* "normal" versions of gstreamer
85 self._setup_playbin_player()
86 log.debug( 'Using playbin (non-maemo)' )
88 self._set_uri_to_be_played(uri)
90 bus = self.player.get_bus()
91 bus.add_signal_watch()
92 bus.connect('message', self._on_message)
94 self._set_volume_level( 1 )
101 state = self.player.get_state()[1]
102 return self.STATES.get(state, 'none')
106 return self.get_state() == 'playing'
111 self.player.set_state(gst.STATE_PLAYING)
115 self.player.set_state(gst.STATE_PAUSED)
119 self.player.set_state(gst.STATE_NULL)
122 def _maemo_setup_hardware_player( self, filetype ):
123 """ Setup a hardware player for mp3 or aac audio using
124 dspaacsink or dspmp3sink """
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'
137 def _maemo_setup_software_player( self ):
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.
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')
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'
158 # Add the various elements to the player pipeline
159 self.player.add( src, decoder, convert, resample, sink )
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 )
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') )
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'
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 )
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)
192 def _set_volume_level(self, value):
193 assert 0 <= value <= 1
195 if self.volume_control is not None:
196 vol = value * self.volume_multiplier
197 self.volume_control.set_property( self.volume_property, vol )
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)
204 def _on_message(self, bus, message):
207 if t == gst.MESSAGE_EOS:
210 elif t == gst.MESSAGE_ERROR:
211 err, debug = message.parse_error()
212 log.critical( 'Error: %s %s', err, debug )
215 def set_eos_callback(self, cb):
216 self.eos_callback = cb
218 if util.platform == 'maemo':
219 class OssoPlayer(_Player):
221 A player which uses osso-media-player for playback (Maemo-specific)
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"
229 self._on_eos = lambda: self.stop()
231 self._audio = self._init_dbus()
234 def play_url(self, filetype, uri):
235 self._audio.play_media(uri)
238 return self._state == 'playing'
240 def play_pause_toggle(self):
241 self.pause() if self.playing() else self.play()
253 def set_eos_callback(self, cb):
257 def _init_dbus(self):
258 session_bus = dbus.SessionBus()
259 oms_object = session_bus.get_object(self.SERVICE_NAME,
262 follow_name_owner_changes = True)
263 return dbus.Interface(oms_object, self.AUDIO_INTERFACE_NAME)
265 def _init_signals(self):
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",
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"
279 # Connect status signals
280 self.audio_proxy.connect_to_signal( "state_changed",
281 self._on_state_changed )
282 self.audio_proxy.connect_to_signal( "end_of_stream",
283 lambda x: self._call_eos() )
285 # Connect error signals
286 for error, msg in error_signals.iteritems():
287 self.audio_proxy.connect_to_signal(error, lambda *x: self._error(msg))
289 def _error(self, msg):
295 def _on_state_changed(self, state):
296 states = ("playing", "paused", "stopped")
297 self.__state = state if state in states else 'none'
299 PlayerBackend = OssoPlayer
301 PlayerBackend = GStreamer
303 class Playlist(object):
305 def __init__(self, data):
306 if isinstance(data, dict):
308 self.name = data['name']
309 self.numalbum = int(data['numalbum'])
310 self.url = data['mp3']
312 elif isinstance(data, basestring): # assume URI
319 return "{%s}" % (", ".join([str(self.name), str(self.numalbum), str(self.url)]))
321 def __init__(self, items = []):
324 self.items = [Playlist.Entry(item) for item in items]
328 self.items.append(Playlist.Entry(item))
332 self.current = self.current + 1
333 return self.items[self.current]
337 return self.current < (len(self.items)-1)
339 class Player(Playlist):
341 self.backend = PlayerBackend()
342 self.backend.set_eos_callback(self._on_eos)
345 def play(self, playlist = None):
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)
361 return self.backend.playing()
364 if self.playlist.has_next():