File size: 9,833 Bytes
1ea66d4
 
 
 
 
 
 
 
 
 
 
 
 
ff8acf8
1ea66d4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
"""
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}")