570 lines
22 KiB
Python
570 lines
22 KiB
Python
#!/usr/bin/env python3
|
|
"""
|
|
PylonisAmp — source.py
|
|
Silnik audio: playbin (GStreamer) + zarządzanie źródłami.
|
|
"""
|
|
|
|
import gi
|
|
gi.require_version('Gst', '1.0')
|
|
gi.require_version('GLib', '2.0')
|
|
from gi.repository import Gst, GLib
|
|
|
|
import os, re, json, time, logging, threading, subprocess
|
|
from typing import Optional, List
|
|
|
|
Gst.init(None)
|
|
log = logging.getLogger('source')
|
|
|
|
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
|
|
CONFIG_PATH = os.path.join(BASE_DIR, 'config.json')
|
|
STATIONS_PATH = os.path.join(BASE_DIR, 'radio', 'stations.json')
|
|
|
|
# ── Spectrum: 4 pasma ręczne + 28 logarytmicznych ─────────────────────────────
|
|
MANUAL_BANDS = [(0, 80), (80, 160), (160, 320), (320, 640)]
|
|
|
|
def _log_edges(n=28, f_lo=640.0, f_hi=20000.0):
|
|
return [f_lo * (f_hi / f_lo) ** (i / n) for i in range(n + 1)]
|
|
|
|
_LOG_EDGES = _log_edges()
|
|
_RE_MAG = re.compile(r'magnitude=\(float\)\{([^}]+)\}')
|
|
|
|
def map_spectrum(raw: List[float], sample_rate: int = 44100) -> List[float]:
|
|
n_in = len(raw)
|
|
if not n_in: return [-60.0] * 32
|
|
hz = (sample_rate / 2.0) / n_in
|
|
result = []
|
|
for f_lo, f_hi in MANUAL_BANDS:
|
|
lo = max(0, int(f_lo / hz))
|
|
hi = min(n_in - 1, int(f_hi / hz))
|
|
result.append(max(-60.0, min(0.0, float(max(raw[lo:hi+1]) if lo <= hi else raw[lo]))))
|
|
for i in range(28):
|
|
lo = max(0, int(_LOG_EDGES[i] / hz))
|
|
hi = min(n_in - 1, int(_LOG_EDGES[i+1] / hz))
|
|
result.append(max(-60.0, min(0.0, float(max(raw[lo:hi+1]) if lo <= hi else raw[lo]))))
|
|
return result
|
|
|
|
|
|
# ══════════════════════════════════════════════════════════════════════════════
|
|
# RadioSource — playbin przez Python API
|
|
# ══════════════════════════════════════════════════════════════════════════════
|
|
|
|
class RadioSource:
|
|
SOURCE_ID = 'radio'
|
|
SOURCE_NAME = 'Internet Radio'
|
|
|
|
def __init__(self, alsa_device='hw:1,0', on_state=None, on_meta=None):
|
|
self._alsa = alsa_device
|
|
self._on_state = on_state
|
|
self._on_meta = on_meta
|
|
self._playbin: Optional[Gst.Element] = None
|
|
self._url = ''
|
|
self._station = ''
|
|
self._title = ''
|
|
self._artist = ''
|
|
self._state = 'stopped'
|
|
self._vol = 0.5
|
|
self._reconnect = ''
|
|
self._lock = threading.Lock()
|
|
|
|
# Pomiary
|
|
self._rms_l = self._rms_r = self._peak_l = self._peak_r = -60.0
|
|
self._bands: List[float] = [-60.0] * 32
|
|
|
|
# Jeden GLib loop dla bus messages
|
|
self._glib = GLib.MainLoop()
|
|
threading.Thread(target=self._glib.run, daemon=True,
|
|
name='radio-glib').start()
|
|
|
|
def play(self, url: str, station: str = ''):
|
|
log.info(f"Radio play: {station!r} → {url}")
|
|
self._url = url
|
|
self._station = station
|
|
self._title = ''
|
|
self._artist = ''
|
|
self._reconnect = url
|
|
self._stop_playbin()
|
|
self._start_playbin(url)
|
|
|
|
def stop(self):
|
|
self._reconnect = ''
|
|
self._stop_playbin()
|
|
self._set_state('stopped')
|
|
|
|
def set_volume(self, vol: int):
|
|
"""Zmiana głośności bez restartu — natychmiastowa."""
|
|
self._vol = max(0, min(100, int(vol))) / 100.0
|
|
if self._playbin:
|
|
self._playbin.set_property('volume', self._vol)
|
|
log.debug(f"Volume: {self._vol:.2f}")
|
|
|
|
def get_status(self) -> dict:
|
|
return {
|
|
'source': self.SOURCE_ID,
|
|
'state': self._state,
|
|
'url': self._url,
|
|
'station': self._station,
|
|
'title': self._title,
|
|
'artist': self._artist,
|
|
}
|
|
|
|
def get_meters(self) -> dict:
|
|
return {
|
|
'rms_l': round(self._rms_l, 1),
|
|
'rms_r': round(self._rms_r, 1),
|
|
'peak_l': round(self._peak_l, 1),
|
|
'peak_r': round(self._peak_r, 1),
|
|
'bands': [round(b, 1) for b in self._bands],
|
|
}
|
|
|
|
# ── Pipeline ──────────────────────────────────────────────────────────────
|
|
|
|
def _start_playbin(self, url: str):
|
|
try:
|
|
playbin = Gst.ElementFactory.make('playbin', 'player')
|
|
if not playbin:
|
|
raise RuntimeError("playbin not available")
|
|
|
|
# Audio sink z level + spectrum dla pomiarów
|
|
audio_sink_str = (
|
|
f'level name=lvl interval=33000000 post-messages=true ! '
|
|
f'spectrum name=spec bands=1024 interval=33000000 '
|
|
f'threshold=-70 post-messages=true '
|
|
f'message-magnitude=true message-phase=false ! '
|
|
f'alsasink device={self._alsa} sync=false'
|
|
)
|
|
audio_sink = Gst.parse_bin_from_description(audio_sink_str, True)
|
|
|
|
playbin.set_property('uri', url)
|
|
playbin.set_property('volume', self._vol)
|
|
playbin.set_property('audio-sink', audio_sink)
|
|
|
|
bus = playbin.get_bus()
|
|
bus.add_signal_watch()
|
|
bus.connect('message', self._on_msg, playbin)
|
|
|
|
with self._lock:
|
|
self._playbin = playbin
|
|
|
|
ret = playbin.set_state(Gst.State.PLAYING)
|
|
if ret == Gst.StateChangeReturn.FAILURE:
|
|
log.error("playbin FAILURE")
|
|
self._set_state('error')
|
|
self._schedule_reconnect()
|
|
else:
|
|
self._set_state('buffering')
|
|
log.info(f"playbin started: {url[:60]}")
|
|
|
|
except Exception as e:
|
|
log.error(f"playbin error: {e}", exc_info=True)
|
|
self._set_state('error')
|
|
self._schedule_reconnect()
|
|
|
|
def _stop_playbin(self):
|
|
with self._lock:
|
|
if self._playbin:
|
|
p, self._playbin = self._playbin, None
|
|
p.set_state(Gst.State.NULL)
|
|
p.get_state(Gst.SECOND // 2)
|
|
|
|
# ── Bus messages ──────────────────────────────────────────────────────────
|
|
|
|
def _on_msg(self, bus, msg, playbin):
|
|
if playbin is not self._playbin:
|
|
return
|
|
|
|
t = msg.type
|
|
|
|
if t == Gst.MessageType.ERROR:
|
|
err, _ = msg.parse_error()
|
|
log.warning(f"GST error: {err.message}")
|
|
self._set_state('buffering')
|
|
self._schedule_reconnect()
|
|
|
|
elif t == Gst.MessageType.EOS:
|
|
log.info("EOS — reconnecting")
|
|
self._schedule_reconnect(delay_ms=500)
|
|
|
|
elif t == Gst.MessageType.STATE_CHANGED:
|
|
if msg.src == playbin:
|
|
_, new, _ = msg.parse_state_changed()
|
|
if new == Gst.State.PLAYING and self._state != 'playing':
|
|
self._set_state('playing')
|
|
|
|
elif t == Gst.MessageType.BUFFERING:
|
|
pct = msg.parse_buffering()
|
|
if pct < 100:
|
|
playbin.set_state(Gst.State.PAUSED)
|
|
self._set_state('buffering')
|
|
else:
|
|
playbin.set_state(Gst.State.PLAYING)
|
|
self._set_state('playing')
|
|
|
|
elif t == Gst.MessageType.TAG:
|
|
self._on_tags(msg.parse_tag())
|
|
|
|
elif t == Gst.MessageType.ELEMENT:
|
|
s = msg.get_structure()
|
|
if s:
|
|
n = s.get_name()
|
|
if n == 'level': self._on_level(s)
|
|
elif n == 'spectrum': self._on_spectrum(s)
|
|
|
|
def _on_tags(self, tags):
|
|
changed = False
|
|
for gst_tag, attr in [('artist', '_artist'), ('title', '_title')]:
|
|
ok, val = tags.get_string(gst_tag)
|
|
if ok and val and val.strip() != getattr(self, attr):
|
|
setattr(self, attr, val.strip())
|
|
changed = True
|
|
if changed and self._on_meta:
|
|
self._on_meta(self.SOURCE_ID, {
|
|
'station': self._station,
|
|
'artist': self._artist,
|
|
'title': self._title,
|
|
})
|
|
|
|
def _on_level(self, s):
|
|
try:
|
|
rms = s.get_value('rms')
|
|
peak = s.get_value('peak')
|
|
self._rms_l = float(rms[0])
|
|
self._rms_r = float(rms[1] if len(rms) > 1 else rms[0])
|
|
self._peak_l = float(peak[0])
|
|
self._peak_r = float(peak[1] if len(peak) > 1 else peak[0])
|
|
except Exception: pass
|
|
|
|
def _on_spectrum(self, s):
|
|
try:
|
|
m = _RE_MAG.search(s.to_string())
|
|
if m:
|
|
raw = [float(x.strip()) for x in m.group(1).split(',') if x.strip()]
|
|
if raw: self._bands = map_spectrum(raw)
|
|
except Exception: pass
|
|
|
|
# ── Reconnect ─────────────────────────────────────────────────────────────
|
|
|
|
def _schedule_reconnect(self, delay_ms: int = 2000):
|
|
if self._reconnect:
|
|
GLib.timeout_add(delay_ms, self._do_reconnect, self._reconnect)
|
|
|
|
def _do_reconnect(self, url: str) -> bool:
|
|
if self._reconnect != url:
|
|
return False
|
|
log.info(f"Reconnecting: {url[:50]}")
|
|
|
|
def _restart():
|
|
self._stop_playbin()
|
|
time.sleep(0.3)
|
|
if self._reconnect == url:
|
|
self._start_playbin(url)
|
|
|
|
threading.Thread(target=_restart, daemon=True,
|
|
name='radio-reconnect').start()
|
|
return False
|
|
|
|
def _set_state(self, s: str):
|
|
if s != self._state:
|
|
self._state = s
|
|
if self._on_state:
|
|
self._on_state(self.SOURCE_ID, s)
|
|
|
|
|
|
# ══════════════════════════════════════════════════════════════════════════════
|
|
# BluetoothSource
|
|
# ══════════════════════════════════════════════════════════════════════════════
|
|
|
|
class BluetoothSource:
|
|
SOURCE_ID = 'bluetooth'
|
|
SOURCE_NAME = 'Bluetooth'
|
|
|
|
def __init__(self, on_state=None, on_meta=None):
|
|
self._on_state = on_state
|
|
self._state = 'stopped'
|
|
self._connected = None
|
|
self._connected_dev = None
|
|
self._bus = None
|
|
self._init_dbus()
|
|
|
|
def _init_dbus(self):
|
|
try:
|
|
import dbus, dbus.mainloop.glib
|
|
ml = dbus.mainloop.glib.DBusGMainLoop(set_as_default=False)
|
|
self._bus = dbus.SystemBus(mainloop=ml)
|
|
loop = GLib.MainLoop()
|
|
threading.Thread(target=loop.run, daemon=True, name='bt-dbus').start()
|
|
except Exception as e:
|
|
log.warning(f"BlueZ: {e}")
|
|
|
|
def activate(self):
|
|
self._set_discoverable(True)
|
|
subprocess.run(['sudo', 'systemctl', 'start', 'bluealsa-aplay'],
|
|
capture_output=True)
|
|
self._set_state('idle')
|
|
|
|
def deactivate(self):
|
|
self._set_discoverable(False)
|
|
subprocess.run(['sudo', 'systemctl', 'stop', 'bluealsa-aplay'],
|
|
capture_output=True)
|
|
self._set_state('stopped')
|
|
|
|
def get_status(self) -> dict:
|
|
return {'source': self.SOURCE_ID, 'state': self._state,
|
|
'connected': self._connected}
|
|
|
|
def get_meters(self) -> dict:
|
|
return {'rms_l': -60.0, 'rms_r': -60.0,
|
|
'peak_l': -60.0, 'peak_r': -60.0, 'bands': [-60.0] * 32}
|
|
|
|
def get_paired_devices(self) -> list:
|
|
if not self._bus: return []
|
|
try:
|
|
import dbus
|
|
mgr = dbus.Interface(self._bus.get_object('org.bluez', '/'),
|
|
'org.freedesktop.DBus.ObjectManager')
|
|
return [{'mac': str(d.get('Address', '')),
|
|
'name': str(d.get('Name', '')),
|
|
'connected': bool(d.get('Connected', False)),
|
|
'trusted': bool(d.get('Trusted', False))}
|
|
for _, ifaces in mgr.GetManagedObjects().items()
|
|
for d in [ifaces.get('org.bluez.Device1')]
|
|
if d and bool(d.get('Paired', False))]
|
|
except Exception as e:
|
|
log.error(f"BT devices: {e}"); return []
|
|
|
|
def connect_device(self, mac: str) -> bool:
|
|
ok = self._dev_call(mac, 'Connect')
|
|
if ok: self._connected = mac; self._connected_dev = mac
|
|
return ok
|
|
|
|
def disconnect_device(self, mac: str):
|
|
self._dev_call(mac, 'Disconnect')
|
|
self._connected = self._connected_dev = None
|
|
|
|
def remove_device(self, mac: str):
|
|
if not self._bus: return
|
|
try:
|
|
import dbus
|
|
dbus.Interface(self._bus.get_object('org.bluez', '/org/bluez/hci0'),
|
|
'org.bluez.Adapter1').RemoveDevice(self._mac_path(mac))
|
|
except Exception as e: log.error(f"BT remove: {e}")
|
|
|
|
def _dev_call(self, mac, method):
|
|
if not self._bus: return False
|
|
try:
|
|
import dbus
|
|
getattr(dbus.Interface(
|
|
self._bus.get_object('org.bluez', self._mac_path(mac)),
|
|
'org.bluez.Device1'), method)()
|
|
return True
|
|
except Exception as e:
|
|
log.error(f"BT {method}: {e}"); return False
|
|
|
|
def _mac_path(self, mac):
|
|
return f"/org/bluez/hci0/dev_{mac.replace(':', '_')}"
|
|
|
|
def _set_discoverable(self, enable):
|
|
if not self._bus: return
|
|
try:
|
|
import dbus
|
|
props = dbus.Interface(
|
|
self._bus.get_object('org.bluez', '/org/bluez/hci0'),
|
|
'org.freedesktop.DBus.Properties')
|
|
props.Set('org.bluez.Adapter1', 'Discoverable', dbus.Boolean(enable))
|
|
if enable:
|
|
props.Set('org.bluez.Adapter1', 'DiscoverableTimeout', dbus.UInt32(0))
|
|
except Exception: pass
|
|
|
|
def _set_state(self, s):
|
|
if s != self._state:
|
|
self._state = s
|
|
if self._on_state: self._on_state(self.SOURCE_ID, s)
|
|
|
|
|
|
# ══════════════════════════════════════════════════════════════════════════════
|
|
# AnalogSource (szkielet)
|
|
# ══════════════════════════════════════════════════════════════════════════════
|
|
|
|
class AnalogSource:
|
|
def __init__(self, source_id, name, channel, on_state=None, on_meta=None):
|
|
self.SOURCE_ID = source_id
|
|
self.SOURCE_NAME = name
|
|
self.CHANNEL = channel
|
|
self._on_state = on_state
|
|
self._state = 'stopped'
|
|
|
|
def activate(self):
|
|
self._state = 'active'
|
|
if self._on_state: self._on_state(self.SOURCE_ID, 'active')
|
|
|
|
def deactivate(self): self._state = 'stopped'
|
|
|
|
def get_status(self): return {'source': self.SOURCE_ID, 'state': self._state}
|
|
def get_meters(self): return {'rms_l': -60.0, 'rms_r': -60.0,
|
|
'peak_l': -60.0, 'peak_r': -60.0,
|
|
'bands': [-60.0] * 32}
|
|
|
|
|
|
# ══════════════════════════════════════════════════════════════════════════════
|
|
# SourceEngine
|
|
# ══════════════════════════════════════════════════════════════════════════════
|
|
|
|
class SourceEngine:
|
|
_config_lock = threading.Lock()
|
|
|
|
def __init__(self, alsa_device='hw:1,0', on_state=None, on_meta=None):
|
|
self._on_state = on_state
|
|
self._on_meta = on_meta
|
|
self._active_src = None
|
|
self._cfg = self._load_config()
|
|
self.alsa_device = alsa_device
|
|
self._dirty = False
|
|
|
|
common = dict(on_state=self._fwd_state, on_meta=self._fwd_meta)
|
|
self._sources = {
|
|
'radio': RadioSource(alsa_device=alsa_device, **common),
|
|
'bluetooth': BluetoothSource(**common),
|
|
'line1': AnalogSource('line1', 'Line In 1', 1, **common),
|
|
'line2': AnalogSource('line2', 'Line In 2', 2, **common),
|
|
'phono': AnalogSource('phono', 'Phono', 0, **common),
|
|
'spdif': AnalogSource('spdif', 'S/PDIF', 3, **common),
|
|
}
|
|
threading.Thread(target=self._save_loop, daemon=True,
|
|
name='cfg-saver').start()
|
|
|
|
def restore(self):
|
|
vol = self._cfg.get('volume', 50)
|
|
last_src = self._cfg.get('last_source', 'radio')
|
|
self.switch(last_src)
|
|
src = self._sources.get(last_src)
|
|
if src and hasattr(src, 'set_volume'): src.set_volume(vol)
|
|
if last_src == 'radio': self._restore_radio()
|
|
|
|
def _restore_radio(self):
|
|
radio = self._sources['radio']
|
|
station = (self._find_station(self._cfg.get('last_station_id'))
|
|
or self._first_station())
|
|
if station:
|
|
radio.play(station['url'], station.get('name', ''))
|
|
log.info(f"Restored: {station.get('name')}")
|
|
else:
|
|
log.warning("Brak stacji")
|
|
|
|
def switch(self, source_id: str) -> bool:
|
|
if source_id not in self._sources: return False
|
|
if self._active_src and self._active_src.SOURCE_ID == source_id: return True
|
|
log.info(f"Switch: {self.active_id} → {source_id}")
|
|
if self._active_src:
|
|
try:
|
|
fn = (getattr(self._active_src, 'deactivate', None)
|
|
or getattr(self._active_src, 'stop', None))
|
|
if fn: fn()
|
|
except Exception as e: log.error(f"Deactivate: {e}")
|
|
src = self._sources[source_id]
|
|
try:
|
|
if hasattr(src, 'activate'): src.activate()
|
|
except Exception as e: log.error(f"Activate: {e}"); return False
|
|
self._active_src = src
|
|
self._cfg['last_source'] = source_id
|
|
self._dirty = True
|
|
return True
|
|
|
|
@property
|
|
def volume(self) -> int: return self._cfg.get('volume', 50)
|
|
def get_volume(self) -> int: return self.volume
|
|
|
|
def set_volume(self, vol: int):
|
|
vol = max(0, min(100, int(vol)))
|
|
self._cfg['volume'] = vol
|
|
src = self._active_src
|
|
if src and hasattr(src, 'set_volume'): src.set_volume(vol)
|
|
self._dirty = True
|
|
|
|
def set_eq(self, source_id, gains):
|
|
if len(gains) != 10: return
|
|
self._cfg.setdefault('eq', {})[source_id] = gains
|
|
self._dirty = True
|
|
|
|
def get_eq(self, source_id):
|
|
return self._cfg.get('eq', {}).get(source_id, [0.0] * 10)
|
|
|
|
def get_meters(self) -> dict:
|
|
src = self._active_src
|
|
return (src.get_meters() if src and hasattr(src, 'get_meters')
|
|
else {'rms_l': -60.0, 'rms_r': -60.0,
|
|
'peak_l': -60.0, 'peak_r': -60.0, 'bands': [-60.0] * 32})
|
|
|
|
@property
|
|
def active(self): return self._active_src
|
|
@property
|
|
def active_id(self): return self._active_src.SOURCE_ID if self._active_src else None
|
|
def get(self, sid): return self._sources.get(sid)
|
|
def get_status(self): return self._active_src.get_status() if self._active_src else {}
|
|
def get_all_status(self):
|
|
return {'active': self.active_id, 'volume': self.volume,
|
|
'status': self.get_status(),
|
|
'sources': [{'id': sid, 'name': src.SOURCE_NAME,
|
|
'active': bool(self._active_src
|
|
and self._active_src.SOURCE_ID == sid)}
|
|
for sid, src in self._sources.items()]}
|
|
|
|
def set_config(self, key, value): self._cfg[key] = value; self._dirty = True
|
|
def get_config(self, key, default=None): return self._cfg.get(key, default)
|
|
def save_source(self, sid): self._cfg['last_source'] = sid; self._dirty = True
|
|
def get_source_gain(self, sid):
|
|
return float(self._cfg.get('source_gains', {}).get(sid, 0.0))
|
|
def set_source_gain(self, sid, gain):
|
|
gain = max(-20.0, min(20.0, float(gain)))
|
|
self._cfg.setdefault('source_gains', {})[sid] = gain
|
|
self._dirty = True
|
|
return gain
|
|
|
|
def get_stations(self):
|
|
try:
|
|
with open(STATIONS_PATH) as f: return json.load(f).get('stations', [])
|
|
except Exception: return []
|
|
|
|
def _find_station(self, sid):
|
|
if not sid: return None
|
|
return next((s for s in self.get_stations()
|
|
if s.get('id') == sid and s.get('enabled', True)), None)
|
|
|
|
def _first_station(self):
|
|
return next((s for s in self.get_stations()
|
|
if s.get('enabled', True)), None)
|
|
|
|
def _load_config(self):
|
|
defaults = {'last_source': 'radio', 'last_station_id': None,
|
|
'volume': 50, 'eq': {}, 'source_gains': {}}
|
|
try:
|
|
with open(CONFIG_PATH) as f: saved = json.load(f)
|
|
for k, v in saved.items():
|
|
if isinstance(v, dict) and isinstance(defaults.get(k), dict):
|
|
defaults[k].update(v)
|
|
else: defaults[k] = v
|
|
except Exception: pass
|
|
return defaults
|
|
|
|
def _save_loop(self):
|
|
while True:
|
|
time.sleep(5)
|
|
if self._dirty:
|
|
self._dirty = False
|
|
self._do_save()
|
|
|
|
def _do_save(self):
|
|
with self._config_lock:
|
|
try:
|
|
try:
|
|
with open(CONFIG_PATH) as f: current = json.load(f)
|
|
except Exception: current = {}
|
|
current.update(self._cfg)
|
|
with open(CONFIG_PATH, 'w') as f:
|
|
json.dump(current, f, indent=2, ensure_ascii=False)
|
|
except Exception as e: log.error(f"Config save: {e}")
|
|
|
|
def _fwd_state(self, sid, state):
|
|
if self._on_state: self._on_state(sid, state)
|
|
|
|
def _fwd_meta(self, sid, meta):
|
|
if self._on_meta: self._on_meta(sid, meta)
|