-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsstv_decoder_ultimate (4).html
More file actions
2336 lines (1978 loc) · 92.5 KB
/
sstv_decoder_ultimate (4).html
File metadata and controls
2336 lines (1978 loc) · 92.5 KB
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
<!DOCTYPE html>
<html lang="fr">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Décodeur SSTV Pro - PLL + AFC</title>
<style>
body {
font-family: 'Consolas', 'Monaco', monospace;
max-width: 1200px;
margin: 0 auto;
padding: 20px;
background-color: #0a0a0f;
color: #00ff00;
}
.container {
background-color: #0f0f18;
padding: 30px;
border-radius: 10px;
border: 1px solid #00ff00;
}
h1 {
color: #00ffff;
text-align: center;
text-shadow: 0 0 10px #00ffff;
}
.subtitle {
text-align: center;
color: #888;
margin-bottom: 20px;
}
.control-group {
margin: 20px 0;
padding: 15px;
border: 1px solid #333;
border-radius: 8px;
background-color: #0a0a10;
}
.control-group h3 {
color: #00ffff;
margin-top: 0;
border-bottom: 1px solid #333;
padding-bottom: 10px;
}
input[type="file"], select, button {
margin: 5px;
padding: 10px 15px;
border-radius: 4px;
border: 1px solid #00ff00;
background-color: #0a0a10;
color: #00ff00;
font-family: inherit;
}
button {
cursor: pointer;
font-weight: bold;
transition: all 0.3s;
}
button:hover {
background-color: #00ff00;
color: #000;
}
button:disabled {
border-color: #333;
color: #333;
cursor: not-allowed;
}
button:disabled:hover {
background-color: #0a0a10;
color: #333;
}
#canvas {
border: 2px solid #00ff00;
display: block;
margin: 20px auto;
background-color: #000;
box-shadow: 0 0 20px rgba(0, 255, 0, 0.3);
}
.progress-bar {
width: 100%;
height: 24px;
background-color: #111;
border-radius: 12px;
overflow: hidden;
margin: 10px 0;
border: 1px solid #333;
}
.progress-fill {
height: 100%;
background: linear-gradient(90deg, #00ff00, #00ffff);
width: 0%;
transition: width 0.1s;
}
.info {
background-color: #001100;
padding: 15px;
border-radius: 5px;
margin: 10px 0;
border-left: 4px solid #00ff00;
}
.warning {
background-color: #111100;
border-left-color: #ffff00;
}
.error {
background-color: #110000;
color: #ff4444;
padding: 15px;
border-radius: 5px;
margin: 10px 0;
border-left: 4px solid #ff4444;
}
.debug {
background-color: #000;
color: #00ff00;
padding: 10px;
border-radius: 5px;
margin: 10px 0;
font-size: 11px;
max-height: 300px;
overflow-y: auto;
border: 1px solid #333;
}
.spectrum-canvas {
width: 100%;
height: 150px;
background-color: #000;
border: 1px solid #333;
border-radius: 4px;
margin: 10px 0;
}
label {
display: inline-block;
width: 200px;
color: #aaa;
}
.detected-mode {
font-size: 18px;
color: #00ffff;
font-weight: bold;
}
.stats {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 10px;
margin: 10px 0;
}
.stat-box {
background: #001100;
padding: 10px;
border-radius: 5px;
text-align: center;
border: 1px solid #333;
}
.stat-value {
font-size: 24px;
color: #00ffff;
}
.stat-label {
font-size: 11px;
color: #666;
}
.row {
display: flex;
gap: 10px;
flex-wrap: wrap;
}
input[type="range"] {
width: 200px;
accent-color: #00ff00;
}
input[type="number"] {
width: 80px;
background: #0a0a10;
border: 1px solid #333;
color: #00ff00;
padding: 5px;
}
</style>
</head>
<body>
<div class="container">
<h1>📡 SSTV Decoder Ultimate</h1>
<p class="subtitle">PLL + AFC + Doppler — WAV File & Live Audio</p>
<!-- TABS -->
<div class="tabs" style="display:flex;gap:5px;margin-bottom:15px;">
<button class="tab-btn active" onclick="switchTab('file')" id="tabFile" style="padding:10px 25px;background:#0f0f18;border:2px solid #00ff00;color:#00ff00;cursor:pointer;border-radius:5px 5px 0 0;font-weight:bold;">📁 WAV File</button>
<button class="tab-btn" onclick="switchTab('live')" id="tabLive" style="padding:10px 25px;background:#0a0a10;border:2px solid #333;color:#888;cursor:pointer;border-radius:5px 5px 0 0;font-weight:bold;">🎤 Live Audio</button>
</div>
<!-- FILE TAB -->
<div id="fileTabContent" class="tab-content" style="display:block;">
<div class="control-group">
<h3>1. Charger un fichier WAV</h3>
<input type="file" id="fileInput" accept=".wav,audio/wav">
<div id="fileInfo" class="info" style="display:none;"></div>
</div>
<div class="control-group">
<h3>2. Configuration</h3>
<div class="row" style="margin-bottom:15px;">
<div>
<label>Mode forcé:</label>
<select id="forceMode">
<option value="auto">Auto-détection (VIS)</option>
<optgroup label="Robot">
<option value="robot36">Robot36 Color</option>
<option value="robot72">Robot72 Color</option>
</optgroup>
<optgroup label="Martin">
<option value="martinM1">Martin M1</option>
<option value="martinM2">Martin M2</option>
</optgroup>
<optgroup label="Scottie">
<option value="scottieS1">Scottie S1</option>
<option value="scottieS2">Scottie S2</option>
</optgroup>
<optgroup label="PD">
<option value="pd90">PD90</option>
<option value="pd120">PD120</option>
<option value="pd160">PD160</option>
<option value="pd180">PD180</option>
<option value="pd240">PD240</option>
</optgroup>
</select>
</div>
</div>
<div class="row" style="margin-bottom:15px;">
<div>
<label>Décalage Doppler manuel (Hz):</label>
<input type="number" id="dopplerOffset" value="0" min="-500" max="500">
</div>
<div>
<label>AFC (Auto Freq Control):</label>
<select id="afcMode">
<option value="auto">Auto (sync pulse)</option>
<option value="off">Désactivé</option>
</select>
</div>
</div>
<div class="row">
<div>
<label>Slant correction (ms/ligne):</label>
<input type="number" id="slantCorrection" value="0" step="0.01" min="-1" max="1">
</div>
</div>
</div>
<div class="control-group">
<h3>3. Décodage</h3>
<button id="analyzeBtn" disabled>📊 Analyser signal</button>
<button id="decodeBtn" disabled>🔍 Décoder</button>
<button id="saveBtn" disabled style="border-color:#00ffff;color:#00ffff;">💾 Sauvegarder PNG</button>
<div class="progress-bar" id="progressBar" style="display:none;">
<div class="progress-fill" id="progressFill"></div>
</div>
<div id="status" class="info" style="display:none;"></div>
</div>
<div class="control-group">
<h3>4. Analyse du signal</h3>
<div class="stats">
<div class="stat-box">
<div class="stat-value" id="statDoppler">--</div>
<div class="stat-label">Doppler estimé (Hz)</div>
</div>
<div class="stat-box">
<div class="stat-value" id="statSNR">--</div>
<div class="stat-label">SNR estimé (dB)</div>
</div>
<div class="stat-box">
<div class="stat-value" id="statMode">--</div>
<div class="stat-label">Mode détecté</div>
</div>
</div>
<canvas id="waveformCanvas" class="spectrum-canvas" width="1000" height="100"></canvas>
<canvas id="spectrogramCanvas" class="spectrum-canvas" width="1000" height="150"></canvas>
</div>
<div class="control-group">
<h3>5. Image décodée</h3>
<canvas id="canvas" width="640" height="496"></canvas>
</div>
<div class="control-group">
<h3>6. Debug</h3>
<div id="debugLog" class="debug"></div>
</div>
</div><!-- END FILE TAB -->
<!-- LIVE TAB -->
<div id="liveTabContent" class="tab-content" style="display:none;">
<div class="control-group">
<h3>🎤 Audio Capture</h3>
<div style="display:flex;justify-content:center;gap:15px;margin-bottom:15px;">
<button id="startLiveBtn" style="padding:15px 30px;font-size:16px;">▶ START</button>
<button id="stopLiveBtn" disabled style="padding:15px 30px;font-size:16px;border-color:#ff4444;color:#ff4444;">■ STOP</button>
</div>
<div style="background:#111;border:1px solid #333;border-radius:4px;height:24px;overflow:hidden;margin:10px 0;">
<div id="levelMeter" style="height:100%;background:linear-gradient(90deg,#00ff00,#ffff00,#ff0000);width:0%;transition:width 0.1s;"></div>
</div>
<div id="liveSourceName" style="font-size:12px;color:#666;text-align:center;">-- Cliquez START pour commencer --</div>
</div>
<div class="control-group">
<h3>📊 Signal Live</h3>
<div style="text-align:center;padding:15px;">
<div style="font-size:42px;color:#00ffff;font-weight:bold;font-family:monospace;" id="liveFreqDisplay">---- Hz</div>
</div>
<div class="stats">
<div class="stat-box">
<div class="stat-value" id="liveStatState">IDLE</div>
<div class="stat-label">État</div>
</div>
<div class="stat-box">
<div class="stat-value" id="liveStatLine">--</div>
<div class="stat-label">Ligne</div>
</div>
<div class="stat-box">
<div class="stat-value" id="liveStatMode">--</div>
<div class="stat-label">Mode</div>
</div>
</div>
</div>
<div class="control-group">
<h3>⚙️ Configuration Live</h3>
<div class="row" style="margin-bottom:15px;">
<div>
<label>Mode forcé:</label>
<select id="liveForceMode">
<option value="auto">Auto-détection (VIS)</option>
<optgroup label="Robot">
<option value="robot36">Robot36</option>
<option value="robot72">Robot72</option>
</optgroup>
<optgroup label="Martin">
<option value="martinM1">Martin M1</option>
<option value="martinM2">Martin M2</option>
</optgroup>
<optgroup label="Scottie">
<option value="scottieS1">Scottie S1</option>
<option value="scottieS2">Scottie S2</option>
</optgroup>
<optgroup label="PD">
<option value="pd90">PD90</option>
<option value="pd120">PD120</option>
<option value="pd180">PD180</option>
<option value="pd240">PD240</option>
</optgroup>
</select>
</div>
<div>
<label>Doppler manuel (Hz):</label>
<input type="number" id="liveDopplerOffset" value="0" min="-500" max="500">
</div>
</div>
</div>
<div class="control-group">
<h3>🖼️ Image Live</h3>
<canvas id="liveCanvas" width="640" height="496" style="border:2px solid #00ff00;display:block;margin:10px auto;background:#000;box-shadow:0 0 20px rgba(0,255,0,0.3);"></canvas>
<div class="progress-bar">
<div class="progress-fill" id="liveProgressFill"></div>
</div>
<div style="text-align:center;margin-top:10px;">
<button id="liveSaveBtn" disabled style="border-color:#00ffff;color:#00ffff;">💾 Sauvegarder PNG</button>
<button id="liveClearBtn">🗑️ Effacer</button>
</div>
</div>
<div class="control-group">
<h3>📝 Log Live</h3>
<div id="liveDebugLog" class="debug"></div>
</div>
</div><!-- END LIVE TAB -->
<div id="error" class="error" style="display:none;"></div>
</div>
<script>
// ==========================================================================
// MODE DEFINITIONS (EXACT SPECS)
// ==========================================================================
const SSTV_MODES = {
robot36: {
name: "Robot36",
visCode: 0x08,
width: 320, height: 240,
scanMs: 88, chromaMs: 44,
syncMs: 9, porchMs: 3,
separatorMs: 4.5, chromaPorchMs: 1.5,
lineSequence: "robot"
},
robot72: {
name: "Robot72",
visCode: 0x0C,
width: 320, height: 240,
scanMs: 138, chromaMs: 69,
syncMs: 9, porchMs: 3,
separatorMs: 4.5, chromaPorchMs: 1.5,
lineSequence: "robot"
},
martinM1: {
name: "Martin M1",
visCode: 0x2C,
width: 320, height: 256,
scanMs: 146.432,
syncMs: 4.862, porchMs: 0.572, separatorMs: 0.572,
lineSequence: "martin"
},
martinM2: {
name: "Martin M2",
visCode: 0x28,
width: 320, height: 256,
scanMs: 73.216,
syncMs: 4.862, porchMs: 0.572, separatorMs: 0.572,
lineSequence: "martin"
},
scottieS1: {
name: "Scottie S1",
visCode: 0x3C,
width: 320, height: 256,
scanMs: 138.240,
syncMs: 9.0, porchMs: 1.5, separatorMs: 1.5,
lineSequence: "scottie"
},
scottieS2: {
name: "Scottie S2",
visCode: 0x38,
width: 320, height: 256,
scanMs: 88.064,
syncMs: 9.0, porchMs: 1.5, separatorMs: 1.5,
lineSequence: "scottie"
},
pd90: {
name: "PD90",
visCode: 0x63,
width: 320, height: 256,
scanMs: 170.240,
syncMs: 20.0, porchMs: 2.08,
lineSequence: "pd"
},
pd120: {
name: "PD120",
visCode: 0x5F,
width: 640, height: 496,
scanMs: 121.6,
syncMs: 20.0, porchMs: 2.08,
lineSequence: "pd"
},
pd160: {
name: "PD160",
visCode: 0x62,
width: 512, height: 400,
scanMs: 195.584,
syncMs: 20.0, porchMs: 2.08,
lineSequence: "pd"
},
pd180: {
name: "PD180",
visCode: 0x60,
width: 640, height: 496,
scanMs: 183.04,
syncMs: 20.0, porchMs: 2.08,
lineSequence: "pd"
},
pd240: {
name: "PD240",
visCode: 0x61,
width: 640, height: 496,
scanMs: 244.48,
syncMs: 20.0, porchMs: 2.08,
lineSequence: "pd"
}
};
// VIS code mapping
const VIS_TO_MODE = {};
for (const [key, mode] of Object.entries(SSTV_MODES)) {
VIS_TO_MODE[mode.visCode] = key;
}
// SSTV frequency constants
const FREQ = {
SYNC: 1200,
BLACK: 1500,
WHITE: 2300,
RANGE: 800, // WHITE - BLACK
VIS_LEADER: 1900,
VIS_BREAK: 1200,
VIS_ONE: 1100,
VIS_ZERO: 1300
};
// ==========================================================================
// GLOBALS
// ==========================================================================
let audioData = null;
let sampleRate = 44100;
let demodulatedFreq = null; // Pre-computed frequency array
let dopplerOffset = 0;
let debugLog = [];
// ==========================================================================
// UI HANDLERS
// ==========================================================================
document.getElementById('fileInput').addEventListener('change', handleFileSelect);
document.getElementById('analyzeBtn').addEventListener('click', analyzeSignal);
document.getElementById('decodeBtn').addEventListener('click', handleDecode);
document.getElementById('saveBtn').addEventListener('click', saveImage);
function log(msg) {
const timestamp = new Date().toISOString().substr(11, 12);
debugLog.push(`[${timestamp}] ${msg}`);
const logDiv = document.getElementById('debugLog');
logDiv.innerHTML = debugLog.slice(-100).join('<br>');
logDiv.scrollTop = logDiv.scrollHeight;
console.log(msg);
}
function updateProgress(percent) {
document.getElementById('progressFill').style.width = percent + '%';
}
function showError(msg) {
const errorDiv = document.getElementById('error');
errorDiv.style.display = 'block';
errorDiv.textContent = msg;
log('ERROR: ' + msg);
}
// ==========================================================================
// WAV LOADING
// ==========================================================================
function handleFileSelect(event) {
const file = event.target.files[0];
if (!file) return;
debugLog = [];
log(`Loading: ${file.name} (${Math.round(file.size/1024)} KB)`);
const reader = new FileReader();
reader.onload = function(e) {
try {
parseWAV(e.target.result);
document.getElementById('analyzeBtn').disabled = false;
document.getElementById('decodeBtn').disabled = false;
const duration = (audioData.length / sampleRate).toFixed(2);
const info = document.getElementById('fileInfo');
info.style.display = 'block';
info.innerHTML = `Sample rate: ${sampleRate} Hz | Duration: ${duration}s | Samples: ${audioData.length.toLocaleString()}`;
log(`WAV loaded: ${sampleRate}Hz, ${duration}s, ${audioData.length} samples`);
drawWaveform();
} catch (err) {
showError('WAV read error: ' + err.message);
}
};
reader.readAsArrayBuffer(file);
}
function parseWAV(arrayBuffer) {
const view = new DataView(arrayBuffer);
const riff = String.fromCharCode(view.getUint8(0), view.getUint8(1), view.getUint8(2), view.getUint8(3));
if (riff !== 'RIFF') throw new Error('Invalid WAV: no RIFF header');
const wave = String.fromCharCode(view.getUint8(8), view.getUint8(9), view.getUint8(10), view.getUint8(11));
if (wave !== 'WAVE') throw new Error('Invalid WAV: no WAVE marker');
let offset = 12;
let bitsPerSample = 16;
while (offset < arrayBuffer.byteLength - 8) {
const chunkId = String.fromCharCode(
view.getUint8(offset), view.getUint8(offset+1),
view.getUint8(offset+2), view.getUint8(offset+3)
);
const chunkSize = view.getUint32(offset + 4, true);
if (chunkId === 'fmt ') {
sampleRate = view.getUint32(offset + 12, true);
bitsPerSample = view.getUint16(offset + 22, true);
log(`Format: PCM ${bitsPerSample}-bit, ${sampleRate} Hz`);
}
if (chunkId === 'data') {
const bytesPerSample = bitsPerSample / 8;
const samples = chunkSize / bytesPerSample;
audioData = new Float32Array(samples);
for (let i = 0; i < samples; i++) {
if (bitsPerSample === 16) {
audioData[i] = view.getInt16(offset + 8 + i * 2, true) / 32768.0;
} else if (bitsPerSample === 8) {
audioData[i] = (view.getUint8(offset + 8 + i) - 128) / 128.0;
}
}
log(`Data loaded: ${samples.toLocaleString()} samples`);
return;
}
offset += 8 + chunkSize;
if (chunkSize % 2 !== 0) offset++;
}
throw new Error('No data chunk found in WAV');
}
// ==========================================================================
// FM DEMODULATION - PLL (Phase-Locked Loop)
// ==========================================================================
class PLL {
constructor(sampleRate, centerFreq = 1900, bandwidth = 500) {
this.sampleRate = sampleRate;
this.centerFreq = centerFreq;
this.phase = 0;
this.freq = centerFreq;
// PLL loop filter coefficients
// Bandwidth determines tracking speed vs noise immunity
const damping = 0.707; // Critically damped
const omega = 2 * Math.PI * bandwidth / sampleRate;
this.alpha = 2 * damping * omega; // Phase detector gain
this.beta = omega * omega; // Frequency detector gain
// Limits
this.minFreq = 1000;
this.maxFreq = 2500;
}
process(sample) {
// Generate local oscillator
const lo_i = Math.cos(this.phase);
const lo_q = Math.sin(this.phase);
// Phase detector (multiply and get phase error)
// For real input, we use a simplified approach
const phaseError = sample * lo_q;
// Loop filter (PI controller)
this.freq += this.beta * phaseError;
this.freq = Math.max(this.minFreq, Math.min(this.maxFreq, this.freq));
const phaseAdj = this.alpha * phaseError;
// Update phase
this.phase += 2 * Math.PI * this.freq / this.sampleRate + phaseAdj;
// Wrap phase
while (this.phase > 2 * Math.PI) this.phase -= 2 * Math.PI;
while (this.phase < 0) this.phase += 2 * Math.PI;
return this.freq;
}
reset(freq = 1900) {
this.freq = freq;
this.phase = 0;
}
}
// ==========================================================================
// FM DEMODULATION - Zero Crossing with Interpolation
// ==========================================================================
function demodulateZeroCrossing(samples, sampleRate, outputLength = null) {
const n = samples.length;
const freqs = new Float32Array(outputLength || n);
let crossings = [];
let lastSign = samples[0] >= 0 ? 1 : -1;
// Find all zero crossings with sub-sample interpolation
for (let i = 1; i < n; i++) {
const sign = samples[i] >= 0 ? 1 : -1;
if (sign !== lastSign) {
// Linear interpolation for exact crossing point
const frac = Math.abs(samples[i-1]) / (Math.abs(samples[i-1]) + Math.abs(samples[i]));
crossings.push(i - 1 + frac);
lastSign = sign;
}
}
// Convert crossings to instantaneous frequency
if (crossings.length < 2) {
freqs.fill(1500);
return freqs;
}
let freqIdx = 0;
for (let i = 1; i < crossings.length; i++) {
const halfPeriod = crossings[i] - crossings[i-1];
const freq = sampleRate / (halfPeriod * 2);
// Only accept valid SSTV frequencies
if (freq >= 1000 && freq <= 2500) {
const startSample = Math.floor(crossings[i-1]);
const endSample = Math.min(Math.floor(crossings[i]), freqs.length - 1);
for (let j = startSample; j <= endSample; j++) {
if (j < freqs.length) freqs[j] = freq;
}
}
}
// Fill gaps (areas with no valid crossings)
let lastValid = 1500;
for (let i = 0; i < freqs.length; i++) {
if (freqs[i] === 0) {
freqs[i] = lastValid;
} else {
lastValid = freqs[i];
}
}
return freqs;
}
// ==========================================================================
// FM DEMODULATION - Quadrature (Hilbert Transform)
// ==========================================================================
function demodulateQuadrature(samples, sampleRate) {
const n = samples.length;
const freqs = new Float32Array(n);
// Hilbert transform via FIR filter (truncated ideal)
// Using a simple 31-tap approximation
const hilbertLen = 31;
const hilbert = new Float32Array(hilbertLen);
const mid = Math.floor(hilbertLen / 2);
for (let i = 0; i < hilbertLen; i++) {
const k = i - mid;
if (k === 0) {
hilbert[i] = 0;
} else if (k % 2 !== 0) {
hilbert[i] = 2 / (Math.PI * k);
} else {
hilbert[i] = 0;
}
}
// Apply Hilbert transform to get quadrature component
const Q = new Float32Array(n);
for (let i = mid; i < n - mid; i++) {
let sum = 0;
for (let j = 0; j < hilbertLen; j++) {
sum += samples[i - mid + j] * hilbert[j];
}
Q[i] = sum;
}
// Instantaneous frequency from phase derivative
// f = (1/2π) * d(atan2(Q,I))/dt
for (let i = 1; i < n - 1; i++) {
const I = samples[i];
const Iq = Q[i];
const I_prev = samples[i-1];
const Q_prev = Q[i-1];
// Phase difference using cross-product formula
// avoids atan2 discontinuities
const num = I * Q_prev - Iq * I_prev;
const den = I * I_prev + Iq * Q_prev;
let dPhase = Math.atan2(num, den);
let freq = dPhase * sampleRate / (2 * Math.PI);
// Shift to positive frequency (baseband to SSTV range)
freq = Math.abs(freq);
// This gives us deviation from carrier - need to add center freq
// Actually for SSTV audio, we measure directly
// Re-estimate using zero-crossing for now on problem areas
if (freq < 500) {
// Low freq = near zero crossing, estimate from amplitude
freq = 1500; // Default to black level
} else if (freq > 2500) {
freq = 2300;
} else if (freq < 1000) {
freq = 1200;
}
freqs[i] = freq;
}
freqs[0] = freqs[1];
freqs[n-1] = freqs[n-2];
return freqs;
}
// ==========================================================================
// HYBRID DEMODULATOR - Best of both methods
// ==========================================================================
function demodulateHybrid(samples, sampleRate) {
const n = samples.length;
// Use zero-crossing as primary (most reliable for clean signals)
const freqZC = demodulateZeroCrossing(samples, sampleRate);
// Apply median filter to remove spikes (3-tap)
const freqs = new Float32Array(n);
for (let i = 1; i < n - 1; i++) {
const a = freqZC[i-1], b = freqZC[i], c = freqZC[i+1];
// Median of 3
if ((a <= b && b <= c) || (c <= b && b <= a)) {
freqs[i] = b;
} else if ((b <= a && a <= c) || (c <= a && a <= b)) {
freqs[i] = a;
} else {
freqs[i] = c;
}
}
freqs[0] = freqs[1];
freqs[n-1] = freqs[n-2];
// Light smoothing (exponential moving average)
const alpha = 0.3;
let smoothed = freqs[0];
for (let i = 0; i < n; i++) {
smoothed = alpha * freqs[i] + (1 - alpha) * smoothed;
freqs[i] = smoothed;
}
return freqs;
}
// ==========================================================================
// FULL AUDIO DEMODULATION (run once, cache result)
// ==========================================================================
function demodulateFullAudio() {
log('Demodulating full audio stream...');
const startTime = performance.now();
// Process in chunks for progress updates
const chunkSize = sampleRate; // 1 second chunks
const numChunks = Math.ceil(audioData.length / chunkSize);
demodulatedFreq = new Float32Array(audioData.length);
for (let chunk = 0; chunk < numChunks; chunk++) {
const start = chunk * chunkSize;
const end = Math.min(start + chunkSize, audioData.length);
const samples = audioData.slice(start, end);
const freqs = demodulateHybrid(samples, sampleRate);
demodulatedFreq.set(freqs, start);
updateProgress((chunk + 1) / numChunks * 50); // First 50%
}
const elapsed = ((performance.now() - startTime) / 1000).toFixed(2);
log(`Demodulation complete in ${elapsed}s`);
return demodulatedFreq;
}
// ==========================================================================
// DOPPLER ESTIMATION via SYNC PULSES
// ==========================================================================
function estimateDoppler() {
if (!demodulatedFreq) demodulateFullAudio();
log('Estimating Doppler shift from sync pulses...');
const samplesPerMs = sampleRate / 1000;
const windowSize = Math.floor(5 * samplesPerMs); // 5ms windows
const step = Math.floor(10 * samplesPerMs); // 10ms steps
const syncFreqs = [];
// Search for 1200Hz sync pulses
for (let i = 0; i < demodulatedFreq.length - windowSize; i += step) {
// Average frequency in window
let sum = 0;
for (let j = 0; j < windowSize; j++) {
sum += demodulatedFreq[i + j];
}
const avgFreq = sum / windowSize;
// If it looks like a sync pulse (around 1200Hz)
if (avgFreq > 1100 && avgFreq < 1350) {
syncFreqs.push({
time: i / sampleRate,
freq: avgFreq
});
}
}
if (syncFreqs.length < 10) {
log('Not enough sync pulses found for Doppler estimation');
return 0;
}
// Calculate average deviation from 1200Hz
let totalDeviation = 0;
for (const s of syncFreqs) {
totalDeviation += s.freq - FREQ.SYNC;
}
const avgDoppler = totalDeviation / syncFreqs.length;
// Also check for Doppler drift (linear regression)
const n = syncFreqs.length;
let sumX = 0, sumY = 0, sumXY = 0, sumXX = 0;
for (const s of syncFreqs) {
sumX += s.time;
sumY += s.freq - FREQ.SYNC;
sumXY += s.time * (s.freq - FREQ.SYNC);
sumXX += s.time * s.time;
}
const slope = (n * sumXY - sumX * sumY) / (n * sumXX - sumX * sumX);
log(`Doppler: avg=${avgDoppler.toFixed(1)}Hz, drift=${slope.toFixed(3)}Hz/s`);
log(`Found ${syncFreqs.length} sync pulses`);
return avgDoppler;
}
// ==========================================================================
// VIS CODE DETECTION
// ==========================================================================
function detectVIS() {
if (!demodulatedFreq) demodulateFullAudio();
log('Searching for VIS code...');
const samplesPerMs = sampleRate / 1000;
const windowSize = Math.floor(20 * samplesPerMs);
// Find VIS leader (1900Hz for ~300ms)
let leaderStart = -1;
for (let i = 0; i < Math.min(demodulatedFreq.length, sampleRate * 5); i += windowSize) {
let sum = 0;
for (let j = 0; j < windowSize && i + j < demodulatedFreq.length; j++) {
sum += demodulatedFreq[i + j];
}
const avgFreq = sum / windowSize;
if (avgFreq > 1850 + dopplerOffset && avgFreq < 1950 + dopplerOffset) {
leaderStart = i;
log(`VIS leader found at ${(i/sampleRate).toFixed(3)}s (${avgFreq.toFixed(0)}Hz)`);
break;
}
}
if (leaderStart < 0) {
log('No VIS leader found');
return null;
}
// Skip: Leader(300ms) + Break(10ms) + Leader(300ms) = 610ms
const visDataStart = leaderStart + Math.floor(620 * samplesPerMs);
const bitDuration = Math.floor(30 * samplesPerMs);
// Read 8 data bits
let visCode = 0;
log('Reading VIS bits:');
for (let bit = 0; bit < 8; bit++) {
const bitStart = visDataStart + bit * bitDuration;
const bitCenter = bitStart + Math.floor(bitDuration / 2);
// Sample middle of bit
let sum = 0;
const sampleWindow = Math.floor(10 * samplesPerMs);
for (let j = 0; j < sampleWindow; j++) {
const idx = bitCenter - sampleWindow/2 + j;
if (idx >= 0 && idx < demodulatedFreq.length) {
sum += demodulatedFreq[idx];
}
}
const avgFreq = sum / sampleWindow;
// 1100Hz = 1, 1300Hz = 0 (with Doppler offset)
const threshold = 1200 + dopplerOffset;
const bitValue = avgFreq < threshold ? 1 : 0;