Console version can now play songs
[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
27 log = logging.getLogger(__name__)
28
29
30 class GStreamer(object):
31     """Wraps GStreamer"""
32     STATES = { gst.STATE_NULL    : 'stopped',
33                gst.STATE_PAUSED  : 'paused',
34                gst.STATE_PLAYING : 'playing' }
35
36     def __init__(self):
37         self.time_format = gst.Format(gst.FORMAT_TIME)
38         self.player = None
39         self.filesrc = None
40         self.filesrc_property = None
41         self.volume_control = None
42         self.volume_multiplier = 1
43         self.volume_property = None
44         self.eos_callback = lambda: self.stop()
45
46     def setup(self, filetype, uri):
47         if None in (filetype, uri):
48             self.player = None
49             return False
50
51         log.debug("Setting up for %s : %s", filetype, uri)
52
53         # On maemo use software decoding to workaround some bugs their gst:
54         # 1. Weird volume bugs in playbin when playing ogg or wma files
55         # 2. When seeking the DSPs sometimes lie about the real position info
56         if util.platform == 'maemo':
57             if not self._maemo_setup_hardware_player(filetype):
58                 self._maemo_setup_software_player()
59                 log.debug( 'Using software decoding (maemo)' )
60             else:
61                 log.debug( 'Using hardware decoding (maemo)' )
62         else:
63             # This is for *ahem* "normal" versions of gstreamer
64             self._setup_playbin_player()
65             log.debug( 'Using playbin (non-maemo)' )
66
67         self._set_uri_to_be_played(uri)
68
69         bus = self.player.get_bus()
70         bus.add_signal_watch()
71         bus.connect('message', self._on_message)
72         return True
73
74     def get_state(self):
75         if self.player:
76             state = self.player.get_state()[1]
77             return self.STATES.get(state, 'none')
78         return 'none'
79
80     def playing(self):
81         return self.get_state() == 'playing'
82
83     def play(self):
84         if self.player:
85             log.debug("playing")
86             self.player.set_state(gst.STATE_PLAYING)
87
88     def pause(self):
89         if self.player:
90             self.player.set_state(gst.STATE_PAUSED)
91
92     def play_pause_toggle(self):
93         self.pause() if self.playing() else self.play()
94
95     def stop(self):
96         if self.player:
97             self.player.set_state(gst.STATE_NULL)
98             self.player = None
99
100     def _maemo_setup_hardware_player( self, filetype ):
101         """ Setup a hardware player for mp3 or aac audio using
102         dspaacsink or dspmp3sink """
103
104         if filetype in [ 'mp3', 'aac', 'mp4', 'm4a' ]:
105             self.player = gst.element_factory_make('playbin', 'player')
106             self.filesrc = self.player
107             self.filesrc_property = 'uri'
108             self.volume_control = self.player
109             self.volume_multiplier = 10.
110             self.volume_property = 'volume'
111             return True
112         else:
113             return False
114
115     def _maemo_setup_software_player( self ):
116         """
117         Setup a software decoding player for maemo, this is the only choice
118         for decoding wma and ogg or if audio is to be piped to a bluetooth
119         headset (this is because the audio must first be decoded only to be
120         re-encoded using sbcenc.
121         """
122
123         self.player = gst.Pipeline('player')
124         src = gst.element_factory_make('gnomevfssrc', 'src')
125         decoder = gst.element_factory_make('decodebin', 'decoder')
126         convert = gst.element_factory_make('audioconvert', 'convert')
127         resample = gst.element_factory_make('audioresample', 'resample')
128         sink = gst.element_factory_make('dsppcmsink', 'sink')
129
130         self.filesrc = src # pointer to the main source element
131         self.filesrc_property = 'location'
132         self.volume_control = sink
133         self.volume_multiplier = 1
134         self.volume_property = 'fvolume'
135
136         # Add the various elements to the player pipeline
137         self.player.add( src, decoder, convert, resample, sink )
138
139         # Link what can be linked now, the decoder->convert happens later
140         gst.element_link_many( src, decoder )
141         gst.element_link_many( convert, resample, sink )
142
143         # We can't link the two halves of the pipeline until it comes
144         # time to start playing, this singal lets us know when it's time.
145         # This is because the output from decoder can't be determined until
146         # decoder knows what it's decoding.
147         decoder.connect('pad-added',
148                         self._on_decoder_pad_added,
149                         convert.get_pad('sink') )
150
151     def _setup_playbin_player( self ):
152         """ This is for situations where we have a normal (read: non-maemo)
153         version of gstreamer like on a regular linux distro. """
154         self.player = gst.element_factory_make('playbin2', 'player')
155         self.filesrc = self.player
156         self.filesrc_property = 'uri'
157         self.volume_control = self.player
158         self.volume_multiplier = 1.
159         self.volume_property = 'volume'
160
161     def _on_decoder_pad_added(self, decoder, src_pad, sink_pad):
162         # link the decoder's new "src_pad" to "sink_pad"
163         src_pad.link( sink_pad )
164
165     def _get_volume_level(self):
166         if self.volume_control is not None:
167             vol = self.volume_control.get_property( self.volume_property )
168             return  vol / float(self.volume_multiplier)
169
170     def _set_volume_level(self, value):
171         assert  0 <= value <= 1
172
173         if self.volume_control is not None:
174             vol = value * self.volume_multiplier
175             self.volume_control.set_property( self.volume_property, vol )
176
177     def _set_uri_to_be_played(self, uri):
178         # Sets the right property depending on the platform of self.filesrc
179         if self.player is not None:
180             self.filesrc.set_property(self.filesrc_property, uri)
181
182     def _on_message(self, bus, message):
183         t = message.type
184
185         if t == gst.MESSAGE_EOS:
186             self.eos_callback()
187
188         elif t == gst.MESSAGE_ERROR:
189             err, debug = message.parse_error()
190             log.critical( 'Error: %s %s', err, debug )
191             self.stop()
192
193     def set_eos_callback(self, cb):
194         self.eos_callback = cb
195
196 class Playlist(object):
197     def __init__(self, items = []):
198         self.items = items
199         self.current = -1
200
201     def add(self, item):
202         self.items.append(item)
203
204     def next(self):
205         if self.has_next():
206             self.current = self.current + 1
207             return self.items[self.current]
208         return None
209
210     def has_next(self):
211         return self.current < (len(self.items)-1)
212
213 class Player(Playlist):
214     def __init__(self):
215         self.gstreamer = GStreamer()
216         self.gstreamer.set_eos_callback(self._on_eos)
217         self.playlist = None
218
219     def play(self, playlist = None):
220         if playlist:
221             self.playlist = playlist
222         if self.playlist is not None:
223             if self.playlist.has_next():
224                 self.gstreamer.setup('mp3', self.playlist.next())
225                 self.gstreamer.play()
226
227     def pause(self):
228         self.gstreamer.pause()
229
230     def stop(self):
231         self.gstreamer.stop()
232
233     def playing(self):
234         return self.gstreamer.playing()
235
236     def next(self):
237         if self.playlist.has_next():
238             self.gstreamer.setup('mp3', self.playlist.next())
239             self.gstreamer.play()
240         else:
241             self.stop()
242
243     def prev(self):
244         pass
245
246     def _on_eos(self):
247         self.next()