-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathmdfourier.c
2915 lines (2472 loc) · 85.7 KB
/
mdfourier.c
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
/*
* MDFourier
* A Fourier Transform analysis tool to compare game console audio
* http://junkerhq.net/MDFourier/
*
* Copyright (C)2019-2020 Artemio Urbina
*
* This file is part of the 240p Test Suite
*
* You can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this software; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* Requires the FFTW library:
* http://www.fftw.org/
*
*/
#include "mdfourier.h"
#include "log.h"
#include "cline.h"
#include "windows.h"
#include "freq.h"
#include "diff.h"
#include "plot.h"
#include "sync.h"
#include "balance.h"
#include "loadfile.h"
#include "profile.h"
int LoadAndProcessAudioFiles(AudioSignal **ReferenceSignal, AudioSignal **ComparisonSignal, parameters *config);
int ProcessSignal(AudioSignal *Signal, parameters *config);
int ExecuteDFFT(AudioBlocks *AudioArray, double *samples, size_t size, double samplerate, double *window, int AudioChannels, int ZeroPad, parameters *config);
int ExecuteDFFTInternal(AudioBlocks *AudioArray, double *samples, size_t size, double samplerate, double *window, char channel, int AudioChannels, int ZeroPad, parameters *config);
int CompareAudioBlocks(AudioSignal *ReferenceSignal, AudioSignal *ComparisonSignal, parameters *config);
int CopySamplesForTimeDomainPlot(AudioBlocks *AudioArray, double *samples, size_t size, size_t diff, double *window, int AudioChannels, int forcecopy, parameters *config);
void CleanUp(AudioSignal **ReferenceSignal, AudioSignal **ComparisonSignal, parameters *config);
void NormalizeTimeDomainByFrequencyRatio(AudioSignal *Signal, double normalizationRatio, parameters *config);
double FindRatio(AudioSignal *Signal, double normalizationRatio, parameters *config);
double FindRatioForBlock(AudioBlocks *AudioArray, double ratio);
void NormalizeBlockByRatio(AudioBlocks *AudioArray, double ratio);
void ProcessWaveformsByBlock(AudioSignal *ReferenceSignal, AudioSignal *ComparisonSignal, double ratioRef, parameters *config);
double FindMaxSampleForWaveform(AudioSignal *Signal, int *block, parameters *config);
double FindMaxSampleInBlock(AudioBlocks *AudioArray);
void FindViewPort(parameters *config);
int ReportClockResults(AudioSignal *ReferenceSignal, AudioSignal *ComparisonSignal, parameters *config);
int RecalculateFrequencyStructures(AudioSignal *ReferenceSignal, AudioSignal *ComparisonSignal, parameters *config);
int NormalizeAndFinishProcess(AudioSignal **ReferenceSignal, AudioSignal **ComparisonSignal, parameters *config);
int FrequencyDomainNormalize(AudioSignal **ReferenceSignal, AudioSignal **ComparisonSignal, parameters *config);
void AdjustTimeDomainData(AudioSignal *ReferenceSignal, AudioSignal *ComparisonSignal, parameters *config);
// Time domain
MaxSample FindMaxSampleAmplitude(AudioSignal *Signal);
void NormalizeAudioByRatio(AudioSignal *Signal, double ratio);
double FindLocalMaximumAroundSample(AudioSignal *Signal, MaxSample refMax);
// Frequency domain
void NormalizeMagnitudesByRatio(AudioSignal *Signal, double ratio, parameters *config);
MaxMagn FindMaxMagnitudeBlock(AudioSignal *Signal, parameters *config);
int FindMultiMaxMagnitudeBlock(AudioSignal *Signal, MaxMagn *MaxMag, int *size, parameters *config);
double FindLocalMaximumInBlock(AudioSignal *Signal, MaxMagn refMax, int allowDifference, parameters *config);
double FindFundamentalMagnitudeAverage(AudioSignal *Signal, parameters *config);
double FindFundamentalMagnitudeStdDev(AudioSignal *Signal, double AvgFundMag, parameters *config);
int main(int argc, char *argv[])
{
AudioSignal *ReferenceSignal = NULL;
AudioSignal *ComparisonSignal = NULL;
parameters config;
struct timespec start, end;
if(!Header(0, argc, argv))
return 1;
if(!commandline(argc, argv, &config))
{
printf(" -h: Shows command line help\n");
CleanUp(&ReferenceSignal, &ComparisonSignal, &config);
return 1;
}
clock_gettime(CLOCK_MONOTONIC, &start);
if(!SetupFolders(config.outputFolder, "Log", &config))
{
logmsg("Aborting\n");
CleanUp(&ReferenceSignal, &ComparisonSignal, &config);
return 1;
}
if(!EndProfileLoad(&config))
{
logmsg("Aborting\n");
CleanUp(&ReferenceSignal, &ComparisonSignal, &config);
return 1;
}
if(strcmp(config.referenceFile, config.comparisonFile) == 0)
{
CleanUp(&ReferenceSignal, &ComparisonSignal, &config);
logmsg("Both inputs are the same file %s, skipping to save time\n",
config.referenceFile);
return 1;
}
if(!LoadAndProcessAudioFiles(&ReferenceSignal, &ComparisonSignal, &config))
{
logmsg("Aborting\n");
if(config.debugSync)
printf("\nResults stored in %s%s\n",
config.outputPath,
config.folderName);
CleanUp(&ReferenceSignal, &ComparisonSignal, &config);
return 1;
}
if(!ReportClockResults(ReferenceSignal, ComparisonSignal, &config))
{
if(config.doClkAdjust)
{
if(!RecalculateFrequencyStructures(ReferenceSignal, ComparisonSignal, &config))
{
logmsg("Could not recalculate frequencies, Aborting\n");
return 1;
}
}
}
AdjustTimeDomainData(ReferenceSignal, ComparisonSignal, &config);
logmsg("\n* Comparing frequencies: ");
if(!CompareAudioBlocks(ReferenceSignal, ComparisonSignal, &config))
{
logmsg("Aborting\n");
CleanUp(&ReferenceSignal, &ComparisonSignal, &config);
return 1;
}
config.averageDifference = FindDifferenceAverage(&config);
logmsg("Average difference is %g dB\n", config.averageDifference);
if(config.substractAveragePlot)
{
config.averageDifferenceOrig = config.averageDifference;
SubstractDifferenceAverageFromResults(&config);
config.averageDifference = FindDifferenceAverage(&config);
logmsg(" - Adjusted plots around average, the new average is %g dB\n", config.averageDifference);
}
FindViewPort(&config);
logmsg("* Plotting results to PNGs:\n");
PlotResults(ReferenceSignal, ComparisonSignal, &config);
if(IsLogEnabled())
endLog();
/* Clear up everything */
ReleaseDifferenceArray(&config);
CleanUp(&ReferenceSignal, &ComparisonSignal, &config);
fftw_cleanup();
//if(config.clock)
{
int minutes = 0;
double elapsedSeconds;
clock_gettime(CLOCK_MONOTONIC, &end);
elapsedSeconds = TimeSpecToSeconds(&end) - TimeSpecToSeconds(&start);
minutes = elapsedSeconds / 60.0;
logmsg("* MDFourier Analysis took %0.2f seconds", elapsedSeconds);
if(minutes)
logmsg(" (%d minute%s %0.2f seconds)", minutes, minutes == 1 ? "" : "s", elapsedSeconds - minutes*60);
logmsg("\n");
}
printf("\nResults stored in %s%s\n",
config.outputPath,
config.folderName);
return(0);
}
void FindViewPort(parameters *config)
{
int type = 0;
char *name = NULL;
double outside = 0, maxDiff = 0;
outside = FindDifferencePercentOutsideViewPort(&maxDiff, &type, fabs(config->maxDbPlotZC), config);
if(outside)
{
name = GetTypeDisplayName(config, type);
if(config->maxDbPlotZCChanged)
{
config->notVisible = outside;
logmsg("- Not auto adjusting vertical, using requested +/-%gdB. Missing [%s]: %g%%\n",
config->maxDbPlotZC, name, outside);
return;
}
logmsg(" - Differences outside +/-%gdB in [%s]: %g%%\n",
config->maxDbPlotZC, name, outside);
if(outside > PCNT_VISIBLE_WRN && outside < PCNT_VISIBLE_ACT)
{
config->notVisible = outside;
logmsg(" - If needed you can graph them all with \"-d %g\" for this particular case\n\n", ceil(maxDiff));
return;
}
if(outside >= PCNT_VISIBLE_ACT && !config->maxDbPlotZCChanged) // if the user has not changed it
{
double value = 0;
value = ceil(FindVisibleInViewPortWithinStandardDeviation(&maxDiff, &outside, type, 1, config));
if(value != -1 && outside < 5)
config->maxDbPlotZC = value;
else
{
value = ceil(FindVisibleInViewPortWithinStandardDeviation(&maxDiff, &outside, type, 2, config));
if(value != -1)
config->maxDbPlotZC = value;
// swap above for this to expand auto expand fully if needed
/*
value = ceil(FindVisibleInViewPortWithinStandardDeviation(&maxDiff, &outside, type, 2, config));
if(value != -1 && outside < 5)
config->maxDbPlotZC = value;
else
{
config->maxDbPlotZC = ceil(maxDiff);
outside = FindDifferencePercentOutsideViewPort(&maxDiff, &type, fabs(config->maxDbPlotZC), config);
}
*/
}
logmsg(" - Auto adjusting viewport to %gdB for graphs\n", config->maxDbPlotZC);
if(outside >= 1)
logmsg(" - The %g%% of differences in [%s] will not be visible within the %gdB for graphs\n - If needed you can graph them all with \"-d %g\" for this particular case\n\n",
outside, name, config->maxDbPlotZC, ceil(maxDiff));
#ifdef DEBUG
logmsg("WARNING: Viewport auto adjusted\n");
#endif
}
}
else
logmsg("\n");
config->notVisible = outside;
}
void PrintSignalCLKData(AudioSignal *Signal, parameters *config)
{
if(Signal->EstimatedSR)
{
if(!config->doSamplerateAdjust)
logmsg(", WARNING: %s sample rate estimated at %gHz from signal length (can be auto matched with -R)",
Signal->role == ROLE_REF ? "Reference" : "Comparison",
Signal->EstimatedSR);
else
{
if(Signal->originalSR)
{
if(Signal->EstimatedSR != (int)Signal->EstimatedSR)
logmsg(" [Sample rate adjusted %dHz->%0.4fHz with -R]",
Signal->originalSR, Signal->EstimatedSR);
else
logmsg(" [Sample rate adjusted %dHz->%dHz with -R]",
Signal->originalSR, (int)Signal->EstimatedSR);
}
}
}
logmsg("\n");
if(config->clkWarning & Signal->role)
logmsg("WARNING: %s has noise or higher harmonics than the fundamental in the clock block.\n",
Signal->role == ROLE_REF ? "Reference" : "Comparison");
if(config->clkNotFound & Signal->role)
logmsg("WARNING: %s clock frequency not found within tolerance. Using highest value.\n",
Signal->role == ROLE_REF ? "Reference" : "Comparison");
}
int ReportClockResults(AudioSignal *ReferenceSignal, AudioSignal *ComparisonSignal, parameters *config)
{
double refClk = 0, compClk = 0;
if(!config->clkMeasure)
return 1;
CalculateCLKAmplitudes(ReferenceSignal, ComparisonSignal, config);
refClk = CalculateClk(ReferenceSignal, config);
compClk = CalculateClk(ComparisonSignal, config);
config->clkRef = refClk;
config->clkCom = compClk;
logmsg("\n* Estimated %s Clocks based on expected %d Hz on note %s# %d:\n",
config->clkName, config->clkFreq, GetBlockName(config, config->clkBlock),
GetBlockSubIndex(config, config->clkBlock));
logmsg(" - Reference: %gHz", refClk);
PrintSignalCLKData(ReferenceSignal, config);
logmsg(" - Comparison: %gHz", compClk);
PrintSignalCLKData(ComparisonSignal, config);
config->centsDifferenceCLK = 1200*log2(refClk/compClk);
if(fabs(config->centsDifferenceCLK) >= MIN_CENTS_DIFF)
{
logmsg(" - Pitch difference in cents: %g\n", config->centsDifferenceCLK);
if(!config->doClkAdjust)
{
/*
int reportOption = 0;
if(config->RefCentsDifferenceSR || config->ComCentsDifferenceSR)
{
double diff = 0;
if(config->RefCentsDifferenceSR)
diff = fabs(config->RefCentsDifferenceSR - config->centsDifferenceCLK);
else
diff = fabs(config->ComCentsDifferenceSR - config->centsDifferenceCLK);
if(diff >= 5) // Same issue between both, reported above
reportOption = 1;
else if(diff >= 1)
reportOption = 1;
}
else
reportOption = 1;
config->diffClkNoMatch = 1;
if(reportOption)
*/
logmsg(" - WARNING: Clocks don't match, results may vary considerably. Can adjust with -j\n");
}
return 0;
}
else
{
if(config->doClkAdjust)
logmsg(" - WARNING: Ignoring -j since pitch difference in cents is: %g\n", config->centsDifferenceCLK);
}
return 1;
}
int LoadAudioFiles(AudioSignal **ReferenceSignal, AudioSignal **ComparisonSignal, parameters *config)
{
AudioSignal *higher = NULL;
if(!LoadFile(ReferenceSignal, config->referenceFile, ROLE_REF, config))
return 0;
if(!LoadFile(ComparisonSignal, config->comparisonFile, ROLE_COMP, config))
return 0;
if(GetSignalMaxInt(*ReferenceSignal) >= GetSignalMaxInt(*ComparisonSignal))
higher = *ReferenceSignal;
else
higher= *ComparisonSignal;
config->highestValueBitDepth = GetSignalMaxInt(higher);
config->lowestValueBitDepth = GetSignalMinInt(higher);
config->lowestDBFS = GetSignalMinDBFS(higher);
return 1;
}
/* Although dithering would be better, there has been no need */
/* Tested a file scaled with ths method against itself using */
/* the frequency domain solution, and differences are negligible */
/* (less than 0.2dBFS) */
int TimeDomainNormalize(AudioSignal **ReferenceSignal, AudioSignal **ComparisonSignal, parameters *config)
{
MaxSample MaxRef, MaxTar;
double ComparisonLocalMaximum = 0;
double ratioTar = 0, ratioRef = 0;
// Find Normalization factors
MaxRef = FindMaxSampleAmplitude(*ReferenceSignal);
if(!MaxRef.maxSample)
{
logmsg("ERROR: Could not detect Max amplitude in 'Reference' File for normalization\n");
return 0;
}
MaxTar = FindMaxSampleAmplitude(*ComparisonSignal);
if(!MaxTar.maxSample)
{
logmsg("ERROR: Could not detect Max amplitude in 'Comparison' file for normalization\n");
return 0;
}
ratioTar = config->highestValueBitDepth/MaxTar.maxSample;
NormalizeAudioByRatio(*ComparisonSignal, ratioTar);
ComparisonLocalMaximum = FindLocalMaximumAroundSample(*ComparisonSignal, MaxRef);
if(!ComparisonLocalMaximum)
{
logmsg("ERROR: Could not detect Max amplitude in 'Comparison' file for normalization\n");
return 0;
}
ratioRef = (ComparisonLocalMaximum/MaxRef.maxSample);
if(config->verbose) { logmsg(" - Sample ratio is %g\n", ratioRef); }
NormalizeAudioByRatio(*ReferenceSignal, ratioRef);
// Uncomment if you want to check the WAV files as normalized
//SaveWAVEChunk(NULL, *ReferenceSignal, (*ReferenceSignal)->Samples, 0, (*ReferenceSignal)->numSamples, config);
//SaveWAVEChunk(NULL, *ComparisonSignal, (*ComparisonSignal)->Samples, 0, (*ComparisonSignal)->numSamples, config);
return 1;
}
/* The default */
int FrequencyDomainNormalize(AudioSignal **ReferenceSignal, AudioSignal **ComparisonSignal, parameters *config)
{
MaxMagn MaxRef, MaxTar;
double ComparisonLocalMaximum = 0;
double ratioRef = 0, ratiodBFS = 0;
double RefAvg = 0;
double CompAvg = 0;
double ratio = 0, maxRatiodBFS = fabs(FREQDOMRATIO);
// Find Normalization factors
MaxRef = FindMaxMagnitudeBlock(*ReferenceSignal, config);
if(!MaxRef.magnitude)
{
logmsg("ERROR: Could not detect Max amplitude in 'Reference' File for normalization\n");
return 0;
}
MaxTar = FindMaxMagnitudeBlock(*ComparisonSignal, config);
if(!MaxTar.magnitude)
{
logmsg("ERROR: Could not detect Max amplitude in 'Comparison' file for normalization\n");
return 0;
}
ComparisonLocalMaximum = FindLocalMaximumInBlock(*ComparisonSignal, MaxRef, 0, config);
if(ComparisonLocalMaximum)
ratioRef = ComparisonLocalMaximum/MaxRef.magnitude;
/* Detect extreme cases, and try another approach */
ratiodBFS = CalculateAmplitudeInternal(ComparisonLocalMaximum, MaxRef.magnitude);
if(!config->allowStereoVsMono &&
MaxRef.block == MaxTar.block &&
MaxRef.channel != MaxTar.channel &&
fabs(ratiodBFS) > STEREO_TOLERANCE_REPORT)
{
logmsg(" - WARNING: Left and right channels might be reversed or converted from mono to stereo");
if(config->verbose)
logmsg(" %g/%g", fabs(ratiodBFS), STEREO_TOLERANCE_REPORT);
logmsg("\n");
config->warningStereoReversed = 1;
}
if(config->verbose) { logmsg(" - Amplitude ratio is %gdB\n", ratiodBFS == NO_AMPLITUDE ? 0 : ratiodBFS); }
if(ComparisonLocalMaximum == 0 || fabs(ratiodBFS) > maxRatiodBFS || ratiodBFS == NO_AMPLITUDE)
{
int found = 0, pos = 1, allowDifference = 0, tries = 0, numMatches = FREQDOMTRIES;
MaxMagn MaxRefArray[FREQDOMTRIES];
double ComparisonLocalMaximumArray = 0, ratioRefArray = 0;
if(config->verbose) { logmsg(" - Searching for lower ratio alternatives\n"); }
memset(MaxRefArray, 0, sizeof(MaxRefArray));
if(FindMultiMaxMagnitudeBlock(*ReferenceSignal, MaxRefArray, &numMatches, config))
{
int matchIndex = -1;
double lowestRatio = 0, ComparisonLocalMaximumArrayforLowest = 0, localRatiodBFS = ratiodBFS;
// We have a do for a second cycle allowing tolerance
do
{
while(MaxRefArray[pos].magnitude != 0 && pos < numMatches)
{
if(config->verbose >= 2) {
logmsg(" - Reference Max Magnitude[%d] found in %s# %d (%d) at %g Hz with %g\n",
pos,
GetBlockName(config, MaxRefArray[pos].block), GetBlockSubIndex(config, MaxRefArray[pos].block),
MaxRefArray[pos].block, MaxRefArray[pos].hertz, MaxRefArray[pos].magnitude);
}
ratioRefArray = 0;
ComparisonLocalMaximumArray = FindLocalMaximumInBlock(*ComparisonSignal, MaxRefArray[pos], allowDifference, config);
if(ComparisonLocalMaximumArray)
{
double dbfsratioArray = 0;
dbfsratioArray = CalculateAmplitudeInternal(ComparisonLocalMaximumArray, MaxRefArray[pos].magnitude);
ratioRefArray = ComparisonLocalMaximumArray/MaxRefArray[pos].magnitude;
if(dbfsratioArray > localRatiodBFS)
{
localRatiodBFS = dbfsratioArray;
lowestRatio = ratioRefArray;
ComparisonLocalMaximumArrayforLowest = ComparisonLocalMaximumArray;
matchIndex = pos;
}
if(config->verbose >= 2) { logmsg(" - Comparision ratio is %gdB\n", dbfsratioArray); }
if(fabs(dbfsratioArray) <= fabs(FREQDOMRATIO)) {
found = 1;
break;
}
}
pos++;
}
if(localRatiodBFS > ratiodBFS)
{
found = 1;
ComparisonLocalMaximumArray = ComparisonLocalMaximumArrayforLowest;
ratioRefArray = lowestRatio;
pos = matchIndex;
if(config->verbose) {
logmsg(" - Reference Max Magnitude[%d] lowest match %s# %d (%d) at %g Hz with %g\n",
pos,
GetBlockName(config, MaxRefArray[pos].block), GetBlockSubIndex(config, MaxRefArray[pos].block),
MaxRefArray[pos].block, MaxRefArray[pos].hertz, MaxRefArray[pos].magnitude);
}
}
if(found){
int copy = 0;
if(ComparisonLocalMaximum) // we are here because no clean match was found
copy = 1;
else /* we are here because of ratio */ {
if(ratioRefArray < ratioRef)
copy = 1;
if(!ratioRef)
copy = 1;
}
if(copy){
ComparisonLocalMaximum = ComparisonLocalMaximumArray;
ratioRef = ratioRefArray;
config->frequencyNormalizationTries = pos + 1;
}
else {
if(config->verbose) { logmsg(" - Alternative matches were worse than original, (%g<-%g)reverting\n", ratioRefArray, ratioRef); }
}
}
else {
config->frequencyNormalizationTries = -1;
allowDifference = 1;
pos = 0;
}
tries ++;
}while(tries == 1 && allowDifference == 1);
}
#ifdef DEBUG
if(found)
logmsg("WARNING: Frequency Domain Normalization at %d value\n", config->frequencyNormalizationTries);
#endif
}
else
config->frequencyNormalizationTries = 0;
if(!ComparisonLocalMaximum || !ratioRef)
{
logmsg("ERROR: Could not detect Local Maximum in 'Comparison' file for normalization\n");
logmsg("\t* Use Time Domain normalization: -n t\n");
logmsgFileOnly("ComparisonLocalMaximum %g ratioRef %g\n", ComparisonLocalMaximum, ratioRef);
PrintFrequenciesWMagnitudes(*ReferenceSignal, config);
PrintFrequenciesWMagnitudes(*ComparisonSignal, config);
return 0;
}
NormalizeMagnitudesByRatio(*ReferenceSignal, ratioRef, config);
RefAvg = FindFundamentalMagnitudeAverage(*ReferenceSignal, config);
CompAvg = FindFundamentalMagnitudeAverage(*ComparisonSignal, config);
if(RefAvg > CompAvg)
ratio = RefAvg/CompAvg;
else
ratio = CompAvg/RefAvg;
if(fabs(ratio) > fabs(FREQDOMRATIO)) {
//double dbfsratioArray = 0;
//dbfsratioArray = CalculateAmplitude(ComparisonLocalMaximum, MaxRef.magnitude);
logmsg("\tWARNING: Average frequency difference after normalization between the signals is too high. (Ratio:%g to 1)\n", ratio);
logmsg("\tIf results make no sense please try the following in the Extra Commands box:\n");
logmsg("\t* Use Time Domain normalization: -n t\n");
logmsg("\tThis can be caused by: comparing very different signals, a capacitor problem,\n");
logmsg("\tframerate difference causing pitch drifting, an unusual frequency scenario, etc.\n");
config->warningRatioTooHigh = ratio;
}
/* This is just for waveform visualization */
if((config->hasTimeDomain && config->plotTimeDomain) || config->plotAllNotes)
ProcessWaveformsByBlock(*ReferenceSignal, *ComparisonSignal, ratioRef, config);
return 1;
}
int AverageNormalize(AudioSignal **ReferenceSignal, AudioSignal **ComparisonSignal, parameters *config)
{
double RefAvg = 0, CompAvg = 0, ratio = 0;
RefAvg = FindFundamentalMagnitudeAverage(*ReferenceSignal, config);
CompAvg = FindFundamentalMagnitudeAverage(*ComparisonSignal, config);
if(CompAvg > RefAvg)
{
ratio = CompAvg/RefAvg;
NormalizeMagnitudesByRatio(*ReferenceSignal, ratio, config);
/* waveforms */
ProcessWaveformsByBlock(*ReferenceSignal, *ComparisonSignal, ratio, config);
}
else
{
ratio = RefAvg/CompAvg;
NormalizeMagnitudesByRatio(*ComparisonSignal, ratio, config);
/* waveforms */
ProcessWaveformsByBlock(*ComparisonSignal, *ReferenceSignal, ratio, config);
}
return 1;
}
// Compensate time normalization to match frequency normalization
/*
int TimeDomainNormalizeCompensate(AudioSignal **ReferenceSignal, AudioSignal **ComparisonSignal, parameters *config)
{
// Check if we have the same peaks
// This is in order to compensate TimeDomain Differences
// But we probably default to Frequency domain and leave this commented out
if((*ReferenceSignal)->MaxMagnitude.hertz == (*ComparisonSignal)->MaxMagnitude.hertz &&
(*ReferenceSignal)->MaxMagnitude.block == (*ComparisonSignal)->MaxMagnitude.block)
{
double diff = 0;
diff = fabs((*ReferenceSignal)->MaxMagnitude.magnitude - (*ComparisonSignal)->MaxMagnitude.magnitude);
if(diff > 0.5)
{
double ratio = 0;
if((*ReferenceSignal)->MaxMagnitude.magnitude > (*ComparisonSignal)->MaxMagnitude.magnitude)
{
//if(config->verbose)
logmsg(" - Both Peaks match in frequency and Block, readjusting magnitudes");
ratio = (*ComparisonSignal)->MaxMagnitude.magnitude/(*ReferenceSignal)->MaxMagnitude.magnitude;
NormalizeMagnitudesByRatio(*ReferenceSignal, ratio, config);
}
else
{
if(config->verbose)
logmsg(" - Both Peaks match in frequency and Block, readjusting magnitudes");
ratio = (*ReferenceSignal)->MaxMagnitude.magnitude/(*ComparisonSignal)->MaxMagnitude.magnitude;
NormalizeMagnitudesByRatio(*ComparisonSignal, ratio, config);
}
}
//ZeroDbMagnitudeRef = (*ReferenceSignal)->MaxMagnitude.magnitude;
}
return 1;
}
*/
int ProcessNoiseFloor(AudioSignal *ReferenceSignal, AudioSignal *ComparisonSignal, parameters *config)
{
int refHasFloor = 0, comHasFloor = 0;
double avgRef = 0, avgComp = 0;
/* analyze silence floor if available */
if(ReferenceSignal->hasSilenceBlock)
{
FindFloor(ReferenceSignal, config);
refHasFloor = ReferenceSignal->floorAmplitude != 0.0;
}
if(ComparisonSignal->hasSilenceBlock)
{
FindFloor(ComparisonSignal, config);
comHasFloor = ComparisonSignal->floorAmplitude != 0.0;
}
avgRef = FindFundamentalAmplitudeAverage(ReferenceSignal, config);
avgComp = FindFundamentalAmplitudeAverage(ComparisonSignal, config);
if(refHasFloor && avgRef < ReferenceSignal->floorAmplitude)
{
config->noiseFloorTooHigh |= ReferenceSignal->role;
logmsg(" - Reference noise floor %g dBFS is louder than the average %g dBFS of the signal, ignoring\n",
ReferenceSignal->floorAmplitude, avgRef);
ReferenceSignal->floorAmplitude = SIGNIFICANT_AMPLITUDE;
}
// Higher noise floor was found, biut low fundamental noise was used
if(config->referenceNoiseFloor > ReferenceSignal->floorAmplitude)
config->noiseFloorTooHigh |= ReferenceSignal->role;
if(comHasFloor && avgComp < ComparisonSignal->floorAmplitude)
{
config->noiseFloorTooHigh |= ComparisonSignal->role;
logmsg(" - Comparison noise floor %g dBFS is louder than the average %g dBFS of the signal, ignoring\n",
ComparisonSignal->floorAmplitude, avgComp);
ComparisonSignal->floorAmplitude = SIGNIFICANT_AMPLITUDE;
}
/* Detect Signal Floor, default to Reference's*/
if(refHasFloor)
config->significantAmplitude = ReferenceSignal->floorAmplitude;
if(refHasFloor && ReferenceSignal->floorAmplitude > HIGHEST_NOISEFLOOR_ALLOWED)
config->noiseFloorTooHigh |= ReferenceSignal->role;
if(comHasFloor && ComparisonSignal->floorAmplitude > HIGHEST_NOISEFLOOR_ALLOWED)
config->noiseFloorTooHigh |= ComparisonSignal->role;
// If comparison is lower than the default and higher than reference, use that
if(config->noiseFloorAutoAdjust)
{
if(refHasFloor && comHasFloor &&
config->significantAmplitude < SIGNIFICANT_AMPLITUDE &&
ComparisonSignal->floorAmplitude <= HIGHEST_NOISEFLOOR_ALLOWED &&
ReferenceSignal->floorAmplitude < ComparisonSignal->floorAmplitude)
{
double diff = 0;
config->significantAmplitude = ComparisonSignal->floorAmplitude;
diff = fabs(ReferenceSignal->floorAmplitude - ComparisonSignal->floorAmplitude);
if(diff > 20)
config->noiseFloorBigDifference = 1;
}
}
else
{
if(config->significantAmplitude < SIGNIFICANT_AMPLITUDE)
{
logmsg(" - Limiting noise floor to %g from %g (from -p 0)\n",
SIGNIFICANT_AMPLITUDE, config->significantAmplitude);
config->significantAmplitude = SIGNIFICANT_AMPLITUDE;
}
}
if(config->significantAmplitude >= HIGHEST_NOISEFLOOR_ALLOWED)
{
logmsg(" - WARNING: Noise floor %g dBFS is louder than the default %g dBFS. If differences are not visible, define a limit with -p <dbfs>\n",
config->significantAmplitude, HIGHEST_NOISEFLOOR_ALLOWED);
//if(!config->noiseFloorTooHigh)
// config->noiseFloorTooHigh = ROLE_COMP;
// we rather not take action for now
//config->significantAmplitude = SIGNIFICANT_VOLUME;
}
/*
// check if digital noise floor, so we limit ourselves to a reasonable noise floor
if(config->significantAmplitude < NOISE_FLOOR_DIGITAL_FAIR)
{
logmsg(" - Found possible digital noise floor at %g dBFS. Limiting to %g dBFS, use -p to override\n",
config->significantAmplitude, NOISE_FLOOR_DIGITAL_FAIR);
config->significantAmplitude = NOISE_FLOOR_DIGITAL_FAIR;
}
else
*/
logmsg(" - Using %g dBFS as minimum significant amplitude for analysis\n", config->significantAmplitude);
if(refHasFloor)
FindNoiseFloorAmplitudeAverage(ReferenceSignal, config);
if(comHasFloor)
FindNoiseFloorAmplitudeAverage(ComparisonSignal, config);
return 1;
}
int LoadAndProcessAudioFiles(AudioSignal **ReferenceSignal, AudioSignal **ComparisonSignal, parameters *config)
{
if(!LoadAudioFiles(ReferenceSignal, ComparisonSignal, config))
return 0;
SelectSilenceProfile(config);
config->referenceFramerate = (*ReferenceSignal)->framerate;
CompareFrameRates(*ReferenceSignal, *ComparisonSignal, config);
/* Balance check */
if(config->channelBalance && !config->noSyncProfile)
{
if((*ReferenceSignal)->AudioChannels == 2 || (*ComparisonSignal)->AudioChannels == 2)
{
int block = NO_INDEX;
char *name = NULL;
if(config->stereoBalanceBlock)
{
block = config->stereoBalanceBlock;
name = GetBlockName(config, block);
if(!name)
{
logmsg("ERROR: Invalid Mono Balance Block %d\n", block);
return 0;
}
}
else
{
block = GetFirstMonoIndex(config);
logmsg("- WARNING: MonoBalanceBlock was 0, Using first Mono Block\n");
}
if(block != NO_INDEX)
{
logmsg("\n* Comparing Stereo channel amplitude\n");
if(config->verbose) {
logmsg(" - Mono block used for balance: %s# %d\n",
name, GetBlockSubIndex(config, block));
}
if(CheckBalance(*ReferenceSignal, block, config) == 0)
return 0;
if(CheckBalance(*ComparisonSignal, block, config) == 0)
return 0;
}
else
{
logmsg(" - WARNING: No mono block for stereo balance check\n");
config->channelBalance = -1;
}
}
}
if(config->normType == max_time)
{
if(!TimeDomainNormalize(ReferenceSignal, ComparisonSignal, config))
return 0;
}
SetAmplitudeMatchByDuration(*ReferenceSignal, config);
logmsg("\n* Executing Discrete Fast Fourier Transforms on 'Reference' file\n");
if(!ProcessSignal(*ReferenceSignal, config))
return 0;
logmsg("* Executing Discrete Fast Fourier Transforms on 'Comparison' file\n");
if(!ProcessSignal(*ComparisonSignal, config))
return 0;
ReleasePCM(*ReferenceSignal);
ReleasePCM(*ComparisonSignal);
CalculateFrequencyBrackets(*ReferenceSignal, config);
CalculateFrequencyBrackets(*ComparisonSignal, config);
if(!NormalizeAndFinishProcess(ReferenceSignal, ComparisonSignal, config))
return 0;
// Display Absolute and independent Noise Floor
/*
if(!config->ignoreFloor)
{
FindStandAloneFloor(*ReferenceSignal, config);
FindStandAloneFloor(*ComparisonSignal, config);
}
*/
if(!config->ignoreFloor)
{
if(!ProcessNoiseFloor(*ReferenceSignal, *ComparisonSignal, config))
return 0;
}
else
logmsg(" - Ignoring Noise floor, using %gdBFS\n", config->significantAmplitude);
return 1;
}
int NormalizeAndFinishProcess(AudioSignal **ReferenceSignal, AudioSignal **ComparisonSignal, parameters *config)
{
double ZeroDbMagnitudeRef = 0;
if(config->normType == max_frequency)
{
if(!FrequencyDomainNormalize(ReferenceSignal, ComparisonSignal, config))
return 0;
}
if(config->normType == average)
{
if(!AverageNormalize(ReferenceSignal, ComparisonSignal, config))
return 0;
}
/*
// Compensate time normalization to match frequency normalization
if(config->normType == max_time)
{
if(!TimeDomainNormalizeCompensate(ReferenceSignal, ComparisonSignal, config))
return 0;
}
*/
logmsg("\n* Processing Signal Frequencies and Amplitudes\n");
if ((*ReferenceSignal)->MaxMagnitude.magnitude < (*ComparisonSignal)->MaxMagnitude.magnitude)
{
ZeroDbMagnitudeRef = (*ComparisonSignal)->MaxMagnitude.magnitude;
if (config->verbose) {
logmsg(" - Comparison file has the highest peak at %g vs %g\n",
ZeroDbMagnitudeRef, (*ReferenceSignal)->MaxMagnitude.magnitude);
}
}
else
{
ZeroDbMagnitudeRef = (*ReferenceSignal)->MaxMagnitude.magnitude;
if (config->verbose) {
logmsg(" - Reference file has the highest peak at %g vs %g\n",
ZeroDbMagnitudeRef, (*ComparisonSignal)->MaxMagnitude.magnitude);
}
}
CalculateAmplitudes(*ReferenceSignal, ZeroDbMagnitudeRef, config);
CalculateAmplitudes(*ComparisonSignal, ZeroDbMagnitudeRef, config);
if(config->verbose)
{
PrintFrequencies(*ReferenceSignal, config);
PrintFrequencies(*ComparisonSignal, config);
}
if(config->types.useWatermark)
{
if(!DetectWatermark(*ReferenceSignal, config))
{
logmsg("ERROR: Reference signal could not be properly evaluated\n");
return 0;
}
if(!DetectWatermark(*ComparisonSignal, config))
{
logmsg("ERROR: Comparison signal could not be properly evaluated\n");
return 0;
}
}
config->referenceSignal = *ReferenceSignal;
config->comparisonSignal = *ComparisonSignal;
return 1;
}
void CleanUp(AudioSignal **ReferenceSignal, AudioSignal **ComparisonSignal, parameters *config)
{
if(*ReferenceSignal)
{
ReleaseAudio(*ReferenceSignal, config);
free(*ReferenceSignal);
*ReferenceSignal = NULL;
}
if(*ComparisonSignal)
{
ReleaseAudio(*ComparisonSignal, config);
free(*ComparisonSignal);
*ComparisonSignal = NULL;
}
ReleaseAudioBlockStructure(config);
}
int CopySamplesForTimeDomainPlotWindowOnly(AudioBlocks *AudioArray, double *window, int AudioChannels, parameters *config)
{
long i = 0, monoSignalSize = 0, difference = 0;
double *signal = NULL, *window_samples = NULL;
if(!AudioArray)
{
logmsg("No Array for results\n");
return 0;
}
if(!config->plotAllNotesWindowed || !window || !config->doClkAdjust)
{
logmsg("Unplanned function call\n");
return 0;
}
if(AudioArray->audio.windowed_samples)
{
logmsg("ERROR: Window waveforms already stored\n");
return 0;
}
if(!AudioArray->audio.samples)
{
logmsg("ERROR: Waveforms not stored\n");
return 0;
}
signal = AudioArray->audio.samples;
monoSignalSize = AudioArray->audio.size;
difference = AudioArray->audio.difference;
window_samples = (double*)malloc(sizeof(double)*(monoSignalSize+1));
if(!window_samples)
{