Debian Codegraph @

beetsplug/bpd/gstplayer.py

raw
1 """A wrapper for the GStreamer Python bindings that exposes a simple
2 music player.
3 """
4
5 from __future__ import annotations
6
7 import _thread
8 import copy
9 import os
10 import sys
11 import time
12 import urllib.parse
13 from typing import TYPE_CHECKING
14
15 import gi
16
17 from beets.exceptions import UserError
18
19 if TYPE_CHECKING:
20 from collections.abc import Callable, Iterable
21
22 try:
23 gi.require_version("Gst", "1.0")
24 except ValueError as e:
25 # on some scenarios, gi may be importable, but we get a ValueError when
26 # trying to specify the required version. This is problematic in the test
27 # suite where test_bpd.py has a call to
28 # pytest.importorskip("beetsplug.bpd"). Re-raising as an ImportError
29 # makes it so the test collector functions as inteded.
30 raise ImportError from e
31
32 from gi.repository import GLib, Gst
33
34 Gst.init(None)
35
36
37 class QueryError(Exception):
38 pass
39
40
41 class GstPlayer:
42 """A music player abstracting GStreamer's Playbin element.
43
44 Create a player object, then call run() to start a thread with a
45 runloop. Then call play_file to play music. Use player.playing
46 to check whether music is currently playing.
47
48 A basic play queue is also implemented (just a Python list,
49 player.queue, whose last element is next to play). To use it,
50 just call enqueue() and then play(). When a track finishes and
51 another is available on the queue, it is played automatically.
52 """
53
54 cached_time: tuple[float, float] | None
55
56 def __init__(
57 self, finished_callback: Callable[[], None] | None = None
58 ) -> None:
59 """Initialize a player.
60
61 If a finished_callback is provided, it is called every time a
62 track started with play_file finishes.
63
64 Once the player has been created, call run() to begin the main
65 runloop in a separate thread.
66 """
67
68 # Set up the Gstreamer player. From the pygst tutorial:
69 # https://pygstdocs.berlios.de/pygst-tutorial/playbin.html (gone)
70 # https://brettviren.github.io/pygst-tutorial-org/pygst-tutorial.html
71 ####
72 # Updated to GStreamer 1.0 with:
73 # https://wiki.ubuntu.com/Novacut/GStreamer1.0
74 self.player = Gst.ElementFactory.make("playbin", "player")
75
76 if self.player is None:
77 raise UserError("Could not create playbin")
78
79 fakesink = Gst.ElementFactory.make("fakesink", "fakesink")
80
81 if fakesink is None:
82 raise UserError("Could not create fakesink")
83
84 self.player.set_property("video-sink", fakesink)
85 bus = self.player.get_bus()
86 bus.add_signal_watch()
87 bus.connect("message", self._handle_message)
88
89 # Set up our own stuff.
90 self.playing = False
91 self.finished_callback = finished_callback
92 self.cached_time = None
93 self._volume = 1.0
94
95 def _get_state(self) -> Gst.State:
96 """Returns the current state flag of the playbin."""
97 # gst's get_state function returns a 3-tuple; we just want the
98 # status flag in position 1.
99 return self.player.get_state(Gst.CLOCK_TIME_NONE)[1]
100
101 def _handle_message(self, bus: Gst.Bus, message: Gst.Message) -> None:
102 """Callback for status updates from GStreamer."""
103 if message.type == Gst.MessageType.EOS:
104 # file finished playing
105 self.player.set_state(Gst.State.NULL)
106 self.playing = False
107 self.cached_time = None
108 if self.finished_callback:
109 self.finished_callback()
110
111 elif message.type == Gst.MessageType.ERROR:
112 # error
113 self.player.set_state(Gst.State.NULL)
114 err, _ = message.parse_error()
115 print(f"Error: {err}")
116 self.playing = False
117
118 def _set_volume(self, volume: float) -> None:
119 """Set the volume level to a value in the range [0, 1.5]."""
120 # And the volume for the playbin.
121 self._volume = volume
122 self.player.set_property("volume", volume)
123
124 def _get_volume(self) -> float:
125 """Get the volume as a float in the range [0, 1.5]."""
126 return self._volume
127
128 volume = property(_get_volume, _set_volume)
129
130 def play_file(self, path: str | bytes) -> None:
131 """Immediately begin playing the audio file at the given
132 path.
133 """
134 self.player.set_state(Gst.State.NULL)
135 if isinstance(path, str):
136 path = path.encode("utf-8")
137 uri = f"file://{urllib.parse.quote(path)}"
138 self.player.set_property("uri", uri)
139 self.player.set_state(Gst.State.PLAYING)
140 self.playing = True
141
142 def play(self) -> None:
143 """If paused, resume playback."""
144 if self._get_state() == Gst.State.PAUSED:
145 self.player.set_state(Gst.State.PLAYING)
146 self.playing = True
147
148 def pause(self) -> None:
149 """Pause playback."""
150 self.player.set_state(Gst.State.PAUSED)
151
152 def stop(self) -> None:
153 """Halt playback."""
154 self.player.set_state(Gst.State.NULL)
155 self.playing = False
156 self.cached_time = None
157
158 def run(self) -> None:
159 """Start a new thread for the player.
160
161 Call this function before trying to play any music with
162 play_file() or play().
163 """
164
165 # If we don't use the MainLoop, messages are never sent.
166
167 def start() -> None:
168 loop = GLib.MainLoop()
169 loop.run()
170
171 _thread.start_new_thread(start, ())
172
173 def time(self) -> tuple[float, float]:
174 """Returns a tuple containing (position, length) where both
175 values are floats in seconds. If no stream is available,
176 returns (0, 0).
177 """
178 fmt = Gst.Format(Gst.Format.TIME)
179 try:
180 posq = self.player.query_position(fmt)
181 if not posq[0]:
182 raise QueryError("query_position failed")
183 pos = posq[1] / (10**9)
184
185 lengthq = self.player.query_duration(fmt)
186 if not lengthq[0]:
187 raise QueryError("query_duration failed")
188 length = lengthq[1] / (10**9)
189
190 self.cached_time = (pos, length)
191 return (pos, length)
192
193 except QueryError:
194 # Stream not ready. For small gaps of time, for instance
195 # after seeking, the time values are unavailable. For this
196 # reason, we cache recent.
197 if self.playing and self.cached_time:
198 return self.cached_time
199 return (0, 0)
200
201 def seek(self, position: float) -> None:
202 """Seeks to position (in seconds)."""
203 _, cur_len = self.time()
204 if position > cur_len:
205 self.stop()
206 return
207
208 fmt = Gst.Format(Gst.Format.TIME)
209 ns = position * 10**9 # convert to nanoseconds
210 self.player.seek_simple(fmt, Gst.SeekFlags.FLUSH, ns)
211
212 # save new cached time
213 self.cached_time = (position, cur_len)
214
215 def block(self) -> None:
216 """Block until playing finishes."""
217 while self.playing:
218 time.sleep(1)
219
220 def get_decoders(self) -> dict[str, tuple[set[str], set[str]]]:
221 return get_decoders()
222
223
224 def get_decoders() -> dict[str, tuple[set[str], set[str]]]:
225 """Get supported audio decoders from GStreamer.
226 Returns a dict mapping decoder element names to the associated media types
227 and file extensions.
228 """
229 # We only care about audio decoder elements.
230 filt = (
231 Gst.ELEMENT_FACTORY_TYPE_DEPAYLOADER
232 | Gst.ELEMENT_FACTORY_TYPE_DEMUXER
233 | Gst.ELEMENT_FACTORY_TYPE_PARSER
234 | Gst.ELEMENT_FACTORY_TYPE_DECODER
235 | Gst.ELEMENT_FACTORY_TYPE_MEDIA_AUDIO
236 )
237
238 decoders: dict[str, tuple[set[str], set[str]]] = {}
239 mime_types = set()
240 for f in Gst.ElementFactory.list_get_elements(filt, Gst.Rank.NONE):
241 for pad in f.get_static_pad_templates():
242 if pad.direction == Gst.PadDirection.SINK:
243 caps = pad.static_caps.get()
244 mimes = set()
245 for i in range(caps.get_size()):
246 struct = caps.get_structure(i)
247 mime = struct.get_name()
248 if mime == "unknown/unknown":
249 continue
250 mimes.add(mime)
251 mime_types.add(mime)
252 if mimes:
253 decoders[f.get_name()] = (mimes, set())
254
255 # Check all the TypeFindFactory plugin features form the registry. If they
256 # are associated with an audio media type that we found above, get the list
257 # of corresponding file extensions.
258 mime_extensions: dict[str, set[str]] = {mime: set() for mime in mime_types}
259 for feat in Gst.Registry.get().get_feature_list(Gst.TypeFindFactory):
260 caps = feat.get_caps()
261 if caps:
262 for i in range(caps.get_size()):
263 struct = caps.get_structure(i)
264 mime = struct.get_name()
265 if mime in mime_types:
266 mime_extensions[mime].update(feat.get_extensions())
267
268 # Fill in the slot we left for file extensions.
269 for name, (mimes, exts) in decoders.items():
270 for mime in mimes:
271 exts.update(mime_extensions[mime])
272
273 return decoders
274
275
276 def play_simple(paths: Iterable[str] | Iterable[bytes]) -> None:
277 """Play the files in paths in a straightforward way, without
278 using the player's callback function.
279 """
280 p = GstPlayer()
281 p.run()
282 for path in paths:
283 p.play_file(path)
284 p.block()
285
286
287 def play_complicated(paths: list[str] | list[bytes]) -> None:
288 """Play the files in the path one after the other by using the
289 callback function to advance to the next song.
290 """
291 my_paths = copy.copy(paths)
292
293 def next_song() -> None:
294 my_paths.pop(0)
295 p.play_file(my_paths[0])
296
297 p = GstPlayer(next_song)
298 p.run()
299 p.play_file(my_paths[0])
300 while my_paths:
301 time.sleep(1)
302
303
304 if __name__ == "__main__":
305 # A very simple command-line player. Just give it names of audio
306 # files on the command line; these are all played in sequence.
307 paths = [os.path.abspath(os.path.expanduser(p)) for p in sys.argv[1:]]
308 # play_simple(paths)
309 play_complicated(paths)