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.
- noneto/__init__.py +1 -0
- noneto/__main__.py +3 -0
- noneto/app.py +113 -0
- noneto/assets/noneto.ico +0 -0
- noneto/audio/__init__.py +1 -0
- noneto/audio/controller.py +427 -0
- noneto/audio/inspector.py +21 -0
- noneto/audio/ipc_unix.py +29 -0
- noneto/audio/ipc_windows.py +94 -0
- noneto/audio/lifetime.py +68 -0
- noneto/audio/media_controls.py +107 -0
- noneto/audio/mpv_install.py +71 -0
- noneto/audio/player.py +222 -0
- noneto/audio/pulse_tap.py +120 -0
- noneto/audio/spectrum.py +44 -0
- noneto/audio/streams.py +101 -0
- noneto/audio/tap.py +208 -0
- noneto/audio/windows_identity.py +79 -0
- noneto/audio/windows_media.py +157 -0
- noneto/auth/__init__.py +1 -0
- noneto/auth/dpapi.py +28 -0
- noneto/auth/service.py +53 -0
- noneto/auth/storage.py +120 -0
- noneto/diagnostics.py +115 -0
- noneto/errors.py +12 -0
- noneto/i18n.py +199 -0
- noneto/platform/__init__.py +1 -0
- noneto/platform/paths.py +27 -0
- noneto/security.py +59 -0
- noneto/services/__init__.py +1 -0
- noneto/services/covers.py +88 -0
- noneto/services/executor.py +83 -0
- noneto/services/library.py +110 -0
- noneto/services/tidal.py +188 -0
- noneto/settings.py +48 -0
- noneto/state/__init__.py +1 -0
- noneto/state/queue.py +130 -0
- noneto/state/writer.py +38 -0
- noneto/ui/__init__.py +1 -0
- noneto/ui/common.py +36 -0
- noneto/ui/cover.py +88 -0
- noneto/ui/dialogs.py +107 -0
- noneto/ui/linux_login.py +57 -0
- noneto/ui/login_window.py +201 -0
- noneto/ui/lyrics.py +142 -0
- noneto/ui/player.py +172 -0
- noneto/ui/quality.py +75 -0
- noneto/ui/queue.py +34 -0
- noneto/ui/terminal.py +65 -0
- noneto/ui/themes.py +352 -0
- noneto/ui/top.py +39 -0
- noneto/ui/tracks.py +139 -0
- noneto/ui/tui.py +601 -0
- noneto/ui/visualizer.py +343 -0
- noneto_cli-1.1.1.dist-info/METADATA +222 -0
- noneto_cli-1.1.1.dist-info/RECORD +59 -0
- noneto_cli-1.1.1.dist-info/WHEEL +4 -0
- noneto_cli-1.1.1.dist-info/entry_points.txt +2 -0
- noneto_cli-1.1.1.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
"""Overlapped Windows pipe: readiness events, bounded writes and verified PID."""
|
|
2
|
+
import _winapi
|
|
3
|
+
import ctypes
|
|
4
|
+
from ctypes import wintypes
|
|
5
|
+
import msvcrt
|
|
6
|
+
import os
|
|
7
|
+
import math
|
|
8
|
+
import subprocess
|
|
9
|
+
import time
|
|
10
|
+
import uuid
|
|
11
|
+
|
|
12
|
+
from ..errors import AppError
|
|
13
|
+
from ..i18n import _
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class WindowsIPC:
|
|
17
|
+
def __init__(self):
|
|
18
|
+
self.name = rf"\\.\pipe\noneto-{uuid.uuid4().hex}"
|
|
19
|
+
self.argument = f"--input-ipc-server={self.name}"
|
|
20
|
+
self.spawn_options = {"creationflags": subprocess.CREATE_NO_WINDOW}
|
|
21
|
+
self.pipe = None
|
|
22
|
+
self._read = None
|
|
23
|
+
|
|
24
|
+
def connect(self, process):
|
|
25
|
+
deadline = time.monotonic() + 10
|
|
26
|
+
while time.monotonic() < deadline:
|
|
27
|
+
if process.poll() is not None:
|
|
28
|
+
raise AppError(_("mpv could not start."))
|
|
29
|
+
try:
|
|
30
|
+
handle = _winapi.CreateFile(self.name, _winapi.GENERIC_READ | _winapi.GENERIC_WRITE,
|
|
31
|
+
0, 0, _winapi.OPEN_EXISTING, _winapi.FILE_FLAG_OVERLAPPED, 0)
|
|
32
|
+
self.pipe = os.fdopen(msvcrt.open_osfhandle(handle, os.O_RDWR | os.O_BINARY), "r+b", buffering=0)
|
|
33
|
+
break
|
|
34
|
+
except OSError:
|
|
35
|
+
time.sleep(0.05)
|
|
36
|
+
if self.pipe is None:
|
|
37
|
+
raise AppError(_("mpv did not respond within 10 seconds."))
|
|
38
|
+
kernel = ctypes.WinDLL("kernel32", use_last_error=True)
|
|
39
|
+
self.handle = msvcrt.get_osfhandle(self.pipe.fileno())
|
|
40
|
+
get_pid = kernel.GetNamedPipeServerProcessId
|
|
41
|
+
get_pid.argtypes = [wintypes.HANDLE, ctypes.POINTER(wintypes.ULONG)]
|
|
42
|
+
get_pid.restype = wintypes.BOOL
|
|
43
|
+
pid = wintypes.ULONG()
|
|
44
|
+
if not get_pid(self.handle, ctypes.byref(pid)) or pid.value != process.pid:
|
|
45
|
+
raise AppError(_("Could not verify the player channel."))
|
|
46
|
+
set_state = kernel.SetNamedPipeHandleState
|
|
47
|
+
set_state.argtypes = [wintypes.HANDLE, ctypes.POINTER(wintypes.DWORD), ctypes.c_void_p, ctypes.c_void_p]
|
|
48
|
+
set_state.restype = wintypes.BOOL
|
|
49
|
+
mode = wintypes.DWORD(0) # Byte mode; OVERLAPPED handles make waits interruptible.
|
|
50
|
+
if not set_state(self.handle, ctypes.byref(mode), None, None):
|
|
51
|
+
raise AppError(_("Could not configure the player channel."))
|
|
52
|
+
|
|
53
|
+
def read(self, size):
|
|
54
|
+
if self.pipe.closed:
|
|
55
|
+
self._cancel_read()
|
|
56
|
+
raise OSError("IPC disconnected")
|
|
57
|
+
if self._read is None:
|
|
58
|
+
self._read, _error = _winapi.ReadFile(self.handle, size, overlapped=True)
|
|
59
|
+
# Data wakes immediately. The timeout only lets shutdown inspect its flag.
|
|
60
|
+
if _winapi.WaitForSingleObject(self._read.event, 100) == _winapi.WAIT_TIMEOUT:
|
|
61
|
+
return None
|
|
62
|
+
pending, self._read = self._read, None
|
|
63
|
+
count, error = pending.GetOverlappedResult(True)
|
|
64
|
+
if error:
|
|
65
|
+
raise OSError("IPC disconnected")
|
|
66
|
+
return bytes(pending.getbuffer())[:count]
|
|
67
|
+
|
|
68
|
+
def write(self, data, timeout=5):
|
|
69
|
+
pending, _error = _winapi.WriteFile(self.handle, data, overlapped=True)
|
|
70
|
+
try:
|
|
71
|
+
if _winapi.WaitForSingleObject(pending.event, max(0, math.ceil(timeout * 1000))) != _winapi.WAIT_OBJECT_0:
|
|
72
|
+
raise OSError("IPC write timed out")
|
|
73
|
+
except BaseException:
|
|
74
|
+
pending.cancel()
|
|
75
|
+
pending.GetOverlappedResult(True)
|
|
76
|
+
raise
|
|
77
|
+
count, error = pending.GetOverlappedResult(True)
|
|
78
|
+
if error:
|
|
79
|
+
raise OSError("IPC disconnected")
|
|
80
|
+
return count
|
|
81
|
+
|
|
82
|
+
def _cancel_read(self):
|
|
83
|
+
if self._read is not None:
|
|
84
|
+
pending, self._read = self._read, None
|
|
85
|
+
try:
|
|
86
|
+
pending.cancel()
|
|
87
|
+
pending.GetOverlappedResult(True)
|
|
88
|
+
except OSError:
|
|
89
|
+
pass
|
|
90
|
+
|
|
91
|
+
def close(self):
|
|
92
|
+
self._cancel_read()
|
|
93
|
+
if self.pipe is not None:
|
|
94
|
+
self.pipe.close()
|
noneto/audio/lifetime.py
ADDED
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
"""Windows owns player cleanup even when Python cannot run its finally blocks.
|
|
2
|
+
|
|
3
|
+
https://learn.microsoft.com/en-us/windows/win32/procthread/job-objects
|
|
4
|
+
"""
|
|
5
|
+
import ctypes
|
|
6
|
+
from ctypes import wintypes
|
|
7
|
+
|
|
8
|
+
from ..errors import AppError
|
|
9
|
+
from ..i18n import _
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class _BasicLimits(ctypes.Structure):
|
|
13
|
+
_fields_ = [("PerProcessUserTimeLimit", ctypes.c_longlong),
|
|
14
|
+
("PerJobUserTimeLimit", ctypes.c_longlong),
|
|
15
|
+
("LimitFlags", wintypes.DWORD),
|
|
16
|
+
("MinimumWorkingSetSize", ctypes.c_size_t),
|
|
17
|
+
("MaximumWorkingSetSize", ctypes.c_size_t),
|
|
18
|
+
("ActiveProcessLimit", wintypes.DWORD),
|
|
19
|
+
("Affinity", ctypes.c_size_t),
|
|
20
|
+
("PriorityClass", wintypes.DWORD),
|
|
21
|
+
("SchedulingClass", wintypes.DWORD)]
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
class _IoCounters(ctypes.Structure):
|
|
25
|
+
_fields_ = [(name, ctypes.c_ulonglong) for name in (
|
|
26
|
+
"ReadOperationCount", "WriteOperationCount", "OtherOperationCount",
|
|
27
|
+
"ReadTransferCount", "WriteTransferCount", "OtherTransferCount")]
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
class _ExtendedLimits(ctypes.Structure):
|
|
31
|
+
_fields_ = [("BasicLimitInformation", _BasicLimits), ("IoInfo", _IoCounters),
|
|
32
|
+
("ProcessMemoryLimit", ctypes.c_size_t), ("JobMemoryLimit", ctypes.c_size_t),
|
|
33
|
+
("PeakProcessMemoryUsed", ctypes.c_size_t), ("PeakJobMemoryUsed", ctypes.c_size_t)]
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
class PlayerJob:
|
|
37
|
+
"""An unnamed, noninheritable job held only by the owning Python process."""
|
|
38
|
+
|
|
39
|
+
def __init__(self):
|
|
40
|
+
self.kernel = ctypes.WinDLL("kernel32", use_last_error=True)
|
|
41
|
+
self.kernel.CreateJobObjectW.argtypes = [ctypes.c_void_p, wintypes.LPCWSTR]
|
|
42
|
+
self.kernel.CreateJobObjectW.restype = wintypes.HANDLE
|
|
43
|
+
self.kernel.SetInformationJobObject.argtypes = [wintypes.HANDLE, ctypes.c_int,
|
|
44
|
+
ctypes.c_void_p, wintypes.DWORD]
|
|
45
|
+
self.kernel.SetInformationJobObject.restype = wintypes.BOOL
|
|
46
|
+
self.kernel.AssignProcessToJobObject.argtypes = [wintypes.HANDLE, wintypes.HANDLE]
|
|
47
|
+
self.kernel.AssignProcessToJobObject.restype = wintypes.BOOL
|
|
48
|
+
self.kernel.CloseHandle.argtypes = [wintypes.HANDLE]
|
|
49
|
+
self.kernel.CloseHandle.restype = wintypes.BOOL
|
|
50
|
+
self.handle = self.kernel.CreateJobObjectW(None, None)
|
|
51
|
+
if not self.handle:
|
|
52
|
+
raise AppError(_("Could not prepare the player's automatic shutdown."))
|
|
53
|
+
limits = _ExtendedLimits()
|
|
54
|
+
limits.BasicLimitInformation.LimitFlags = 0x2000 # JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE
|
|
55
|
+
if not self.kernel.SetInformationJobObject(self.handle, 9, ctypes.byref(limits),
|
|
56
|
+
ctypes.sizeof(limits)):
|
|
57
|
+
self.close()
|
|
58
|
+
raise AppError(_("Could not configure the player's automatic shutdown."))
|
|
59
|
+
|
|
60
|
+
def attach(self, process):
|
|
61
|
+
# Popen retains the original Windows process handle, avoiding PID reuse.
|
|
62
|
+
if not self.kernel.AssignProcessToJobObject(self.handle, int(process._handle)):
|
|
63
|
+
raise AppError(_("Could not tie the player to Noneto CLI's shutdown."))
|
|
64
|
+
|
|
65
|
+
def close(self):
|
|
66
|
+
if self.handle:
|
|
67
|
+
self.kernel.CloseHandle(self.handle)
|
|
68
|
+
self.handle = None
|
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
"""Mirror playback into the system media session without blocking UI or audio."""
|
|
2
|
+
import math
|
|
3
|
+
import threading
|
|
4
|
+
import time
|
|
5
|
+
|
|
6
|
+
from ..diagnostics import emit, failure
|
|
7
|
+
from ..security import terminal_text
|
|
8
|
+
from .windows_media import WindowsMedia
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
class MediaControls:
|
|
12
|
+
def __init__(self, playback, artwork, backend_factory=WindowsMedia):
|
|
13
|
+
self.playback = playback
|
|
14
|
+
self.artwork = artwork # returns a future; SDK access stays serialized by Library
|
|
15
|
+
self.backend_factory = backend_factory
|
|
16
|
+
self.available = False
|
|
17
|
+
self._ready = threading.Event()
|
|
18
|
+
self._closing = threading.Event()
|
|
19
|
+
self._thread = threading.Thread(target=self._run, name="noneto-media", daemon=True)
|
|
20
|
+
self._thread.start()
|
|
21
|
+
if not self._ready.wait(3):
|
|
22
|
+
self._closing.set()
|
|
23
|
+
|
|
24
|
+
def _button(self, name):
|
|
25
|
+
if self._closing.is_set():
|
|
26
|
+
return
|
|
27
|
+
try:
|
|
28
|
+
if name in ("PLAY", "PAUSE"):
|
|
29
|
+
self.playback.send("set_pause", name == "PAUSE")
|
|
30
|
+
elif name in ("NEXT", "PREVIOUS", "STOP"):
|
|
31
|
+
self.playback.send(name.lower())
|
|
32
|
+
except Exception as error:
|
|
33
|
+
failure("media.command_failed", error)
|
|
34
|
+
|
|
35
|
+
def _seek(self, seconds):
|
|
36
|
+
if not self._closing.is_set() and math.isfinite(seconds):
|
|
37
|
+
try:
|
|
38
|
+
self.playback.send("seek_absolute", seconds)
|
|
39
|
+
except Exception as error:
|
|
40
|
+
failure("media.command_failed", error)
|
|
41
|
+
|
|
42
|
+
def _run(self):
|
|
43
|
+
backend = None
|
|
44
|
+
track_key = object()
|
|
45
|
+
cover = None
|
|
46
|
+
last_update = 0
|
|
47
|
+
try:
|
|
48
|
+
backend = self.backend_factory(self._button, self._seek)
|
|
49
|
+
self.available = True
|
|
50
|
+
self._ready.set()
|
|
51
|
+
emit("media.started")
|
|
52
|
+
while not self._closing.is_set():
|
|
53
|
+
backend.pump()
|
|
54
|
+
state = self.playback.snapshot()
|
|
55
|
+
track = state.tracks[state.index] if 0 <= state.index < len(state.tracks) else None
|
|
56
|
+
key = getattr(track, "id", None)
|
|
57
|
+
if key != track_key:
|
|
58
|
+
track_key = key
|
|
59
|
+
if cover is not None:
|
|
60
|
+
cover.cancel()
|
|
61
|
+
cover = None
|
|
62
|
+
text = lambda value: terminal_text(str(value or ""))[:300]
|
|
63
|
+
backend.metadata(text(getattr(track, "name", "")),
|
|
64
|
+
text(getattr(getattr(track, "artist", None), "name", "")),
|
|
65
|
+
text(getattr(getattr(track, "album", None), "name", "")))
|
|
66
|
+
if track is not None:
|
|
67
|
+
cover = self.artwork(track)
|
|
68
|
+
last_update = 0
|
|
69
|
+
if cover is not None and cover.done():
|
|
70
|
+
pending, cover = cover, None
|
|
71
|
+
try:
|
|
72
|
+
data = pending.result()
|
|
73
|
+
if data:
|
|
74
|
+
backend.thumbnail(data)
|
|
75
|
+
except Exception as error:
|
|
76
|
+
failure("media.artwork_unavailable", error)
|
|
77
|
+
now = time.monotonic()
|
|
78
|
+
if now - last_update >= 0.25:
|
|
79
|
+
duration = max(0, state.duration or getattr(track, "duration", 0) or 0)
|
|
80
|
+
position = min(duration, max(0, state.position))
|
|
81
|
+
status = {"Playing": "playing", "Paused": "paused",
|
|
82
|
+
"Loading": "loading"}.get(state.status, "stopped")
|
|
83
|
+
backend.update(status, position, duration, state.index > 0 or position > 3,
|
|
84
|
+
state.index + 1 < len(state.tracks) or state.repeat == "all")
|
|
85
|
+
last_update = now
|
|
86
|
+
self._closing.wait(0.05)
|
|
87
|
+
except Exception as error:
|
|
88
|
+
failure("media.unavailable", error)
|
|
89
|
+
finally:
|
|
90
|
+
self.available = False
|
|
91
|
+
self._ready.set()
|
|
92
|
+
if cover is not None:
|
|
93
|
+
cover.cancel()
|
|
94
|
+
if backend is not None:
|
|
95
|
+
try:
|
|
96
|
+
backend.close()
|
|
97
|
+
except Exception as error:
|
|
98
|
+
failure("media.close_failed", error)
|
|
99
|
+
if not self._closing.is_set():
|
|
100
|
+
try:
|
|
101
|
+
self.playback.send("media_controls", True)
|
|
102
|
+
except Exception as error:
|
|
103
|
+
failure("media.fallback_failed", error)
|
|
104
|
+
|
|
105
|
+
def close(self):
|
|
106
|
+
self._closing.set()
|
|
107
|
+
self._thread.join(timeout=5)
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
"""Download the pinned mpv build for Windows, verify its SHA-256 and extract it for Noneto CLI only."""
|
|
2
|
+
import hashlib
|
|
3
|
+
import os
|
|
4
|
+
from pathlib import Path
|
|
5
|
+
from ..platform.paths import data_dir
|
|
6
|
+
import shutil
|
|
7
|
+
import subprocess
|
|
8
|
+
import sys
|
|
9
|
+
import tempfile
|
|
10
|
+
|
|
11
|
+
import requests
|
|
12
|
+
|
|
13
|
+
from ..errors import AppError
|
|
14
|
+
from ..i18n import _
|
|
15
|
+
|
|
16
|
+
# shinchiro/mpv-winbuild-cmake release 20260927 (mpv a1bf4b6559). Change both together.
|
|
17
|
+
MPV_URL = ("https://downloads.sourceforge.net/project/mpv-player-windows/64bit/"
|
|
18
|
+
"mpv-x86_64-20260927-git-a1bf4b6559.7z")
|
|
19
|
+
MPV_SHA256 = "04852d5e37730dfa74dec8f88d7cc80b8f756beb52c354c0a3753d3eb2c030e4"
|
|
20
|
+
MAX_ARCHIVE_BYTES = 256 * 1024 * 1024
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def mpv_dir():
|
|
24
|
+
if os.name == "nt" and getattr(sys, "frozen", False):
|
|
25
|
+
return Path(sys.executable).resolve().parent / "mpv"
|
|
26
|
+
return data_dir() / "mpv"
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def install_mpv():
|
|
30
|
+
"""Return the installed mpv.exe, downloading it first when missing. Never uses mpv from PATH."""
|
|
31
|
+
if os.name != "nt":
|
|
32
|
+
from .player import find_mpv
|
|
33
|
+
return Path(find_mpv())
|
|
34
|
+
executable = mpv_dir() / "mpv.exe"
|
|
35
|
+
if executable.is_file():
|
|
36
|
+
return executable
|
|
37
|
+
tar = Path(os.environ.get("SystemRoot", r"C:\Windows")) / "System32" / "tar.exe"
|
|
38
|
+
if not tar.is_file():
|
|
39
|
+
raise AppError(_("Windows tar.exe is missing; it is needed to extract mpv."))
|
|
40
|
+
with tempfile.TemporaryDirectory(prefix="noneto-mpv-") as work:
|
|
41
|
+
archive = Path(work) / "mpv.7z"
|
|
42
|
+
digest, size = hashlib.sha256(), 0
|
|
43
|
+
with requests.Session() as http:
|
|
44
|
+
http.trust_env = False
|
|
45
|
+
# GitHub redirects release assets to its CDN; the hash below is what authenticates the file.
|
|
46
|
+
with http.get(MPV_URL, stream=True, timeout=(10, 60), verify=True) as response:
|
|
47
|
+
if response.status_code != 200:
|
|
48
|
+
raise AppError(_("Could not download mpv (HTTP {status}).", status=response.status_code))
|
|
49
|
+
with archive.open("wb") as output:
|
|
50
|
+
for chunk in response.iter_content(65536):
|
|
51
|
+
size += len(chunk)
|
|
52
|
+
if size > MAX_ARCHIVE_BYTES:
|
|
53
|
+
raise AppError(_("The mpv download is too large."))
|
|
54
|
+
digest.update(chunk)
|
|
55
|
+
output.write(chunk)
|
|
56
|
+
if digest.hexdigest() != MPV_SHA256:
|
|
57
|
+
raise AppError(_("The mpv SHA-256 hash does not match; it was not installed."))
|
|
58
|
+
staging = Path(work) / "mpv"
|
|
59
|
+
staging.mkdir()
|
|
60
|
+
# bsdtar refuses absolute paths and ".." entries by default.
|
|
61
|
+
result = subprocess.run([str(tar), "-xf", str(archive), "-C", str(staging)],
|
|
62
|
+
stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL,
|
|
63
|
+
stderr=subprocess.DEVNULL, creationflags=subprocess.CREATE_NO_WINDOW)
|
|
64
|
+
if result.returncode != 0 or not (staging / "mpv.exe").is_file():
|
|
65
|
+
raise AppError(_("The downloaded file does not contain mpv.exe."))
|
|
66
|
+
target = mpv_dir()
|
|
67
|
+
target.parent.mkdir(parents=True, exist_ok=True)
|
|
68
|
+
if target.exists():
|
|
69
|
+
shutil.rmtree(target) # leftover of an interrupted install without mpv.exe
|
|
70
|
+
shutil.move(str(staging), str(target))
|
|
71
|
+
return executable
|
noneto/audio/player.py
ADDED
|
@@ -0,0 +1,222 @@
|
|
|
1
|
+
"""mpv JSON IPC transport: bounded messages, acknowledgements and explicit failure."""
|
|
2
|
+
import json
|
|
3
|
+
from pathlib import Path
|
|
4
|
+
import queue
|
|
5
|
+
import subprocess
|
|
6
|
+
import threading
|
|
7
|
+
import time
|
|
8
|
+
import os
|
|
9
|
+
import shutil
|
|
10
|
+
|
|
11
|
+
from ..errors import AppError
|
|
12
|
+
from ..i18n import _
|
|
13
|
+
from ..diagnostics import emit, failure, mpv_message
|
|
14
|
+
if os.name == "nt":
|
|
15
|
+
from .lifetime import PlayerJob
|
|
16
|
+
from .mpv_install import mpv_dir
|
|
17
|
+
|
|
18
|
+
MAX_FRAME = 1024 * 1024
|
|
19
|
+
COMMAND_TIMEOUT = 5
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def find_mpv():
|
|
23
|
+
if os.name == "nt":
|
|
24
|
+
local = mpv_dir() / "mpv.exe"
|
|
25
|
+
if not local.is_file():
|
|
26
|
+
raise AppError(_("mpv is missing. Install it with: noneto --install-mpv"))
|
|
27
|
+
return str(local)
|
|
28
|
+
executable = shutil.which("mpv")
|
|
29
|
+
if executable is None:
|
|
30
|
+
raise AppError(_("mpv is missing. Install it with your system package manager."))
|
|
31
|
+
return executable
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
class Player:
|
|
35
|
+
def __init__(self, executable=None, extra_args=(), media_controls=True):
|
|
36
|
+
self.events = queue.Queue(maxsize=128)
|
|
37
|
+
self.failed = threading.Event()
|
|
38
|
+
self._closing = threading.Event()
|
|
39
|
+
self._lock = threading.Lock()
|
|
40
|
+
self._command_lock = threading.Lock()
|
|
41
|
+
self._pending = {}
|
|
42
|
+
self._sequence = 0
|
|
43
|
+
self.pipe = None
|
|
44
|
+
self.thread = None
|
|
45
|
+
self._job = None
|
|
46
|
+
self._wakeup = None
|
|
47
|
+
if os.name == "nt":
|
|
48
|
+
from .ipc_windows import WindowsIPC
|
|
49
|
+
self._transport = WindowsIPC()
|
|
50
|
+
else:
|
|
51
|
+
from .ipc_unix import UnixIPC
|
|
52
|
+
self._transport = UnixIPC()
|
|
53
|
+
self.process = None
|
|
54
|
+
try:
|
|
55
|
+
self.process = subprocess.Popen([
|
|
56
|
+
str(Path(executable or find_mpv()).resolve()), *extra_args,
|
|
57
|
+
"--no-config", "--idle=yes", "--no-video", "--audio-display=no",
|
|
58
|
+
"--terminal=no", "--volume=60", "--load-scripts=no", "--ytdl=no",
|
|
59
|
+
"--load-unsafe-playlists=no", "--access-references=no", "--tls-verify=yes",
|
|
60
|
+
"--network-timeout=30",
|
|
61
|
+
*([f"--media-controls={'yes' if media_controls else 'no'}"] if os.name == "nt" else []),
|
|
62
|
+
"--prefetch-playlist=yes",
|
|
63
|
+
"--demuxer-lavf-o=protocol_whitelist=[file,https,tls,tcp]",
|
|
64
|
+
self._transport.argument,
|
|
65
|
+
], stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL,
|
|
66
|
+
stderr=subprocess.DEVNULL, **self._transport.spawn_options)
|
|
67
|
+
# mpv is idle: bind its lifetime before IPC can load any audio.
|
|
68
|
+
# Abrupt terminal closure may bypass close()/finally entirely.
|
|
69
|
+
if os.name == "nt":
|
|
70
|
+
self._job = PlayerJob()
|
|
71
|
+
self._job.attach(self.process)
|
|
72
|
+
self._transport.connect(self.process)
|
|
73
|
+
self.pipe = self._transport.pipe
|
|
74
|
+
self.thread = threading.Thread(target=self._listen, daemon=True, name="mpv-ipc")
|
|
75
|
+
self.thread.start()
|
|
76
|
+
self.command("get_property", "mpv-version")
|
|
77
|
+
self.command("request_log_messages", "warn")
|
|
78
|
+
except BaseException:
|
|
79
|
+
self.close()
|
|
80
|
+
raise
|
|
81
|
+
|
|
82
|
+
def _receive(self, message):
|
|
83
|
+
if not isinstance(message, dict):
|
|
84
|
+
raise ValueError("Invalid IPC object")
|
|
85
|
+
if message.get("event") == "log-message":
|
|
86
|
+
mpv_message(message)
|
|
87
|
+
return
|
|
88
|
+
request_id = message.get("request_id")
|
|
89
|
+
if request_id is not None:
|
|
90
|
+
with self._lock:
|
|
91
|
+
pending = self._pending.get(request_id)
|
|
92
|
+
if pending:
|
|
93
|
+
pending[1].update(message)
|
|
94
|
+
pending[0].set()
|
|
95
|
+
if message.get("event") in {"start-file", "file-loaded", "end-file", "shutdown"}:
|
|
96
|
+
self.events.put_nowait(message)
|
|
97
|
+
if self._wakeup is not None:
|
|
98
|
+
self._wakeup()
|
|
99
|
+
|
|
100
|
+
def set_wakeup(self, wakeup):
|
|
101
|
+
self._wakeup = wakeup
|
|
102
|
+
wakeup() # Includes events already delivered before attachment.
|
|
103
|
+
|
|
104
|
+
def _listen(self):
|
|
105
|
+
buffer = b""
|
|
106
|
+
try:
|
|
107
|
+
while not self._closing.is_set() and self.process.poll() is None:
|
|
108
|
+
chunk = self._transport.read(65536)
|
|
109
|
+
if chunk is None:
|
|
110
|
+
continue
|
|
111
|
+
if not chunk:
|
|
112
|
+
break
|
|
113
|
+
buffer += chunk
|
|
114
|
+
if len(buffer) > MAX_FRAME:
|
|
115
|
+
raise ValueError("IPC frame too large")
|
|
116
|
+
while b"\n" in buffer:
|
|
117
|
+
line, buffer = buffer.split(b"\n", 1)
|
|
118
|
+
self._receive(json.loads(line))
|
|
119
|
+
except (OSError, ValueError, TypeError, queue.Full) as error:
|
|
120
|
+
if not self._closing.is_set():
|
|
121
|
+
failure("ipc.failed", error, stage="read")
|
|
122
|
+
finally:
|
|
123
|
+
if not self._closing.is_set():
|
|
124
|
+
self.failed.set()
|
|
125
|
+
if self._wakeup is not None:
|
|
126
|
+
self._wakeup()
|
|
127
|
+
with self._lock:
|
|
128
|
+
for ready, _response in self._pending.values():
|
|
129
|
+
ready.set()
|
|
130
|
+
|
|
131
|
+
def command(self, *args, timeout=COMMAND_TIMEOUT, allow_unavailable=False):
|
|
132
|
+
with self._command_lock:
|
|
133
|
+
return self._command(*args, timeout=timeout, allow_unavailable=allow_unavailable)
|
|
134
|
+
|
|
135
|
+
def _command(self, *args, timeout, allow_unavailable=False):
|
|
136
|
+
if self.failed.is_set() or self._closing.is_set():
|
|
137
|
+
raise AppError(_("Lost communication with the player."))
|
|
138
|
+
ready, response = threading.Event(), {}
|
|
139
|
+
with self._lock:
|
|
140
|
+
self._sequence += 1
|
|
141
|
+
request_id = self._sequence
|
|
142
|
+
self._pending[request_id] = (ready, response)
|
|
143
|
+
deadline = time.monotonic() + timeout
|
|
144
|
+
try:
|
|
145
|
+
message = (json.dumps({"command": list(args), "request_id": request_id}) + "\n").encode()
|
|
146
|
+
if len(message) > 65536:
|
|
147
|
+
raise AppError(_("Playback command too large."))
|
|
148
|
+
offset = 0
|
|
149
|
+
while offset < len(message):
|
|
150
|
+
if time.monotonic() >= deadline:
|
|
151
|
+
raise AppError(_("mpv did not answer the command in time."))
|
|
152
|
+
count = self._transport.write(message[offset:], timeout=max(0, deadline - time.monotonic()))
|
|
153
|
+
if count:
|
|
154
|
+
offset += count
|
|
155
|
+
else:
|
|
156
|
+
time.sleep(0.01)
|
|
157
|
+
if not ready.wait(max(0, deadline - time.monotonic())):
|
|
158
|
+
emit("ipc.timeout", request_id=request_id)
|
|
159
|
+
raise AppError(_("mpv did not answer the command in time."))
|
|
160
|
+
if (allow_unavailable and args and args[0] == "get_property"
|
|
161
|
+
and response.get("error") == "property unavailable"):
|
|
162
|
+
return None
|
|
163
|
+
if response.get("error") != "success":
|
|
164
|
+
emit("ipc.rejected", request_id=request_id)
|
|
165
|
+
raise AppError(_("mpv rejected a command or disconnected."))
|
|
166
|
+
return response.get("data")
|
|
167
|
+
except OSError:
|
|
168
|
+
self.failed.set()
|
|
169
|
+
raise AppError(_("Lost communication with the player.")) from None
|
|
170
|
+
finally:
|
|
171
|
+
with self._lock:
|
|
172
|
+
self._pending.pop(request_id, None)
|
|
173
|
+
|
|
174
|
+
def play(self, target):
|
|
175
|
+
self.command("stop")
|
|
176
|
+
# Barrier: all messages already read before the synchronous command response.
|
|
177
|
+
while True:
|
|
178
|
+
try:
|
|
179
|
+
self.events.get_nowait()
|
|
180
|
+
except queue.Empty:
|
|
181
|
+
break
|
|
182
|
+
self.command("set_property", "pause", False)
|
|
183
|
+
if str(target).endswith(".mpd"):
|
|
184
|
+
# A DASH manifest is made of segment URLs. Only manifests written by stream_target reach here,
|
|
185
|
+
# after validate_dash checked every reference; the per-file option reverts when the file ends.
|
|
186
|
+
self.command("loadfile", str(target), "replace", -1, "access-references=yes")
|
|
187
|
+
else:
|
|
188
|
+
self.command("loadfile", str(target), "replace")
|
|
189
|
+
|
|
190
|
+
def stage(self, target):
|
|
191
|
+
"""Append one validated target so mpv can open it before the current EOF."""
|
|
192
|
+
self.clear_next()
|
|
193
|
+
if str(target).endswith(".mpd"):
|
|
194
|
+
self.command("loadfile", str(target), "append", -1, "access-references=yes")
|
|
195
|
+
else:
|
|
196
|
+
self.command("loadfile", str(target), "append")
|
|
197
|
+
|
|
198
|
+
def clear_next(self):
|
|
199
|
+
self.command("playlist-clear")
|
|
200
|
+
|
|
201
|
+
def close(self):
|
|
202
|
+
self._closing.set()
|
|
203
|
+
try:
|
|
204
|
+
if self.process is not None and self.process.poll() is None:
|
|
205
|
+
self.process.terminate()
|
|
206
|
+
try:
|
|
207
|
+
self.process.wait(timeout=5)
|
|
208
|
+
except subprocess.TimeoutExpired:
|
|
209
|
+
self.process.kill()
|
|
210
|
+
self.process.wait(timeout=5)
|
|
211
|
+
finally:
|
|
212
|
+
if self._job:
|
|
213
|
+
self._job.close()
|
|
214
|
+
if self.thread:
|
|
215
|
+
self.thread.join(timeout=2)
|
|
216
|
+
self._transport.close()
|
|
217
|
+
|
|
218
|
+
def __enter__(self):
|
|
219
|
+
return self
|
|
220
|
+
|
|
221
|
+
def __exit__(self, *exc_info):
|
|
222
|
+
self.close()
|
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
"""Capture only mpv's stream with a PulseAudio monitor (PulseAudio or PipeWire's pulse server).
|
|
2
|
+
|
|
3
|
+
Read-only tap for the visualizer: `parec --monitor-stream` reads a copy of mpv's sink input and
|
|
4
|
+
never touches its output path. Samples stay in a small in-memory ring and are never written anywhere.
|
|
5
|
+
"""
|
|
6
|
+
import json
|
|
7
|
+
import os
|
|
8
|
+
import shutil
|
|
9
|
+
import subprocess
|
|
10
|
+
import threading
|
|
11
|
+
|
|
12
|
+
from ..diagnostics import emit, failure
|
|
13
|
+
|
|
14
|
+
RATE = 48000
|
|
15
|
+
CHANNELS = 2
|
|
16
|
+
FRAME_BYTES = 4 * CHANNELS # float32 stereo
|
|
17
|
+
RING_FRAMES = 4096
|
|
18
|
+
SEARCH_SECONDS = 0.5 # mpv opens its stream on the first file and may reopen it on format changes
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def sink_input_for(listing, pid):
|
|
22
|
+
"""Index of the sink input owned by `pid` in `pactl -f json list sink-inputs` output, or None."""
|
|
23
|
+
for entry in json.loads(listing or "[]"):
|
|
24
|
+
if str(entry.get("properties", {}).get("application.process.id")) == str(pid):
|
|
25
|
+
return entry.get("index")
|
|
26
|
+
return None
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
class PulseTap:
|
|
30
|
+
"""Keeps the latest RING_FRAMES of mpv's output as interleaved float32 stereo."""
|
|
31
|
+
|
|
32
|
+
def __init__(self, pid):
|
|
33
|
+
self.pid = int(pid)
|
|
34
|
+
self.rate = RATE
|
|
35
|
+
self._ring = bytearray()
|
|
36
|
+
self._lock = threading.Lock()
|
|
37
|
+
self._stop = threading.Event()
|
|
38
|
+
self._process = None
|
|
39
|
+
self.failed = threading.Event()
|
|
40
|
+
self._thread = threading.Thread(target=self._run, name="noneto-tap", daemon=True)
|
|
41
|
+
|
|
42
|
+
def start(self):
|
|
43
|
+
self._thread.start()
|
|
44
|
+
return self
|
|
45
|
+
|
|
46
|
+
def stop(self):
|
|
47
|
+
self._stop.set()
|
|
48
|
+
with self._lock:
|
|
49
|
+
process = self._process
|
|
50
|
+
if process is not None and process.poll() is None:
|
|
51
|
+
process.terminate()
|
|
52
|
+
if self._thread.is_alive() and self._thread is not threading.current_thread():
|
|
53
|
+
self._thread.join(timeout=2)
|
|
54
|
+
|
|
55
|
+
def samples(self):
|
|
56
|
+
with self._lock:
|
|
57
|
+
return bytes(self._ring)
|
|
58
|
+
|
|
59
|
+
def _push(self, chunk):
|
|
60
|
+
with self._lock:
|
|
61
|
+
self._ring += chunk
|
|
62
|
+
excess = len(self._ring) - RING_FRAMES * FRAME_BYTES
|
|
63
|
+
if excess > 0:
|
|
64
|
+
del self._ring[:excess]
|
|
65
|
+
|
|
66
|
+
def _run(self):
|
|
67
|
+
try:
|
|
68
|
+
pactl, parec = shutil.which("pactl"), shutil.which("parec")
|
|
69
|
+
if not pactl or not parec:
|
|
70
|
+
raise OSError("pactl/parec not found")
|
|
71
|
+
started = False
|
|
72
|
+
while not self._stop.is_set():
|
|
73
|
+
index = self._find(pactl)
|
|
74
|
+
if index is None:
|
|
75
|
+
self._stop.wait(SEARCH_SECONDS)
|
|
76
|
+
continue
|
|
77
|
+
if not started:
|
|
78
|
+
emit("visualizer.tap_started")
|
|
79
|
+
started = True
|
|
80
|
+
self._capture(parec, index)
|
|
81
|
+
except (OSError, ValueError, subprocess.SubprocessError) as error:
|
|
82
|
+
self.failed.set()
|
|
83
|
+
failure("visualizer.tap_failed", error)
|
|
84
|
+
|
|
85
|
+
def _find(self, pactl):
|
|
86
|
+
result = subprocess.run([pactl, "-f", "json", "list", "sink-inputs"], capture_output=True,
|
|
87
|
+
text=True, timeout=5)
|
|
88
|
+
if result.returncode != 0:
|
|
89
|
+
raise OSError(f"pactl exited with {result.returncode}")
|
|
90
|
+
return sink_input_for(result.stdout, self.pid)
|
|
91
|
+
|
|
92
|
+
def _capture(self, parec, index):
|
|
93
|
+
"""Read until the stream ends (mpv closed or reopened it) or the tap stops."""
|
|
94
|
+
process = subprocess.Popen(
|
|
95
|
+
[parec, f"--monitor-stream={index}", "--raw", "--format=float32le",
|
|
96
|
+
f"--rate={RATE}", f"--channels={CHANNELS}", "--latency-msec=20"],
|
|
97
|
+
stdin=subprocess.DEVNULL, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL)
|
|
98
|
+
with self._lock:
|
|
99
|
+
self._process = process
|
|
100
|
+
carry = b""
|
|
101
|
+
try:
|
|
102
|
+
if self._stop.is_set():
|
|
103
|
+
return
|
|
104
|
+
while True:
|
|
105
|
+
chunk = os.read(process.stdout.fileno(), 4096)
|
|
106
|
+
if not chunk:
|
|
107
|
+
break
|
|
108
|
+
carry += chunk
|
|
109
|
+
whole = len(carry) - len(carry) % FRAME_BYTES # never split a frame across the ring
|
|
110
|
+
self._push(carry[:whole])
|
|
111
|
+
carry = carry[whole:]
|
|
112
|
+
finally:
|
|
113
|
+
if process.poll() is None:
|
|
114
|
+
process.terminate()
|
|
115
|
+
process.wait(timeout=2)
|
|
116
|
+
process.stdout.close()
|
|
117
|
+
with self._lock:
|
|
118
|
+
self._process = None
|
|
119
|
+
if not self._stop.is_set():
|
|
120
|
+
self._stop.wait(SEARCH_SECONDS)
|