-
Notifications
You must be signed in to change notification settings - Fork 0
/
WangWav2Tape.cpp
1805 lines (1525 loc) · 56.7 KB
/
WangWav2Tape.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
// Prerelease version, 1/14/16
// Author: Jim Battle
// This program reads a .wav file containing sampled data from a Wang 3300 or
// Wang 2200 cassette tape.
//
// Read the associated README to understand how to capture the audio waveforms
// off the cassette tapes, and how to preprocess them into a format this
// program can deal with.
//
// The program does this:
//
// (1) It scans the two channels, detecting each peak and building a list
// logging where each of these peaks occurs in the waveform. BTW,
// rather than reading the full file into memory, a sliding window
// is used. This permits the program to think it is randomly accessing
// the sample buffer, without the memory requirements.
//
// At this point, there is no more use for the waves, and the file
// can be closed.
//
// (2) The separate lists of left and right peaks are merged into a time-
// ordered list.
//
// (3) The list of peaks are scanned for gaps, which demark data blocks.
// For each isolated block,
//
// (3a) Transitions may occur in the left and right tracks in any
// order, but not both at the same time, we may have L->L, L->R,
// R->R, and R->L transition sequences. Statistics about the
// average and variance of these transitions are kept for each
// of the four categories.
//
// (3b) It may be, for various reasons, there is a time shift between
// the left and right tracks. Based on the transition stats,
// shift one track or the other by some amount of time such that
// the average L->R and R->L transitions are identical. We must
// be prepared, though, for a block of data which doesn't have
// all types of transitions (eg, all 0s).
//
// (3c) Sweep through the transition lists again like (3a), measuring
// the transition statistics, but with the time shift taken into
// account.
//
// (3d) Sweep through the transition lists again, and discard unlikely
// peaks. A peak is unlikely if it doesn't occur within about
// three std deviations of the mean, yet the following edge does.
// That means that the discarded edge was likely spurious.
//
// (3e) Do one final sweep, turning the peaks into ones and zeros,
// assembling each group of 8 into a byte. The 3300 tape format
// includes checksum bytes, which aids in verifying a successful
// decode. Both the 3300 and 2200 tape formats record each block
// of data twice, which also helps verify the result. While the
// 2200 doesn't have a checksum (why, oh why, not?), we know that
// there should be exactly 256 bytes. If we end up with the wrong
// byte count, or if we have extra transition bits at the end,
// it is a strong clue that something is amiss.
//
// TODO and further ideas:
//
// *) sometimes a section of the tape will show fading -- localized loss
// of amplitude. It might last only a few dozen bits (probably due to
// poor tape oxide thickness, or something stuck on the tape to move
// the r/w head away from the tape surface), but it can cause edges to
// be dropped. one idea is to have a very localized normalization.
// eg, have a rolling window of, about 10 bits wide. based on the
// average amplitude, or perhaps average peak amplitude, normalize
// the signal level. this is most easily done at the edge stage,
// since I don't want to write out or store a modified copy of the
// wav data.
//
// *) the 2200 tape format records each block twice for redundancy,
// yet neither has a checksum. thus, if a bit got flipped in one,
// there is no simple way to know which is correct.
//
// it would be thinkable to parse the block contents to make sure it
// has valid structure. while not perfect, it is better than nothing.
// BASIC and structured data files have a known format.
//
// *) sometimes one channel has fading/distortion or is unusable.
// it would be possible to infer the contents of the opposite track
// by assuming that if the good track didn't transition, the bad track
// did. there is some ambiguity since the bad track may have N
// transitions to start the block, so it would require manual fiddling,
// or perhaps automatically inserting 1 to N assumed transitions and
// then parse the block to see if it makes sense. (see previous idea)
#include <string>
#include <vector>
#include <iostream>
#include <iomanip>
#include <fstream>
#include <memory>
#include <cmath> // sqrt() requires this
#include <algorithm> // std::max()
#include <cassert>
using std::string;
using std::vector;
using std::ifstream;
using std::ofstream;
using std::cout;
using std::cerr;
using std::ios;
using std::endl;
using std::hex;
using std::dec;
using std::fixed;
using std::setfill;
using std::setw;
// ========================================================================
// type definitions
#include <cstdint>
typedef uint32_t uint32;
typedef uint16_t uint16;
typedef uint8_t uint8;
// pack two and four byte items in little endian fashion
#define PACK2(a, b) (((uint8)a << 0) + ((uint8)b << 8))
#define PACK4(a, b, c, d) \
(((uint8)a << 0) + ((uint8)b << 8) + ((uint8)c << 16) + ((uint8)d << 24))
// ========================================================================
// global variables
// command line options
int opt_v; // verbosity level
string opt_ofn; // output filename
string opt_ifn; // input filename
enum { FMT_3300, FMT_2200 } opt_fmt;
// any peak with amplitude less this is simply ignored
// FIXME: it is currently predicated on opt_fmt, but it might be useful to
// expose it as a command line option.
float opt_min_thold;
// ugly globals to avoid passing them around as parameters
int g_bit_per; // expected bit period
int g_gap_thold; // threshold for gap detection
float g_devs_filter = 2.5f; // # std devs before an runt interval is filtered out
float g_devs_warn = 3.5f; // how many std devs before an interval is flagged
// ========================================================================
// this class opens a .wav file given a filename.
// there are methods to return various properties of the file, as well
// as the left and right sample at offset "n". The sample is returned
// as a pair of single precision floats, normalized in the range of 0.0
// to 1.0. If the file is mono, the left and right samples are the same;
// sample depths of 8b and 16b are both supported.
//
// The assumption is that samples will be processed approximately sequentially.
// It will return the correct value, no matter what order, but performance
// may be terrible if the access pattern is poor.
//
// This code isn't very efficient, just simple.
//
// One glossary term, quoting Microsoft:
// Frame - A frame is like a sample, but in multichannel format -
// it is a snapshot of all the channels at a specific data point.
struct samplePair_t {
float channel[2];
};
class ReadWav
{
public:
ReadWav(string filename);
~ReadWav();
// samples/sec
int SampleFrequency() const;
// number of samples in file, as declared by header
// (which can be wrong -- perhaps the file is truncated)
int ExpectedFrames() const;
// calculated actual sample count
int NumFrames() const;
// random access interface:
// return the sample pair at specified sample offset
samplePair_t Sample(int offset);
// sequential access interface:
// return the sample pair at specified sample offset
void SetOffset(int off);
samplePair_t NextFrame();
private:
// methods to read items directly from the file stream
// values interpret the stream in little endian format.
uint8 read_raw_8b();
uint16 read_raw_16b();
uint32 read_raw_32b();
// save it for error messages later
string m_filename;
// the wav file stream object
ifstream m_istream;
// cache attributes read in from the file header
int m_num_channels;
int m_bytes_per_sample;
int m_bytes_per_frame; // == #channels * (bytes/channel)
int m_sample_rate;
int m_expected_frames;
int m_actual_frames;
int m_data_start;
int m_data_end;
// we keep a direct cache of N sample buffers, each holding K samples.
const static int N_buffers_log2 = 4;
const static int K_samples_log2 = 10;
const static int N_buffers = (1 << N_buffers_log2);
const static int K_samples = (1 << K_samples_log2);
samplePair_t m_cache[N_buffers][K_samples];
bool m_cache_valid[N_buffers];
int m_cache_tag[N_buffers];
// sequential sample interface
int m_seq_offset;
};
uint8
ReadWav::read_raw_8b()
{
char buff[1];
m_istream.read(buff, 1);
if (!m_istream.good()) {
cerr << "Error: failure to read 8b quantity from file stream" << endl;
exit(-1);
}
return (uint8)buff[0];
}
uint16
ReadWav::read_raw_16b()
{
char buff[2];
m_istream.read(buff, 2);
if (!m_istream.good()) {
cerr << "Error: failure to read 16b quantity from file stream" << endl;
exit(-1);
}
return PACK2( buff[0], buff[1] );
}
uint32
ReadWav::read_raw_32b()
{
char buff[4];
m_istream.read(buff, 4);
if (!m_istream.good()) {
cerr << "Error: failure to read 32b quantity from file stream" << endl;
exit(-1);
}
return PACK4( buff[0], buff[1], buff[2], buff[3] );
}
// RIFF WAV file format
// __________________________
// | RIFF WAVE Chunk |
// | groupID = 'RIFF' |
// | riffType = 'WAVE' |
// | __________________ |
// | | Format Chunk | |
// | | ckID = 'fmt ' | |
// | |__________________| |
// | __________________ |
// | | Sound Data Chunk | |
// | | ckID = 'data' | |
// | |__________________| |
// |__________________________|
//
// although it is legal to have more than one data chunk,
// this program assumes there is only one.
ReadWav::ReadWav(string filename)
{
// save filename for error messages
m_filename = filename;
// invalidate the cache
for (int i=0; i<N_buffers; i++) {
m_cache_valid[i] = false;
}
if (opt_v >= 1) {
cout << "File: '" << m_filename << "'\n";
}
m_istream.open(m_filename.c_str(), ios::in | ios::binary);
if (!m_istream.is_open()) {
cerr << "Error: couldn't open file '" << m_filename << "'" << endl;
exit(-1);
}
int chunkNum = 0;
bool done = false;
while (!done) {
// now read the next chunk ID to see what is up next
chunkNum++;
uint32 chunkId = read_raw_32b();
uint32 chunkSize = read_raw_32b();
if (chunkId == PACK4('R','I','F','F')) {
uint32 riffType = read_raw_32b();
if (riffType != PACK4('W','A','V','E')) {
cerr << "Error: input file not a WAV file" << endl;
exit(-1);
}
} else if (chunkId == PACK4('f','m','t',' ')) {
uint16 fmtTag = read_raw_16b();
if (fmtTag != 1) {
cerr << "Error: can't deal with compressed WAV files" << endl;
exit(-1);
}
uint16 chan = read_raw_16b();
if (chan < 1 || chan > 2) {
cerr << "Error: can't handle more than two channels" << endl;
exit(-1);
}
m_num_channels = chan;
m_sample_rate = read_raw_32b();
if (m_sample_rate < 11000) {
cerr << "Warning: the sample rate is low -- it might hurt conversion" << endl;
}
uint32 avgpbs = read_raw_32b();
uint16 blockAlign = read_raw_16b();
uint16 sampbits = read_raw_16b();
if (sampbits == 8) {
m_bytes_per_sample = 1;
} else if (sampbits == 16) {
m_bytes_per_sample = 2;
} else {
cerr << "Error: samples must be either 8b or 16b" << endl;
exit(-1);
}
m_bytes_per_frame = m_bytes_per_sample * m_num_channels;
} else if (chunkId != PACK4('d','a','t','a')) {
// the first chunk MUST be a RIFF type
if (chunkNum == 1) {
cerr << "Error: input file not a WAV file" << endl;
exit(-1);
}
cerr << "Unknown chunk type: '" <<
(char)((chunkId >> 0) & 0xFF) <<
(char)((chunkId >> 8) & 0xFF) <<
(char)((chunkId >> 16) & 0xFF) <<
(char)((chunkId >> 24) & 0xFF) << "'" << endl;
cerr << " " << chunkSize << " bytes skipped" << endl;
// skip rest of header
m_istream.seekg(chunkSize, ios::cur);
if (!m_istream.good()) {
cerr << "Error: failure to seek to end of chunk" << endl;
exit(-1);
}
} else {
// got a data chunk
// remember where data begins
m_data_start = m_istream.tellg();
// compute dependent parameters
m_expected_frames = chunkSize / m_bytes_per_frame;
m_istream.seekg(0, ios::end);
m_data_end = m_istream.tellg();
m_actual_frames = (m_data_end - m_data_start + 1) / m_bytes_per_frame;
SetOffset(0);
done = true;
}
} // while (!done)
if (opt_v >= 1) {
cout << "WAV format:\n";
cout << " uncompressed\n";
cout << " " << m_num_channels << " channels\n";
cout << " " << (8*m_bytes_per_sample) << " bits/sample\n";
cout << " " << m_sample_rate << " samples/sec\n";
cout << " " << m_expected_frames << " samples expected\n";
cout << " " << m_actual_frames << " samples in file\n";
cout << " " << (float)m_expected_frames/m_sample_rate << " seconds\n";
}
}
ReadWav::~ReadWav()
{
m_istream.close();
}
int
ReadWav::SampleFrequency() const
{
return m_sample_rate;
}
int
ReadWav::ExpectedFrames() const
{
return m_expected_frames;
}
int
ReadWav::NumFrames() const
{
return m_actual_frames;
}
samplePair_t
ReadWav::Sample(int offset)
{
// |<--- buf_tag --->|<--- buf --->|<--- buf_offset --->|
const int clamped_offset = std::max(0, offset);
const int buf_offset = (clamped_offset & (K_samples - 1));
const int blk_offset = (clamped_offset >> K_samples_log2);
const int buf = blk_offset & (N_buffers - 1);
const int buf_tag = (clamped_offset >> (N_buffers_log2 + K_samples_log2));
if (!m_cache_valid[buf] || (m_cache_tag[buf] != buf_tag)) {
// cache miss
m_cache_valid[buf] = true;
m_cache_tag[buf] = buf_tag;
int block_first = m_data_start + (K_samples*m_bytes_per_frame)*blk_offset;
int block_last = block_first + (K_samples*m_bytes_per_frame) - 1;
#if 0
cout << "Cache miss: buf #" << hex << buf <<
", tag=" << hex << buf_tag <<
", off=" << hex << buf_offset <<
", start=" << hex << block_first <<
", end =" << hex << block_last << "\n";
#endif
if (block_first > m_data_end) {
#if 0
cout << "Filling end with 0.0\n";
#endif
// none of the buffer exists
for (int i=0; i<K_samples; i++) {
m_cache[buf][i].channel[0] =
m_cache[buf][i].channel[1] = 0.0f;
}
} else {
// at least part of the buffer exists in the file
m_istream.seekg(block_first);
if (!m_istream.good()) {
cerr << "Error: couldn't seek to valid file offset" << endl;
exit(-1);
}
char raw[4*K_samples];
m_istream.read( raw, K_samples*m_bytes_per_frame );
m_istream.clear();
if ((m_num_channels == 1) && (m_bytes_per_sample == 1)) {
// mono 8b
for (int n=0; n<K_samples; n++) {
int s0 = (uint8)raw[n] - 128;
m_cache[buf][n].channel[0] =
m_cache[buf][n].channel[1] = s0 / 128.0f;
}
} else if ((m_num_channels == 1) && (m_bytes_per_sample == 2)) {
// mono 16b
for (int n=0; n<K_samples; n++) {
int s0 = ((uint8)raw[2*n+1] << 8) + (uint8)raw[2*n+0];
int ss0 = (s0 & 0x7FFF) - (s0 & 0x8000);
m_cache[buf][n].channel[0] =
m_cache[buf][n].channel[1] = ss0 / 32768.0f;
}
} else if ((m_num_channels == 2) && (m_bytes_per_sample == 1)) {
// 8b stereo
for (int n=0; n<K_samples; n++) {
int s0 = (uint8)raw[2*n+0] - 128;
int s1 = (uint8)raw[2*n+1] - 128;
m_cache[buf][n].channel[0] = s0 / 128.0f;
m_cache[buf][n].channel[1] = s1 / 128.0f;
}
} else if ((m_num_channels == 2) && (m_bytes_per_sample == 2)) {
// 16b stereo
for (int n=0; n<K_samples; n++) {
int s0 = ((uint8)raw[4*n+1] << 8) + (uint8)raw[4*n+0];
int ss0 = (s0 & 0x7FFF) - (s0 & 0x8000);
int s1 = ((uint8)raw[4*n+3] << 8) + (uint8)raw[4*n+2];
int ss1 = (s1 & 0x7FFF) - (s1 & 0x8000);
m_cache[buf][n].channel[0] = ss0 / 32768.0f;
m_cache[buf][n].channel[1] = ss1 / 32768.0f;
}
}
// check if the final block is a partial block
if (block_last > m_data_end) {
#if 0
cout << "Filling trailing end with 0.0\n";
#endif
for (int n=m_data_end - block_first; n<K_samples; n++) {
m_cache[buf][n].channel[0] =
m_cache[buf][n].channel[1] = 0.0f;
}
}
}
}
return m_cache[buf][buf_offset];
}
void
ReadWav::SetOffset(int off)
{
assert(off >= 0);
m_seq_offset = off;
}
samplePair_t
ReadWav::NextFrame()
{
return Sample(m_seq_offset++);
}
// ========================================================================
// simple peak detector
// ========================================================================
// item in the peak list
struct peak_t {
int channel; // 0=left, 1=right
float maxima_orig; // value at peak, including sign
float maxima; // value at peak, absolute value
int sample_orig; // sample where local maxima ocurred in wav file
int sample; // local maxima location after time shift
};
typedef vector<peak_t> peakvec_t;
class PeakDet
{
public:
PeakDet(ReadWav &wavobj, int channel, float min_thold);
~PeakDet();
// feed another value
void Stuff(float v);
// indicate no more values are coming
void Flush();
// return the collection of edges
peakvec_t &PeakDet::GetList();
private:
const int m_channel; // 0=left, 1=right
const float m_min_peak; // peaks must be at least this tall
float m_window[3]; // window of three most recent values
int m_samples; // number of samples received
static int m_prev_sample; // shared by both channels
peakvec_t m_peaks; // list of detected peaks
ReadWav &m_wavobj; // associated wav file
};
// static member needs explicit initialization
int PeakDet::m_prev_sample = 0;
PeakDet::PeakDet(ReadWav &wavobj, int channel, float min_thold) :
m_wavobj(wavobj),
m_channel(channel),
m_min_peak(min_thold),
m_samples(0)
{
// nothing
}
PeakDet::~PeakDet()
{
// nothing
}
// as each new sample is read in, check to see if it is a local maxima,
// and log it if it eppears to be so.
void
PeakDet::Stuff(float v)
{
// roll window
m_window[0] = m_window[1];
m_window[1] = m_window[2];
m_window[2] = std::abs(v);
m_samples++;
// can't do anything until the window is filled
if (m_samples < 2) {
return;
}
// this is used for debugging:
bool interesting = false && (m_samples-2 >= 438614 && m_samples-2 <= 438614 && m_channel == 1);
if (interesting) cout << "@" << m_samples-2 << ", v=" << m_window[1] << "\n";
// fast test to discard samples that obviously aren't maxima.
// we also discard any peaks that have too small of an amplitude.
if ( (m_window[1] < m_window[0]) ||
(m_window[1] < m_window[2]) ||
(m_window[1] < m_min_peak) )
return;
int this_sample = m_samples - 2; // -1 because we incremented m_samples,
// and -1 because we are looking back one item in the window
// do a more thorough job than the quick test above.
// try and ensure we don't have a local bump in the middle of a larger trend.
// search +/- 6/16ths of a bit period.
int off_delta = (6*g_bit_per + 8) >> 4;
int earlier = 0;
for (int offset = -off_delta; offset <= off_delta; offset++) {
float s = m_wavobj.Sample(this_sample + offset).channel[m_channel];
s = std::abs(s);
if (m_window[1] < s) {
if (opt_v >= 4) {
cout << " rejecting fake peak " << m_window[1] <<
" @" << this_sample << ", channel " << m_channel << "\n";
}
return;
} else {
// if two points have the same value, ignore the later one
if ((offset < 0) && (m_window[1] == s)) {
earlier = offset;
}
}
}
if (earlier) {
if (opt_v >= 4) {
cout << " rejecting redundant peak @" << this_sample <<
", earlier @" << this_sample+earlier <<
", channel " << m_channel << "\n";
}
return;
}
// TODO: incorporate the idea of hysteresis?
// this is what the actual wang hardware uses
// use a wider window and make sure that there is a significant dip
// to both sides of the peak. experience has shown that if there is
// no quick flux reversal on the track, it can take a while for the
// signal to droop. thus we use the wider window, and we are less
// stringent about the test on the samples after the peak.
// search +/- 12/16ths of a bit period.
int off_delt = (12*g_bit_per + 8) >> 4;
bool higherL = false;
bool higherR = false;
for (int offset = -off_delt; offset <= off_delt; offset++) {
float s = m_wavobj.Sample(this_sample + offset).channel[m_channel];
s = std::abs(s);
if (interesting) {
cout << " @(" << this_sample << " + " << offset << "), v=" << s;
}
// make sure we aren't just stuck in a flat spot
higherL |= (offset < 0) &&
(m_window[1] > 1.12f*s) && (m_window[1] > s + 0.07f);
higherR |= (offset > 0) &&
(m_window[1] > 1.08f*s) && (m_window[1] > s + 0.05f);
if (interesting) {
cout << " hl=" << higherL << ", hr=" << higherR << "\n";
}
}
if (!higherL || !higherR) {
if (opt_v >= 4) {
cout << " rejecting flat peak " << m_window[1] <<
" @" << this_sample << ", channel " << m_channel << "\n";
}
return;
}
peak_t p;
p.channel = m_channel;
p.sample_orig = this_sample;
p.sample = this_sample; // no shift yet
p.maxima_orig = m_wavobj.Sample(this_sample).channel[m_channel];
p.maxima = m_window[1];
// sanity check: make sure the signs of peaks alternates
if (!m_peaks.empty()) {
bool prev_neg = (m_peaks.back().maxima_orig < 0.0f);
bool curr_neg = (p.maxima_orig < 0.0f);
if ((opt_v >= 3) && (prev_neg == curr_neg)) {
cout << "Adjacent peaks with like signs, channel " << m_channel <<
", @" << m_peaks.back().sample << " and " << p.sample << "\n";
}
}
// we have a new peak to add
m_peaks.push_back(p);
if (opt_v >= 3) {
char name = (m_channel) ? 'R' : 'L';
cout << name << " peak: @" << dec << this_sample << ", delta=" << this_sample-m_prev_sample << ", " << fixed << p.maxima << "\n";
}
// this information is shared between the two channels for reporting
m_prev_sample = this_sample;
}
void
PeakDet::Flush()
{
// nothing right now
// let's assume that a peak doesn't occur on the last sample of the stream
}
// return ref to list; caller must make a copy or there will be hell to pay
peakvec_t&
PeakDet::GetList()
{
return m_peaks;
}
// ========================================================================
// utility class to compute average and std deviation of a stream of #'s
// ========================================================================
class Stat
{
public:
Stat();
void Clear(); // wipe out any accumulated stats
void Input(float v); // feed a new term in the series
float Mean() const; // get arithmetic mean
float StdDev() const; // get standard deviation
int SeqLength() const; // return # of samples in sequence
private:
int count; // number of items
double sum; // sum of all input values
double sqsum; // sum of (each input value squared)
double M;
double Q;
};
Stat::Stat()
{
Clear();
}
void
Stat::Clear()
{
count = 0;
sum = 0;
sqsum = 0;
}
void
Stat::Input(float v)
{
count++;
// simple but numerically unstable
sum += v;
sqsum += v*v;
// a bit more complicated, but well behaved
// see: http://www.cs.berkeley.edu/~mhoemmen/cs194/Tutorials/variance.pdf
if (count == 1) {
M = v;
Q = 0;
} else {
double prev_M = M;
double prev_Q = Q;
M = prev_M + (v - prev_M) / count;
Q = prev_Q + ((count-1)*(v-prev_M)*(v-prev_M)) / count;
}
}
float
Stat::Mean() const
{
if (count == 0) {
return 0;
}
return float(sum / count);
}
float
Stat::StdDev() const
{
if (count == 0) {
return 0;
}
#if 0
return sqrt( sqrt((sqsum - sum*sum/count) / count) );
#else
return sqrt( float(Q) / count );
#endif
}
int
Stat::SeqLength() const
{
return count;
}
// =========================================================================
// interleave two peak vectors into a single time ordered vector
// =========================================================================
// zip together the two peaks in time order
peakvec_t
Merge(peakvec_t &p0, peakvec_t &p1)
{
auto ptr0 = begin(p0);
auto ptr1 = begin(p1);
peakvec_t rslt;
if (opt_v >= 1) {
cout << "Merging..." << endl;
}
// merge until one list or the other has been fully scanned
while ( (ptr0 < p0.end()) && (ptr1 < p1.end()) ) {
if (ptr0->sample <= ptr1->sample) {
rslt.push_back(*ptr0++);
} else {
rslt.push_back(*ptr1++);
}
}
// just push the remainder from the non-empty list
while (ptr0 < p0.end()) {
rslt.push_back(*ptr0++);
}
while (ptr1 < p1.end()) {
rslt.push_back(*ptr1++);
}
if (opt_v >= 1) {
cout << " merged list has " << rslt.size() << " edges" << endl;
}
return rslt;
}
// =========================================================================
// Filtering a list of peaks
// =========================================================================
// Filtering the block means
// taking stats on the peaks
// shifting the right track to make L->R and R->L similar
// tossing out unlikely peaks
enum { LL=0, LR=1, RL=2, RR=3 }; // transition classification
void
Filter(const int blk_num, peakvec_t &peaks, Stat *stats)
{
if (peaks.size() < 32) {
return;
}
// run through the peaks, calculating the mean and standard deviation
// of the amplitude of the peaks, and the L->L, L->R, R->L, and R->R
// transition intervales. It is possible that not all transitions
// occur in a given block.
Stat amp;
for (auto i=begin(peaks); i < end(peaks); i++) {
amp.Input(i->maxima);
if (i > peaks.begin()) { // delta is relative to previous sample
int xition = 2*((i-1)->channel) + (i->channel);
int tdelta = i->sample - (i-1)->sample;
stats[xition].Input(float(tdelta));
}
}
if (opt_v >= 1) {
cout << " " << amp.SeqLength() << " peaks" <<
", avg=" << amp.Mean() <<
", std dev=" << amp.StdDev() << "\n";
cout << " " << stats[LL].SeqLength() << " LL" <<
", avg=" << stats[LL].Mean() <<
", std dev=" << stats[LL].StdDev() << "\n";
cout << " " << stats[LR].SeqLength() << " LR" <<
", avg=" << stats[LR].Mean() <<
", std dev=" << stats[LR].StdDev() << "\n";
cout << " " << stats[RL].SeqLength() << " RL" <<
", avg=" << stats[RL].Mean() <<
", std dev=" << stats[RL].StdDev() << "\n";
cout << " " << stats[RR].SeqLength() << " RR" <<
", avg=" << stats[RR].Mean() <<
", std dev=" << stats[RR].StdDev() << "\n";
}
// loop through the peaks again, shifting the tracks by
// an amount that will equalize the LR and RL difference,
// and toss out peaks that are not tall enough.
int tshift = int(stats[RL].Mean() - stats[LR].Mean() + 0.5f) >> 1;
if (opt_v >= 1) {
cout << " applying R channel shift of " << tshift << " samples\n";
}
peakvec_t shifted;
for (auto i=begin(peaks); i < end(peaks); i++) {
peak_t p = *i;
if (p.channel == 1) {
p.sample += tshift;
}
shifted.push_back(p);
}
// rerun the stats on the updated block
amp.Clear();
for (int i=0; i<4; i++) {
stats[i].Clear();
}
for (auto i=begin(shifted); i < end(shifted); i++) {
amp.Input(i->maxima);
if (i > shifted.begin()) { // delta is relative to previous sample
int xition = 2*((i-1)->channel) + (i->channel);
int tdelta = i->sample - (i-1)->sample;
stats[xition].Input(float(tdelta));
}
}
for (int i=0; i<4; i++) {
if ( (g_bit_per < stats[i].Mean() - g_devs_warn*stats[i].StdDev()) ||
(g_bit_per > stats[i].Mean() + g_devs_warn*stats[i].StdDev()) ) {
if (stats[i].SeqLength() > 4) // guard against inadequate stats
cerr << "Warning: block #" << blk_num <<
", apriori samples/bit = " << g_bit_per <<
", measured samples/bit = " << stats[i].Mean() << endl;
}
}
// loop through the shifted peaks again, tossing out any implausible
// edges. an edge is implausible if it isn't within three std dev (or so)
// of the normal transition time and the following edge is.
int lower[4], upper[4];
for (int i=0; i<4; i++) {
lower[i] = int(stats[i].Mean() - g_devs_filter*stats[i].StdDev() + 0.5f);
upper[i] = int(stats[i].Mean() + g_devs_filter*stats[i].StdDev() + 0.5f);
}
peakvec_t rslt;
for (auto i=begin(shifted); i < end(shifted); i++) {
if (!rslt.empty()) {
peak_t prev = rslt.back();
int xition = 2*((i-1)->channel) + (i->channel);
if ( (i != shifted.end()-1) &&