""" 音频播放层:负责设备、音量、异步播放状态、续播/进度、下载。 MCP 工具调用会立即返回 buffering/playback_id;前端可用 wait_playback 等 playing 再走进度条。 """ from __future__ import annotations import logging import os import re import subprocess import threading import time from pathlib import Path from typing import Callable, Optional log = logging.getLogger("ai-speaker.audio") PIPEWIRE_RUNTIME_DIR = "/run/user/0" DBUS_ADDR_FILE = Path("/run/pipewire-dbus-address") VOLUME_HARD_CAP = 100 DEFAULT_VOLUME = 30 NIGHT_CAP = 60 STATE_BUFFERING = "buffering" STATE_STARTING = "starting" STATE_PLAYING = "playing" STATE_STOPPED = "stopped" STATE_COMPLETED = "completed" STATE_FAILED = "failed" TERMINAL_STATES = {STATE_STOPPED, STATE_COMPLETED, STATE_FAILED} def _env() -> dict[str, str]: env = dict(os.environ) env["PATH"] = env.get("PATH", "") + ":/usr/local/bin:/usr/sbin:/sbin:/bin" env["PIPEWIRE_RUNTIME_DIR"] = PIPEWIRE_RUNTIME_DIR addr = DBUS_ADDR_FILE.read_text().strip() if DBUS_ADDR_FILE.exists() else "" if addr: env["DBUS_SESSION_BUS_ADDRESS"] = addr return env def _run(cmd: list[str], timeout: float = 8, stdin=None, stdout=None, stderr=None): return subprocess.run(cmd, env=_env(), timeout=timeout, stdin=stdin, stdout=stdout, stderr=stderr) # ---------- 音量 ---------- def _effective_cap() -> int: h = time.localtime().tm_hour + time.localtime().tm_min / 60.0 return NIGHT_CAP if (h >= 22.0 or h < 8.5) else VOLUME_HARD_CAP def clamp_volume(v: Optional[int]) -> int: cap = _effective_cap() if v is None: return min(DEFAULT_VOLUME, cap) try: v = int(v) except (TypeError, ValueError): return min(DEFAULT_VOLUME, cap) return max(0, min(cap, v)) _sink_cache: dict[str, tuple[str, float]] = {} def find_sink(keyword: str = "JBL", retries: int = 8) -> Optional[str]: now = time.time() cached = _sink_cache.get(keyword) if cached and now - cached[1] < 60 and _read_volume(cached[0]) is not None: return cached[0] for _ in range(retries): r = _run(["wpctl", "status"], timeout=6, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL) text = re.sub(r"\x1b\[[0-9;]*m", "", r.stdout.decode(errors="ignore") if r.stdout else "") in_sink = False for line in text.splitlines(): if "Sinks:" in line: in_sink = True continue if in_sink and re.match(r"^[ │]*[├└]─", line): in_sink = False if in_sink and keyword.lower() in line.lower(): m = re.search(r"(\d+)\.", line) if m: _sink_cache[keyword] = (m.group(1), now) return m.group(1) time.sleep(0.3) return None def _read_volume(node: str) -> Optional[float]: r = _run(["wpctl", "get-volume", node], timeout=5, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL) m = re.search(r"([0-9.]+)", r.stdout.decode() if r.stdout else "") return float(m.group(1)) if m else None def device_info(node: str) -> dict: info = {"node": node, "name": None, "description": None, "address": None, "codec": None, "profile": None, "transport": None, "volume": None} try: r = _run(["pw-dump", node], timeout=6, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL) text = r.stdout.decode(errors="ignore") if r.stdout else "" for key, field in [("node.name", "name"), ("node.description", "description"), ("api.bluez5.address", "address"), ("api.bluez5.codec", "codec"), ("api.bluez5.profile", "profile"), ("api.bluez5.transport", "transport")]: m = re.search(rf'"{re.escape(key)}":\s*"([^"\n]+)"', text) if m: info[field] = m.group(1).strip() info["volume"] = _read_volume(node) except Exception: pass return info def set_volume(node: str, vol_pct: int) -> float: target = vol_pct / 100.0 cur = _read_volume(node) if cur is not None and abs(cur - target) < 0.02: return cur time.sleep(0.4) for i in range(3): _run(["wpctl", "set-mute", node, "0"], timeout=5) _run(["wpctl", "set-volume", node, f"{target:.4f}"], timeout=5) time.sleep(0.5 if i == 0 else 0.9) cur = _read_volume(node) if cur is not None and abs(cur - target) < 0.02: break return cur if cur is not None else target # ---------- 蓝牙 ---------- def ensure_bluetooth(mac: str = "43:5A:DC:68:1B:F8") -> bool: r = _run(["bluetoothctl", "info", mac], timeout=6, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL) if r.stdout and b"Connected: yes" in r.stdout: return True log.info("蓝牙未连接,尝试连接 %s", mac) _run(["bluetoothctl", "connect", mac], timeout=30, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) time.sleep(3) r = _run(["bluetoothctl", "info", mac], timeout=6, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL) return bool(r.stdout and b"Connected: yes" in r.stdout) # ---------- 异步播放状态 ---------- _play_lock = threading.Lock() _state_lock = threading.Lock() _current_lock = threading.Lock() _current: Optional[subprocess.Popen] = None _playback_counter = 0 _playback: dict = { "id": None, "state": None, "source": None, "title": None, "duration": None, "node": None, "volume": None, "start_at": 0.0, "started_at": None, "stopped_at": None, "ended_at": None, "error": None, "resumed_from_sec": None, "seek_to_sec": None, } def _new_playback(**kwargs) -> int: global _playback_counter, _playback with _state_lock: _playback_counter += 1 _playback = { "id": _playback_counter, "state": STATE_BUFFERING, "source": None, "title": None, "duration": None, "node": None, "volume": None, "start_at": 0.0, "started_at": None, "stopped_at": None, "ended_at": None, "error": None, "resumed_from_sec": None, "seek_to_sec": None, } _playback.update(kwargs) return _playback["id"] def _set_state(pid: int, state: str, **kwargs) -> None: with _state_lock: if _playback.get("id") != pid: return _playback["state"] = state _playback.update(kwargs) if state in TERMINAL_STATES: _playback["ended_at"] = time.time() def _probe_duration(src: str) -> Optional[float]: try: r = _run(["ffprobe", "-v", "error", "-show_entries", "format=duration", "-of", "csv=p=0", src], timeout=8, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL) return float(r.stdout.decode().strip().splitlines()[0]) if r.stdout else None except Exception: return None def _elapsed() -> float: with _state_lock: st = dict(_playback) if st.get("state") == STATE_PLAYING and st.get("started_at"): return st["start_at"] + max(0.0, time.time() - st["started_at"]) return st.get("stopped_at") or 0.0 def player_state() -> dict: with _state_lock: st = dict(_playback) state = st.get("state") or STATE_STOPPED playing = state == STATE_PLAYING dur = st.get("duration") elapsed = _elapsed() st.update({ "state": state, "playing": playing, "elapsed_sec": round(elapsed, 1) if playing else None, "progress_pct": round(min(100.0, elapsed / dur * 100), 1) if playing and dur else None, "remaining_sec": round(max(0.0, dur - elapsed), 1) if playing and dur else None, "resumable": bool(st.get("source") and st.get("stopped_at") and state != STATE_PLAYING and st["stopped_at"] > 1), "server_time": time.time(), }) return st def playback_status(playback_id: Optional[int] = None) -> dict: st = player_state() if playback_id is not None and st.get("id") != playback_id: return {"ok": False, "error": "playback_id 不匹配", "current": st} return {"ok": True, **st} def wait_playback(playback_id: Optional[int], timeout: float = 15.0) -> dict: deadline = time.time() + timeout while True: st = player_state() if playback_id is not None and st.get("id") != playback_id: return {"ok": False, "error": "playback_id 不匹配", "current": st} if st.get("state") in {STATE_PLAYING, *TERMINAL_STATES}: return {"ok": st.get("state") in {STATE_PLAYING, STATE_COMPLETED}, **st} if time.time() >= deadline: return {"ok": False, "error": "等待播放启动超时", **st} time.sleep(0.15) def resume_position() -> Optional[float]: st = player_state() return st["stopped_at"] if st["resumable"] else None def stop() -> bool: global _current with _state_lock: pid = _playback.get("id") state = _playback.get("state") if state == STATE_PLAYING: pos = _elapsed() with _state_lock: if _playback.get("id") == pid: _playback["stopped_at"] = round(pos, 1) with _current_lock: p = _current if p and p.poll() is None: try: p.terminate() p.wait(timeout=3) except Exception: p.kill() if pid: _set_state(pid, STATE_STOPPED) return True if pid and state in {STATE_BUFFERING, STATE_STARTING}: _set_state(pid, STATE_STOPPED) return True return False def _wait_node_running(node: str, proc: subprocess.Popen, timeout: float = 12.0) -> bool: deadline = time.time() + timeout while time.time() < deadline: if proc.poll() is not None: return False try: r = _run(["pw-dump", node], timeout=3, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL) text = r.stdout.decode(errors="ignore") if r.stdout else "" m = re.search(r'"state":\s*"(\w+)"', text) if m and m.group(1) in {"running", "idle"}: return True except Exception: pass time.sleep(0.3) return proc.poll() is None # 读不到状态时,只要进程活着就认为可播放 def _run_playback(pid: int, src: str, node: str, vol_pct: int, start_at: float, title: Optional[str] = None, duration: Optional[float] = None, resumed_from_sec: Optional[float] = None, seek_to_sec: Optional[float] = None) -> None: global _current try: _set_state(pid, STATE_STARTING, source=src, node=node, title=title, duration=duration if duration is not None else _probe_duration(src), start_at=start_at, resumed_from_sec=resumed_from_sec, seek_to_sec=seek_to_sec) final_vol = set_volume(node, vol_pct) with _state_lock: if _playback.get("id") == pid and _playback.get("duration") is None: _playback["duration"] = _probe_duration(src) _set_state(pid, STATE_STARTING, volume=final_vol) ss = ["-ss", f"{max(0.0, start_at):.2f}"] if start_at > 0 else [] dec = subprocess.Popen( ["ffmpeg", "-v", "error", *ss, "-i", src, "-f", "wav", "-ac", "2", "-ar", "44100", "-"], env=_env(), stdout=subprocess.PIPE, stderr=subprocess.PIPE, ) pw = subprocess.Popen( ["pw-cat", "--playback", "-", "--target", node], env=_env(), stdin=dec.stdout, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, ) dec.stdout.close() with _current_lock: _current = pw ready = _wait_node_running(node, pw) if ready: _set_state(pid, STATE_PLAYING, started_at=time.time(), volume=final_vol) rc = pw.wait() if dec.poll() is None: dec.kill() err = dec.stderr.read().decode(errors="ignore").strip().splitlines()[-1:] or [""] dec.stderr.close() with _current_lock: _current = None if rc == 0: _set_state(pid, STATE_COMPLETED, stopped_at=None) else: _set_state(pid, STATE_FAILED, error=err[0][:200] if err[0] else f"播放进程退出码 {rc}") except Exception as e: with _current_lock: _current = None _set_state(pid, STATE_FAILED, error=f"{type(e).__name__}: {str(e)[:180]}") finally: if _play_lock.locked(): try: _play_lock.release() except RuntimeError: pass def submit_playback(preparer: Callable[[], tuple[str, str, Optional[float]]], vol_pct: Optional[int] = None, start_at: float = 0.0, title: Optional[str] = None, resumed_from_sec: Optional[float] = None, seek_to_sec: Optional[float] = None) -> dict: """立即返回 buffering;后台 preparer 返回 (src, node, duration) 后开始播放。""" vol = clamp_volume(vol_pct) if not _play_lock.acquire(blocking=False): stop() time.sleep(0.3) if not _play_lock.acquire(timeout=5): return {"ok": False, "error": "另一个播放正在进行"} pid = _new_playback(state=STATE_BUFFERING, title=title, volume=vol / 100.0, start_at=start_at, resumed_from_sec=resumed_from_sec, seek_to_sec=seek_to_sec) t = threading.Thread(target=_prepare_and_play, args=(pid, preparer, vol, start_at), daemon=True) t.start() return {"ok": True, "playback_id": pid, "state": STATE_BUFFERING, "message": "正在缓冲/准备播放", "estimated_wait_ms": 3000, "volume": vol, "node": None} def _prepare_and_play(pid: int, preparer: Callable[[], tuple[str, str, Optional[float]]], vol: int, start_at: float) -> None: try: src, node, duration = preparer() _run_playback(pid, src, node, vol, start_at, duration=duration) except Exception as e: _set_state(pid, STATE_FAILED, error=f"{type(e).__name__}: {str(e)[:180]}") if _play_lock.locked(): try: _play_lock.release() except RuntimeError: pass def play(src: str, node: str, vol_pct: Optional[int] = None, timeout: float = 600.0, start_at: float = 0.0) -> dict: def preparer(): return src, node, _probe_duration(src) return submit_playback(preparer, vol_pct=vol_pct, start_at=start_at, title=os.path.basename(src) if not src.startswith("http") else src) # ---------- 下载 ---------- def download(url: str, save_dir: str = "/vol1/1000/Music", timeout: float = 600.0) -> dict: Path(save_dir).mkdir(parents=True, exist_ok=True) ext = Path(url.split("?")[0]).suffix.lower() if ext not in {".mp3", ".m4a", ".flac", ".wav", ".ogg", ".opus", ".aac", ".m4b", ".wma", ".ape"}: ext = ".mp3" name = Path(url.split("?")[0]).stem[:60] or "audio" name = re.sub(r"[\\/:*?\"<>|]", "_", name) dst = Path(save_dir) / f"{name}{ext}" if dst.exists(): dst = dst.with_name(f"{name}-{int(time.time())}{ext}") r = _run(["ffmpeg", "-v", "error", "-y", "-i", url, "-c", "copy", str(dst)], timeout=timeout, stdout=subprocess.DEVNULL, stderr=subprocess.PIPE) if r.returncode != 0: dst.unlink(missing_ok=True) err = (r.stderr or b"").decode(errors="ignore").strip().splitlines()[-1:] or ["unknown"] return {"ok": False, "error": err[0][:200]} return {"ok": True, "path": str(dst), "bytes": dst.stat().st_size}