forked from x1aoqv/DSRE---Digital-Sound-Resolution-Enhancer
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDSRE.py
More file actions
2026 lines (1683 loc) · 81 KB
/
DSRE.py
File metadata and controls
2026 lines (1683 loc) · 81 KB
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
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import os
import sys
import traceback
import json
import time
from typing import Optional, Dict, Any, List, Tuple
import subprocess
import soundfile as sf
import tempfile
import numpy as np
from scipy import signal
import librosa
import resampy
from PySide6 import QtCore, QtWidgets
from PySide6.QtGui import QIcon, QTextCursor, QDragEnterEvent, QDropEvent, QKeySequence, QAction
def add_ffmpeg_to_path():
if hasattr(sys, "_MEIPASS"): # Temporary directory after packaging
ffmpeg_dir = os.path.join(sys._MEIPASS, "ffmpeg")
else:
ffmpeg_dir = os.path.join(os.path.dirname(__file__), "ffmpeg")
# Check if ffmpeg directory exists
if not os.path.exists(ffmpeg_dir):
print(f"Warning: FFmpeg directory not found: {ffmpeg_dir}")
print("Please ensure FFmpeg is installed in the 'ffmpeg' directory next to this script.")
else:
ffmpeg_exe = os.path.join(ffmpeg_dir, "ffmpeg.exe")
if not os.path.exists(ffmpeg_exe):
print(f"Warning: ffmpeg.exe not found in: {ffmpeg_dir}")
else:
print(f"FFmpeg found: {ffmpeg_exe}")
os.environ["PATH"] += os.pathsep + ffmpeg_dir
add_ffmpeg_to_path()
def save_wav24_out(in_path, y_out, sr, out_path, fmt="ALAC", normalize=True):
import tempfile, subprocess, numpy as np, soundfile as sf, os
# Input validation
if not os.path.exists(in_path):
raise FileNotFoundError(f"Input file not found: {in_path}")
if y_out is None or y_out.size == 0:
raise ValueError("Empty audio data provided")
if sr <= 0:
raise ValueError(f"Invalid sample rate: {sr}")
if fmt.upper() not in ["ALAC", "FLAC", "MP3"]:
raise ValueError(f"Unsupported format: {fmt}")
# Ensure shape is (samples, channels) for soundfile
if y_out.ndim == 1:
data = y_out[:, None] # Add channel dimension
else:
# Convert from (channels, samples) to (samples, channels)
data = y_out.T if y_out.shape[0] < y_out.shape[1] else y_out
# Convert to float32 and normalize
data = data.astype(np.float32, copy=False)
# Debug: Log data properties before saving
print(f"DEBUG: Audio data shape: {data.shape}, dtype: {data.dtype}")
print(f"DEBUG: Audio data range: {np.min(data):.6f} to {np.max(data):.6f}")
print(f"DEBUG: Audio data RMS: {np.sqrt(np.mean(data**2)):.6f}")
# Check for NaN values
if np.any(np.isnan(data)):
print(f"ERROR: Audio data contains NaN values! This will cause silent output.")
print(f"DEBUG: NaN count: {np.sum(np.isnan(data))} out of {data.size} samples")
raise ValueError("Audio data contains NaN values - cannot save")
# Check for infinite values
if np.any(np.isinf(data)):
print(f"ERROR: Audio data contains infinite values!")
print(f"DEBUG: Inf count: {np.sum(np.isinf(data))} out of {data.size} samples")
raise ValueError("Audio data contains infinite values - cannot save")
if normalize:
peak = float(np.max(np.abs(data)))
if peak > 1.0:
data /= peak
else:
data = np.clip(data, -1.0, 1.0)
# Ensure we have valid audio data
if np.max(np.abs(data)) < 1e-10:
raise ValueError("Audio data is essentially silent - cannot save")
# Temporary WAV file with proper cleanup
tmp_wav = None
cover_tmp = None
try:
tmp_wav = tempfile.NamedTemporaryFile(delete=False, suffix=".wav")
tmp_wav.close()
# Write temporary WAV file
sf.write(tmp_wav.name, data, sr, subtype="FLOAT")
# Verify the temporary file was written correctly
if not os.path.exists(tmp_wav.name):
raise Exception("Failed to create temporary WAV file")
# Check file size
file_size = os.path.getsize(tmp_wav.name)
if file_size < 1000: # Less than 1KB is suspicious
raise Exception(f"Temporary WAV file is too small ({file_size} bytes) - audio data may be invalid")
print(f"DEBUG: Created temporary WAV file: {tmp_wav.name} ({file_size} bytes)")
fmt = fmt.upper()
# Set correct file extension based on format
if fmt == "ALAC":
out_path = os.path.splitext(out_path)[0] + ".m4a"
elif fmt == "FLAC":
out_path = os.path.splitext(out_path)[0] + ".flac"
elif fmt == "MP3":
out_path = os.path.splitext(out_path)[0] + ".mp3"
codec_map = {"ALAC": "alac", "FLAC": "flac", "MP3": "libmp3lame"}
sample_fmt_map = {"ALAC": "s32p", "FLAC": "s32", "MP3": "s16p"} # MP3 uses 16bit planar
if fmt == "ALAC":
cmd = [
"ffmpeg", "-y",
"-i", tmp_wav.name,
"-i", in_path,
"-map", "0:a", # Temporary WAV audio
"-map", "1:v?", # Cover
"-map_metadata", "1",# Metadata
"-c:a", codec_map[fmt],
"-sample_fmt", sample_fmt_map[fmt],
"-c:v", "copy",
out_path
]
elif fmt == "MP3":
# MP3 encoding with high quality settings
cmd = [
"ffmpeg", "-y",
"-i", tmp_wav.name,
"-i", in_path,
"-map", "0:a", # Temporary WAV audio
"-map", "1:v?", # Cover (optional)
"-map_metadata", "1",# Metadata
"-c:a", codec_map[fmt],
"-sample_fmt", sample_fmt_map[fmt],
"-b:a", "320k", # High quality bitrate
"-c:v", "copy",
out_path
]
elif fmt == "FLAC":
# Extract cover image
try:
cover_tmp = tempfile.NamedTemporaryFile(delete=False, suffix=".jpg")
cover_tmp.close()
subprocess.run(
["ffmpeg", "-y", "-i", in_path, "-an", "-c:v", "copy", cover_tmp.name],
check=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL
)
except Exception:
cover_tmp = None
if cover_tmp and os.path.exists(cover_tmp.name):
cmd = [
"ffmpeg", "-y",
"-i", tmp_wav.name, # WAV audio
"-i", in_path, # Metadata source
"-i", cover_tmp.name, # Cover
"-map", "0:a", # Audio
"-map", "2:v", # Cover
"-disposition:v", "attached_pic",
"-map_metadata", "1",# Metadata
"-c:a", codec_map[fmt],
"-sample_fmt", sample_fmt_map[fmt],
"-c:v", "copy",
out_path
]
else:
cmd = [
"ffmpeg", "-y",
"-i", tmp_wav.name,
"-i", in_path,
"-map", "0:a",
"-map_metadata", "1",
"-c:a", codec_map[fmt],
"-sample_fmt", sample_fmt_map[fmt],
out_path
]
try:
print(f"DEBUG: Running FFmpeg command: {' '.join(cmd)}")
result = subprocess.run(cmd, check=True, capture_output=True, text=True)
print(f"DEBUG: FFmpeg completed successfully")
# Verify output file was created and has reasonable size
if not os.path.exists(out_path):
raise Exception(f"Output file was not created: {out_path}")
output_size = os.path.getsize(out_path)
if output_size < 1000: # Less than 1KB is suspicious
raise Exception(f"Output file is too small ({output_size} bytes) - may be silent")
print(f"DEBUG: Output file created successfully: {out_path} ({output_size} bytes)")
except subprocess.CalledProcessError as e:
print(f"DEBUG: FFmpeg stderr: {e.stderr}")
print(f"DEBUG: FFmpeg stdout: {e.stdout}")
raise Exception(f"FFmpeg command failed: {' '.join(cmd)}. Error: {e.stderr}")
except FileNotFoundError as e:
raise Exception(f"FFmpeg not found. Please ensure FFmpeg is installed in the 'ffmpeg' directory next to this script. Error: {e}")
return out_path
finally:
# Cleanup temporary files
if tmp_wav and os.path.exists(tmp_wav.name):
try:
os.remove(tmp_wav.name)
except OSError:
pass
if cover_tmp and os.path.exists(cover_tmp.name):
try:
os.remove(cover_tmp.name)
except OSError:
pass
# ======== ENHANCED AUDIO PROCESSING ALGORITHMS ========
def generate_harmonics(signal_band, fundamental_freq, sr, num_harmonics=5, harmonic_strength=0.3):
"""Generate harmonic content for a frequency band"""
if len(signal_band) == 0:
return signal_band
# Check for NaN values in input
if np.any(np.isnan(signal_band)):
print("WARNING: NaN values in input to generate_harmonics, returning original")
return signal_band
# Create harmonic series
enhanced = signal_band.copy()
for h in range(2, num_harmonics + 2): # 2nd, 3rd, 4th, 5th harmonics
harmonic_freq = fundamental_freq * h
if harmonic_freq < sr / 2: # Below Nyquist
# Create harmonic by frequency shifting
phase_increment = 2 * np.pi * harmonic_freq / sr
# Check for invalid phase increment
if np.isnan(phase_increment) or np.isinf(phase_increment):
print(f"WARNING: Invalid phase increment for harmonic {h}, skipping...")
continue
harmonic_oscillator = np.sin(phase_increment * np.arange(len(signal_band)))
# Check for NaN values in oscillator
if np.any(np.isnan(harmonic_oscillator)):
print(f"WARNING: NaN values in harmonic oscillator {h}, skipping...")
continue
# Modulate the original signal to create harmonic content
harmonic_content = signal_band * harmonic_oscillator * (harmonic_strength / h)
# Check for NaN values in harmonic content
if np.any(np.isnan(harmonic_content)):
print(f"WARNING: NaN values in harmonic content {h}, skipping...")
continue
enhanced += harmonic_content
# Final check for NaN values
if np.any(np.isnan(enhanced)):
print("WARNING: NaN values in enhanced signal, returning original")
return signal_band
return enhanced
def multiband_exciter(x, sr, progress_cb=None, abort_cb=None):
"""
Multi-band harmonic exciter that adds pleasant harmonics and presence
"""
if x.ndim == 1:
x = x[np.newaxis, :]
enhanced = np.zeros_like(x)
# Define frequency bands for enhancement with better frequency range validation
nyquist = sr // 2
bands = []
# Only add bands that are well within the valid frequency range
band_definitions = [
{"name": "Sub Bass", "low": 20, "high": 80, "gain": 1.2, "harmonics": 3, "strength": 0.15},
{"name": "Bass", "low": 80, "high": 250, "gain": 1.4, "harmonics": 4, "strength": 0.25},
{"name": "Low Mid", "low": 250, "high": 800, "gain": 1.6, "harmonics": 5, "strength": 0.35},
{"name": "Mid", "low": 800, "high": 2500, "gain": 1.8, "harmonics": 6, "strength": 0.4},
{"name": "High Mid", "low": 2500, "high": 8000, "gain": 2.2, "harmonics": 4, "strength": 0.45},
{"name": "Presence", "low": 8000, "high": 16000, "gain": 2.8, "harmonics": 3, "strength": 0.3},
{"name": "Air", "low": 16000, "high": min(20000, nyquist - 1000), "gain": 3.5, "harmonics": 2, "strength": 0.2}
]
# Filter bands to only include those that are valid for the current sample rate
for band in band_definitions:
if band["low"] < nyquist and band["high"] < nyquist and band["high"] > band["low"]:
bands.append(band)
else:
print(f"INFO: Skipping band {band['name']} due to sample rate limitations (nyquist={nyquist}Hz)")
if not bands:
print("WARNING: No valid frequency bands for current sample rate, using original signal")
return x
for ch in range(x.shape[0]):
if abort_cb and abort_cb():
break
# Start with original signal instead of zeros
channel_enhanced = x[ch].copy()
for i, band in enumerate(bands):
if abort_cb and abort_cb():
break
if progress_cb:
progress = int((i + ch * len(bands)) * 100 / (len(bands) * x.shape[0]))
progress_cb(progress, f"Processing band {band['name']}")
# Skip if band exceeds Nyquist
if band["low"] >= sr // 2:
continue
# Design bandpass filter with better parameter validation
low_norm = band["low"] / (sr / 2)
high_norm = min(band["high"] / (sr / 2), 0.99)
# Debug: Log frequency range information
print(f"DEBUG: Band {band['name']}: {band['low']}-{band['high']}Hz -> {low_norm:.4f}-{high_norm:.4f} (nyquist={sr//2}Hz)")
# Ensure valid frequency range
if low_norm >= high_norm or low_norm <= 0 or high_norm >= 1.0:
print(f"WARNING: Invalid frequency range for band {band['name']} ({low_norm:.4f}-{high_norm:.4f}), skipping...")
continue
# Ensure minimum frequency separation (very lenient for low frequencies)
if low_norm < 0.01: # Very low frequencies (below 1% of Nyquist)
min_separation = 0.0001 # Very lenient
elif low_norm < 0.1: # Low frequencies (below 10% of Nyquist)
min_separation = 0.001 # Lenient
else:
min_separation = 0.01 # Standard
if high_norm - low_norm < min_separation:
print(f"WARNING: Frequency range too narrow for band {band['name']} ({low_norm:.4f}-{high_norm:.4f}), skipping...")
continue
try:
# Use lower order filter for better stability
filter_order = min(4, max(2, int(4 * (high_norm - low_norm))))
b, a = signal.butter(filter_order, [low_norm, high_norm], btype='band')
# Check for invalid filter coefficients
if np.any(np.isnan(b)) or np.any(np.isnan(a)) or np.any(np.isinf(b)) or np.any(np.isinf(a)):
print(f"WARNING: Invalid filter coefficients for band {band['name']}, skipping...")
continue
# Apply filter with error handling
try:
band_signal = signal.filtfilt(b, a, x[ch])
except Exception as filter_error:
print(f"WARNING: Filter application failed for band {band['name']}: {filter_error}, skipping...")
continue
# Check for NaN values after filtering
if np.any(np.isnan(band_signal)):
print(f"WARNING: NaN values after filtering in band {band['name']}, skipping...")
continue
# Add harmonic excitement
center_freq = (band["low"] + band["high"]) / 2
harmonics_added = generate_harmonics(
band_signal, center_freq, sr,
band["harmonics"], band["strength"]
)
# Check for NaN values after harmonic generation
if np.any(np.isnan(harmonics_added)):
print(f"WARNING: NaN values after harmonic generation in band {band['name']}, skipping...")
continue
# Apply gentle saturation for warmth
saturated = np.tanh(harmonics_added * 1.5) * 0.8
# Check for NaN values after saturation
if np.any(np.isnan(saturated)):
print(f"WARNING: NaN values after saturation in band {band['name']}, skipping...")
continue
# Apply band gain and blend with original
band_enhanced = saturated * band["gain"]
# Check for NaN values in band processing
if np.any(np.isnan(band_enhanced)):
print(f"WARNING: NaN values detected in band {band['name']} processing, skipping...")
continue
# Blend the enhanced band with the channel (subtle enhancement)
channel_enhanced = channel_enhanced + band_enhanced * 0.3
except Exception as e:
# Skip problematic bands but continue processing
continue
enhanced[ch] = channel_enhanced
return enhanced
def psychoacoustic_enhancer(x, sr, progress_cb=None, abort_cb=None):
"""
Psychoacoustic enhancement targeting human hearing sensitivity
"""
if x.ndim == 1:
x = x[np.newaxis, :]
enhanced = np.zeros_like(x)
# A-weighting inspired frequency response (emphasizes 2-5kHz)
critical_bands = [
{"freq": 1000, "boost": 1.8, "q": 1.5}, # Fundamental vocal range
{"freq": 2500, "boost": 2.5, "q": 2.0}, # Presence and clarity
{"freq": 4000, "boost": 3.0, "q": 1.8}, # Maximum hearing sensitivity
{"freq": 6000, "boost": 2.2, "q": 1.2}, # Consonant definition
{"freq": 10000, "boost": 1.6, "q": 0.8}, # Air and sparkle
]
for ch in range(x.shape[0]):
if abort_cb and abort_cb():
break
channel_enhanced = x[ch].copy()
for i, band in enumerate(critical_bands):
if abort_cb and abort_cb():
break
if progress_cb:
progress = int((i + ch * len(critical_bands)) * 100 / (len(critical_bands) * x.shape[0]))
progress_cb(progress, f"Psychoacoustic enhancement at {band['freq']}Hz")
# Skip if frequency exceeds Nyquist
if band["freq"] >= sr // 2:
continue
try:
# Create bell filter (peaking EQ)
freq_norm = band["freq"] / (sr / 2)
if freq_norm >= 0.99:
continue
# Design peaking filter
# Using a simple approach since scipy doesn't have direct peaking filter
w = 2 * np.pi * band["freq"] / sr
cosw = np.cos(w)
sinw = np.sin(w)
alpha = sinw / (2 * band["q"])
A = 10**(band["boost"]/40) # Convert dB to linear
# Peaking filter coefficients
b0 = 1 + alpha * A
b1 = -2 * cosw
b2 = 1 - alpha * A
a0 = 1 + alpha / A
a1 = -2 * cosw
a2 = 1 - alpha / A
# Normalize
b = np.array([b0, b1, b2]) / a0
a = np.array([1, a1/a0, a2/a0])
# Apply filter
filtered = signal.lfilter(b, a, x[ch])
# Blend with original (subtle enhancement)
blend_factor = 0.4
channel_enhanced = channel_enhanced * (1 - blend_factor) + filtered * blend_factor
except Exception as e:
continue
enhanced[ch] = channel_enhanced
return enhanced
def stereo_width_enhancer(x, width_factor=1.4):
"""
Enhance stereo width using M/S processing
"""
if x.shape[0] != 2: # Only works on stereo
return x
left = x[0]
right = x[1]
# Convert to Mid/Side
mid = (left + right) / 2
side = (left - right) / 2
# Enhance side channel for wider stereo image
side_enhanced = side * width_factor
# Convert back to L/R
left_enhanced = mid + side_enhanced
right_enhanced = mid - side_enhanced
return np.array([left_enhanced, right_enhanced])
def dynamic_range_enhancer(x, ratio=1.3, attack_ms=5, release_ms=50, sr=44100):
"""
Gentle upward expansion to increase dynamic range and liveliness
"""
# Convert ms to samples
attack_samples = int(attack_ms * sr / 1000)
release_samples = int(release_ms * sr / 1000)
enhanced = np.zeros_like(x)
for ch in range(x.shape[0]):
signal_ch = x[ch]
# Calculate envelope
envelope = np.abs(signal_ch)
# Smooth envelope
if len(envelope) > 0:
# Simple envelope follower
smoothed_env = np.zeros_like(envelope)
current_env = envelope[0]
for i in range(len(envelope)):
if envelope[i] > current_env:
# Attack
current_env += (envelope[i] - current_env) / attack_samples
else:
# Release
current_env -= (current_env - envelope[i]) / release_samples
smoothed_env[i] = current_env
# Apply upward expansion
threshold = 0.1 # -20dB
gain = np.ones_like(smoothed_env)
# Only expand signals above threshold
above_threshold = smoothed_env > threshold
gain[above_threshold] = (smoothed_env[above_threshold] / threshold) ** (ratio - 1)
# Limit maximum gain
gain = np.clip(gain, 1.0, 3.0)
enhanced[ch] = signal_ch * gain
return enhanced
def enhanced_audio_algorithm(
x: np.ndarray,
sr: int,
enhancement_strength: float = 0.7,
harmonic_intensity: float = 0.6,
stereo_width: float = 1.3,
dynamic_enhancement: float = 1.2,
progress_cb: Optional[callable] = None,
abort_cb: Optional[callable] = None,
) -> np.ndarray:
"""
Complete enhanced audio processing algorithm
Args:
x: Input audio data (channels, samples)
sr: Sample rate in Hz
enhancement_strength: Overall enhancement strength (0.1-1.0)
harmonic_intensity: Harmonic generation intensity (0.1-1.0)
stereo_width: Stereo width enhancement (1.0-2.0)
dynamic_enhancement: Dynamic range enhancement (1.0-2.0)
progress_cb: Optional callback for progress updates
abort_cb: Optional callback to check for abort signal
Returns:
Enhanced audio data with same shape as input
"""
# Input validation
if x is None or x.size == 0:
raise ValueError("Input audio data is empty or None")
if np.max(np.abs(x)) < 1e-10:
raise ValueError("Input audio data appears to be silent")
# Check for NaN values in input
if np.any(np.isnan(x)):
raise ValueError("Input audio data contains NaN values")
# Check for infinite values in input
if np.any(np.isinf(x)):
raise ValueError("Input audio data contains infinite values")
if progress_cb:
progress_cb(0, "Starting enhancement process")
# Step 1: Multi-band harmonic excitement
if progress_cb:
progress_cb(10, "Applying multi-band harmonic excitement")
enhanced = multiband_exciter(x, sr,
lambda p, desc: progress_cb(10 + p//4, desc) if progress_cb else None,
abort_cb)
# Check for NaN values after multiband processing
if np.any(np.isnan(enhanced)):
print("ERROR: NaN values detected after multiband processing!")
print("INFO: Falling back to simple enhancement approach...")
# Fallback: Simple gentle enhancement without complex filtering
enhanced = x.copy()
for ch in range(x.shape[0]):
# Simple gentle saturation and harmonic enhancement
signal_ch = x[ch]
# Add gentle harmonic content
enhanced_ch = signal_ch.copy()
for harmonic in [2, 3, 4]:
if harmonic * 1000 < sr // 2: # Ensure harmonic is below Nyquist
phase = 2 * np.pi * harmonic * 1000 / sr * np.arange(len(signal_ch))
harmonic_content = signal_ch * np.sin(phase) * 0.1
enhanced_ch += harmonic_content
# Gentle saturation
enhanced_ch = np.tanh(enhanced_ch * 1.2) * 0.9
# Blend with original
enhanced[ch] = signal_ch * 0.7 + enhanced_ch * 0.3
if abort_cb and abort_cb():
return x
# Step 2: Psychoacoustic enhancement
if progress_cb:
progress_cb(35, "Applying psychoacoustic enhancement")
psycho_enhanced = psychoacoustic_enhancer(enhanced, sr,
lambda p, desc: progress_cb(35 + p//4, desc) if progress_cb else None,
abort_cb)
# Check for NaN values after psychoacoustic processing
if np.any(np.isnan(psycho_enhanced)):
print("ERROR: NaN values detected after psychoacoustic processing!")
return x # Return original audio
if abort_cb and abort_cb():
return x
# Step 3: Dynamic range enhancement
if progress_cb:
progress_cb(60, "Enhancing dynamic range")
dynamic_enhanced = dynamic_range_enhancer(psycho_enhanced, dynamic_enhancement, sr=sr)
# Check for NaN values after dynamic range processing
if np.any(np.isnan(dynamic_enhanced)):
print("ERROR: NaN values detected after dynamic range processing!")
return x # Return original audio
if abort_cb and abort_cb():
return x
# Step 4: Stereo width enhancement (if stereo)
if progress_cb:
progress_cb(75, "Enhancing stereo width")
if x.shape[0] == 2:
stereo_enhanced = stereo_width_enhancer(dynamic_enhanced, stereo_width)
else:
stereo_enhanced = dynamic_enhanced
if abort_cb and abort_cb():
return x
# Step 5: Final blend and normalization
if progress_cb:
progress_cb(90, "Final processing and normalization")
# Ensure we have valid audio data
if np.max(np.abs(stereo_enhanced)) < 1e-10:
# If enhanced signal is essentially silent, return original
final = x.copy()
else:
# Blend enhanced with original - ensure we don't lose the original signal
blend_factor = min(enhancement_strength, 0.8) # Cap at 80% to preserve original
final = x * (1 - blend_factor) + stereo_enhanced * blend_factor
# Gentle limiting to prevent clipping
peak = np.max(np.abs(final))
if peak > 0.95:
final = final * (0.95 / peak)
# Ensure we have some audio content
if np.max(np.abs(final)) < 1e-10:
# If final result is silent, return original
final = x.copy()
if progress_cb:
progress_cb(100, "Enhancement complete")
return final
# ======== Custom List Widget with Drag & Drop ========
class DragDropListWidget(QtWidgets.QListWidget):
def __init__(self, parent=None):
super().__init__(parent)
self.setAcceptDrops(True)
self.setDragDropMode(QtWidgets.QAbstractItemView.DragDropMode.DropOnly)
self.setDefaultDropAction(QtCore.Qt.DropAction.CopyAction)
# Add placeholder text
self.placeholder_item = QtWidgets.QListWidgetItem("Drag and drop audio files here...")
self.placeholder_item.setFlags(QtCore.Qt.ItemFlag.NoItemFlags) # Make it non-selectable
self.addItem(self.placeholder_item)
# Enable drag and drop explicitly
self.setAcceptDrops(True)
def dragEnterEvent(self, event: QDragEnterEvent):
if event.mimeData().hasUrls():
urls = event.mimeData().urls()
audio_extensions = {'.wav', '.mp3', '.m4a', '.flac', '.ogg', '.aiff', '.aif', '.aac', '.wma', '.mka'}
for url in urls:
file_path = url.toLocalFile()
if os.path.isfile(file_path):
_, ext = os.path.splitext(file_path.lower())
if ext in audio_extensions:
event.acceptProposedAction()
return
event.ignore()
def dragMoveEvent(self, event):
if event.mimeData().hasUrls():
event.acceptProposedAction()
else:
event.ignore()
def dropEvent(self, event: QDropEvent):
if event.mimeData().hasUrls():
urls = event.mimeData().urls()
audio_extensions = {'.wav', '.mp3', '.m4a', '.flac', '.ogg', '.aiff', '.aif', '.aac', '.wma', '.mka'}
# Remove placeholder if it exists
if self.count() == 1 and self.item(0) == self.placeholder_item:
self.takeItem(0)
for url in urls:
file_path = url.toLocalFile()
if os.path.isfile(file_path):
_, ext = os.path.splitext(file_path.lower())
if ext in audio_extensions:
# Add file if not already in list
if not self.findItems(file_path, QtCore.Qt.MatchFlag.MatchExactly):
self.addItem(file_path)
event.acceptProposedAction()
else:
event.ignore()
# ======== Background Worker Thread ========
class DSREWorker(QtCore.QThread):
sig_log = QtCore.Signal(str) # Text log
sig_file_progress = QtCore.Signal(int, int, str) # Current file progress (cur, total, filename)
sig_step_progress = QtCore.Signal(int, str) # Single file internal progress(0~100), filename
sig_overall_progress = QtCore.Signal(int, int) # Overall progress (done, total)
sig_file_done = QtCore.Signal(str, str) # Single file completed (in_path, out_path)
sig_error = QtCore.Signal(str, str) # Error (filename, err_msg)
sig_finished = QtCore.Signal() # All completed
sig_retry_available = QtCore.Signal(str, str) # Retry available (filename, error)
sig_processing_stats = QtCore.Signal(dict) # Processing statistics
def __init__(self, files, output_dir, params, parent=None):
super().__init__(parent)
self.files = files
self.output_dir = output_dir
self.params = params
self._abort = False
self.processing_stats = {
'total_files': len(files),
'processed_files': 0,
'failed_files': 0,
'total_size_mb': 0,
'processed_size_mb': 0,
'start_time': None,
'estimated_remaining': 0
}
def abort(self):
self._abort = True
def get_file_size_mb(self, file_path: str) -> float:
"""Get file size in MB"""
try:
return os.path.getsize(file_path) / (1024 * 1024)
except OSError:
return 0.0
def estimate_processing_time(self, file_size_mb: float) -> float:
"""Estimate processing time based on file size (seconds)"""
# Rough estimation: ~1MB per second for processing
return max(1.0, file_size_mb * 0.5)
def process_audio_chunked(self, y: np.ndarray, sr: int, chunk_size: int = 44100 * 10) -> np.ndarray:
"""Process audio in chunks for large files"""
if len(y) <= chunk_size:
return enhanced_audio_algorithm(
y, sr,
enhancement_strength=float(self.params["decay"]),
harmonic_intensity=float(self.params["m"]) / 16.0,
progress_cb=None,
abort_cb=lambda: self._abort
)
# Process in chunks
chunks = []
total_chunks = (len(y) + chunk_size - 1) // chunk_size
for i in range(0, len(y), chunk_size):
if self._abort:
break
chunk = y[i:i + chunk_size]
if len(chunk) > 0:
processed_chunk = enhanced_audio_algorithm(
chunk, sr,
enhancement_strength=float(self.params["decay"]),
harmonic_intensity=float(self.params["m"]) / 16.0,
progress_cb=None,
abort_cb=lambda: self._abort
)
chunks.append(processed_chunk)
return np.concatenate(chunks) if chunks else y
def check_audio_file_format(self, file_path: str) -> bool:
"""Check if the audio file format is supported"""
try:
import soundfile as sf
with sf.SoundFile(file_path) as f:
# Just check if we can open the file
return True
except Exception:
return False
def load_audio_with_recovery(self, file_path: str) -> Tuple[np.ndarray, int]:
"""Load audio with multiple fallback strategies for corrupted files"""
import warnings
# Check file format first
if not self.check_audio_file_format(file_path):
self.sig_log.emit(f"WARNING: Audio file format may not be fully supported: {os.path.basename(file_path)}")
# Suppress librosa warnings for cleaner output
with warnings.catch_warnings():
warnings.filterwarnings("ignore", category=UserWarning, module="librosa")
warnings.filterwarnings("ignore", category=FutureWarning, module="librosa")
try:
# First attempt: Normal loading with explicit format detection
self.sig_log.emit(f"Loading audio: {os.path.basename(file_path)}")
y, sr = librosa.load(file_path, mono=False, sr=None)
# Validate loaded audio
if y is None or y.size == 0:
raise ValueError("Empty audio data loaded")
self.sig_log.emit(f"Successfully loaded: {y.shape}, {sr}Hz")
return y, sr
except Exception as e1:
self.sig_log.emit(f"Primary load failed: {str(e1)[:100]}...")
try:
# Second attempt: Force mono and resample
self.sig_log.emit(f"Attempting mono recovery...")
y, sr = librosa.load(file_path, mono=True, sr=None)
if y is None or y.size == 0:
raise ValueError("Empty audio data loaded")
self.sig_log.emit(f"Mono recovery successful: {y.shape}, {sr}Hz")
return y, sr
except Exception as e2:
try:
# Third attempt: Use soundfile directly with error handling
self.sig_log.emit(f"Attempting direct soundfile loading...")
import soundfile as sf
y, sr = sf.read(file_path, always_2d=True)
if y is None or y.size == 0:
raise ValueError("Empty audio data loaded")
if y.ndim == 1:
y = y[:, np.newaxis]
self.sig_log.emit(f"Soundfile loading successful: {y.shape}, {sr}Hz")
return y.T, sr # Convert to (channels, samples)
except Exception as e3:
try:
# Fourth attempt: Load with different parameters
self.sig_log.emit(f"Attempting alternative loading parameters...")
y, sr = librosa.load(file_path, mono=False, sr=44100) # Force 44.1kHz
if y is None or y.size == 0:
raise ValueError("Empty audio data loaded")
self.sig_log.emit(f"Alternative loading successful: {y.shape}, {sr}Hz")
return y, sr
except Exception as e4:
# Final attempt: Raise error instead of creating silence
self.sig_log.emit(f"All recovery methods failed for {os.path.basename(file_path)}")
self.sig_log.emit(f"Error details: {str(e1)[:50]}, {str(e2)[:50]}, {str(e3)[:50]}, {str(e4)[:50]}")
raise Exception(f"Unable to load audio file {os.path.basename(file_path)}. All recovery methods failed.")
def categorize_error(self, error: Exception) -> str:
"""Categorize errors for better retry handling"""
error_str = str(error).lower()
# Fatal errors - don't retry
if any(keyword in error_str for keyword in ['permission denied', 'access denied', 'disk full', 'no space']):
return "fatal"
# I/O errors - retry with longer delay
if any(keyword in error_str for keyword in ['file not found', 'no such file', 'network', 'timeout', 'connection']):
return "io"
# Memory errors - retry with chunked processing
if any(keyword in error_str for keyword in ['memory', 'out of memory', 'allocation']):
return "memory"
# Audio format errors - retry with different parameters
if any(keyword in error_str for keyword in ['format', 'codec', 'sample rate', 'bitrate']):
return "format"
# FFmpeg errors - retry
if any(keyword in error_str for keyword in ['ffmpeg', 'encoder', 'decoder']):
return "ffmpeg"
# Default - retry
return "retry"
def run(self):
total = len(self.files)
done = 0
self.processing_stats['start_time'] = time.time()
# Calculate total file sizes for better progress estimation
total_size = sum(self.get_file_size_mb(f) for f in self.files)
self.processing_stats['total_size_mb'] = total_size
self.sig_overall_progress.emit(done, total)
self.sig_processing_stats.emit(self.processing_stats.copy())
for idx, in_path in enumerate(self.files, start=1):
if self._abort:
break
fname = os.path.basename(in_path)
file_size_mb = self.get_file_size_mb(in_path)
self.sig_file_progress.emit(idx, total, fname)
self.sig_step_progress.emit(0, fname)
# Estimate processing time
estimated_time = self.estimate_processing_time(file_size_mb)
self.sig_log.emit(f"Processing {fname} ({file_size_mb:.1f}MB, est. {estimated_time:.1f}s)")
retry_count = 0
max_retries = 3
while retry_count <= max_retries:
try:
# Read with error recovery
self.sig_log.emit(f"Loading: {in_path}")
y, sr = self.load_audio_with_recovery(in_path)
# Align to (ch, n)
if y.ndim == 1:
y = y[np.newaxis, :]
# Resample
target_sr = int(self.params["target_sr"])
if sr != target_sr:
self.sig_log.emit(f"Processing: {fname}: {sr} -> {target_sr}")
y = resampy.resample(y, sr, target_sr, filter='kaiser_fast')