noneto-cli 1.1.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (59) hide show
  1. noneto/__init__.py +1 -0
  2. noneto/__main__.py +3 -0
  3. noneto/app.py +113 -0
  4. noneto/assets/noneto.ico +0 -0
  5. noneto/audio/__init__.py +1 -0
  6. noneto/audio/controller.py +427 -0
  7. noneto/audio/inspector.py +21 -0
  8. noneto/audio/ipc_unix.py +29 -0
  9. noneto/audio/ipc_windows.py +94 -0
  10. noneto/audio/lifetime.py +68 -0
  11. noneto/audio/media_controls.py +107 -0
  12. noneto/audio/mpv_install.py +71 -0
  13. noneto/audio/player.py +222 -0
  14. noneto/audio/pulse_tap.py +120 -0
  15. noneto/audio/spectrum.py +44 -0
  16. noneto/audio/streams.py +101 -0
  17. noneto/audio/tap.py +208 -0
  18. noneto/audio/windows_identity.py +79 -0
  19. noneto/audio/windows_media.py +157 -0
  20. noneto/auth/__init__.py +1 -0
  21. noneto/auth/dpapi.py +28 -0
  22. noneto/auth/service.py +53 -0
  23. noneto/auth/storage.py +120 -0
  24. noneto/diagnostics.py +115 -0
  25. noneto/errors.py +12 -0
  26. noneto/i18n.py +199 -0
  27. noneto/platform/__init__.py +1 -0
  28. noneto/platform/paths.py +27 -0
  29. noneto/security.py +59 -0
  30. noneto/services/__init__.py +1 -0
  31. noneto/services/covers.py +88 -0
  32. noneto/services/executor.py +83 -0
  33. noneto/services/library.py +110 -0
  34. noneto/services/tidal.py +188 -0
  35. noneto/settings.py +48 -0
  36. noneto/state/__init__.py +1 -0
  37. noneto/state/queue.py +130 -0
  38. noneto/state/writer.py +38 -0
  39. noneto/ui/__init__.py +1 -0
  40. noneto/ui/common.py +36 -0
  41. noneto/ui/cover.py +88 -0
  42. noneto/ui/dialogs.py +107 -0
  43. noneto/ui/linux_login.py +57 -0
  44. noneto/ui/login_window.py +201 -0
  45. noneto/ui/lyrics.py +142 -0
  46. noneto/ui/player.py +172 -0
  47. noneto/ui/quality.py +75 -0
  48. noneto/ui/queue.py +34 -0
  49. noneto/ui/terminal.py +65 -0
  50. noneto/ui/themes.py +352 -0
  51. noneto/ui/top.py +39 -0
  52. noneto/ui/tracks.py +139 -0
  53. noneto/ui/tui.py +601 -0
  54. noneto/ui/visualizer.py +343 -0
  55. noneto_cli-1.1.1.dist-info/METADATA +222 -0
  56. noneto_cli-1.1.1.dist-info/RECORD +59 -0
  57. noneto_cli-1.1.1.dist-info/WHEEL +4 -0
  58. noneto_cli-1.1.1.dist-info/entry_points.txt +2 -0
  59. noneto_cli-1.1.1.dist-info/licenses/LICENSE +21 -0
noneto/__init__.py ADDED
@@ -0,0 +1 @@
1
+ """Noneto CLI: unofficial Windows terminal client for TIDAL. UI, authentication and audio are independent."""
noneto/__main__.py ADDED
@@ -0,0 +1,3 @@
1
+ from .app import main
2
+
3
+ raise SystemExit(main())
noneto/app.py ADDED
@@ -0,0 +1,113 @@
1
+ """Composition root: connects UI, auth, catalog and audio."""
2
+ import argparse
3
+ import os
4
+ import sys
5
+ import tempfile
6
+
7
+ from .auth.service import login, logout
8
+ from .auth.storage import SessionPersistence
9
+ from .audio.controller import PlaybackController
10
+ from .audio.mpv_install import install_mpv, mpv_dir
11
+ from .audio.player import Player, find_mpv
12
+ from .audio.streams import stream_target
13
+ from .services.library import Library
14
+ from .services.tidal import Catalog, create_session
15
+ from .ui.terminal import Terminal
16
+ from .ui.themes import available_themes, load_user_themes
17
+ from .ui.visualizer import available_visualizer_modes
18
+ from .diagnostics import configure, emit, failure
19
+ from .i18n import LANGUAGES, _, set_language, DEFAULT_LANGUAGE
20
+ from .settings import load_settings, save_settings
21
+ from .state.queue import QueueStore
22
+
23
+
24
+ def main(argv=None):
25
+ # The language must be set before help texts are built and before the TUI module is imported.
26
+ early = argparse.ArgumentParser(add_help=False)
27
+ early.add_argument("--lang", choices=LANGUAGES)
28
+ set_language(early.parse_known_args(argv)[0].lang or DEFAULT_LANGUAGE)
29
+ parser = argparse.ArgumentParser(prog="noneto", description=_("Noneto CLI: unofficial TIDAL client for the terminal."))
30
+ parser.add_argument("--playlist", help=_("Link or UUID of the playlist to open at startup"))
31
+ parser.add_argument("--quality", choices=["HIGH", "LOSSLESS", "HI_RES_LOSSLESS"], default="HI_RES_LOSSLESS",
32
+ help=_("Highest quality requested from TIDAL; by default, the best available"))
33
+ parser.add_argument("--lang", choices=LANGUAGES, help=_("Interface language (default: English)"))
34
+ parser.add_argument("--logout", action="store_true", help=_("Delete the local session and exit"))
35
+ parser.add_argument("--install-mpv", action="store_true",
36
+ help=_("Download mpv (pinned version, SHA-256 verified) and exit"))
37
+ args = parser.parse_args(argv)
38
+ if sys.platform != "win32":
39
+ print(_("This release supports Windows only. Linux support is still in development."), file=sys.stderr)
40
+ return 1
41
+ from .ui.cover import terminal_artwork
42
+ from .ui.lyrics import LAYOUTS
43
+ from .ui.tui import NonetoApp
44
+ session = None
45
+ ui = Terminal()
46
+ try:
47
+ if args.logout:
48
+ logout()
49
+ ui.notify("logout")
50
+ return 0
51
+ if args.install_mpv:
52
+ ui.notify("mpv-installing")
53
+ ui.notify("mpv-ready", path=install_mpv())
54
+ return 0
55
+ try:
56
+ log_path = configure()
57
+ except OSError:
58
+ ui.notify("logs-unavailable")
59
+ else:
60
+ ui.notify("logs-ready", path=log_path)
61
+ emit("app.started", quality=args.quality)
62
+ if os.name == "nt" and not (mpv_dir() / "mpv.exe").is_file():
63
+ ui.notify("mpv-installing")
64
+ ui.notify("mpv-ready", path=install_mpv())
65
+ find_mpv()
66
+ ui.notify("welcome")
67
+ session = create_session(args.quality)
68
+ login(session, ui.notify, ui.ask)
69
+ catalog = Catalog(session)
70
+ with tempfile.TemporaryDirectory(prefix="noneto-") as directory:
71
+ library = Library(catalog, persist=SessionPersistence(session))
72
+ controls = None
73
+ playback = PlaybackController(lambda track: library.resolve(stream_target, track, directory),
74
+ player_factory=lambda: Player(media_controls=not (controls and controls.available)),
75
+ queue_store=QueueStore(session.user.id))
76
+ try:
77
+ if os.name == "nt":
78
+ from .audio.media_controls import MediaControls
79
+ controls = MediaControls(playback, lambda track: library.submit("media_cover", track))
80
+ load_user_themes()
81
+ settings = load_settings(available_themes(), allowed_visualizer_modes=available_visualizer_modes(),
82
+ allowed_lyrics_layouts=LAYOUTS)
83
+
84
+ def update_setting(key, value):
85
+ settings[key] = value
86
+ save_settings(settings)
87
+
88
+ artwork = terminal_artwork() # probes the terminal before Textual takes stdin
89
+ interface = NonetoApp(library, playback, args.quality, args.playlist,
90
+ getattr(session.user, "first_name", None), theme=settings.get("theme"),
91
+ on_theme=lambda name: update_setting("theme", name),
92
+ visualizer_mode=settings.get("visualizer_mode"),
93
+ on_visualizer_mode=lambda mode: update_setting("visualizer_mode", mode),
94
+ artwork=artwork, lyrics_layout=settings.get("lyrics_layout"),
95
+ on_lyrics_layout=lambda layout: update_setting("lyrics_layout", layout))
96
+ interface.run()
97
+ finally:
98
+ if controls is not None:
99
+ controls.close()
100
+ playback.close()
101
+ library.close()
102
+ return interface.return_code
103
+ except (KeyboardInterrupt, EOFError):
104
+ ui.notify("bye")
105
+ return 0
106
+ except Exception as error:
107
+ failure("app.failed", error)
108
+ ui.notify("error", error=error)
109
+ return 1
110
+ finally:
111
+ if session is not None:
112
+ session.request_session.close()
113
+ emit("app.stopped")
Binary file
@@ -0,0 +1 @@
1
+ """Stream validation, playback queue, mpv transport and visualizer capture."""
@@ -0,0 +1,427 @@
1
+ """Nonblocking playback queue. Receives a future-returning stream resolver."""
2
+ from dataclasses import dataclass, replace
3
+ import queue
4
+ import random
5
+ import threading
6
+ import time
7
+
8
+ from ..diagnostics import emit, failure, track_id
9
+ from ..errors import AppError, error_label
10
+ from ..i18n import _
11
+ from ..state.writer import QueueWriter
12
+ from .player import Player
13
+ from .inspector import describe_audio
14
+ import os
15
+ import sys
16
+
17
+
18
+ def process_tap(pid):
19
+ if os.name == "nt":
20
+ from .tap import ProcessTap as WindowsTap
21
+ return WindowsTap(pid)
22
+ if sys.platform.startswith("linux"):
23
+ from .pulse_tap import PulseTap
24
+ return PulseTap(pid)
25
+ return None
26
+
27
+
28
+ @dataclass(frozen=True)
29
+ class PlaybackState:
30
+ tracks: tuple = ()
31
+ index: int = -1
32
+ status: str = "Not playing"
33
+ position: float = 0
34
+ duration: float = 0
35
+ volume: int = 60
36
+ paused: bool = False
37
+ shuffle: bool = False
38
+ repeat: str = "off"
39
+ error: str = ""
40
+ audio: tuple = () # (short, detail, tier) of what mpv decodes, empty until loaded
41
+
42
+
43
+ class PlaybackController:
44
+ def __init__(self, resolve, player_factory=Player, tap_factory=process_tap, queue_store=None):
45
+ self.resolve = resolve
46
+ self.player_factory = player_factory
47
+ self.tap_factory = tap_factory
48
+ self._tap = None
49
+ self._spectrum = None
50
+ self.queue_store = queue_store
51
+ self._restored = queue_store.load() if queue_store is not None else None
52
+ self._state = PlaybackState()
53
+ if self._restored:
54
+ saved = self._restored
55
+ self._state = PlaybackState(tracks=tuple(saved["tracks"][i] for i in saved["order"]),
56
+ index=saved["index"], position=saved["position"],
57
+ volume=saved["volume"], shuffle=saved["shuffle"],
58
+ repeat=saved["repeat"], paused=saved["index"] >= 0,
59
+ status="Paused" if saved["index"] >= 0 else "Stopped")
60
+ self._lock = threading.Lock()
61
+ self._commands = queue.Queue(maxsize=128)
62
+ self._wake = threading.Event()
63
+ self._writer = (QueueWriter(queue_store, lambda error: failure("queue.save_failed", error))
64
+ if queue_store is not None else None)
65
+ self._random = random.Random()
66
+ self._closing = threading.Event()
67
+ self._thread = threading.Thread(target=self._run, name="noneto-audio", daemon=True)
68
+ self._thread.start()
69
+
70
+ def snapshot(self):
71
+ with self._lock:
72
+ return self._state
73
+
74
+ def _set(self, **values):
75
+ with self._lock:
76
+ self._state = replace(self._state, **values)
77
+
78
+ def send(self, action, value=None):
79
+ try:
80
+ self._commands.put_nowait((action, value))
81
+ self._wake.set()
82
+ except queue.Full:
83
+ raise AppError(_("Too many pending actions. Wait a moment.")) from None
84
+
85
+ def close(self):
86
+ self._closing.set()
87
+ self._wake.set()
88
+ self._thread.join(timeout=20)
89
+
90
+ def bands(self, count):
91
+ """Spectrum of what mpv is playing right now, or None when there is no capture."""
92
+ tap = self._tap
93
+ if tap is None or tap.failed.is_set():
94
+ return None
95
+ if self._spectrum is None:
96
+ from .spectrum import Spectrum
97
+ self._spectrum = Spectrum(tap.rate)
98
+ return self._spectrum.bands(tap.samples(), count)
99
+
100
+ def _tap_player(self, player, wanted):
101
+ """Capture only while the visualizer is visible and mpv exists; follow mpv restarts."""
102
+ tap = self._tap
103
+ pid = player.process.pid if wanted and player is not None else None
104
+ if tap is not None and tap.pid != pid:
105
+ self._tap = None
106
+ tap.stop()
107
+ if pid is not None and self._tap is None:
108
+ capture = self.tap_factory(pid)
109
+ if capture is not None:
110
+ self._tap = capture.start()
111
+
112
+ def _run(self):
113
+ player = None
114
+ future = None
115
+ loading = None
116
+ started = False
117
+ last_poll = 0
118
+ source_tracks = self._restored["tracks"] if self._restored else ()
119
+ queue_order = tuple(self._restored["order"]) if self._restored else ()
120
+ resume_position = self._state.position if self._restored else 0
121
+ seek_on_load = 0
122
+ prepared = None # (index, track object, future, monotonic time, staged in mpv)
123
+ last_save = time.monotonic()
124
+ prefetch_blocked = None
125
+
126
+ def persist():
127
+ nonlocal last_save
128
+ if self._writer is not None:
129
+ self._writer.submit(self.snapshot(), source_tracks, queue_order)
130
+ last_save = time.monotonic()
131
+
132
+ def discard_prepared(clear=True):
133
+ nonlocal prepared, prefetch_blocked
134
+ if prepared is not None:
135
+ prepared[2].cancel()
136
+ if clear and prepared[4] and player is not None and hasattr(player, "clear_next"):
137
+ player.clear_next()
138
+ prepared = None
139
+ prefetch_blocked = None
140
+
141
+ def predicted_next():
142
+ state = self.snapshot()
143
+ if state.index < 0:
144
+ return -1
145
+ if state.repeat == "one":
146
+ return state.index
147
+ if state.index + 1 < len(state.tracks):
148
+ return state.index + 1
149
+ if state.repeat == "all" and not state.shuffle and state.tracks:
150
+ return 0
151
+ return -1 # A shuffled cycle is selected on EOF, preserving duplicate rules.
152
+
153
+ def prefetch():
154
+ nonlocal prepared, prefetch_blocked
155
+ state = self.snapshot()
156
+ index = predicted_next()
157
+ if index < 0 or state.status != "Playing" or state.paused:
158
+ return
159
+ # Resolve close to EOF so signed targets are not held through an entire long song.
160
+ if state.duration <= 0 or state.duration - state.position > 30:
161
+ return
162
+ track = state.tracks[index]
163
+ if prepared is not None and time.monotonic() - prepared[3] > 90:
164
+ discard_prepared()
165
+ if prepared is None and prefetch_blocked is not track:
166
+ try:
167
+ prepared = (index, track, self.resolve(track), time.monotonic(), False)
168
+ prepared[2].add_done_callback(lambda _future: self._wake.set())
169
+ except Exception as error:
170
+ prefetch_blocked = track
171
+ failure("playback.prefetch_failed", error)
172
+ return
173
+ if prepared is not None and prepared[2].done() and not prepared[4]:
174
+ try:
175
+ target = prepared[2].result()
176
+ if hasattr(player, "stage"):
177
+ player.stage(target)
178
+ prepared = (*prepared[:4], True)
179
+ except Exception as error:
180
+ discard_prepared()
181
+ prefetch_blocked = track
182
+ failure("playback.prefetch_failed", error)
183
+
184
+ visualizer = False
185
+
186
+ def set_order(order):
187
+ nonlocal queue_order
188
+ queue_order = tuple(order)
189
+ self._set(tracks=tuple(source_tracks[index] for index in order))
190
+
191
+ def select(index):
192
+ nonlocal future, loading, started, prepared, resume_position, seek_on_load
193
+ if future is not None:
194
+ future.cancel()
195
+ future = None
196
+ cached = prepared
197
+ usable = (cached is not None and cached[0] == index and 0 <= index < len(self.snapshot().tracks)
198
+ and cached[1] is self.snapshot().tracks[index]
199
+ and time.monotonic() - cached[3] <= 90
200
+ and not cached[2].cancelled()
201
+ and (not cached[2].done() or cached[2].exception() is None))
202
+ if usable:
203
+ prepared = None
204
+ if cached[4] and hasattr(player, "clear_next"):
205
+ player.clear_next()
206
+ else:
207
+ discard_prepared()
208
+ resume_position, seek_on_load = 0, 0
209
+ loading, started = None, False
210
+ if player is not None:
211
+ player.command("stop")
212
+ while not player.events.empty():
213
+ try:
214
+ player.events.get_nowait()
215
+ except queue.Empty:
216
+ break
217
+ state = self.snapshot()
218
+ if 0 <= index < len(state.tracks):
219
+ self._set(index=index, status="Loading", position=0, duration=0,
220
+ paused=False, error="", audio=())
221
+ emit("track.selected", track_id=track_id(state.tracks[index]), index=index,
222
+ count=len(state.tracks))
223
+ future = cached[2] if usable else self.resolve(state.tracks[index])
224
+ future.add_done_callback(lambda _future: self._wake.set())
225
+ else:
226
+ self._set(index=-1, status="Stopped", position=0, duration=0, paused=False, audio=())
227
+
228
+ def read_audio():
229
+ # audio-params exists only once the decoder starts, usually after file-loaded: retried on each poll.
230
+ audio = describe_audio(player.command("get_property", "audio-codec-name", allow_unavailable=True),
231
+ player.command("get_property", "audio-params", allow_unavailable=True))
232
+ if audio:
233
+ state = self.snapshot()
234
+ self._set(audio=audio)
235
+ emit("playback.audio", track_id=track_id(state.tracks[state.index]), quality=audio[1])
236
+
237
+ def advance(ended=False):
238
+ nonlocal prepared, loading, started
239
+ state = self.snapshot()
240
+ next_index = predicted_next()
241
+ if (ended and prepared is not None and prepared[4] and hasattr(player, "stage")
242
+ and prepared[0] == next_index and prepared[1] is state.tracks[next_index]):
243
+ prepared = None
244
+ self._set(index=next_index, status="Loading", position=0, duration=0,
245
+ paused=False, error="", audio=())
246
+ loading, started = time.monotonic(), False
247
+ return # mpv continues into the prefetched playlist entry without stop/loadfile.
248
+
249
+ if ended and state.repeat == "one" and state.index >= 0:
250
+ select(state.index)
251
+ elif state.index + 1 < len(state.tracks):
252
+ select(state.index + 1)
253
+ elif state.repeat == "all" and state.tracks:
254
+ if state.shuffle:
255
+ order = list(queue_order)
256
+ self._random.shuffle(order)
257
+ last = source_tracks[queue_order[state.index]]
258
+ last_id = getattr(last, "id", None)
259
+
260
+ def same_song(index):
261
+ track = source_tracks[index]
262
+ return track is last or (last_id is not None and getattr(track, "id", None) == last_id)
263
+
264
+ if same_song(order[0]):
265
+ alternative = next((i for i, index in enumerate(order) if not same_song(index)), None)
266
+ if alternative is not None:
267
+ order[0], order[alternative] = order[alternative], order[0]
268
+ set_order(order)
269
+ select(0)
270
+ else:
271
+ select(-1)
272
+
273
+ try:
274
+ while not self._closing.is_set():
275
+ pending_event = player is not None and not player.events.empty()
276
+ if self._commands.empty() and not pending_event:
277
+ # Real players notify IPC events; legacy/test players retain bounded polling.
278
+ interval = .5 if player is not None and callable(getattr(player, "set_wakeup", None)) else .05
279
+ self._wake.wait(interval if player is not None or future is not None else 5)
280
+ self._wake.clear()
281
+ if self._closing.is_set():
282
+ break
283
+ try:
284
+ action, value = self._commands.get_nowait()
285
+ except queue.Empty:
286
+ action, value = None, None
287
+ try:
288
+ state = self.snapshot()
289
+ if action == "play":
290
+ discard_prepared()
291
+ tracks, index = value
292
+ source_tracks = tuple(tracks)
293
+ queue_order = list(range(len(source_tracks)))
294
+ if state.shuffle:
295
+ suffix = queue_order[index + 1:]
296
+ self._random.shuffle(suffix)
297
+ queue_order[index + 1:] = suffix
298
+ set_order(queue_order)
299
+ select(index)
300
+ elif action == "enqueue":
301
+ discard_prepared()
302
+ source_tracks += (value,)
303
+ set_order((*queue_order, len(source_tracks) - 1))
304
+ elif action == "next":
305
+ advance()
306
+ elif action == "previous":
307
+ select(max(0, state.index - 1))
308
+ elif action == "stop":
309
+ select(-1)
310
+ elif action == "shuffle":
311
+ discard_prepared()
312
+ order = list(queue_order)
313
+ start = max(0, state.index + 1)
314
+ suffix = order[start:]
315
+ if state.shuffle:
316
+ suffix.sort()
317
+ else:
318
+ self._random.shuffle(suffix)
319
+ set_order(order[:start] + suffix)
320
+ self._set(shuffle=not state.shuffle)
321
+ elif action == "visualizer":
322
+ visualizer = bool(value)
323
+ elif action == "media_controls" and player:
324
+ player.command("set_property", "media-controls", bool(value))
325
+ elif action == "repeat":
326
+ discard_prepared()
327
+ self._set(repeat={"off": "all", "all": "one", "one": "off"}[state.repeat])
328
+ elif action in ("pause", "set_pause") and player is None and state.index >= 0:
329
+ if action == "pause" or not value:
330
+ position = resume_position
331
+ select(state.index)
332
+ seek_on_load = position
333
+ elif action in ("pause", "set_pause") and player and state.status in ("Playing", "Paused"):
334
+ paused = not state.paused if action == "pause" else bool(value)
335
+ if paused != state.paused:
336
+ player.command("set_property", "pause", paused)
337
+ if paused:
338
+ discard_prepared()
339
+ self._set(paused=paused, status="Paused" if paused else "Playing")
340
+ elif action == "volume":
341
+ volume = max(0, min(100, state.volume + value))
342
+ if player:
343
+ player.command("set_property", "volume", volume)
344
+ self._set(volume=volume)
345
+ elif action == "seek" and player and state.status in ("Playing", "Paused"):
346
+ discard_prepared()
347
+ player.command("seek", value, "relative")
348
+ elif (action == "seek_absolute" and player
349
+ and state.status in ("Playing", "Paused") and state.duration > 0):
350
+ discard_prepared()
351
+ target = max(0.0, min(state.duration, float(value)))
352
+ player.command("seek", target, "absolute")
353
+ self._set(position=target)
354
+
355
+ if future is not None and future.done():
356
+ pending, future = future, None
357
+ target = pending.result()
358
+ if player is None:
359
+ player = self.player_factory()
360
+ if callable(getattr(player, "set_wakeup", None)):
361
+ player.set_wakeup(self._wake.set)
362
+ player.command("set_property", "volume", self.snapshot().volume)
363
+ player.play(target)
364
+ loading, started = time.monotonic(), False
365
+ self._tap_player(player, visualizer)
366
+ if player:
367
+ if player.failed.is_set() or player.process.poll() is not None:
368
+ raise AppError(_("Lost communication with mpv. Try playing again."))
369
+ while True:
370
+ try:
371
+ event = player.events.get_nowait()
372
+ except queue.Empty:
373
+ break
374
+ kind = event.get("event")
375
+ if kind == "start-file":
376
+ started = True
377
+ elif kind == "file-loaded" and started:
378
+ loading = None
379
+ self._set(status="Playing")
380
+ if seek_on_load:
381
+ player.command("seek", seek_on_load, "absolute")
382
+ self._set(position=seek_on_load)
383
+ seek_on_load = 0
384
+ emit("playback.loaded", track_id=track_id(self.snapshot().tracks[self.snapshot().index]))
385
+ read_audio()
386
+ elif kind == "end-file" and started and event.get("reason") == "eof":
387
+ advance(ended=True)
388
+ persist()
389
+ break
390
+ elif kind == "end-file" and started and event.get("reason") == "error":
391
+ raise AppError(_("Could not load the audio. Try again or pick another song."))
392
+ if loading is not None and time.monotonic() - loading > 45:
393
+ raise AppError(_("The audio did not load within 45 seconds. Try again."))
394
+ if (self.snapshot().status in ("Playing", "Paused")
395
+ and time.monotonic() - last_poll > 0.5):
396
+ last_poll = time.monotonic()
397
+ self._set(position=player.command("get_property", "time-pos", allow_unavailable=True) or 0,
398
+ duration=player.command("get_property", "duration", allow_unavailable=True) or 0)
399
+ if not self.snapshot().audio:
400
+ read_audio()
401
+ if player:
402
+ prefetch()
403
+ if action in {"play", "enqueue", "next", "previous", "stop", "shuffle", "repeat", "volume"} or time.monotonic() - last_save >= 5:
404
+ persist()
405
+ except Exception as error:
406
+ failure("playback.failed", error)
407
+ discard_prepared(clear=False)
408
+ if future is not None:
409
+ future.cancel()
410
+ future, loading, started = None, None, False
411
+ self._set(status="Error", error=str(error) if isinstance(error, AppError) else error_label(error))
412
+ if player:
413
+ player.close()
414
+ player = None
415
+ self._tap_player(None, False)
416
+ finally:
417
+ persist()
418
+ discard_prepared(clear=False)
419
+ self._tap_player(None, False)
420
+ if future is not None:
421
+ future.cancel()
422
+ try:
423
+ if player:
424
+ player.close()
425
+ finally:
426
+ if self._writer is not None:
427
+ self._writer.close()
@@ -0,0 +1,21 @@
1
+ """Describe the audio mpv actually decodes."""
2
+ LOSSY_CODECS = {"aac", "mp3", "opus", "vorbis", "ac3", "eac3"}
3
+
4
+
5
+ def describe_audio(codec, params):
6
+ """Label the decoded stream and rank it as a TIDAL tier (None when it maps to none).
7
+
8
+ TIDAL FLAC is 16-bit (decoded as s16) or 24-bit (decoded as s32).
9
+ """
10
+ rate = params.get("samplerate") if isinstance(params, dict) else None
11
+ if not isinstance(codec, str) or not isinstance(rate, int) or rate <= 0:
12
+ return ()
13
+ khz = f"{rate / 1000:g}"
14
+ if codec == "flac":
15
+ bits = {"s16": 16, "s16p": 16, "s32": 24, "s32p": 24}.get(params.get("format"))
16
+ if bits:
17
+ tier = "HI_RES_LOSSLESS" if bits > 16 or rate > 48000 else "LOSSLESS"
18
+ return (f"FLAC {bits}/{khz}", f"FLAC {bits}-bit / {khz} kHz", tier)
19
+ return (f"FLAC {khz}", f"FLAC / {khz} kHz", "LOSSLESS")
20
+ name = codec.upper()
21
+ return (f"{name} {khz}", f"{name} / {khz} kHz", "HIGH" if codec in LOSSY_CODECS else None)
@@ -0,0 +1,29 @@
1
+ """Private Unix socketpair inherited by mpv; closing the owner also stops mpv."""
2
+ import socket
3
+
4
+
5
+ class UnixIPC:
6
+ def __init__(self):
7
+ self.pipe, self.child = socket.socketpair(socket.AF_UNIX, socket.SOCK_STREAM)
8
+ self.pipe.settimeout(0.1)
9
+ self.argument = f"--input-ipc-client=fd://{self.child.fileno()}"
10
+ self.spawn_options = {"pass_fds": (self.child.fileno(),)}
11
+
12
+ def connect(self, process):
13
+ self.child.close()
14
+
15
+ def read(self, size):
16
+ try:
17
+ return self.pipe.recv(size)
18
+ except socket.timeout:
19
+ return None
20
+
21
+ def write(self, data, timeout=5):
22
+ try:
23
+ return self.pipe.send(data)
24
+ except (socket.timeout, BlockingIOError):
25
+ return 0
26
+
27
+ def close(self):
28
+ self.pipe.close()
29
+ self.child.close()