diff --git a/audio/audio_engine.py b/audio/audio_engine.py deleted file mode 100644 index 238eddc..0000000 --- a/audio/audio_engine.py +++ /dev/null @@ -1,247 +0,0 @@ -# audio/audio_engine.py -"""Silnik audio oparty na GStreamer. - -Obsługuje: -- konwersję i resampling, -- pomiar VU (element `level`), -- korektor 10‑bandowy (element `equalizer-10bands` → opcjonalny), -- kontrolę głośności, balansu, mono i loudness, -- przekazywanie poziomów VU do `HardwareInterface`. -""" - -import logging -import threading -import time - -# ------------------------------------------------- -# Wymagamy konkretnej wersji biblioteki GObject‑Introspection -# ------------------------------------------------- -import gi - -gi.require_version("Gst", "1.0") -gi.require_version("GLib", "2.0") -from gi.repository import Gst, GLib - -# ------------------------------------------------- -# Inicjalizacja GStreamer (tylko raz) -# ------------------------------------------------- -Gst.init(None) - -log = logging.getLogger(__name__) - - -class AudioEngine: - VU_SEND_INTERVAL = 0.1 - - def __init__(self, alsa_device: str, eq_manager, hardware_interface): - """ - :param alsa_device: nazwa urządzenia ALSA (np. ``hw:0,0`` lub ``default``) - :param eq_manager: obiekt :class:`audio.eq_manager.EQManager` - :param hardware_interface: obiekt :class:`app.hardware_interface.HardwareInterface` - """ - self.alsa_device = alsa_device - self.eq_manager = eq_manager - self.hw = hardware_interface - - # Domyślne parametry audio – mogą być zmieniane później - self.volume = 75 - self.balance = 0 - self.loudness = True - self.mono = False - - # Poziomy VU (w %) - self._vu_left = 0.0 - self._vu_right = 0.0 - - # Uruchomienie GLib MainLoop w osobnym wątku (potrzebne do obsługi bus‑messages) - self._glib_loop = GLib.MainLoop() - self._loop_thread = threading.Thread(target=self._glib_loop.run, daemon=True) - self._loop_thread.start() - - # Tworzymy podstawowy pipeline - self._create_base_pipeline() - - log.info( - "AudioEngine – zainicjowano, device=%s, EQ %s", - alsa_device, - "włączony" if hasattr(self, "equalizer") else "wyłączony", - ) - - # ---------------------------------------------------------------------- - # Budowanie pipeline - # ---------------------------------------------------------------------- - def _create_base_pipeline(self): - """ - Buduje pipeline: - - ┌─────────────┐ ┌─────────────┐ ┌───────┐ ┌────────────┐ ┌───────┐ - │ source? │ → │ audioconvert│ → │ level │ → │ equalizer? │ → │ volume│ → alsasink - └─────────────┘ └─────────────┘ └───────┘ └────────────┘ └───────┘ - """ - # ────────────────────── - # 1️⃣ elementy, które zawsze będą w pipeline - # ────────────────────── - pipeline_desc = f""" - audiotestsrc wave=sine freq=440 num-buffers=0 ! audio/x-raw,format=S16LE,channels=2,rate=44100 ! - audioconvert ! audioresample ! - level name=vu_level interval=100000000 post-messages=true ! - volume name=vol ! - alsasink device={self.alsa_device} - """ - - # Tworzymy pipeline z opisu powyżej - self.pipeline = Gst.parse_launch(pipeline_desc) - - # Pobieramy referencje do elementów, które będziemy sterować - self.level = self.pipeline.get_by_name("vu_level") - self.volume_elem = self.pipeline.get_by_name("vol") - - # ------------------------------------------------------------------ - # 2️⃣ spróbuj dodać equalizer‑10bands (jeśli wtyczka jest dostępna) - # ------------------------------------------------------------------ - equalizer = Gst.ElementFactory.make("equalizer-10bands", "eq") - if equalizer: - # Przenosimy element `volume` za equalizer – w pipeline ma być - # source → ... → level → equalizer → volume → sink - self.pipeline.add(equalizer) - # Musimy odłączyć istniejący link `level → volume` i podłączyć nowy: - self.level.unlink(self.volume_elem) - self.level.link(equalizer) - equalizer.link(self.volume_elem) - self.equalizer = equalizer - log.info("Equalizer‑10bands został dodany do pipeline.") - else: - # Jeśli nie udało się znaleźć elementu – logujemy i kontynuujemy bez EQ - self.equalizer = None - log.warning( - "Element 'equalizer-10bands' nie został znaleziony – EQ będzie wyłączony. " - "Zainstaluj pakiet gstreamer1.0-plugins-bad." - ) - - # ------------------------------------------------------------------ - # 3️⃣ Obsługa komunikatów z busa (m.in. poziomy VU) - # ------------------------------------------------------------------ - bus = self.pipeline.get_bus() - bus.add_signal_watch() - bus.connect("message", self._on_bus_message) - - # Uruchamiamy pipeline - self.pipeline.set_state(Gst.State.PLAYING) - - # ---------------------------------------------------------------------- - # Obsługa komunikatów (głównie poziomy VU) - # ---------------------------------------------------------------------- - def _on_bus_message(self, bus, message): - if message.type != Gst.MessageType.ELEMENT: - return - struct = message.get_structure() - if not struct or struct.get_name() != "level": - return - - rms = struct.get_value("rms") - if isinstance(rms, (list, tuple)) and len(rms) >= 2: - left = max(0.0, min(100.0, (rms[0] + 60) * 1.6667)) - right = max(0.0, min(100.0, (rms[1] + 60) * 1.6667)) - now = time.time() - if now - self._last_vu_sent >= self.VU_SEND_INTERVAL: - self._vu_left, self._vu_right = left, right - self.hw.update_vu(left, right) - self._last_vu_sent = now - - # ---------------------------------------------------------------------- - # Publiczne API – kontrola audio - # ---------------------------------------------------------------------- - def set_volume(self, level: int): - """Ustawia głośność (0‑100).""" - self.volume = max(0, min(100, level)) - # GStreamer przyjmuje wartość 0.0‑1.0 - self.volume_elem.set_property("volume", self.volume / 100.0) - log.info("Volume → %d", self.volume) - - def set_balance(self, value: int): - """Ustawia balans (‑50 lewy, 0 środek, +50 prawy).""" - self.balance = max(-50, min(50, value)) - # Implementujemy balans przy pomocy elementu `audiopanorama` - pan = Gst.ElementFactory.make("audiopanorama", None) - if not pan: - log.warning("Element 'audiopanorama' nie dostępny – balans zostanie zignorowany.") - return - # Dodajemy panoramę do pipeline (po level, przed equalizer/volume) - self.pipeline.add(pan) - self.level.unlink(self.equalizer or self.volume_elem) # odłączmy to, co było po level - self.level.link(pan) - # Po panoramie linkujemy dalej - if self.equalizer: - pan.link(self.equalizer) - else: - pan.link(self.volume_elem) - - # Ustawiamy właściwość `panorama` (wartość -1.0 … 1.0) - pan.set_property("panorama", self.balance / 50.0) - log.info("Balance → %d (panorama = %.2f)", self.balance, self.balance / 50.0) - - def set_mono(self, enabled: bool): - """Włącza/wyłącza tryb mono (połączenie kanałów).""" - self.mono = enabled - # Mono jest realizowane przez element `audioconvert` + `audioresample` + `audiomixer` - # Dla prostoty zamykamy pipeline i rekonfigurujemy przy zmianie. - # W bardziej zaawansowanym projekcie można dynamicznie podmienić element. - log.info("Mono → %s (re‑konfiguracja pipeline wymagana)", enabled) - - def set_loudness(self, enabled: bool): - """Włącza lub wyłącza filtr „loudness”. """ - self.loudness = enabled - # GStreamer nie ma wbudowanego filtru loudness, ale można dodać element `compand`. - # W tej wersji pozostawiamy jako placeholder. - log.info("Loudness → %s (placeholder)", enabled) - - def set_source(self, gst_src): - """ - Podmienia aktywne źródło audio w pipeline. - - :param gst_src: gotowy element GStreamer (np. ``uridecodebin`` lub własny ``src``). - """ - # Zatrzymujemy bieżący pipeline - self.pipeline.set_state(Gst.State.NULL) - - # Usuwamy poprzedni element „src” (jeśli istnieje) - src_old = self.pipeline.get_by_name("src") - if src_old: - self.pipeline.remove(src_old) - - # Dodajemy nowy element - gst_src.set_name("src") - self.pipeline.add(gst_src) - - # Łączymy nowy element z resztą pipeline (po source -> level) - # Najprostsze podejście: podpinamy src → level (przez audioconvert + audioresample) - # (Zależnie od typu źródła może być potrzebne autoplugowanie.) - # W tym przykładzie zakładamy, że `gst_src` już samodzielnie dekoduje audio do raw PCM. - gst_src.link(self.level) - - # Restartujemy odtwarzanie - self.pipeline.set_state(Gst.State.PLAYING) - log.info("Source changed – nowy element: %s", gst_src.get_name()) - - def set_eq(self, bands): - """ - Ustawia wartości korektora 10‑bandowego. - - :param bands: lista 10 liczb (dB) np. [-5, 0, 2, …]. - """ - if not self.equalizer: - log.warning("Equalizer nie został włączony – ignoruję ustawienia EQ.") - return - - if len(bands) != 10: - raise ValueError("EQ wymaga dokładnie 10 wartości") - for i, v in enumerate(bands): - self.equalizer.set_property(f"band{i}", float(v)) - log.info("EQ → %s", bands) - - def get_vu_levels(self): - """Zwraca aktualne poziomy VU w % (słownik ``{'left': …, 'right': …}``).""" - return { - "left": round(self._vu_left, 1), - "right": round(self._vu_right, 1), - } diff --git a/audio/cover_manager.py b/audio/cover_manager.py deleted file mode 100644 index 2a6bbe2..0000000 --- a/audio/cover_manager.py +++ /dev/null @@ -1,49 +0,0 @@ -# audio/cover_manager.py -import os -import json -import hashlib -import logging -import pathlib -import urllib.request - -log = logging.getLogger(__name__) - - -class CoverManager: - """ - Pobiera i buforuje okładki stacji radiowych. - - - `cache_dir` – katalog, w którym trzymane są pobrane pliki. - - `get_cover_path(station_id)` – zwraca pełną ścieżkę do pliku, albo None. - - `fetch_and_save(url, station_id)` – pobiera z sieci i zapisuje. - """ - - def __init__(self, cache_dir: str = "cover"): - self.cache_dir = pathlib.Path(cache_dir) - self.cache_dir.mkdir(parents=True, exist_ok=True) - - def _hash(self, text: str) -> str: - return hashlib.sha1(text.encode("utf-8")).hexdigest()[:10] - - def get_cover_path(self, station_id: str) -> str | None: - """Sprawdza, czy istnieje już pobrana okładka o danym ID.""" - pattern = self.cache_dir / f"{self._hash(station_id)}.*" - matches = list(pattern.parent.glob(pattern.name)) - if matches: - return str(matches[0]) - return None - - def fetch_and_save(self, url: str, station_id: str) -> str | None: - """Pobiera okładkę i zapisuje pod hash‑owaną nazwą.""" - try: - resp = urllib.request.urlopen(url, timeout=10) - data = resp.read() - ext = pathlib.Path(resp.url).suffix or ".jpg" - filename = self.cache_dir / f"{self._hash(station_id)}{ext}" - with open(filename, "wb") as f: - f.write(data) - log.info("Pobrano okładkę → %s", filename) - return str(filename) - except Exception as exc: - log.error("Nie udało się pobrać okładki (%s): %s", url, exc) - return None \ No newline at end of file diff --git a/audio/eq_manager.py b/audio/eq_manager.py deleted file mode 100644 index f239243..0000000 --- a/audio/eq_manager.py +++ /dev/null @@ -1,41 +0,0 @@ -# audio/eq_manager.py -import logging - -log = logging.getLogger(__name__) - - -class EQManager: - """ - Przechowuje i udostępnia ustawienia korektora dla każdego źródła. - Konfiguracja jest wczytywana z `config.json` przy starcie. - """ - - def __init__(self, eq_cfg: dict): - """ - `eq_cfg` – słownik z kluczami: radio, bluetooth, phono, line1, line2, spdif, - każda wartość to lista 10 liczb (dB). - """ - self._eq = eq_cfg.copy() - log.info("EQManager – załadowano konfigurację dla %d źródeł", len(self._eq)) - - def get_eq(self, source_name: str): - """Zwraca listę 10 wartości dla podanego źródła (lub domyślny flat).""" - return self._eq.get(source_name, [0] * 10) - - def set_eq(self, source_name: str, bands: list): - if len(bands) != 10: - raise ValueError("EQ wymaga dokładnie 10 wartości") - self._eq[source_name] = bands - log.info("EQ set dla %s → %s", source_name, bands) - - # --------- Używane w AudioEngine ---------- - def apply_to_engine(self, audio_engine, source_name: str): - """Przekazuje aktualny zestaw bandów do silnika audio.""" - bands = self.get_eq(source_name) - audio_engine.set_eq(bands) - - def get_current_eq(self): - """Zwraca aktualny zestaw EQ – najprostsze API do UI.""" - # Zakładamy, że `audio_engine` ma atrybut `current_source_name` - # W tym uproszczonym przykładzie nie wiemy, więc zwracamy all. - return self._eq \ No newline at end of file diff --git a/audio/source_manager.py b/audio/source_manager.py deleted file mode 100644 index e48c9b7..0000000 --- a/audio/source_manager.py +++ /dev/null @@ -1,119 +0,0 @@ -# audio/source_manager.py -import json -import logging -import os - -from audio.sources import ( - RadioSource, - BluetoothSource, - AnalogSource, - SpdifSource, - CdSource, - UsbSource, -) - -log = logging.getLogger(__name__) - - -class SourceManager: - """ - Zarządza wszystkimi dostępnymi źródłami audio. - - - `available` – dict name → AudioSource - - `current` – aktualnie wybrany AudioSource - - Metody: `switch(name)`, `save_state()`, `load_state()` - """ - - def __init__(self, audio_engine, config: dict): - self.audio = audio_engine - self.cfg_path = os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "config", "config.json")) - self.available = {} - self.current = None - self._build_sources(config) - self.load_state() - - # ------------------------------------------------------------------ - # Tworzenie instancji źródeł (na podstawie config) - # ------------------------------------------------------------------ - def _build_sources(self, config): - # radio – przykładowa lista stacji (z stations.json zostanie wczytana później) - self.available["radio"] = RadioSource( - station_url="http://example.com/stream.mp3", station_name="radio" - ) - # bluetooth - self.available["bluetooth"] = BluetoothSource() - # analog – w przykładowym config nie ma szczegółów, więc używamy dummy device - self.available["phono"] = AnalogSource(device="hw:0,0", name="phono") - self.available["line1"] = AnalogSource(device="hw:0,1", name="line1") - self.available["line2"] = AnalogSource(device="hw:0,2", name="line2") - # spdif - self.available["spdif"] = SpdifSource(device="hw:0,3") - # cd / usb (szkielet) - self.available["cd"] = CdSource() - self.available["usb"] = UsbSource() - - # ------------------------------------------------------------------ - # Publiczne API - # ------------------------------------------------------------------ - @property - def available_names(self): - return list(self.available.keys()) - - @property - def current_name(self): - return self.current.name if self.current else None - - def switch(self, name: str): - """Przełącza aktywne źródło audio.""" - if name not in self.available: - raise ValueError(f"Nieznane źródło: {name}") - - src = self.available[name] - src.activate() - src_elm = src.build_source() - self.audio.set_source(src_elm) - - # Dezaktywujemy poprzednie (jeśli istnieje) - if self.current and self.current != src: - self.current.deactivate() - - self.current = src - log.info("Source switched → %s", name) - self.save_state() - - # ------------------------------------------------------------------ - # Zapis / odczyt stanu (vol, source, ostatnia stacja) - # ------------------------------------------------------------------ - def load_state(self): - """Wczytuje ostatni stan z config.json (jeśli istnieje).""" - try: - with open(self.cfg_path, "r", encoding="utf-8") as f: - data = json.load(f) - except (FileNotFoundError, json.JSONDecodeError): - log.warning("Nie udało się wczytać config.json – używam domyślnych wartości") - data = {} - - # Odtwarzamy ostatnie źródło (lub radio jako fallback) - last_src = data.get("last_source", "radio") - if last_src in self.available: - self.switch(last_src) - - # Ustawiamy głośność (domyślnie 75) - vol = data.get("volume", 75) - self.audio.set_volume(vol) - - def save_state(self): - """Zapisuje aktualny stan do pliku config.json.""" - state = { - "last_source": self.current_name, - "volume": self.audio.volume, - "balance": self.audio.balance, - "loudness": self.audio.loudness, - "mono": self.audio.mono, - } - try: - with open(self.cfg_path, "w", encoding="utf-8") as f: - json.dump(state, f, indent=2) - log.debug("Zapisano stan do config.json") - except Exception as exc: - log.error("Błąd przy zapisie config.json: %s", exc) \ No newline at end of file diff --git a/audio/sources.py b/audio/sources.py deleted file mode 100644 index 54b19f3..0000000 --- a/audio/sources.py +++ /dev/null @@ -1,123 +0,0 @@ -# audio/sources.py -import logging -from gi.repository import Gst - -log = logging.getLogger(__name__) - -# ---------------------------------------------------------------------- -# Abstrakcyjna klasa bazowa -# ---------------------------------------------------------------------- -class AudioSource: - """Bazowa klasa źródła audio – implementuje jedynie interfejs.""" - - def __init__(self, name: str): - self.name = name - self.pipeline_src = None # GStreamer element (np. uridecodebin) - - def build_source(self): - """Zwraca gotowy element GStreamer, który można podłączyć do AudioEngine.""" - raise NotImplementedError - - def activate(self): - """Przygotowanie (np. połączenie z DBus, Bluetooth itp.).""" - log.debug("%s – activate()", self.name) - - def deactivate(self): - """Czyszczenie zasobów.""" - log.debug("%s – deactivate()", self.name) - - -# ---------------------------------------------------------------------- -# Radio – odtwarzanie strumienia HTTP (np. Icecast) -# ---------------------------------------------------------------------- -class RadioSource(AudioSource): - def __init__(self, station_url: str, station_name: str = "radio"): - super().__init__(station_name) - self.url = station_url - - def build_source(self): - src = Gst.ElementFactory.make("souphttpsrc", None) - src.set_property("location", self.url) - decode = Gst.ElementFactory.make("decodebin", None) - bin_ = Gst.Bin.new("radio_bin") - bin_.add(src) - bin_.add(decode) - src.link(decode) - self.pipeline_src = bin_ - return bin_ - - -# ---------------------------------------------------------------------- -# Bluetooth – używamy pulse‑audio source (simplified) -# ---------------------------------------------------------------------- -class BluetoothSource(AudioSource): - def __init__(self, name: str = "bluetooth"): - super().__init__(name) - - def build_source(self): - # Zakładamy, że Bluetooth jest już połączony z PulseAudio jako "bluez_source" - src = Gst.ElementFactory.make("pulsesrc", None) - src.set_property("device", "bluez_source") - self.pipeline_src = src - return src - - -# ---------------------------------------------------------------------- -# Analog – Phono / Line1 / Line2 (przez ALSA) -# ---------------------------------------------------------------------- -class AnalogSource(AudioSource): - def __init__(self, device: str, name: str): - """ - `device` – nazwa ALSA (np. "hw:1,0"). - `name` – przyjazna nazwa (phono, line1, line2) - """ - super().__init__(name) - self.device = device - - def build_source(self): - src = Gst.ElementFactory.make("alsasrc", None) - src.set_property("device", self.device) - self.pipeline_src = src - return src - - -# ---------------------------------------------------------------------- -# SPDIF (digital) – także ALSA, ale inny adres -# ---------------------------------------------------------------------- -class SpdifSource(AudioSource): - def __init__(self, device: str = "hw:1,0", name: str = "spdif"): - super().__init__(name) - self.device = device - - def build_source(self): - src = Gst.ElementFactory.make("alsasrc", None) - src.set_property("device", self.device) - self.pipeline_src = src - return src - - -# ---------------------------------------------------------------------- -# CD / USB – tylko szkielet (można rozbudować później) -# ---------------------------------------------------------------------- -class CdSource(AudioSource): - def __init__(self, device: str = "/dev/cdrom", name: str = "cd"): - super().__init__(name) - self.device = device - - def build_source(self): - src = Gst.ElementFactory.make("cdparanoiasrc", None) - src.set_property("device", self.device) - self.pipeline_src = src - return src - - -class UsbSource(AudioSource): - def __init__(self, device: str = "/dev/sr0", name: str = "usb"): - super().__init__(name) - self.device = device - - def build_source(self): - src = Gst.ElementFactory.make("alsasrc", None) - src.set_property("device", self.device) - self.pipeline_src = src - return src \ No newline at end of file