-
Notifications
You must be signed in to change notification settings - Fork 7
/
mdwave.c
1122 lines (970 loc) · 31 KB
/
mdwave.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/
*
*/
#define MDWVERSION MDVERSION
#define FORWARD_FFTW 0
#define REVERSE_FFTW 1
#include "mdfourier.h"
#include "log.h"
#include "windows.h"
#include "freq.h"
#include "diff.h"
#include "cline.h"
#include "sync.h"
#include "balance.h"
#include "loadfile.h"
#include "profile.h"
int ProcessSignalMDW(AudioSignal *Signal, parameters *config);
int ExecuteDFFT(AudioBlocks *AudioArray, double *samples, long int size, double samplerate, double *window, parameters *config, int fftw_direction, AudioSignal *Signal);
int ExecuteDFFTInternal(AudioBlocks *AudioArray, double *samples, long int size, double samplerate, double *window, char channel, parameters *config, int fftw_direction, AudioSignal *Signal);
int commandline_wave(int argc , char *argv[], parameters *config);
void PrintUsage_wave(void);
void Header_wave(int log);
void CleanUp(AudioSignal **ReferenceSignal, parameters *config);
int ExecuteMDWave(parameters *config, int discardMDW);
int main(int argc , char *argv[])
{
parameters config;
struct timespec start, end;
Header_wave(0);
if(!commandline_wave(argc, argv, &config))
{
printf(" -h: Shows command line help\n");
return 1;
}
if(config.clock)
clock_gettime(CLOCK_MONOTONIC, &start);
if(!LoadProfile(&config))
{
logmsg("Aborting\n");
return 1;
}
if(!SetupFolders(OUTPUT_FOLDER_MDW, "WAVE_Log_", &config))
{
logmsg("Aborting\n");
return 1;
}
if(!EndProfileLoad(&config))
{
logmsg("Aborting\n");
return 1;
}
if(ExecuteMDWave(&config, 0) == 1)
{
logmsg("Aborting\n");
return 1;
}
if(config.executefft)
{
if(!LoadProfile(&config))
return 1;
if(ExecuteMDWave(&config, 1) == 1)
return 1;
}
else
{
printf("\nResults stored in %s%s\n",
config.outputPath,
config.folderName);
}
if(config.clock)
{
double elapsedSeconds;
clock_gettime(CLOCK_MONOTONIC, &end);
elapsedSeconds = TimeSpecToSeconds(&end) - TimeSpecToSeconds(&start);
logmsg(" - clk: MDWave took %0.2fs\n", elapsedSeconds);
}
fftw_cleanup();
if(IsLogEnabled())
endLog();
return 0;
}
int ExecuteMDWave(parameters *config, int discardMDW)
{
AudioSignal *ReferenceSignal = NULL;
char *MainPath = NULL;
if(discardMDW)
{
logmsg("\n* Calculating values for Discard file\n");
config->discardMDW = 1;
}
if(!LoadFile(&ReferenceSignal, config->referenceFile, ROLE_REF, config))
{
CleanUp(&ReferenceSignal, config);
return 1;
}
if(!config->useCompProfile)
ReferenceSignal->role = ROLE_REF;
else
ReferenceSignal->role = ROLE_COMP;
config->referenceFramerate = ReferenceSignal->framerate;
config->smallerFramerate = ReferenceSignal->framerate;
/* Balance check */
if(config->channelBalance && !config->noSyncProfile)
{
if(ReferenceSignal->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;
}
else
{
logmsg(" - WARNING: No mono block for stereo balance check\n");
config->channelBalance = -1;
}
}
}
SetAmplitudeMatchByDurationMDW(ReferenceSignal, config);
logmsg("\n* Processing Audio\n");
MainPath = PushMainPath(config);
if(!ProcessSignalMDW(ReferenceSignal, config))
{
CleanUp(&ReferenceSignal, config);
PopMainPath(&MainPath);
return 1;
}
PopMainPath(&MainPath);
//logmsg("* Max blanked frequencies per block %d\n", config->maxBlanked);
CleanUp(&ReferenceSignal, config);
if(discardMDW)
printf("\nResults stored in %s%s\n",
config->outputPath,
config->folderName);
return(0);
}
void CleanUp(AudioSignal **ReferenceSignal, parameters *config)
{
if(*ReferenceSignal)
{
ReleaseAudio(*ReferenceSignal, config);
free(*ReferenceSignal);
*ReferenceSignal = NULL;
}
ReleaseAudioBlockStructure(config);
}
char *GenerateFileNamePrefix(parameters *config)
{
return(config->discardMDW ? "2_Discarded" : "1_Used");
}
int CreateChunksFolder(parameters *config)
{
char name[BUFFER_SIZE*4];
sprintf(name, "%s%cChunks", config->folderName, FOLDERCHAR);
if(!CreateFolder(name))
return 0;
sprintf(name, "%s%cChunks%cProcessed", config->folderName, FOLDERCHAR, FOLDERCHAR);
if(!CreateFolder(name))
return 0;
sprintf(name, "%s%cChunks%cSource", config->folderName, FOLDERCHAR, FOLDERCHAR);
if(!CreateFolder(name))
return 0;
return 1;
}
int ProcessSignalMDW(AudioSignal *Signal, parameters *config)
{
long int pos = 0;
double longest = 0;
double *sampleBuffer;
long int sampleBufferSize = 0;
windowManager windows;
double *windowUsed = NULL;
long int loadedBlockSize = 0, i = 0, syncAdvance = 0;
struct timespec start, end;
char Name[BUFFER_SIZE*2+256], tempName[BUFFER_SIZE];
int discardSamples = 0, syncinternal = 0, hadSync = 0;
double leftDecimals = 0;
FILE *processed = NULL;
pos = Signal->startOffset;
longest = FramesToSeconds(Signal->framerate, GetLongestElementFrames(config));
if(!longest)
{
logmsg("\tERROR: Block definitions are invalid, total length is 0.\n");
return 0;
}
sampleBufferSize = SecondsToSamples(Signal->SampleRate, longest, Signal->AudioChannels, NULL, NULL);
sampleBuffer = (double*)malloc(sampleBufferSize*sizeof(double));
if(!sampleBuffer)
{
logmsg("\tERROR: malloc failed.\n");
return(0);
}
if(!initWindows(&windows, Signal->SampleRate, config->window, config))
{
logmsg("\tERROR: Could not create FFTW windows.\n");
return 0;
}
CompareFrameRatesMDW(Signal, GetMSPerFrame(Signal, config), config);
if(config->chunks && !CreateChunksFolder(config))
{
logmsg("\tERROR: Could not create output folders.\n");
return 0;
}
if(config->clock)
clock_gettime(CLOCK_MONOTONIC, &start);
while(i < config->types.totalBlocks)
{
double duration = 0, framerate = 0;
long int frames = 0, difference = 0, cutFrames = 0;
if(!syncinternal)
framerate = Signal->framerate;
else
framerate = config->referenceFramerate;
frames = GetBlockFrames(config, i);
cutFrames = GetBlockCutFrames(config, i);
duration = FramesToSeconds(framerate, frames);
if(Signal->Blocks[i].maskType == MASK_USE_WINDOW)
difference = GetSampleSizeDifferenceByFrameRate(framerate, frames, Signal->SampleRate, Signal->AudioChannels, config);
loadedBlockSize = SecondsToSamples(Signal->SampleRate, duration, Signal->AudioChannels, &discardSamples, &leftDecimals);
windowUsed = NULL;
if(Signal->Blocks[i].type >= TYPE_SILENCE || Signal->Blocks[i].type == TYPE_WATERMARK)
{
if(!syncinternal && Signal->Blocks[i].maskType == MASK_USE_WINDOW)
windowUsed = getWindowByLength(&windows, frames, cutFrames, config->smallerFramerate, config);
else
windowUsed = getWindowByLength(&windows, frames, cutFrames, framerate, config);
}
//logmsg("Loaded %ld Left %ld Discard %ld difference %ld Decimals %g\n", loadedBlockSize, discardSamples, difference, leftDecimals);
if(pos + loadedBlockSize > Signal->numSamples)
{
if(i != config->types.totalBlocks - 1)
{
config->smallFile |= Signal->role;
logmsg("\tUnexpected end of File, please record the full Audio Test from the 240p Test Suite.\n");
if(config->verbose)
logmsg("load: %ld size: %ld exceed: %ld pos: %ld limit: %ld\n", loadedBlockSize, sampleBufferSize, pos + loadedBlockSize, pos, Signal->numSamples);
}
break;
}
// Clean Buffer and fill it
memset(sampleBuffer, 0, sampleBufferSize*sizeof(double));
memcpy(sampleBuffer, Signal->Samples + pos, loadedBlockSize*sizeof(double));
if(Signal->Blocks[i].type >= TYPE_SILENCE && config->executefft)
{
if(!ExecuteDFFT(&Signal->Blocks[i], sampleBuffer, loadedBlockSize-difference, Signal->SampleRate, windowUsed, config, FORWARD_FFTW, Signal))
return 0;
}
if(config->chunks && !config->discardMDW)
{
sprintf(Name, "%s%cChunks%cSource%c%03ld_0_%010ld_%s_%03d_chunk.wav",
config->folderName, FOLDERCHAR, FOLDERCHAR, FOLDERCHAR,
i, SamplesForDisplay(pos+syncAdvance, Signal->AudioChannels),
GetBlockName(config, i), GetBlockSubIndex(config, i));
SaveWAVEChunk(Name, Signal, sampleBuffer, 0, loadedBlockSize, 0, config);
}
pos += loadedBlockSize;
pos += discardSamples;
if(Signal->Blocks[i].type == TYPE_INTERNAL_KNOWN)
{
if(!ProcessInternalSync(Signal, i, pos, &syncinternal, &syncAdvance, TYPE_INTERNAL_KNOWN, config))
return 0;
if(!syncinternal)
syncAdvance = 0;
hadSync = 1;
}
if(Signal->Blocks[i].type == TYPE_INTERNAL_UNKNOWN)
{
if(!ProcessInternalSync(Signal, i, pos, &syncinternal, &syncAdvance, TYPE_INTERNAL_UNKNOWN, config))
return 0;
if(!syncinternal)
syncAdvance = 0;
hadSync = 1;
}
i++;
}
if(config->executefft)
{
GlobalNormalize(Signal, config);
CalculateFrequencyBrackets(Signal, config);
if(Signal->hasSilenceBlock && !config->ignoreFloor) // analyze noise floor if available
{
FindFloor(Signal, config);
if(Signal->floorAmplitude != 0.0 && Signal->floorAmplitude > config->significantAmplitude)
config->significantAmplitude = Signal->floorAmplitude;
}
logmsg(" - Using %g dBFS as minimum significant amplitude for analysis\n",
config->significantAmplitude);
if(config->verbose)
PrintFrequencies(Signal, config);
}
if(config->clock)
{
double elapsedSeconds;
clock_gettime(CLOCK_MONOTONIC, &end);
elapsedSeconds = TimeSpecToSeconds(&end) - TimeSpecToSeconds(&start);
logmsg(" - clk: FFTW on Audio chunks took %0.2fs\n", elapsedSeconds);
}
if(config->executefft)
{
if(config->clock)
clock_gettime(CLOCK_MONOTONIC, &start);
// Clean up everything again
pos = Signal->startOffset;
discardSamples = 0;
leftDecimals = 0;
i = 0;
// redo after processing
while(i < config->types.totalBlocks)
{
double duration = 0, framerate = 0;
long int frames = 0, difference = 0, cutFrames = 0;
if(!syncinternal)
framerate = Signal->framerate;
else
framerate = config->referenceFramerate;
frames = GetBlockFrames(config, i);
cutFrames = GetBlockCutFrames(config, i);
duration = FramesToSeconds(framerate, frames);
if(Signal->Blocks[i].maskType == MASK_USE_WINDOW)
difference = GetSampleSizeDifferenceByFrameRate(framerate, frames, Signal->SampleRate, Signal->AudioChannels, config);
loadedBlockSize = SecondsToSamples(Signal->SampleRate, duration, Signal->AudioChannels, &discardSamples, &leftDecimals);
windowUsed = NULL;
if(Signal->Blocks[i].type >= TYPE_SILENCE || Signal->Blocks[i].type == TYPE_WATERMARK)
{
if(!syncinternal && Signal->Blocks[i].maskType == MASK_USE_WINDOW)
windowUsed = getWindowByLength(&windows, frames, cutFrames, config->smallerFramerate, config);
else
windowUsed = getWindowByLength(&windows, frames, cutFrames, framerate, config);
}
//logmsg("Loaded %ld Left %ld Discard %ld difference %ld Decimals %g\n", loadedBlockSize, discardSamples, difference, leftDecimals);
if(pos + loadedBlockSize > Signal->numSamples)
{
if(i != config->types.totalBlocks - 1)
{
config->smallFile |= Signal->role;
logmsg("\tUnexpected end of File, please record the full Audio Test from the 240p Test Suite.\n");
if(config->verbose)
logmsg("load: %ld size: %ld exceed: %ld pos: %ld limit: %ld\n", loadedBlockSize, sampleBufferSize, pos + loadedBlockSize, pos, Signal->numSamples);
}
break;
}
// Clean Buffer and fill it
memset(sampleBuffer, 0, sampleBufferSize*sizeof(double));
memcpy(sampleBuffer, Signal->Samples + pos, loadedBlockSize*sizeof(double));
// Empty original signal, and overlap
if(pos > 4 && pos+loadedBlockSize+discardSamples+4 <= Signal->numSamples)
memset(Signal->Samples + pos-4, 0, (loadedBlockSize+discardSamples+4)*sizeof(double));
else
memset(Signal->Samples + pos, 0, loadedBlockSize*sizeof(double));
if(Signal->Blocks[i].type >= TYPE_SILENCE)
{
if(!ExecuteDFFT(&Signal->Blocks[i], sampleBuffer, loadedBlockSize-difference, Signal->SampleRate, windowUsed, config, REVERSE_FFTW, Signal))
return 0;
}
if(Signal->Blocks[i].type < TYPE_SILENCE && !config->discardMDW)
{
if(Signal->Blocks[i].type != TYPE_SYNC) // Copy control notes to discarded for reference
memcpy(sampleBuffer, Signal->Samples + pos, loadedBlockSize*sizeof(double));
}
// Fill back original signal with whatever we have in sampleBuffer
memcpy(Signal->Samples + pos, sampleBuffer, loadedBlockSize*sizeof(double));
pos += loadedBlockSize;
pos += discardSamples;
if(config->chunks && (Signal->Blocks[i].type >= TYPE_SILENCE || Signal->Blocks[i].type == TYPE_WATERMARK))
{
sprintf(tempName, "Chunks%cProcessed%c%03ld_%s_%s_%03d_chunk", FOLDERCHAR, FOLDERCHAR, i,
GenerateFileNamePrefix(config), GetBlockName(config, i),
GetBlockSubIndex(config, i));
ComposeFileName(Name, tempName, ".wav", config);
SaveWAVEChunk(Name, Signal, sampleBuffer, 0, loadedBlockSize, 0, config);
}
// Use original framerate for CD-DA chunks
if(Signal->Blocks[i].type == TYPE_INTERNAL_KNOWN || Signal->Blocks[i].type == TYPE_INTERNAL_UNKNOWN)
syncinternal = !syncinternal;
i++;
}
// clear the rest of the buffer
memset(Signal->Samples + pos, 0, (sizeof(double)*(Signal->numSamples - pos)));
ComposeFileName(Name, GenerateFileNamePrefix(config), ".wav", config);
processed = fopen(Name, "wb");
if(!processed)
{
logmsg("\tCould not open processed file %s\n", Name);
return 0;
}
SaveWAVEChunk(Name, Signal, Signal->Samples, 0, Signal->numSamples, 0, config);
if(processed)
{
fclose(processed);
processed = NULL;
}
}
// save frequency unprocesed wav if requested with -n, for internal sync and verification
if(hadSync && !config->executefft)
{
ComposeFileName(Name, "SyncRemoved", ".wav", config);
processed = fopen(Name, "wb");
if(!processed)
{
logmsg("\tCould not open processed file %s\n", Name);
return 0;
}
SaveWAVEChunk(Name, Signal, Signal->Samples, 0, Signal->numSamples, 0, config);
if(processed)
{
fclose(processed);
processed = NULL;
}
}
if(config->clock)
{
double elapsedSeconds;
clock_gettime(CLOCK_MONOTONIC, &end);
elapsedSeconds = TimeSpecToSeconds(&end) - TimeSpecToSeconds(&start);
logmsg(" - clk: iFFTW on Audio chunks took %0.2fs\n", elapsedSeconds);
}
free(sampleBuffer);
freeWindows(&windows);
return 1;
}
int ExecuteDFFT(AudioBlocks *AudioArray, double *samples, long int size, double samplerate, double *window, parameters *config, int fftw_direction, AudioSignal *Signal)
{
int AudioChannels = Signal->AudioChannels;
char channel = CHANNEL_STEREO;
if(AudioChannels == 1)
channel = CHANNEL_LEFT;
else
{
// If we are procesing a mono signal in a stereo file, use both channels
if(AudioArray->channel == CHANNEL_MONO)
channel = CHANNEL_STEREO;
if(AudioArray->channel == CHANNEL_STEREO)
{
channel = CHANNEL_RIGHT;
if(!ExecuteDFFTInternal(AudioArray, samples, size, samplerate, window, channel, config, fftw_direction, Signal))
return 0;
channel = CHANNEL_LEFT;
}
}
if(!ExecuteDFFTInternal(AudioArray, samples, size, samplerate, window, channel, config, fftw_direction, Signal))
return 0;
if(fftw_direction == FORWARD_FFTW)
{
if(!FillFrequencyStructures(Signal, AudioArray, config))
return 0;
}
return 1;
}
int ExecuteDFFTInternal(AudioBlocks *AudioArray, double *samples, long int size, double samplerate, double *window, char channel, parameters *config, int fftw_direction, AudioSignal *Signal)
{
fftw_plan p = NULL, pBack = NULL;
long int stereoSignalSize = 0, blanked = 0;
long int i = 0, monoSignalSize = 0, zeropadding = 0;
double *signal = NULL;
fftw_complex *spectrum = NULL;
double boxsize = 0, seconds = 0;
double CutOff = 0;
long int startBin = 0, endBin = 0;
int AudioChannels = Signal->AudioChannels;
if(!AudioArray)
{
logmsg("No Array for results\n");
return 0;
}
//logmsg("discardMDW %d fftw_direction %s\n", config->discardMDW, fftw_direction == FORWARD_FFTW ? "forward" : "reverse");
stereoSignalSize = (long)size;
monoSignalSize = stereoSignalSize/AudioChannels;
seconds = (double)size/(samplerate*(double)AudioChannels);
if(config->ZeroPad) /* disabled by default */
zeropadding = GetZeroPadValues(&monoSignalSize, &seconds, samplerate);
// Round to 3 decimal places so that 48kHz and 44 kHz line up
boxsize = RoundFloat(AudioArray->seconds, 3);
startBin = floor(config->startHz*boxsize);
endBin = floor(config->endHz*boxsize);
if(Signal->nyquistLimit && endBin > size/2)
endBin = ceil(size/2);
signal = (double*)malloc(sizeof(double)*(monoSignalSize+1));
if(!signal)
{
logmsg("Not enough memory (malloc)\n");
return(0);
}
spectrum = (fftw_complex*)fftw_malloc(sizeof(fftw_complex)*(monoSignalSize/2+1));
if(!spectrum)
{
logmsg("Not enough memory (fftw_malloc)\n");
return(0);
}
if(!config->model_plan)
{
config->model_plan = fftw_plan_dft_r2c_1d(monoSignalSize, signal, spectrum, FFTW_MEASURE);
if(!config->model_plan)
{
logmsg("FFTW failed to create FFTW_MEASURE plan\n");
free(signal);
signal = NULL;
return 0;
}
}
p = fftw_plan_dft_r2c_1d(monoSignalSize, signal, spectrum, FFTW_MEASURE);
if(!p)
{
logmsg("FFTW failed to create FFTW_MEASURE plan\n");
free(signal);
signal = NULL;
return 0;
}
if(fftw_direction == REVERSE_FFTW)
{
if(!config->reverse_plan)
{
config->reverse_plan = fftw_plan_dft_c2r_1d(monoSignalSize, spectrum, signal, FFTW_MEASURE);
if(!config->reverse_plan)
{
logmsg("FFTW failed to create FFTW_MEASURE reverse plan\n");
free(signal);
signal = NULL;
return 0;
}
}
pBack = fftw_plan_dft_c2r_1d(monoSignalSize, spectrum, signal, FFTW_MEASURE);
if(!pBack)
{
logmsg("FFTW failed to create FFTW_MEASURE plan\n");
free(signal);
signal = NULL;
return 0;
}
}
memset(signal, 0, sizeof(double)*(monoSignalSize+1));
memset(spectrum, 0, sizeof(fftw_complex)*(monoSignalSize/2+1));
for(i = 0; i < monoSignalSize - zeropadding; i++)
{
if(channel == CHANNEL_LEFT)
signal[i] = samples[i*AudioChannels];
if(channel == CHANNEL_RIGHT)
signal[i] = samples[i*AudioChannels+1];
if(channel == CHANNEL_STEREO)
signal[i] = (samples[i*AudioChannels]+samples[i*AudioChannels+1])/2.0;
if(window)
signal[i] = signal[i]*window[i];
}
fftw_execute(p);
fftw_destroy_plan(p);
p = NULL;
if(fftw_direction == FORWARD_FFTW)
{
if(channel != CHANNEL_RIGHT)
{
AudioArray->fftwValues.spectrum = spectrum;
AudioArray->fftwValues.size = monoSignalSize;
AudioArray->fftwValues.ENBW = monoSignalSize;
}
else
{
AudioArray->fftwValuesRight.spectrum = spectrum;
AudioArray->fftwValuesRight.size = monoSignalSize;
AudioArray->fftwValuesRight.ENBW = monoSignalSize;
}
AudioArray->seconds = seconds;
}
if(fftw_direction == REVERSE_FFTW)
{
long int endBinLimit = 0;
double MinAmplitude = 0;
Frequency *targetFreq = NULL;
// Find the Max magnitude for frequency at -f cuttoff
if(channel != CHANNEL_RIGHT)
targetFreq = AudioArray->freq;
else
targetFreq = AudioArray->freqRight;
if(!targetFreq)
{
logmsg("Invalid channel data\n");
return 0;
}
for(int j = 0; j < config->MaxFreq; j++)
{
if(!targetFreq[j].hertz)
break;
if(targetFreq[j].amplitude < MinAmplitude)
MinAmplitude = targetFreq[j].amplitude;
}
CutOff = MinAmplitude;
if(CutOff < config->significantAmplitude)
CutOff = config->significantAmplitude;
if(!config->ignoreFloor && Signal->hasSilenceBlock &&
CutOff < Signal->floorAmplitude && Signal->floorAmplitude != 0.0)
CutOff = Signal->floorAmplitude;
//Process the defined frequency spectrum
endBinLimit = floor(boxsize*(samplerate/2));
if(endBinLimit > monoSignalSize/2)
endBinLimit = monoSignalSize/2;
for(i = 1; i < endBinLimit; i++)
{
double amplitude = 0, magnitude = 0;
int blank = 0;
magnitude = CalculateMagnitude(&spectrum[i], monoSignalSize);
amplitude = CalculateAmplitude(magnitude, Signal->MaxMagnitude.magnitude);
// limit by noise cut frequncy count/amplitude
if(amplitude <= CutOff)
blank = 1;
// Limit startHz to endHz
if(i < startBin || i > endBin)
blank = 1;
if(config->discardMDW)
blank = !blank;
if(blank)
{
fftw_complex filter;
// This should never be done as such
// A proper filter should be used, or you'll get
// ringing artifacts via Gibbs phenomenon
// Here it "works" because we are just
// "visualizing" the results
filter = 0;
spectrum[i] = spectrum[i]*filter;
blanked ++;
}
}
// Magic! iFFTW
fftw_execute(pBack);
fftw_destroy_plan(pBack);
pBack = NULL;
for(i = 0; i < monoSignalSize - zeropadding; i++)
{
double value;
// reversing window causes distortion since we have zeroes
// but we do want to see the windows in the iFFT anyway
// uncomment if needed
//if(window && window[i])
//value = (signal[i]/window[i])/monoSignalSize;
//else
value = signal[i]/monoSignalSize; /* check CalculateMagnitude if changed */
if(channel == CHANNEL_LEFT || channel == CHANNEL_STEREO || channel == CHANNEL_MONO)
samples[i*AudioChannels] = value;
if(channel == CHANNEL_RIGHT || channel == CHANNEL_STEREO)
samples[i*AudioChannels+1] = value;
}
//logmsg("Blanked %ld frequencies from a total of %ld\n", blanked, monoSignalSize/2);
if(blanked > config->maxBlanked)
config->maxBlanked = blanked;
fftw_free(spectrum);
}
free(signal);
signal = NULL;
return(1);
}
int commandline_wave(int argc , char *argv[], parameters *config)
{
FILE *file = NULL;
int c, index, ref = 0;
opterr = 0;
CleanParameters(config);
config->maxBlanked = 0;
config->discardMDW = 0;
config->chunks = 0;
config->useCompProfile = 0;
config->executefft = 1;
while ((c = getopt (argc, argv, "qnhvzcklyCBis:e:f:m:t:p:w:r:P:IY:T0:9")) != -1)
switch (c)
{
case 'h':
PrintUsage_wave();
return 0;
break;
case 'n':
config->executefft = 0;
break;
case 'v':
config->verbose = 1;
break;
case 'c':
config->chunks = 1;
break;
case 'k':
config->clock = 1;
break;
case 'l':
EnableLog();
break;
case 'z':
config->ZeroPad = 1;
break;
case 'i':
config->ignoreFloor = 1; // RELEVANT HERE!
break;
case 'y':
config->debugSync = 1;
break;
case 's':
config->startHz = atof(optarg);
if(config->startHz < 1.0 || config->startHz > MAX_HZ-100.0)
{
logmsg("-ERROR: Requested %g start frequency is out of range\n", atof(optarg));
return 0;
}
break;
case 'e':
config->endHz = atof(optarg);
if(config->endHz < START_HZ*2.0)
{
logmsg("- ERROR: Requested %g end frequency is lower than possible\n", atof(optarg));
return 0;
}
if(config->endHz > MAX_HZ)
{
logmsg("-ERROR: Requested %g end frequency is higher than possible\n", atof(optarg));
return 0;
}
if(config->endHz > END_HZ)
config->endHzPlot = config->endHz;
break;
case 'f':
config->MaxFreq = atoi(optarg);
if(config->MaxFreq < 1 || config->MaxFreq > MAX_FREQ_COUNT)
{
logmsg("-ERROR: Number fo frequencies must be between %d and %d\n", 1, MAX_FREQ_COUNT);
return 0;
}
break;
case 'm':
{
char manualType = '\0';
long start = 0, end = 0;
if(sscanf(optarg, "%c:%ld:%ld\n", &manualType, &start, &end) != 3 ||
(manualType != 'r' && manualType != 'c'))
{
logmsg("-ERROR: Invalid manual offset (-m) parameter: %s.\n", optarg);
logmsg(" Must be of the form [r|c]:<start sample>:<end sample>\n");
return 0;
}
if(end <= start)
{
logmsg("ERROR: For manual sample offset, ending offset must be bigger than the starting offset\n");
return 0;
}
if(manualType == 'r')
{
config->ManualSyncRef = 1;
config->ManualSyncRefStart = start;
config->ManualSyncRefEnd = end;
logmsg("- Reference ");
}
if(manualType == 'c')
{
config->ManualSyncComp = 1;
config->ManualSyncCompStart = start;
config->ManualSyncCompEnd = end;
logmsg("- Comparison ");
}
logmsg("manual sample offset set %ld-%ld\n", start, end);
}
break;
case 'p':
config->significantAmplitude = atof(optarg);
if(config->significantAmplitude == 0)
{
config->noiseFloorAutoAdjust = 0;
config->significantAmplitude = SIGNIFICANT_AMPLITUDE;
}
else if(config->significantAmplitude < -250.0 || config->significantAmplitude > -1.0)
{
logmsg("-ERROR: Significant amplitude must be between %d and %d\n", -1, -250);
return 0;
} else {
config->ignoreFloor = 2;
config->origSignificantAmplitude = config->significantAmplitude;
}
break;
case 'q':
config->compressToBlocks = 1;
break;
case 'Y':
config->videoFormatRef = atoi(optarg);
if(config->videoFormatRef < 0 || config->videoFormatRef > MAX_SYNC) // We'll confirm this later
{
logmsg("- ERROR: Profile can have up to %d types\n", MAX_SYNC);
return 0;
}
break;
case 'w':
switch(optarg[0])
{
case 'n':
case 'f':
case 'h':
case 't':
config->window = optarg[0];
break;
default:
logmsg("- ERROR: Invalid Window for FFT option '%c'\n", optarg[0]);
logmsg("\tUse n for None, t for Tukey window (default), f for Flattop or h for Hann window\n");
return 0;
break;
}
break;
case 'r':
sprintf(config->referenceFile, "%s", optarg);
ref = 1;
break;
case 'P':
sprintf(config->profileFile, "%s", optarg);
break;
case 'B':
config->channelBalance = 0;
break;
case 'C':
config->useCompProfile = 1;
break;
case 'I':