-
Notifications
You must be signed in to change notification settings - Fork 2
/
Program.cs
2200 lines (1921 loc) · 86.6 KB
/
Program.cs
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
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Globalization;
using DSPUtil;
// Copyright (c) 2006-2009 by Hugh Pyle, inguzaudio.com
// this code is particularly ugly, sorry to anyone trying to read it :-(
// there are lots of "quote"experimental"quote" and otherwise broken things
namespace ImpulsePrep
{
/// <summary>
/// ImpulsePrep
/// commandline app for impulse-response preparation from sweep recordings
/// and DRC for creation of the correction filters
/// </summary>
class Program
{
static char slash = Path.DirectorySeparatorChar;
// config
static int _nInFiles = 0;
static string _thisFolder;
static string _impulsesFolder;
static List<string> _impulseFiles = new List<string>();
static List<string> _filterFiles = new List<string>();
static List<string> _tempFiles = new List<string>();
static int _filterLen = 32768;
static bool _noNorm = false;
static bool _noDRC = false;
static bool _noSkew = false;
static bool _dbl = false;
static bool _pcm = false;
static bool _split = false;
static bool _keepTempFiles = false;
static bool _copy;
static bool _env = false;
static int _fmin = 0;
static int _fmax = int.MaxValue;
static bool _fminSpecified = false;
static bool _fmaxSpecified = false;
static bool _returnAll = false;
static int _power = 0;
static bool _doDirectFilters = false;
static bool _noOverrideDRC = false;
static bool _noSubsonicFilter = false;
static int _peakPosL;
static int _peakPosR;
static int _refchannel = -1;
static double _gain = Double.NaN; // dB. NaN means normalize instead.
// state
static uint _sampleRate = 44100;
static void Main(string[] args)
{
// Find where this executable is launched from
string[] cargs = Environment.GetCommandLineArgs();
_thisFolder = Path.GetDirectoryName(cargs[0]);
if (String.IsNullOrEmpty(_thisFolder))
{
_thisFolder = Environment.CurrentDirectory;
}
string appData = Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData);
_impulsesFolder = Path.GetFullPath(Path.Combine(appData, "InguzEQ" + slash + "Impulses" + slash));
string[] inFiles = new string[4];
string inL = "";
string inR = "";
if (!DisplayInfo())
{
return;
}
bool ok = (args.Length > 0);
bool longUsage = false;
for (int j = 0; ok && j < args.Length; j++)
{
string arg = args[j];
switch (args[j].ToUpperInvariant())
{
case "/?":
case "-?":
case "/H":
case "/HELP":
ok = false;
longUsage = true;
break;
case "/L":
case "/0":
inFiles[0] = args[++j];
_nInFiles = Math.Max(_nInFiles, 1);
break;
case "/R":
case "/1":
inFiles[1] = args[++j];
_nInFiles = Math.Max(_nInFiles, 2);
break;
case "/2":
inFiles[2] = args[++j];
_nInFiles = Math.Max(_nInFiles, 3);
break;
case "/3":
inFiles[3] = args[++j];
_nInFiles = Math.Max(_nInFiles, 4);
break;
case "/LENGTH":
_filterLen = int.Parse(args[++j], CultureInfo.InvariantCulture);
if (_filterLen < 16)
{
throw new Exception("Length is too small.");
}
break;
case "/DBL":
_dbl = true;
break;
case "/PCM":
_pcm = true;
break;
case "/NODRC":
_noDRC = true;
break;
case "/NOSKEW":
_noSkew = true;
break;
case "/NONORM":
// No normalization of the impulse response (undocumented)
_noNorm = true;
break;
case "/SPLIT":
_split = true;
break;
case "/COPY":
_copy = true;
break;
case "/GAIN":
_gain = double.Parse(args[++j], CultureInfo.InvariantCulture);
break;
case "/ALL":
// Returns negative-time components as part of the impulse response
// (experimental, to be used for THD measurement)
_returnAll = true;
break;
case "/POWER":
// Raises sweep to power n
// (experimental, to be used for THD measurement)
_power = int.Parse(args[++j], CultureInfo.InvariantCulture);
break;
case "/FMIN":
// (experimental, i.e. broken)
_fmin = int.Parse(args[++j], CultureInfo.InvariantCulture);
_fminSpecified = true;
break;
case "/FMAX":
// (experimental, i.e. broken)
_fmax = int.Parse(args[++j], CultureInfo.InvariantCulture);
_fmaxSpecified = true;
break;
case "/DIRECT":
// Create filtered (direct-sound) filters
_doDirectFilters = true;
break;
case "/NOSUB":
// Don't apply subsonic filter to the impulse response
_noSubsonicFilter = true;
break;
case "/NOOVER":
// Don't override DRC's settings for filter type and length
_noOverrideDRC = true;
break;
case "/KEEPTEMP":
// Undocumented
_keepTempFiles = true;
break;
case "/REFCH":
// Override the reference-channel detection
_refchannel = int.Parse(args[++j], CultureInfo.InvariantCulture);
if (_refchannel<0 || _refchannel > _nInFiles - 1)
{
throw new Exception(String.Format("RefCh can only be from 0 to {0}.", _nInFiles-1));
}
break;
case "/ENV":
// Undocumented. Save the Hilbert envelope
_env = true;
break;
case "-":
// ignore
break;
default:
ok = false;
break;
}
}
if (!ok)
{
DisplayUsage(longUsage);
}
else
{
try
{
if (!_noDRC)
{
if (!File.Exists(GetDRCExe()))
{
stderr.WriteLine("Denis Sbragion's DRC (http://drc-fir.sourceforge.net/) was not found.");
stderr.WriteLine("Only the impulse response will be calculated, not correction filters.");
stderr.WriteLine("");
_noDRC = true;
}
}
if (!_noDRC)
{
FileInfo[] drcfiles = new DirectoryInfo(_thisFolder).GetFiles("*.drc");
if (drcfiles.Length == 0)
{
stderr.WriteLine("No .drc files were found in the current folder.");
stderr.WriteLine("Only the impulse response will be calculated, not correction filters.");
stderr.WriteLine("");
_noDRC = true;
}
}
for(int i=0; i<_nInFiles; i++)
{
string inFile = inFiles[i];
if (String.IsNullOrEmpty(inFile))
{
stderr.WriteLine("Error: The {0} input file was not specified.", FileDescription(i));
return;
}
if (!File.Exists(inFile))
{
stderr.WriteLine("Error: The {0} input file {1} was not found.", FileDescription(i), inFile);
return;
}
for (int j = 0; j < i; j++)
{
if (inFile.Equals(inFiles[j]))
{
stderr.WriteLine("Warning: The same input file ({0}) was specified for both {1} and {2}!", inFile, FileDescription(j), FileDescription(i));
//stderr.WriteLine();
}
}
}
// Temporary
if (_nInFiles != 2)
{
stderr.WriteLine("Error: Two input files must be specified.");
return;
}
inL = inFiles[0];
inR = inFiles[1];
// end temporary
uint sampleRate;
List<SoundObj> impulses;
List<ISoundObj> filteredImpulses;
List<string> impDirects;
List<Complex[]> impulseFFTs;
List<double> maxs;
SoundObj impulseL;
SoundObj impulseR;
ISoundObj filteredImpulseL = null;
ISoundObj filteredImpulseR = null;
string impDirectL = null;
string impDirectR = null;
Complex[] impulseLFFT;
Complex[] impulseRFFT;
WaveWriter writer;
ISoundObj buff;
double g;
if (!_keepTempFiles)
{
_tempFiles.Add("rps.pcm");
_tempFiles.Add("rtc.pcm");
}
// Find the left impulse
stderr.WriteLine("Processing left measurement ({0})...", inL);
impulseL = Deconvolve(inL, out impulseLFFT, out _peakPosL);
sampleRate = impulseL.SampleRate;
_sampleRate = sampleRate;
double peakM = Math.Round(MathUtil.Metres(_peakPosL, sampleRate), 2);
double peakFt = Math.Round(MathUtil.Feet(_peakPosL, sampleRate), 2);
stderr.WriteLine(" Impulse peak at sample {0} ({1}m, {2}ft)", _peakPosL, peakM, peakFt);
// Write to PCM
string impFileL = Path.GetFileNameWithoutExtension(inL) + "_imp" + ".pcm";
if (!_keepTempFiles)
{
_tempFiles.Add(impFileL);
}
writer = new WaveWriter(impFileL);
writer.Input = impulseL;
writer.Format = WaveFormat.IEEE_FLOAT;
writer.BitsPerSample = 32;
writer.SampleRate = _sampleRate;
writer.Raw = true;
writer.Run();
writer.Close();
// Write the impulseFFT to disk
int L = impulseLFFT.Length;
string impTempL = Path.GetFileNameWithoutExtension(inL) + "_imp" + ".dat";
_tempFiles.Add(impTempL);
writer = new WaveWriter(impTempL);
writer.Input = new CallbackSource(2, sampleRate, delegate(long j)
{
if (j >= L / 2)
{
return null;
}
Complex si = impulseLFFT[j]; // +impulseLFFT[L - j - 1];
ISample s = new Sample2();
s[0] = si.Magnitude;
s[1] = si.Phase / Math.PI;
return s;
});
writer.Format = WaveFormat.IEEE_FLOAT;
writer.BitsPerSample = 32;
writer.SampleRate = _sampleRate;
writer.Raw = false;
writer.Run();
writer.Close();
writer = null;
impulseLFFT = null;
GC.Collect();
if (_doDirectFilters)
{
// Sliding low-pass filter over the impulse
stderr.WriteLine(" Filtering...");
filteredImpulseL = SlidingLowPass(impulseL, _peakPosL);
// Write PCM for the filtered impulse
impDirectL = Path.GetFileNameWithoutExtension(inL) + "_impfilt" + ".pcm";
if (!_keepTempFiles)
{
_tempFiles.Add(impDirectL);
}
writer = new WaveWriter(impDirectL);
writer.Input = filteredImpulseL;
writer.Format = WaveFormat.IEEE_FLOAT;
writer.SampleRate = _sampleRate;
writer.BitsPerSample = 32;
writer.Raw = false;
writer.Run();
writer.Close();
writer = null;
filteredImpulseL.Reset();
}
GC.Collect();
stderr.WriteLine(" Deconvolution: left impulse done.");
stderr.WriteLine();
// Find the right impulse
stderr.WriteLine("Processing right measurement ({0})...", inR);
impulseR = Deconvolve(inR, out impulseRFFT, out _peakPosR);
peakM = Math.Round(MathUtil.Metres(_peakPosR, sampleRate), 2);
peakFt = Math.Round(MathUtil.Feet(_peakPosR, sampleRate), 2);
stderr.WriteLine(" Impulse peak at sample {0} ({1}m, {2}ft)", _peakPosR, peakM, peakFt);
// Write to PCM
string impFileR = Path.GetFileNameWithoutExtension(inR) + "_imp" + ".pcm";
if (!_keepTempFiles)
{
_tempFiles.Add(impFileR);
}
writer = new WaveWriter(impFileR);
writer.Input = impulseR;
writer.Format = WaveFormat.IEEE_FLOAT;
writer.BitsPerSample = 32;
writer.SampleRate = _sampleRate;
writer.Raw = true;
writer.Run();
writer.Close();
// Write the impulseFFT magnitude to disk
L = impulseRFFT.Length;
string impTempR = Path.GetFileNameWithoutExtension(inR) + "_imp" + ".dat";
_tempFiles.Add(impTempR);
writer = new WaveWriter(impTempR);
writer.Input = new CallbackSource(2, impulseR.SampleRate, delegate(long j)
{
if (j >= L / 2)
{
return null;
}
Complex si = impulseRFFT[j]; // +impulseRFFT[L - j - 1];
ISample s = new Sample2();
s[0] = si.Magnitude;
s[1] = si.Phase / Math.PI;
return s;
});
writer.Format = WaveFormat.IEEE_FLOAT;
writer.BitsPerSample = 32;
writer.SampleRate = _sampleRate;
writer.Raw = false;
writer.Run();
writer.Close();
writer = null;
impulseRFFT = null;
GC.Collect();
if (_doDirectFilters)
{
// Sliding low-pass filter over the impulse
stderr.WriteLine(" Filtering...");
filteredImpulseR = SlidingLowPass(impulseR, _peakPosR);
// Write PCM for the filtered impulse
impDirectR = Path.GetFileNameWithoutExtension(inR) + "_impfilt" + ".pcm";
if (!_keepTempFiles)
{
_tempFiles.Add(impDirectR);
}
writer = new WaveWriter(impDirectR);
writer.Input = filteredImpulseR;
writer.Format = WaveFormat.IEEE_FLOAT;
writer.BitsPerSample = 32;
writer.SampleRate = _sampleRate;
writer.Raw = false;
writer.Run();
writer.Close();
writer = null;
filteredImpulseR.Reset();
}
GC.Collect();
stderr.WriteLine(" Deconvolution: right impulse done.");
stderr.WriteLine();
// Join the left and right impulse files (truncated at 65536) into a WAV
// and normalize loudness for each channel
stderr.WriteLine("Splicing and normalizing (1)");
ChannelSplicer longstereoImpulse = new ChannelSplicer();
// (Don't normalize each channel's volume separately if _returnAll, it's just too expensive)
if (_returnAll)
{
buff = impulseL;
}
else
{
buff = new SoundBuffer(new SampleBuffer(impulseL).Subset(0, 131071));
g = Loudness.WeightedVolume(buff);
(buff as SoundBuffer).ApplyGain(1 / g);
}
longstereoImpulse.Add(buff);
if (_returnAll)
{
buff = impulseR;
}
else
{
buff = new SoundBuffer(new SampleBuffer(impulseR).Subset(0, 131071));
g = Loudness.WeightedVolume(buff);
(buff as SoundBuffer).ApplyGain(1 / g);
}
longstereoImpulse.Add(buff);
ISoundObj stereoImpulse = longstereoImpulse;
_impulseFiles.Add("Impulse_Response_Measured.wav: stereo impulse response from measurements");
writer = new WaveWriter("Impulse_Response_Measured.wav");
writer.Input = longstereoImpulse;
writer.Format = WaveFormat.IEEE_FLOAT;
writer.BitsPerSample = 32;
writer.SampleRate = _sampleRate;
writer.Normalization = -1;
writer.Raw = false;
writer.Run();
writer.Close();
writer = null;
if (_env)
{
// Also save the Hilbert envelope
HilbertEnvelope env = new HilbertEnvelope(8191);
env.Input = longstereoImpulse;
_impulseFiles.Add("Impulse_Response_Envelope.wav: Hilbert envelope of the impulse response");
writer = new WaveWriter("Impulse_Response_Envelope.wav");
writer.Input = env;
writer.Format = WaveFormat.IEEE_FLOAT;
writer.BitsPerSample = 32;
writer.SampleRate = _sampleRate;
writer.Normalization = -1;
writer.Raw = false;
writer.Run();
writer.Close();
writer = null;
}
if (_dbl)
{
// Create DBL files for Acourate
_impulseFiles.Add("PulseL.dbl: impulse response, raw data (64-bit float), left channel ");
_impulseFiles.Add("PulseR.dbl: impulse response, raw data (64-bit float), right channel");
_impulseFiles.Add(" (use skew=" + (_peakPosL - _peakPosR) + " for time alignment)");
WriteImpulseDBL(stereoImpulse, "PulseL.dbl", "PulseR.dbl");
}
if (_pcm)
{
// Create PCM files for Octave (etc)
_impulseFiles.Add("LUncorrected.pcm: impulse response, raw data (32-bit float), left channel");
_impulseFiles.Add("RUncorrected.pcm: impulse response, raw data (32-bit float), right channel");
WriteImpulsePCM(stereoImpulse, "LUncorrected.pcm", "RUncorrected.pcm");
}
stereoImpulse = null;
longstereoImpulse = null;
buff = null;
GC.Collect();
if (_doDirectFilters)
{
// Same for the filtered impulse response
stderr.WriteLine("Splicing and normalizing (2)");
ChannelSplicer longstereoImpulseF = new ChannelSplicer();
buff = new SoundBuffer(new SampleBuffer(filteredImpulseL).Subset(0, 131071));
double gL = Loudness.WeightedVolume(buff);
(buff as SoundBuffer).ApplyGain(1 / gL);
longstereoImpulseF.Add(buff);
FilterProfile lfgDirectL = new FilterProfile(buff, 0.5);
buff = new SoundBuffer(new SampleBuffer(filteredImpulseR).Subset(0, 131071));
double gR = Loudness.WeightedVolume(buff);
(buff as SoundBuffer).ApplyGain(1 / gR);
longstereoImpulseF.Add(buff);
FilterProfile lfgDirectR = new FilterProfile(buff, 0.5);
_impulseFiles.Add("Impulse_Response_Filtered.wav: approximation to direct-sound impulse response");
writer = new WaveWriter("Impulse_Response_Filtered.wav");
writer.Input = longstereoImpulseF;
writer.Format = WaveFormat.IEEE_FLOAT;
writer.BitsPerSample = 32;
writer.SampleRate = _sampleRate;
writer.Normalization = -1;
writer.Raw = false;
writer.Run();
writer.Close();
double gg = writer.Gain;
writer = null;
longstereoImpulseF = null;
ChannelSplicer longstereoImpulseD = new ChannelSplicer();
Mixer diffuse = new Mixer();
diffuse.Add(impulseL, 1.0);
diffuse.Add(filteredImpulseL, -1.0);
buff = new SoundBuffer(new SampleBuffer(diffuse).Subset(0, 131071));
(buff as SoundBuffer).ApplyGain(1 / gL);
longstereoImpulseD.Add(buff);
FilterProfile lfgDiffuseL = new FilterProfile(buff, 0.5);
diffuse = new Mixer();
diffuse.Add(impulseR, 1.0);
diffuse.Add(filteredImpulseR, -1.0);
buff = new SoundBuffer(new SampleBuffer(diffuse).Subset(0, 131071));
(buff as SoundBuffer).ApplyGain(1 / gR);
longstereoImpulseD.Add(buff);
FilterProfile lfgDiffuseR = new FilterProfile(buff, 0.5);
_impulseFiles.Add("Impulse_Response_Diffuse.wav: approximation to diffuse-field remnant");
writer = new WaveWriter("Impulse_Response_Diffuse.wav");
writer.Input = longstereoImpulseD;
writer.Format = WaveFormat.IEEE_FLOAT;
writer.BitsPerSample = 32;
writer.SampleRate = _sampleRate;
writer.Gain = gg;
writer.Raw = false;
writer.Run();
writer.Close();
writer = null;
// Filter the diffuse-field curve against double the diffuse-field curve
FilterImpulse fiDiffuse = new FilterImpulse(8192, HRTF.diffuseDiff0() * 2, FilterInterpolation.COSINE, sampleRate);
FastConvolver co = new FastConvolver(longstereoImpulseD, fiDiffuse);
SoundBuffer buffd = new SoundBuffer(co);
_impulseFiles.Add("Impulse_Response_Diffuse_Comp.wav: filtered diffuse-field remnant");
writer = new WaveWriter("Impulse_Response_Diffuse_Comp.wav");
writer.Input = buffd.Subset(4096);
writer.Format = WaveFormat.IEEE_FLOAT;
writer.BitsPerSample = 32;
writer.SampleRate = _sampleRate;
writer.Gain = gg;
writer.Raw = false;
writer.Run();
writer.Close();
writer = null;
longstereoImpulseD = null;
bool any = false;
string jsonFile = "Diff.json";
FileStream fs = new FileStream(jsonFile, FileMode.Create);
StreamWriter sw = new StreamWriter(fs);
sw.WriteLine("{");
FilterProfile lfgDiffL = lfgDirectL - lfgDiffuseL;
if (lfgDiffL != null)
{
if (any) sw.WriteLine(",");
any = true;
sw.Write(lfgDiffL.ToJSONString("DiffL", "Diffuse field relative to direct, left channel"));
}
FilterProfile lfgDiffR = lfgDirectR - lfgDiffuseR;
if (lfgDiffR != null)
{
if (any) sw.WriteLine(",");
any = true;
sw.Write(lfgDiffR.ToJSONString("DiffR", "Diffuse field relative to direct, right channel"));
}
sw.WriteLine("}");
sw.Close();
fs.Close();
}
buff = null;
GC.Collect();
System.Console.Error.WriteLine();
if (!_noDRC)
{
// Analyze the freq response
// and create targets
// target_full.txt and target_half.txt
stderr.WriteLine("Analyzing response curves.");
Prep(impTempL, impTempR, "Impulse_Response_Measured.wav", "NoCorrection");
// Call DRC to create the filters
// then splice the DRC left & right output files together
stderr.WriteLine("Preparing for DRC.");
if (DoDRC(impFileL, impFileR, impDirectL, impDirectR, _peakPosL, _peakPosR, "Impulse_Response_Measured.wav", "Impulse_Response_Filtered.wav"))
{
stderr.WriteLine("Success!");
}
}
// Report names of the impulse files created
if (_impulseFiles.Count == 0)
{
System.Console.Error.WriteLine("No impulse response files were created.");
}
if (_impulseFiles.Count > 0)
{
System.Console.Error.WriteLine("Impulse response files were created:");
foreach (string f in _impulseFiles)
{
string s = " " + f;
System.Console.Error.WriteLine(s);
}
}
// Report names of the filter files created
if (_filterFiles.Count == 0 && !_noDRC)
{
System.Console.Error.WriteLine("No correction filter files were created.");
}
if (_filterFiles.Count > 0)
{
System.Console.Error.WriteLine("Correction filter files were created:");
foreach (string f in _filterFiles)
{
string s = " " + f;
if (_copy)
{
try
{
File.Copy(f, Path.Combine(_impulsesFolder, f), true);
s += " (copied)";
}
catch (Exception e)
{
s += " (not copied: " + e.Message + ")";
}
}
System.Console.Error.WriteLine(s);
}
}
if (_peakPosL == _peakPosR)
{
System.Console.Error.WriteLine();
System.Console.Error.WriteLine("Zero time difference between channels. Are you sure the recordings are correct?");
}
}
catch (Exception e)
{
stderr.WriteLine();
stderr.WriteLine(e.Message);
stderr.WriteLine(e.StackTrace);
}
finally
{
foreach (string tempFile in _tempFiles)
{
try
{
File.Delete(tempFile);
}
catch (Exception) { /* ignore */ }
}
}
}
stderr.Flush();
}
static string FileDescription(int nFile)
{
if (_nInFiles == 2)
{
return nFile == 0 ? "left" : "right";
}
else
{
return String.Format("channel {0}", nFile);
}
}
static void WriteImpulseDBL(ISoundObj stereoImpulse, string fileNameL, string fileNameR)
{
ISoundObj sb;
WaveWriter writer;
ushort bits = 64;
int nTot = 65535;
int nBef = 6000;
// need padding before the sample.
// window the sample first, then pad it.
// Total length 65536, includes nPad and _peakPosL before impulse
int nPad = nBef - _peakPosL;
int usableLength = nTot - nPad;
int windowCenter = usableLength / 2;
int windowSide = _peakPosL * 2 / 3;
int windowFlat = windowCenter - windowSide;
ISoundObj ch = new SingleChannel(stereoImpulse, 0);
ISoundObj wn = new BlackmanHarris(windowCenter, windowSide, windowFlat);
wn.Input = ch;
sb = new SampleBuffer(wn).PaddedSubset(-nPad, nTot);
writer = new WaveWriter(fileNameL);
writer.Input = sb;
writer.Format = WaveFormat.IEEE_FLOAT;
writer.BitsPerSample = bits;
writer.SampleRate = _sampleRate;
writer.Raw = true;
writer.Run();
writer.Close();
writer = null;
nPad = nBef - _peakPosR;
usableLength = nTot - nPad;
windowCenter = usableLength / 2;
windowSide = _peakPosR * 2 / 3;
windowFlat = windowCenter - windowSide;
ch = new SingleChannel(stereoImpulse, 1);
wn = new BlackmanHarris(windowCenter, windowSide, windowFlat);
wn.Input = ch;
sb = new SampleBuffer(wn).PaddedSubset(-nPad, nTot);
writer = new WaveWriter(fileNameR);
writer.Input = sb;
writer.Format = WaveFormat.IEEE_FLOAT;
writer.BitsPerSample = bits;
writer.SampleRate = _sampleRate;
writer.Raw = true;
writer.Run();
writer.Close();
writer = null;
}
static void WriteImpulsePCM(ISoundObj stereoImpulse, string fileNameL, string fileNameR)
{
ISoundObj sb;
WaveWriter writer;
ushort bits = 32;
int nTot = 196607;
int nBef = 98300;
// need padding before the sample.
// window the sample first, then pad it.
// Total length 65536, includes nPad and _peakPosL before impulse
int nPad = nBef - _peakPosL;
int usableLength = nTot - nPad;
int windowCenter = usableLength / 2;
int windowSide = _peakPosL * 2 / 3;
int windowFlat = windowCenter - windowSide;
ISoundObj ch = new SingleChannel(stereoImpulse, 0);
ISoundObj wn = new BlackmanHarris(windowCenter, windowSide, windowFlat);
wn.Input = ch;
sb = new SampleBuffer(wn).PaddedSubset(-nPad, nTot);
writer = new WaveWriter(fileNameL);
writer.Input = sb;
writer.Format = WaveFormat.IEEE_FLOAT;
writer.BitsPerSample = bits;
writer.SampleRate = _sampleRate;
writer.Raw = true;
writer.Normalization = -6.0;
writer.NormalizationType = NormalizationType.PEAK_DBFS;
writer.Run();
writer.Close();
double g = writer.Gain;
writer = null;
nPad = nBef - _peakPosR;
usableLength = nTot - nPad;
windowCenter = usableLength / 2;
windowSide = _peakPosR * 2 / 3;
windowFlat = windowCenter - windowSide;
ch = new SingleChannel(stereoImpulse, 1);
wn = new BlackmanHarris(windowCenter, windowSide, windowFlat);
wn.Input = ch;
sb = new SampleBuffer(wn).PaddedSubset(-nPad, nTot);
writer = new WaveWriter(fileNameR);
writer.Input = sb;
writer.Format = WaveFormat.IEEE_FLOAT;
writer.BitsPerSample = bits;
writer.SampleRate = _sampleRate;
writer.Raw = true;
writer.Gain = g;
writer.Run();
writer.Close();
writer = null;
}
static ISoundObj LowPassFiltered(ISoundObj input, double freqStart, double gainEnd)
{
uint sampleRate = input.SampleRate;
FilterProfile lfg = new FilterProfile();
lfg.Add(new FreqGain(freqStart, 0));
lfg.Add(new FreqGain(0.499*sampleRate, gainEnd));
FastConvolver conv = new FastConvolver();
conv.Input = input;
conv.impulse = new FilterImpulse(8192, lfg, FilterInterpolation.COSINE, sampleRate);
return conv;
}
static ISoundObj SlidingLowPass(ISoundObj impulse, int peakPos)
{
// Filter the impulse response with a sliding lowpass filter
// - Take the first (peakpos) samples unchanged
// - Take the next 2.5ms (~110 samples @ 44100) unchanged
// - Fade to a lowpass-filtered version
uint sampleRate = impulse.SampleRate;
int startpos1 = (int)(sampleRate * 0.0025); // 2.5mS, 110 samples
int startpos2 = (int)(sampleRate * 0.0050);
int startpos3 = (int)(sampleRate * 0.0100);
int startpos4 = (int)(sampleRate * 0.0200);
int startpos5 = (int)(sampleRate * 0.0400);
List<IEnumerator<ISample>> filters = null;
int nFilter = 0;
int nFilters = 0;
int x = 0;
int f0len = 0;
ISoundObj filteredImpulse = new CallbackSource(1, sampleRate, delegate(long j)
{
if(j==0)
{
// initialize the list of filters
impulse.Reset();
filters = new List<IEnumerator<ISample>>(6);
ISoundObj f0 = LowPassFiltered(impulse, 20, 0);
f0len = f0.Iterations;
filters.Add(f0.Samples); // unfiltered
filters.Add(LowPassFiltered(impulse, 640, -10).Samples); // LPF from 640Hz, kick in at +110
filters.Add(LowPassFiltered(impulse, 320, -20).Samples); // LPF from 320Hz, kick in at +220 (etc)
filters.Add(LowPassFiltered(impulse, 160, -30).Samples); // +440
filters.Add(LowPassFiltered(impulse, 80, -40).Samples); // +880
filters.Add(LowPassFiltered(impulse, 40, -50).Samples); // +1760 = 40ms
nFilter = 0;
nFilters = filters.Count;
}
// Move the filters along a notch.
// (or, right at the beginning, move all the filters along by a lot, compensating for their center)
// For perf, we don't need to keep enumerating the filters we've finished using.
bool moreData = true;
int nSkip = 1;
if (j == 0)
{
nSkip = (f0len/2)+1;
}
for (int skip = 0; skip < nSkip; skip++)
{
int nStart = (nFilter == 0) ? 0 : nFilter - 1; // Keep moving even the old filters along so mixing works later
for (int f = nStart; f < nFilters; f++)
{
moreData &= filters[f].MoveNext();
}
}
if (!moreData) return null;
// Decide which filter we'll use
x++;
if (j == peakPos + startpos1) { nFilter = 1; x = 0; }
if (j == peakPos + startpos2) { nFilter = 2; x = 0; }
if (j == peakPos + startpos3) { nFilter = 3; x = 0; }
if (j == peakPos + startpos4) { nFilter = 4; x = 0; }
if (j == peakPos + startpos5) { nFilter = 5; x = 0; }
// Pick the sample from the current filter
ISample s = filters[nFilter].Current;
// For a short region after switch-over, mix slowly with the sample from the previous filter
int w = 20;
if (x < w && nFilter > 0)
{
ISample sPrev = filters[nFilter-1].Current;
for (int c = 0; c < s.NumChannels; c++)
{
s[c] = ((double)x/w)*s[c] + ((double)(w-x)/w)*sPrev[c];
}
}
return s;
});
return filteredImpulse;
}
static FilterProfile bandpass(uint centerFreq, uint sr)
{
FilterProfile lfg = new FilterProfile();
lfg.Add(new FreqGain(centerFreq * 0.5, -190));
lfg.Add(new FreqGain(centerFreq * 1.00, 0));
lfg.Add(new FreqGain(Math.Min(centerFreq * 2,sr), -190));
return lfg;
}
static void FindPeaks(ISoundObj impulse)
{
// Input: a single-channel impulse
// Find the peak positions:
// - unfiltered
// - filtered with various bandpass filters
uint sr = impulse.SampleRate;
ushort nc = impulse.NumChannels;
double peakM = Math.Round(MathUtil.Metres(_peakPosL, sr), 2);