| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388 |
- # -*- coding: utf-8 -*-
- """
- FLAC-Decoder.
- Dekodiert FLAC-Dateien (verlustfrei) zu PCM.
- """
- import asyncio
- import io
- import logging
- import struct
- from pathlib import Path
- from typing import AsyncIterator
- from trixy_core.music.formats.base import (
- AudioDecoder,
- AudioFormat,
- AudioInfo,
- DecodedAudio,
- DecoderError,
- )
- class FLACDecoder(AudioDecoder):
- """
- FLAC-Decoder.
- FLAC ist ein verlustfreies Format, perfekt für hochwertige Audio-Wiedergabe.
- Verwendet pydub/ffmpeg als Backend.
- """
- FORMAT = AudioFormat.FLAC
- EXTENSIONS = {"flac", "fla"}
- MIME_TYPES = {"audio/flac", "audio/x-flac"}
- def __init__(self) -> None:
- super().__init__()
- self.logger = logging.getLogger(__name__)
- self._use_pydub = False
- self._use_ffmpeg = False
- def _check_dependencies(self) -> bool:
- """Prüft verfügbare Decoder-Backends."""
- # Versuche pydub
- try:
- from pydub import AudioSegment
- self._use_pydub = True
- return True
- except ImportError:
- pass
- # Versuche ffmpeg
- import shutil
- if shutil.which("ffmpeg"):
- self._use_ffmpeg = True
- return True
- return False
- async def get_info(self, source: Path | bytes) -> AudioInfo:
- """Liest FLAC-Informationen."""
- if isinstance(source, bytes):
- return await self._get_info_from_bytes(source)
- return await self._get_info_from_file(source)
- async def _get_info_from_file(self, path: Path) -> AudioInfo:
- """Liest Informationen aus FLAC-Datei."""
- if not path.exists():
- raise DecoderError(f"Datei nicht gefunden: {path}")
- file_size = path.stat().st_size
- # Versuche Mutagen
- try:
- import mutagen.flac
- audio = mutagen.flac.FLAC(path)
- return AudioInfo(
- format=AudioFormat.FLAC,
- duration_ms=int(audio.info.length * 1000),
- sample_rate=audio.info.sample_rate,
- channels=audio.info.channels,
- bit_depth=audio.info.bits_per_sample,
- bit_rate=int(file_size * 8 / audio.info.length) if audio.info.length > 0 else 0,
- file_size=file_size,
- )
- except ImportError:
- pass
- except Exception as e:
- self.logger.debug(f"Mutagen FLAC Fehler: {e}")
- # Fallback: FLAC-Header parsen
- try:
- return await asyncio.to_thread(self._parse_flac_header, path)
- except Exception as e:
- self.logger.debug(f"FLAC-Header Fehler: {e}")
- return AudioInfo(format=AudioFormat.FLAC, file_size=file_size)
- async def _get_info_from_bytes(self, data: bytes) -> AudioInfo:
- """Liest Informationen aus FLAC-Bytes."""
- info = self._parse_flac_header_bytes(data)
- info.file_size = len(data)
- return info
- def _parse_flac_header(self, path: Path) -> AudioInfo:
- """Parst FLAC-Header aus Datei."""
- with open(path, "rb") as f:
- data = f.read(1024)
- info = self._parse_flac_header_bytes(data)
- info.file_size = path.stat().st_size
- return info
- def _parse_flac_header_bytes(self, data: bytes) -> AudioInfo:
- """
- Parst FLAC-Header.
- FLAC Format:
- - 4 bytes: "fLaC" Marker
- - Metadata Blocks (STREAMINFO ist immer erster Block)
- """
- info = AudioInfo(format=AudioFormat.FLAC)
- # Prüfe Magic
- if data[:4] != b"fLaC":
- raise DecoderError("Keine gültige FLAC-Datei")
- # STREAMINFO Block (ab Byte 4)
- # Format: 1 bit (last-block) + 7 bit (type) + 24 bit (length)
- block_header = data[4]
- is_last = bool(block_header & 0x80)
- block_type = block_header & 0x7F
- if block_type != 0: # 0 = STREAMINFO
- return info
- # Block-Länge (3 Bytes, Big-Endian)
- block_length = (data[5] << 16) | (data[6] << 8) | data[7]
- if block_length < 34:
- return info
- # STREAMINFO Daten (34 Bytes)
- streaminfo = data[8:8+34]
- # Minimum Block Size (2 bytes)
- min_block_size = (streaminfo[0] << 8) | streaminfo[1]
- # Maximum Block Size (2 bytes)
- max_block_size = (streaminfo[2] << 8) | streaminfo[3]
- # Minimum Frame Size (3 bytes)
- # Maximum Frame Size (3 bytes)
- # -> Bytes 4-9
- # Sample Rate (20 bits) + Channels (3 bits) + Bit Depth (5 bits) + Total Samples (36 bits)
- # Bytes 10-17
- # Sample Rate (20 bits): Bytes 10-11 + obere 4 bits von Byte 12
- sample_rate = (streaminfo[10] << 12) | (streaminfo[11] << 4) | (streaminfo[12] >> 4)
- # Channels - 1 (3 bits): untere 4 bits von Byte 12 + oberstes Bit
- channels = ((streaminfo[12] & 0x0E) >> 1) + 1
- # Bit Depth - 1 (5 bits)
- bit_depth = ((streaminfo[12] & 0x01) << 4) | (streaminfo[13] >> 4) + 1
- # Total Samples (36 bits)
- total_samples = (
- ((streaminfo[13] & 0x0F) << 32) |
- (streaminfo[14] << 24) |
- (streaminfo[15] << 16) |
- (streaminfo[16] << 8) |
- streaminfo[17]
- )
- # Dauer berechnen
- if sample_rate > 0:
- duration_ms = int((total_samples / sample_rate) * 1000)
- else:
- duration_ms = 0
- return AudioInfo(
- format=AudioFormat.FLAC,
- duration_ms=duration_ms,
- sample_rate=sample_rate,
- channels=channels,
- bit_depth=bit_depth,
- )
- async def decode(
- self,
- source: Path | bytes,
- target_sample_rate: int | None = None,
- target_channels: int | None = None,
- ) -> DecodedAudio:
- """Dekodiert FLAC vollständig zu PCM."""
- target_sr = target_sample_rate or self.OUTPUT_SAMPLE_RATE
- target_ch = target_channels or self.OUTPUT_CHANNELS
- if self._use_pydub:
- return await self._decode_pydub(source, target_sr, target_ch)
- elif self._use_ffmpeg:
- return await self._decode_ffmpeg(source, target_sr, target_ch)
- else:
- raise DecoderError("Kein FLAC-Decoder verfügbar")
- async def _decode_pydub(
- self,
- source: Path | bytes,
- target_sr: int,
- target_ch: int,
- ) -> DecodedAudio:
- """Dekodiert mit pydub."""
- try:
- from pydub import AudioSegment
- def decode():
- if isinstance(source, bytes):
- audio = AudioSegment.from_file(io.BytesIO(source), format="flac")
- else:
- audio = AudioSegment.from_file(str(source), format="flac")
- # Resampling falls nötig
- if audio.frame_rate != target_sr:
- audio = audio.set_frame_rate(target_sr)
- # Channel-Anpassung
- if audio.channels != target_ch:
- audio = audio.set_channels(target_ch)
- # Auf 16-bit normalisieren
- audio = audio.set_sample_width(2)
- return DecodedAudio(
- pcm_data=audio.raw_data,
- sample_rate=audio.frame_rate,
- channels=audio.channels,
- bit_depth=16,
- )
- return await asyncio.to_thread(decode)
- except Exception as e:
- raise DecoderError(f"pydub FLAC-Dekodierung fehlgeschlagen: {e}")
- async def _decode_ffmpeg(
- self,
- source: Path | bytes,
- target_sr: int,
- target_ch: int,
- ) -> DecodedAudio:
- """Dekodiert mit ffmpeg."""
- try:
- if isinstance(source, bytes):
- cmd = [
- "ffmpeg", "-y", "-hide_banner", "-loglevel", "error",
- "-i", "pipe:0",
- "-f", "s16le",
- "-acodec", "pcm_s16le",
- "-ar", str(target_sr),
- "-ac", str(target_ch),
- "pipe:1"
- ]
- process = await asyncio.create_subprocess_exec(
- *cmd,
- stdin=asyncio.subprocess.PIPE,
- stdout=asyncio.subprocess.PIPE,
- stderr=asyncio.subprocess.PIPE,
- )
- stdout, stderr = await process.communicate(input=source)
- else:
- cmd = [
- "ffmpeg", "-y", "-hide_banner", "-loglevel", "error",
- "-i", str(source),
- "-f", "s16le",
- "-acodec", "pcm_s16le",
- "-ar", str(target_sr),
- "-ac", str(target_ch),
- "pipe:1"
- ]
- process = await asyncio.create_subprocess_exec(
- *cmd,
- stdout=asyncio.subprocess.PIPE,
- stderr=asyncio.subprocess.PIPE,
- )
- stdout, stderr = await process.communicate()
- if process.returncode != 0:
- raise DecoderError(f"ffmpeg Fehler: {stderr.decode()}")
- return DecodedAudio(
- pcm_data=stdout,
- sample_rate=target_sr,
- channels=target_ch,
- bit_depth=16,
- )
- except DecoderError:
- raise
- except Exception as e:
- raise DecoderError(f"ffmpeg FLAC-Dekodierung fehlgeschlagen: {e}")
- async def decode_stream(
- self,
- source: Path | bytes,
- chunk_duration_ms: int = 100,
- ) -> AsyncIterator[DecodedAudio]:
- """Dekodiert FLAC als Stream."""
- bytes_per_sample = 2
- samples_per_chunk = int(self.OUTPUT_SAMPLE_RATE * chunk_duration_ms / 1000)
- chunk_size = samples_per_chunk * bytes_per_sample * self.OUTPUT_CHANNELS
- if self._use_pydub:
- decoded = await self.decode(source)
- data = decoded.pcm_data
- for i in range(0, len(data), chunk_size):
- yield DecodedAudio(
- pcm_data=data[i:i + chunk_size],
- sample_rate=decoded.sample_rate,
- channels=decoded.channels,
- bit_depth=decoded.bit_depth,
- )
- elif self._use_ffmpeg:
- async for chunk in self._stream_ffmpeg(source, chunk_size):
- yield chunk
- async def _stream_ffmpeg(
- self,
- source: Path | bytes,
- chunk_size: int,
- ) -> AsyncIterator[DecodedAudio]:
- """Streaming mit ffmpeg."""
- try:
- if isinstance(source, bytes):
- cmd = [
- "ffmpeg", "-y", "-hide_banner", "-loglevel", "error",
- "-i", "pipe:0",
- "-f", "s16le",
- "-acodec", "pcm_s16le",
- "-ar", str(self.OUTPUT_SAMPLE_RATE),
- "-ac", str(self.OUTPUT_CHANNELS),
- "pipe:1"
- ]
- process = await asyncio.create_subprocess_exec(
- *cmd,
- stdin=asyncio.subprocess.PIPE,
- stdout=asyncio.subprocess.PIPE,
- stderr=asyncio.subprocess.PIPE,
- )
- if process.stdin:
- process.stdin.write(source)
- await process.stdin.drain()
- process.stdin.close()
- else:
- cmd = [
- "ffmpeg", "-y", "-hide_banner", "-loglevel", "error",
- "-i", str(source),
- "-f", "s16le",
- "-acodec", "pcm_s16le",
- "-ar", str(self.OUTPUT_SAMPLE_RATE),
- "-ac", str(self.OUTPUT_CHANNELS),
- "pipe:1"
- ]
- process = await asyncio.create_subprocess_exec(
- *cmd,
- stdout=asyncio.subprocess.PIPE,
- stderr=asyncio.subprocess.PIPE,
- )
- while True:
- chunk = await process.stdout.read(chunk_size)
- if not chunk:
- break
- yield DecodedAudio(
- pcm_data=chunk,
- sample_rate=self.OUTPUT_SAMPLE_RATE,
- channels=self.OUTPUT_CHANNELS,
- bit_depth=16,
- )
- await process.wait()
- except Exception as e:
- raise DecoderError(f"FLAC Streaming fehlgeschlagen: {e}")
|