forked from Sneeds-Feed-and-Seed/sneedacity
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathVoiceKey.cpp
1019 lines (793 loc) · 36.8 KB
/
VoiceKey.cpp
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
/**********************************************************************
Sneedacity: A Digital Audio Editor
VoiceKey.cpp
?? Dominic Mazzoni
?? Shane Muller
*******************************************************************//*!
\class VoiceKey
\brief
This implements a voice key, detecting either the next "ON"
or "OFF" point
*//*******************************************************************/
#include "VoiceKey.h"
#include <wx/string.h>
#include <math.h>
#include <stdio.h>
#include <wx/textfile.h>
#include <wx/intl.h>
#include <iostream>
#include "WaveTrack.h"
#include "widgets/SneedacityMessageBox.h"
#include "widgets/ErrorDialog.h"
using std::cout;
using std::endl;
VoiceKey::VoiceKey()
{
mWindowSize = 0.01; //size of analysis window in seconds
mEnergyMean = .0006; // reasonable initial levels assuming sampling rate of
mEnergySD = .0002; // 44100 hertz
mSignChangesMean = .08;
mSignChangesSD= .02;
mDirectionChangesMean = .25;
mDirectionChangesSD = .2;
AdjustThreshold(2);
mSilentWindowSize = .05; //Amount of time (in seconds) below threshold to call it silence
mSignalWindowSize = .05; //Amount of time (in seconds) above threshold to call it signal
mUseEnergy = true;
mUseSignChangesLow = false;
mUseSignChangesHigh = false;
mUseDirectionChangesLow = false;
mUseDirectionChangesHigh = false;
};
VoiceKey::~VoiceKey()
{
};
//---------------------------------------------------------------------------
// VoiceKey::On/Off Forward/Backward
// This operates in two phases:
// First, you take chunks of samples that are WindowSize big.
// If you have a run of them where something passes the threshold for SignalWindowSize seconds,
// you return to the last empty block and scan forward one sample at a time until you find the
// starting point of the speech.
//Move forward to find an ON region.
sampleCount VoiceKey::OnForward (
const WaveTrack & t, sampleCount start, sampleCount len)
{
if((mWindowSize) >= (len + 10).as_double() ){
/* i18n-hint: Voice key is an experimental/incomplete feature that
is used to navigate in vocal recordings, to move forwards and
backwards by words. So 'key' is being used in the sense of an index.
This error message means that you've selected too short
a region of audio to be able to use this feature.*/
SneedacityMessageBox( XO("Selection is too small to use voice key.") );
return start;
}
else {
//Change the millisecond-based parameters into sample-based parameters
double rate = t.GetRate(); //Translates seconds to samples
size_t WindowSizeInt = (rate * mWindowSize); //Size of window to examine
size_t SignalWindowSizeInt = (rate * mSignalWindowSize); //This much signal is necessary to trip key
auto samplesleft = len - WindowSizeInt; //Indexes the number of samples remaining in the selection
auto lastsubthresholdsample = start; //start this off at the selection start
// keeps track of the sample number of the last sample to not exceed the threshold
int blockruns=0; //keeps track of the number of consecutive above-threshold blocks
//This loop goes through the selection a block at a time. If a long enough run
//of above-threshold blocks occur, we return to the last sub-threshold block and
//go through one sample at a time.
//If there are fewer than 10 samples leftover, don't bother.
for(auto i = start; samplesleft >= 10;
i += (WindowSizeInt - 1) , samplesleft -= (WindowSizeInt - 1)) {
//Set blocksize so that it is the right size
const auto blocksize = limitSampleBufferSize( WindowSizeInt, samplesleft);
//Test whether we are above threshold (the number of stats)
if(AboveThreshold(t,i,blocksize))
{
blockruns++; //Hit
} else {
blockruns=0; //Miss--start over
lastsubthresholdsample = i;
}
//If the blockrun is long enough, break out of the loop early:
if(blockruns > mSignalWindowSize/mWindowSize)
break;
}
//Now, if we broke out early (samplesleft > 10), go back to the lastsubthresholdsample and look more carefully
if(samplesleft > 10) {
//Calculate how many to scan through--we only have to go through (at most)
//the first window + 1 samples--but we need another window samples to draw from.
size_t remaining = 2*WindowSizeInt+1;
//To speed things up, create a local buffer to store things in, to avoid the costly t.Get();
//Only go through the first SignalWindowSizeInt samples, and choose the first that trips the key.
Floats buffer{ remaining };
t.GetFloats(buffer.get(),
lastsubthresholdsample, remaining);
//Initialize these trend markers atrend and ztrend. They keep track of the
//up/down trends at the start and end of the evaluation window.
int atrend = sgn(buffer[1]-buffer[0]);
int ztrend = sgn(buffer[WindowSizeInt+1]-buffer[WindowSizeInt]);
double erg=0;
double sc=0;
double dc=0;
//Get initial test statistic values.
if(mUseEnergy)
erg = TestEnergy(t, lastsubthresholdsample, WindowSizeInt);
if(mUseSignChangesLow || mUseSignChangesHigh)
sc = TestSignChanges(t,lastsubthresholdsample, WindowSizeInt);
if(mUseDirectionChangesLow || mUseDirectionChangesHigh)
dc = TestDirectionChanges(t,lastsubthresholdsample,WindowSizeInt);
//Now, go through the sound again, sample by sample.
wxASSERT(WindowSizeInt < SignalWindowSizeInt);
size_t i;
for(i = 0; i + WindowSizeInt < SignalWindowSizeInt; i++) {
int tests = 0;
int testThreshold = 0;
//Update the test statistics
if(mUseEnergy)
{
TestEnergyUpdate(erg, WindowSizeInt,buffer[i],buffer[i+WindowSizeInt+1]);
tests += (int)(erg>mThresholdEnergy);
testThreshold++;
}
if(mUseSignChangesLow)
{
TestSignChangesUpdate(sc,WindowSizeInt,buffer[i],buffer[i+1],buffer[i+WindowSizeInt],buffer[i+WindowSizeInt+1]);
tests += (int)(sc < mThresholdSignChangesLower);
testThreshold++;
}
if(mUseSignChangesHigh)
{
TestSignChangesUpdate(sc,WindowSizeInt,buffer[i],buffer[i+1],buffer[i+WindowSizeInt],buffer[i+WindowSizeInt+1]);
tests += (int)(sc > mThresholdSignChangesUpper);
testThreshold++;
}
if(mUseDirectionChangesLow)
{
TestDirectionChangesUpdate(dc,WindowSizeInt,atrend,buffer[i],buffer[i+1],ztrend,buffer[i+WindowSizeInt],buffer[i+WindowSizeInt+1]);
tests += (int)(dc < mThresholdDirectionChangesLower);
testThreshold++;
}
if(mUseDirectionChangesHigh)
{
TestDirectionChangesUpdate(dc,WindowSizeInt,atrend,buffer[i],buffer[i+1],ztrend,buffer[i+WindowSizeInt],buffer[i+WindowSizeInt+1]);
tests += (int)(dc > mThresholdDirectionChangesUpper);
testThreshold++;
}
if(tests >= testThreshold)
{ //Finish off on the first hit
break;
}
}
//When we get here, i+lastsubthresholdsample is the best guess for where the word starts
return i + lastsubthresholdsample;
}
else {
//If we failed to find anything, return the start position
return start ;
}
}
}
//Move backward from end to find an ON region.
sampleCount VoiceKey::OnBackward (
const WaveTrack & t, sampleCount end, sampleCount len)
{
if((mWindowSize) >= (len + 10).as_double() ){
SneedacityMessageBox( XO("Selection is too small to use voice key.") );
return end;
}
else {
//Change the millisecond-based parameters into sample-based parameters
double rate = t.GetRate(); //Translates seconds to samples
size_t WindowSizeInt = (rate * mWindowSize); //Size of window to examine
//unsigned int SilentWindowSizeInt = (unsigned int)(rate * mSilentWindowSize); //This much signal is necessary to trip key
auto samplesleft = len - WindowSizeInt; //Indexes the number of samples remaining in the selection
auto lastsubthresholdsample = end; //start this off at the end
// keeps track of the sample number of the last sample to not exceed the threshold
int blockruns=0; //keeps track of the number of consecutive above-threshold blocks
//This loop goes through the selection a block at a time in reverse order. If a long enough run
//of above-threshold blocks occur, we return to the last sub-threshold block and
//go through one sample at a time.
//If there are fewer than 10 samples leftover, don't bother.
for(auto i = end - WindowSizeInt; samplesleft >= 10;
i -= (WindowSizeInt - 1) , samplesleft -= (WindowSizeInt - 1)) {
//Set blocksize so that it is the right size
const auto blocksize = limitSampleBufferSize( WindowSizeInt, samplesleft);
//Test whether we are above threshold
if(AboveThreshold(t,i,blocksize))
{
blockruns++; //Hit
}
else
{
blockruns=0; //Miss--start over
lastsubthresholdsample = i+WindowSizeInt;
}
//If the blockrun is long enough, break out of the loop early:
if(blockruns > mSilentWindowSize/mWindowSize)
break;
}
//Now, if we broke out early (samplesleft > 10), go back to the lastsubthresholdsample and look more carefully
if(samplesleft > 10) {
//Calculate how many to scan through--we only have to go through (at most)
//the first window + 1 samples--but we need another window samples to draw from.
size_t remaining = 2*WindowSizeInt+1;
//To speed things up, create a local buffer to store things in, to avoid the costly t.Get();
//Only go through the first mSilentWindowSizeInt samples, and choose the first that trips the key.
Floats buffer{ remaining };
t.GetFloats(buffer.get(),
lastsubthresholdsample - remaining, remaining);
//Initialize these trend markers atrend and ztrend. They keep track of the
//up/down trends at the start and end of the evaluation window.
int atrend = sgn(buffer[remaining - 2]-buffer[remaining - 1]);
int ztrend = sgn(buffer[remaining - WindowSizeInt - 2] -
buffer[remaining - WindowSizeInt
// PVS-Studio detected a probable error here
// when it read - 2.
// is - 1 correct?
// This code is unused. I didn't study further.
- 1
]);
double erg=0;
double sc = 0;
double dc = 0;
//Get initial test statistic values.
if(mUseEnergy)
erg = TestEnergy(t, lastsubthresholdsample, WindowSizeInt);
if(mUseSignChangesLow || mUseSignChangesHigh)
sc = TestSignChanges(t,lastsubthresholdsample, WindowSizeInt);
if(mUseDirectionChangesLow || mUseDirectionChangesHigh)
dc = TestDirectionChanges(t,lastsubthresholdsample,WindowSizeInt);
//Now, go through the sound again, sample by sample.
size_t i;
for(i = remaining - 1; i > WindowSizeInt; i--) {
int tests = 0;
int testThreshold = 0;
//Update the test statistics
if(mUseEnergy)
{
TestEnergyUpdate(erg, WindowSizeInt,buffer[i],buffer[i+WindowSizeInt+1]);
tests += (int)(erg>mThresholdEnergy);
testThreshold++;
}
if(mUseSignChangesLow)
{
TestSignChangesUpdate(sc,WindowSizeInt,buffer[i],buffer[i+1],buffer[i+WindowSizeInt],buffer[i+WindowSizeInt+1]);
tests += (int)(sc < mThresholdSignChangesLower);
testThreshold++;
}
if(mUseSignChangesHigh)
{
TestSignChangesUpdate(sc,WindowSizeInt,buffer[i],buffer[i+1],buffer[i+WindowSizeInt],buffer[i+WindowSizeInt+1]);
tests += (int)(sc > mThresholdSignChangesUpper);
testThreshold++;
}
if(mUseDirectionChangesLow)
{
TestDirectionChangesUpdate(dc,WindowSizeInt,atrend,buffer[i],buffer[i+1],ztrend,buffer[i+WindowSizeInt],buffer[i+WindowSizeInt+1]);
tests += (int)(dc < mThresholdDirectionChangesLower);
testThreshold++;
}
if(mUseDirectionChangesHigh)
{
TestDirectionChangesUpdate(dc,WindowSizeInt,atrend,buffer[i],buffer[i+1],ztrend,buffer[i+WindowSizeInt],buffer[i+WindowSizeInt+1]);
tests += (int)(dc > mThresholdDirectionChangesUpper);
testThreshold++;
}
if(tests >= testThreshold)
{ //Finish off on the first hit
break;
}
}
//When we get here, i+lastsubthresholdsample is the best guess for where the word starts
return lastsubthresholdsample - remaining + i;
}
else {
//If we failed to find anything, return the start position
return end ;
}
}
}
//Move forward from the start to find an OFF region.
sampleCount VoiceKey::OffForward (
const WaveTrack & t, sampleCount start, sampleCount len)
{
if((mWindowSize) >= (len + 10).as_double() ){
SneedacityMessageBox( XO("Selection is too small to use voice key.") );
return start;
}
else {
//Change the millisecond-based parameters into sample-based parameters
double rate = t.GetRate(); //Translates seconds to samples
unsigned int WindowSizeInt = (unsigned int)(rate * mWindowSize); //Size of window to examine
unsigned int SilentWindowSizeInt = (unsigned int)(rate * mSilentWindowSize); //This much signal is necessary to trip key
sampleCount samplesleft ( len.as_double() - WindowSizeInt ); //Indexes the number of samples remaining in the selection
auto lastsubthresholdsample = start; //start this off at the selection start
// keeps track of the sample number of the last sample to not exceed the threshold
int blockruns=0; //keeps track of the number of consecutive above-threshold blocks
//This loop goes through the selection a block at a time. If a long enough run
//of above-threshold blocks occur, we return to the last sub-threshold block and
//go through one sample at a time.
//If there are fewer than 10 samples leftover, don't bother.
for(auto i = start; samplesleft >= 10;
i += (WindowSizeInt - 1) , samplesleft -= (WindowSizeInt - 1)) {
//Set blocksize so that it is the right size
const auto blocksize = limitSampleBufferSize( WindowSizeInt, samplesleft);
if(!AboveThreshold(t,i,blocksize))
{
blockruns++; //Hit
}
else
{
blockruns=0; //Above threshold--start over
lastsubthresholdsample = i;
}
//If the blockrun is long enough, break out of the loop early:
if(blockruns > mSilentWindowSize/mWindowSize)
break;
}
//Now, if we broke out early (samplesleft > 10), go back to the lastsubthresholdsample and look more carefully
if(samplesleft > 10) {
//Calculate how many to scan through--we only have to go through (at most)
//the first window + 1 samples--but we need another window samples to draw from.
size_t remaining = 2*WindowSizeInt+1;
//To speed things up, create a local buffer to store things in, to avoid the costly t.Get();
//Only go through the first SilentWindowSizeInt samples, and choose the first that trips the key.
Floats buffer{ remaining };
t.GetFloats(buffer.get(),
lastsubthresholdsample, remaining);
//Initialize these trend markers atrend and ztrend. They keep track of the
//up/down trends at the start and end of the evaluation window.
int atrend = sgn(buffer[1]-buffer[0]);
int ztrend = sgn(buffer[WindowSizeInt+1]-buffer[WindowSizeInt]);
double erg=0;
double sc=0;
double dc=0;
//Get initial test statistic values.
if(mUseEnergy)
erg = TestEnergy(t, lastsubthresholdsample, WindowSizeInt);
if(mUseSignChangesLow || mUseSignChangesHigh)
sc = TestSignChanges(t,lastsubthresholdsample, WindowSizeInt);
if(mUseDirectionChangesLow || mUseDirectionChangesHigh)
dc = TestDirectionChanges(t,lastsubthresholdsample,WindowSizeInt);
//Now, go through the sound again, sample by sample.
size_t i;
for(i = 0; i < SilentWindowSizeInt - WindowSizeInt; i++) {
int tests = 0;
int testThreshold = 0;
//Update the test statistics
if(mUseEnergy)
{
TestEnergyUpdate(erg, WindowSizeInt,buffer[i],buffer[i+WindowSizeInt+1]);
tests += (int)(erg>mThresholdEnergy);
testThreshold++;
}
if(mUseSignChangesLow)
{
TestSignChangesUpdate(sc,WindowSizeInt,buffer[i],buffer[i+1],buffer[i+WindowSizeInt],buffer[i+WindowSizeInt+1]);
tests += (int)(sc < mThresholdSignChangesLower);
testThreshold++;
}
if(mUseSignChangesHigh)
{
TestSignChangesUpdate(sc,WindowSizeInt,buffer[i],buffer[i+1],buffer[i+WindowSizeInt],buffer[i+WindowSizeInt+1]);
tests += (int)(sc > mThresholdSignChangesUpper);
testThreshold++;
}
if(mUseDirectionChangesLow)
{
TestDirectionChangesUpdate(dc,WindowSizeInt,atrend,buffer[i],buffer[i+1],ztrend,buffer[i+WindowSizeInt],buffer[i+WindowSizeInt+1]);
tests += (int)(dc < mThresholdDirectionChangesLower);
testThreshold++;
}
if(mUseDirectionChangesHigh)
{
TestDirectionChangesUpdate(dc,WindowSizeInt,atrend,buffer[i],buffer[i+1],ztrend,buffer[i+WindowSizeInt],buffer[i+WindowSizeInt+1]);
tests += (int)(dc > mThresholdDirectionChangesUpper);
testThreshold++;
}
if(tests < testThreshold)
{ //Finish off on the first below-threshold block
break;
}
}
//When we get here, i+lastsubthresholdsample is the best guess for where the word starts
return i + lastsubthresholdsample;
}
else {
//If we failed to find anything, return the start position
return start ;
}
}
}
//Move backward from the end to find an OFF region
sampleCount VoiceKey::OffBackward (
const WaveTrack & t, sampleCount end, sampleCount len)
{
if((mWindowSize) >= (len + 10).as_double() ){
SneedacityMessageBox( XO("Selection is too small to use voice key.") );
return end;
}
else {
//Change the millisecond-based parameters into sample-based parameters
double rate = t.GetRate(); //Translates seconds to samples
unsigned int WindowSizeInt = (unsigned int)(rate * mWindowSize); //Size of window to examine
//unsigned int SilentWindowSizeInt = (unsigned int)(rate * mSilentWindowSize); //This much signal is necessary to trip key
auto samplesleft = len - WindowSizeInt; //Indexes the number of samples remaining in the selection
auto lastsubthresholdsample = end; //start this off at the end
// keeps track of the sample number of the last sample to not exceed the threshold
int blockruns=0; //keeps track of the number of consecutive above-threshold blocks
//This loop goes through the selection a block at a time in reverse order. If a long enough run
//of above-threshold blocks occur, we return to the last sub-threshold block and
//go through one sample at a time.
//If there are fewer than 10 samples leftover, don't bother.
for(auto i = end - WindowSizeInt; samplesleft >= 10;
i -= (WindowSizeInt - 1), samplesleft -= (WindowSizeInt -1 )) {
//Set blocksize so that it is the right size
const auto blocksize = limitSampleBufferSize( WindowSizeInt, samplesleft);
if(!AboveThreshold(t,i,blocksize))
{
blockruns++; //Hit
}
else
{
blockruns=0; //Miss--start over
lastsubthresholdsample = i+WindowSizeInt;
}
//If the blockrun is long enough, break out of the loop early:
if(blockruns > mSilentWindowSize/mWindowSize)
break;
}
//Now, if we broke out early (samplesleft > 10), go back to the lastsubthresholdsample and look more carefully
if(samplesleft > 10) {
//Calculate how many to scan through--we only have to go through (at most)
//the first window + 1 samples--but we need another window samples to draw from.
const size_t remaining = 2*WindowSizeInt+1;
//To speed things up, create a local buffer to store things in, to avoid the costly t.Get();
//Only go through the first SilentWindowSizeInt samples, and choose the first that trips the key.
Floats buffer{ remaining };
t.GetFloats(buffer.get(),
lastsubthresholdsample - remaining, remaining);
//Initialize these trend markers atrend and ztrend. They keep track of the
//up/down trends at the start and end of the remaining window.
int atrend = sgn(buffer[remaining - 2] - buffer[remaining - 1]);
int ztrend =
sgn(buffer[remaining - WindowSizeInt - 2] -
buffer[remaining - WindowSizeInt - 2]);
double erg=0;
double sc=0;
double dc=0;
//Get initial test statistic values.
if(mUseEnergy)
erg = TestEnergy(t, lastsubthresholdsample, WindowSizeInt);
if(mUseSignChangesLow || mUseSignChangesHigh)
sc = TestSignChanges(t,lastsubthresholdsample, WindowSizeInt);
if(mUseDirectionChangesLow || mUseDirectionChangesHigh)
dc = TestDirectionChanges(t,lastsubthresholdsample,WindowSizeInt);
//Now, go through the sound again, sample by sample.
size_t i;
for(i = remaining - 1; i > WindowSizeInt; i--) {
int tests = 0;
int testThreshold = 0;
//Update the test statistics
if(mUseEnergy)
{
TestEnergyUpdate(erg, WindowSizeInt,buffer[i],buffer[i+WindowSizeInt+1]);
tests += (int)(erg>mThresholdEnergy);
testThreshold++;
}
if(mUseSignChangesLow)
{
TestSignChangesUpdate(sc,WindowSizeInt,buffer[i],buffer[i+1],buffer[i+WindowSizeInt],buffer[i+WindowSizeInt+1]);
tests += (int)(sc < mThresholdSignChangesLower);
testThreshold++;
}
if(mUseSignChangesHigh)
{
TestSignChangesUpdate(sc,WindowSizeInt,buffer[i],buffer[i+1],buffer[i+WindowSizeInt],buffer[i+WindowSizeInt+1]);
tests += (int)(sc > mThresholdSignChangesUpper);
testThreshold++;
}
if(mUseDirectionChangesLow)
{
TestDirectionChangesUpdate(dc,WindowSizeInt,atrend,buffer[i],buffer[i+1],ztrend,buffer[i+WindowSizeInt],buffer[i+WindowSizeInt+1]);
tests += (int)(dc < mThresholdDirectionChangesLower);
testThreshold++;
}
if(mUseDirectionChangesHigh)
{
TestDirectionChangesUpdate(dc,WindowSizeInt,atrend,buffer[i],buffer[i+1],ztrend,buffer[i+WindowSizeInt],buffer[i+WindowSizeInt+1]);
tests += (int)(dc > mThresholdDirectionChangesUpper);
testThreshold++;
}
if(tests < testThreshold)
{ //Finish off on the first hit
break;
}
}
//When we get here, i+lastsubthresholdsample is the best guess for where the word starts
return lastsubthresholdsample - remaining + i;
}
else {
//If we failed to find anything, return the start position
return end ;
}
}
}
//This tests whether a specified block region is above or below threshold.
bool VoiceKey::AboveThreshold(
const WaveTrack & t, sampleCount start, sampleCount len)
{
double erg=0;
double sc=0;
double dc=0; //These store three statistics: energy, signchanges, and directionchanges
int tests =0; //Keeps track of how many statistics surpass the threshold.
int testThreshold=0; //Keeps track of the threshold.
//Calculate the test statistics
if(mUseEnergy)
{
testThreshold++;
erg = TestEnergy(t, start,len);
tests +=(int)(erg > mThresholdEnergy);
#if 0
std::cout << "Energy: " << erg << " " <<mThresholdEnergy << std::endl;
#endif
}
if(mUseSignChangesLow)
{
testThreshold++;
sc = TestSignChanges(t,start,len);
tests += (int)(sc < mThresholdSignChangesLower);
#if 0
std::cout << "SignChanges: " << sc << " " <<mThresholdSignChangesLower<< " < " << mThresholdSignChangesUpper << std::endl;
#endif
}
if(mUseSignChangesHigh)
{
testThreshold++;
sc = TestSignChanges(t,start,len);
tests += (int)(sc > mThresholdSignChangesUpper);
#if 0
std::cout << "SignChanges: " << sc << " " <<mThresholdSignChangesLower<< " < " << mThresholdSignChangesUpper << std::endl;
#endif
}
if(mUseDirectionChangesLow)
{
testThreshold++;
dc = TestDirectionChanges(t,start,len);
tests += (int)(dc < mThresholdDirectionChangesLower);
#if 0
std::cout << "DirectionChanges: " << dc << " " <<mThresholdDirectionChangesLower<< " < " << mThresholdDirectionChangesUpper << std::endl;
#endif
}
if(mUseDirectionChangesHigh)
{
testThreshold++;
dc = TestDirectionChanges(t,start,len);
tests += (int)(dc > mThresholdDirectionChangesUpper);
#if 0
std::cout << "DirectionChanges: " << dc << " " <<mThresholdDirectionChangesLower<< " < " << mThresholdDirectionChangesUpper << std::endl;
#endif
}
//Test whether we are above threshold (the number of stats)
return (tests >= testThreshold);
}
//This adjusts the threshold. Larger values of t expand the noise region,
//making more things be classified as noise (and requiring a stronger signal).
void VoiceKey::AdjustThreshold(double t)
{
mThresholdAdjustment = t;
mThresholdEnergy = mEnergyMean + mEnergySD * t;
mThresholdSignChangesUpper = mSignChangesMean + mSignChangesSD * t;
mThresholdSignChangesLower = mSignChangesMean - mSignChangesSD * t;
mThresholdDirectionChangesUpper = mDirectionChangesMean + mDirectionChangesSD * t;
mThresholdDirectionChangesLower = mDirectionChangesMean - mDirectionChangesSD * t;
};
//This 'calibrates' the voicekey to noise
void VoiceKey::CalibrateNoise(const WaveTrack & t, sampleCount start, sampleCount len)
{
//To calibrate the noise, we need to scan the sample block just like in the voicekey and
//calculate the mean and standard deviation of the test statistics.
//Then, we set the BaselineThreshold to be one
wxBusyCursor busy;
//initialize some sample statistics: sums of X and X^2
double sumerg, sumerg2;
double sumsc, sumsc2;
double sumdc, sumdc2;
double erg, sc, dc;
//Now, change the millisecond-based parameters into sample-based parameters
//(This depends on WaveTrack t)
double rate = t.GetRate();
unsigned int WindowSizeInt = (unsigned int)(rate * mWindowSize);
// unsigned int SignalWindowSizeInt = (unsigned int)(rate * mSignalWindowSize);
//Get the first test statistics
//Calibrate all of the statistic, because they might be
//changed later.
// if(mUseEnergy)
erg = TestEnergy(t, start, WindowSizeInt);
// if(mUseSignChanges)
sc = TestSignChanges(t,start, WindowSizeInt);
// if(mUseDirectionChanges)
dc = TestDirectionChanges(t,start,WindowSizeInt);
sumerg =0.0;
sumerg2 = 0.0;
sumsc =0.0;
sumsc2 = 0.0;
sumdc =0.0;
sumdc2 =0.0;
// int n = len - WindowSizeInt; //This is how many samples we have
auto samplesleft = len - WindowSizeInt;
int samples=0;
for(auto i = start; samplesleft >= 10;
i += (WindowSizeInt - 1), samplesleft -= (WindowSizeInt -1) ) {
//Take samples chunk-by-chunk.
//Normally, this should be in WindowSizeInt chunks, but at the end (if there are more than 10
//samples left) take a chunk that eats the rest of the samples.
samples++; //Increment the number of samples we have
const auto blocksize = limitSampleBufferSize( WindowSizeInt, samplesleft);
erg = TestEnergy(t, i, blocksize);
sumerg +=(double)erg;
sumerg2 += pow((double)erg,2);
sc = TestSignChanges(t,i, blocksize);
sumsc += (double)sc;
sumsc2 += pow((double)sc,2);
dc = TestDirectionChanges(t,i,blocksize);
sumdc += (double)dc;
sumdc2 += pow((double)dc,2);
}
mEnergyMean = sumerg / samples;
mEnergySD = sqrt(sumerg2/samples - mEnergyMean*mEnergyMean);
mSignChangesMean = sumsc / samples;
mSignChangesSD = sqrt(sumsc2 / samples - mSignChangesMean * mSignChangesMean);
mDirectionChangesMean = sumdc / samples;
mDirectionChangesSD =sqrt(sumdc2 / samples - mDirectionChangesMean * mDirectionChangesMean) ;
auto text = XO("Calibration Results\n");
text +=
/* i18n-hint: %1.4f is replaced by a number. sd stands for 'Standard Deviations'*/
XO("Energy -- mean: %1.4f sd: (%1.4f)\n")
.Format( mEnergyMean, mEnergySD );
text +=
XO("Sign Changes -- mean: %1.4f sd: (%1.4f)\n")
.Format( mSignChangesMean, mSignChangesSD );
text +=
XO("Direction Changes -- mean: %1.4f sd: (%1.4f)\n")
.Format( mDirectionChangesMean, mDirectionChangesSD );
SneedacityMessageDialog{
nullptr,
text,
XO("Calibration Complete"),
wxOK | wxICON_INFORMATION,
wxPoint(-1, -1)
}
.ShowModal();
AdjustThreshold(mThresholdAdjustment);
}
void VoiceKey::SetKeyType(bool erg, bool scLow , bool scHigh,
bool dcLow, bool dcHigh)
{
mUseEnergy = erg;
mUseSignChangesLow = scLow;
mUseSignChangesHigh = scHigh;
mUseDirectionChangesLow = dcLow;
mUseDirectionChangesHigh = dcHigh;
}
//This might continue over a number of blocks.
double VoiceKey::TestEnergy (
const WaveTrack & t, sampleCount start, sampleCount len)
{
double sum = 1;
auto s = start; //Keep track of start
auto originalLen = len; //Keep track of the length of block to process (its not the length of t)
const auto blockSize = limitSampleBufferSize(
t.GetMaxBlockSize(), len); //Determine size of sampling buffer
Floats buffer{ blockSize }; //Get a sampling buffer
while(len > 0)
{
//Figure out how much to grab
auto block = limitSampleBufferSize ( t.GetBestBlockSize(s), len );
t.GetFloats(buffer.get(), s,block); //grab the block;
//Now, go through the block and calculate energy
for(decltype(block) i = 0; i< block; i++)
{
sum += buffer[i]*buffer[i];
}
len -= block;
s += block;
}
return sum / originalLen.as_double();
}
//This will update RMSE by adding one element and subtracting another
void VoiceKey::TestEnergyUpdate (double & prevErg, int len, const float & drop, const float & add)
{
//This is an updating formula for RMSE. It will only recalculate what's changed.
prevErg = prevErg + (double)(fabs(add) - fabs(drop))/len;
}
double VoiceKey::TestSignChanges(
const WaveTrack & t, sampleCount start, sampleCount len)
{
auto s = start; //Keep track of start
auto originalLen = len; //Keep track of the length of block to process (its not the length of t)
const auto blockSize = limitSampleBufferSize(
t.GetMaxBlockSize(), len); //Determine size of sampling buffer
unsigned long signchanges = 1;
int currentsign=0;
Floats buffer{ blockSize }; //Get a sampling buffer
while(len > 0) {
//Figure out how much to grab
auto block = limitSampleBufferSize ( t.GetBestBlockSize(s), len );
t.GetFloats(buffer.get(), s, block); //grab the block;
if (len == originalLen)
{
//The first time through, set stuff up special.
currentsign = sgn(buffer[0]);
}
//Now, go through the block and calculate zero crossings
for(decltype(block) i = 0; i< block; i++)
{
if( sgn(buffer[i]) != currentsign)
{
currentsign = sgn(buffer[i]);
signchanges++;
}
}
len -= block;
s += block;
}
return (double)signchanges / originalLen.as_double();
}
void VoiceKey::TestSignChangesUpdate(double & currentsignchanges, int len,
const float & a1,
const float & a2,
const float & z1,
const float & z2)
{
if(sgn(a1)!=sgn(a2)) currentsignchanges -= 1.0/len;
if(sgn(z1)!=sgn(z2)) currentsignchanges += 1.0/len;
}
double VoiceKey::TestDirectionChanges(
const WaveTrack & t, sampleCount start, sampleCount len)
{
auto s = start; //Keep track of start
auto originalLen = len; //Keep track of the length of block to process (its not the length of t)
const auto blockSize = limitSampleBufferSize(
t.GetMaxBlockSize(), len); //Determine size of sampling buffer
unsigned long directionchanges = 1;
float lastval=float(0);
int lastdirection=1;
Floats buffer{ blockSize }; //Get a sampling buffer
while(len > 0) {
//Figure out how much to grab
auto block = limitSampleBufferSize ( t.GetBestBlockSize(s), len );
t.GetFloats(buffer.get(), s, block); //grab the block;
if (len == originalLen) {
//The first time through, set stuff up special.
lastval = buffer[0];
}
//Now, go through the block and calculate zero crossings
for(decltype(block) i = 0; i< block; i++){
if( sgn(buffer[i]-lastval) != lastdirection) {
directionchanges++;
lastdirection = sgn(buffer[i] - lastval);
}
lastval = buffer[i];
}
len -= block;
s += block;
}
return (double)directionchanges/originalLen.as_double();
}