audio-mastering-engine / src /dsp /processor.py
Shahzroux's picture
Upload processor.py
ff8acf8 verified
Raw History Blame Contribute Delete
9.83 kB
"""
DSP Processing Engine
Applies mastering chain using Pedalboard (Spotify's audio processing library)
"""
import numpy as np
import soundfile as sf
from pedalboard import (
Pedalboard, Compressor, Limiter, Gain,
HighpassFilter, LowpassFilter, PeakFilter,
Distortion, Reverb
)
from pedalboard.io import AudioFile
from typing import Optional, Tuple, Dict
import pyloudnorm as pyln
from ai.preset_system import MasteringPreset, EQBand
class MasteringProcessor:
"""
Main mastering processor that applies DSP chain
"""
def __init__(self, sample_rate: int = 44100):
self.sample_rate = sample_rate
self.loudness_meter = pyln.Meter(sample_rate)
def process_file(self,
input_path: str,
output_path: str,
preset: MasteringPreset,
verbose: bool = True) -> Dict:
"""
Process audio file with mastering preset
Args:
input_path: Input audio file path
output_path: Output audio file path
preset: MasteringPreset to apply
verbose: Print processing steps
Returns:
Dictionary with processing results and measurements
"""
if verbose:
print(f"\nπŸŽ›οΈ Processing with preset: {preset.name}")
print(f"πŸ“₯ Input: {input_path}")
# Load audio
audio, sr = sf.read(input_path, always_2d=True)
if sr != self.sample_rate:
if verbose:
print(f"⚠️ Resampling from {sr}Hz to {self.sample_rate}Hz")
import librosa
audio = librosa.resample(audio.T, orig_sr=sr, target_sr=self.sample_rate).T
# Transpose to (channels, samples) for Pedalboard
audio = audio.T
# Measure input
input_lufs = self._measure_loudness(audio)
input_peak = np.abs(audio).max()
if verbose:
print(f"πŸ“Š Input: {input_lufs:.1f} LUFS, Peak: {20*np.log10(input_peak+1e-10):.1f} dBFS")
# Build and apply processing chain
board = self._build_chain(preset)
if verbose:
print(f"βš™οΈ Applying {len(board)} processors...")
# Process
processed = board(audio, self.sample_rate)
# Measure output
output_lufs = self._measure_loudness(processed)
output_peak = np.abs(processed).max()
# Final gain adjustment to hit target LUFS
lufs_diff = preset.target_lufs - output_lufs
if abs(lufs_diff) > 0.5: # If more than 0.5 LU off target
gain_adjustment = lufs_diff
if verbose:
print(f"🎚️ Final gain adjustment: {gain_adjustment:+.1f} dB")
gain_board = Pedalboard([Gain(gain_db=gain_adjustment)])
processed = gain_board(processed, self.sample_rate)
output_lufs = self._measure_loudness(processed)
output_peak = np.abs(processed).max()
if verbose:
print(f"πŸ“Š Output: {output_lufs:.1f} LUFS, Peak: {20*np.log10(output_peak+1e-10):.1f} dBFS")
# Transpose back to (samples, channels) for saving
processed = processed.T
# Save
sf.write(output_path, processed, self.sample_rate, subtype='PCM_24')
if verbose:
print(f"πŸ’Ύ Saved to: {output_path}\n")
# Return results
results = {
'input_lufs': float(input_lufs),
'output_lufs': float(output_lufs),
'input_peak_db': float(20 * np.log10(input_peak + 1e-10)),
'output_peak_db': float(20 * np.log10(output_peak + 1e-10)),
'lufs_change': float(output_lufs - input_lufs),
'preset_used': preset.name
}
return results
def _build_chain(self, preset: MasteringPreset) -> Pedalboard:
"""
Build processing chain from preset
"""
processors = []
# === 1. EQ ===
for band in preset.eq_bands:
processors.append(self._create_eq_band(band))
# === 2. Compression ===
if preset.comp_ratio > 1.0:
compressor = Compressor(
threshold_db=preset.comp_threshold_db,
ratio=preset.comp_ratio,
attack_ms=preset.comp_attack_ms,
release_ms=preset.comp_release_ms
)
processors.append(compressor)
# === 3. Saturation ===
if preset.saturation_amount > 0:
# Use Distortion with low drive for saturation effect
saturation = Distortion(
drive_db=preset.saturation_amount * 20
)
processors.append(saturation)
# === 4. Limiting ===
limiter = Limiter(
threshold_db=preset.limiter_threshold_db,
release_ms=preset.limiter_release_ms
)
processors.append(limiter)
# Build Pedalboard
board = Pedalboard(processors)
return board
def _create_eq_band(self, band: EQBand):
"""Create EQ processor from EQBand"""
if band.type == 'highpass':
return HighpassFilter(cutoff_frequency_hz=band.frequency)
elif band.type == 'lowpass':
return LowpassFilter(cutoff_frequency_hz=band.frequency)
elif band.type == 'peak':
return PeakFilter(
cutoff_frequency_hz=band.frequency,
gain_db=band.gain,
q=band.q
)
# Note: Pedalboard doesn't have shelving filters yet
# For production, you'd use scipy or custom implementation
else:
# Default to peak filter
return PeakFilter(
cutoff_frequency_hz=band.frequency,
gain_db=band.gain,
q=band.q
)
def _measure_loudness(self, audio: np.ndarray) -> float:
"""
Measure integrated loudness (LUFS)
Args:
audio: Audio array in (channels, samples) format
"""
# Convert to mono for loudness measurement
if audio.ndim > 1:
audio_mono = np.mean(audio, axis=0)
else:
audio_mono = audio
try:
loudness = self.loudness_meter.integrated_loudness(audio_mono)
# Handle -inf (silence)
if np.isinf(loudness) or loudness < -70:
loudness = -70.0
except:
loudness = -70.0
return loudness
def preview(self,
audio_path: str,
preset: MasteringPreset,
duration_seconds: float = 30.0) -> Tuple[np.ndarray, np.ndarray]:
"""
Process short preview of audio
Args:
audio_path: Path to audio file
preset: Preset to apply
duration_seconds: Length of preview
Returns:
Tuple of (original_audio, processed_audio)
"""
# Load audio
audio, sr = sf.read(audio_path, always_2d=True)
# Take first N seconds
samples = int(duration_seconds * sr)
audio = audio[:samples]
# Resample if needed
if sr != self.sample_rate:
import librosa
audio = librosa.resample(audio.T, orig_sr=sr, target_sr=self.sample_rate).T
else:
audio = audio.T
# Process
board = self._build_chain(preset)
processed = board(audio, self.sample_rate)
return audio, processed
class SimpleDSP:
"""
Simplified DSP functions without Pedalboard (fallback)
Uses scipy for basic processing
"""
@staticmethod
def apply_gain(audio: np.ndarray, gain_db: float) -> np.ndarray:
"""Apply gain in dB"""
gain_linear = 10 ** (gain_db / 20)
return audio * gain_linear
@staticmethod
def simple_limiter(audio: np.ndarray, threshold_db: float = -1.0) -> np.ndarray:
"""
Simple hard limiter
"""
threshold = 10 ** (threshold_db / 20)
limited = np.clip(audio, -threshold, threshold)
return limited
@staticmethod
def normalize_to_lufs(audio: np.ndarray,
target_lufs: float,
sample_rate: int) -> np.ndarray:
"""
Normalize audio to target LUFS
"""
meter = pyln.Meter(sample_rate)
# Measure current loudness
if audio.ndim > 1:
audio_mono = np.mean(audio, axis=0 if audio.shape[0] > audio.shape[1] else 1)
else:
audio_mono = audio
try:
current_lufs = meter.integrated_loudness(audio_mono)
except:
current_lufs = -23.0
# Calculate gain needed
gain_db = target_lufs - current_lufs
# Apply gain
normalized = SimpleDSP.apply_gain(audio, gain_db)
return normalized
if __name__ == "__main__":
# Example usage
from ai.preset_system import PresetLibrary
# Load preset
library = PresetLibrary()
preset = library.get_preset('edm_club_master')
# Process file
processor = MasteringProcessor()
input_file = "path/to/input.wav"
output_file = "path/to/output_mastered.wav"
try:
results = processor.process_file(input_file, output_file, preset)
print("\nβœ… Processing complete!")
print(f"πŸ“Š Results: {results}")
except Exception as e:
print(f"❌ Error: {e}")