forked from ha7ilm/openwebrx
-
Notifications
You must be signed in to change notification settings - Fork 169
Expand file tree
/
Copy pathopenwebrx.js
More file actions
1722 lines (1532 loc) · 62.5 KB
/
Copy pathopenwebrx.js
File metadata and controls
1722 lines (1532 loc) · 62.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
/*
This file is part of OpenWebRX,
an open-source SDR receiver software with a web UI.
Copyright (c) 2013-2015 by Andras Retzler <randras@sdr.hu>
Copyright (c) 2019-2020 by Jakob Ketterl <dd5jfk@darc.de>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
"""
*/
is_firefox = navigator.userAgent.indexOf("Firefox") >= 0;
var bandwidth;
var center_freq;
var fft_size;
var fft_compression = "none";
var fft_codec;
var waterfall_setup_done = 0;
var secondary_fft_size;
function e(what) {
return document.getElementById(what);
}
function updateVolume() {
audioEngine.setVolume(parseFloat(e("openwebrx-panel-volume").value) / 100);
}
function toggleMute() {
if (mute) {
mute = false;
e("openwebrx-mute-on").id = "openwebrx-mute-off";
e("openwebrx-panel-volume").disabled = false;
e("openwebrx-panel-volume").value = volumeBeforeMute;
} else {
mute = true;
e("openwebrx-mute-off").id = "openwebrx-mute-on";
e("openwebrx-panel-volume").disabled = true;
volumeBeforeMute = e("openwebrx-panel-volume").value;
e("openwebrx-panel-volume").value = 0;
}
updateVolume();
}
function zoomInOneStep() {
zoom_set(zoom_level + 1);
}
function zoomOutOneStep() {
zoom_set(zoom_level - 1);
}
function zoomInTotal() {
zoom_set(zoom_levels.length - 1);
}
function zoomOutTotal() {
zoom_set(0);
}
var waterfall_min_level;
var waterfall_max_level;
var waterfall_min_level_default;
var waterfall_max_level_default;
var waterfall_colors = buildWaterfallColors(['#000', '#FFF']);
var waterfall_auto_level_margin;
function buildWaterfallColors(input) {
return chroma.scale(input).colors(256, 'rgb')
}
function updateWaterfallColors(which) {
var $wfmax = $("#openwebrx-waterfall-color-max");
var $wfmin = $("#openwebrx-waterfall-color-min");
waterfall_max_level = parseInt($wfmax.val());
waterfall_min_level = parseInt($wfmin.val());
if (waterfall_min_level >= waterfall_max_level) {
if (!which) {
waterfall_min_level = waterfall_max_level -1;
} else {
waterfall_max_level = waterfall_min_level + 1;
}
}
updateWaterfallSliders();
}
function updateWaterfallSliders() {
$('#openwebrx-waterfall-color-max')
.val(waterfall_max_level)
.attr('title', 'Waterfall maximum level (' + Math.round(waterfall_max_level) + ' dB)');
$('#openwebrx-waterfall-color-min')
.val(waterfall_min_level)
.attr('title', 'Waterfall minimum level (' + Math.round(waterfall_min_level) + ' dB)');
}
function waterfallColorsDefault() {
waterfall_min_level = waterfall_min_level_default;
waterfall_max_level = waterfall_max_level_default;
updateWaterfallSliders();
waterfallColorsContinuousReset();
}
function waterfallColorsAuto(levels) {
var min_level = levels.min - waterfall_auto_level_margin.min;
var max_level = levels.max + waterfall_auto_level_margin.max;
max_level = Math.max(min_level + (waterfall_auto_level_margin.min_range || 0), max_level);
waterfall_min_level = min_level;
waterfall_max_level = max_level;
updateWaterfallSliders();
}
var waterfall_continuous = {
min: -150,
max: 0
};
function waterfallColorsContinuousReset() {
waterfall_continuous.min = waterfall_min_level;
waterfall_continuous.max = waterfall_max_level;
}
function waterfallColorsContinuous(levels) {
if (levels.max > waterfall_continuous.max + 1) {
waterfall_continuous.max += 1;
} else if (levels.max < waterfall_continuous.max - 1) {
waterfall_continuous.max -= .1;
}
if (levels.min < waterfall_continuous.min - 1) {
waterfall_continuous.min -= 1;
} else if (levels.min > waterfall_continuous.min + 1) {
waterfall_continuous.min += .1;
}
waterfallColorsAuto(waterfall_continuous);
}
function setSmeterRelativeValue(value) {
if (value < 0) value = 0;
if (value > 1.0) value = 1.0;
var bar = e("openwebrx-smeter-bar");
var outer = e("openwebrx-smeter-outer");
bar.style.width = (outer.offsetWidth * value).toString() + "px";
var bgRed = "linear-gradient(to top, #ff5939 , #961700)";
var bgGreen = "linear-gradient(to top, #22ff2f , #008908)";
var bgYellow = "linear-gradient(to top, #fff720 , #a49f00)";
bar.style.background = (value > 0.9) ? bgRed : ((value > 0.7) ? bgYellow : bgGreen);
}
function setSquelchSliderBackground(val) {
var $slider = $('#openwebrx-panel-receiver .openwebrx-squelch-slider');
var min = Number($slider.attr('min'));
var max = Number($slider.attr('max'));
var sliderPosition = $slider.val();
var relative = (val - min) / (max - min);
// use a brighter color when squelch is open
var color = val >= sliderPosition ? '#22ff2f' : '#008908';
// we don't use the gradient, but separate the colors discretely using css tricks
var style = 'linear-gradient(90deg, ' + color + ', ' + color + ' ' + relative * 100 + '%, #B6B6B6 ' + relative * 100 + '%)';
$slider.css('--track-background', style);
}
function getLogSmeterValue(value) {
return 10 * Math.log10(value);
}
function setSmeterAbsoluteValue(value) //the value that comes from `csdr squelch_and_smeter_cc`
{
var logValue = getLogSmeterValue(value);
setSquelchSliderBackground(logValue);
var lowLevel = waterfall_min_level - 20;
var highLevel = waterfall_max_level + 20;
var percent = (logValue - lowLevel) / (highLevel - lowLevel);
setSmeterRelativeValue(percent);
e("openwebrx-smeter-db").innerHTML = logValue.toFixed(1) + " dB";
}
function typeInAnimation(element, timeout, what, onFinish) {
if (!what) {
onFinish();
return;
}
element.innerHTML += what[0];
window.setTimeout(function () {
typeInAnimation(element, timeout, what.substring(1), onFinish);
}, timeout);
}
// ========================================================
// ================ DEMODULATOR ROUTINES ================
// ========================================================
function getDemodulators() {
return [
$('#openwebrx-panel-receiver').demodulatorPanel().getDemodulator()
].filter(function(d) {
return !!d;
});
}
function mkenvelopes(visible_range) //called from mkscale
{
var demodulators = getDemodulators();
scale_ctx.clearRect(0, 0, scale_ctx.canvas.width, 22); //clear the upper part of the canvas (where filter envelopes reside)
for (var i = 0; i < demodulators.length; i++) {
demodulators[i].envelope.draw(visible_range);
}
if (demodulators.length) {
var bandpass = demodulators[0].getBandpass();
secondary_demod_waterfall_set_zoom(bandpass.low_cut, bandpass.high_cut);
}
}
function waterfallWidth() {
return $('body').width();
}
// ========================================================
// =================== SCALE ROUTINES ===================
// ========================================================
var scale_ctx;
var scale_canvas;
function scale_setup() {
scale_canvas = e("openwebrx-scale-canvas");
scale_ctx = scale_canvas.getContext("2d");
scale_canvas.addEventListener("mousedown", scale_canvas_mousedown, false);
scale_canvas.addEventListener("mousemove", scale_canvas_mousemove, false);
scale_canvas.addEventListener("mouseup", scale_canvas_mouseup, false);
resize_scale();
var frequency_container = e("openwebrx-frequency-container");
frequency_container.addEventListener("mousemove", frequency_container_mousemove, false);
}
var scale_canvas_drag_params = {
mouse_down: false,
drag: false,
start_x: 0,
key_modifiers: {shiftKey: false, altKey: false, ctrlKey: false}
};
function scale_canvas_mousedown(evt) {
scale_canvas_drag_params.mouse_down = true;
scale_canvas_drag_params.drag = false;
scale_canvas_drag_params.start_x = evt.pageX;
scale_canvas_drag_params.key_modifiers.shiftKey = evt.shiftKey;
scale_canvas_drag_params.key_modifiers.altKey = evt.altKey;
scale_canvas_drag_params.key_modifiers.ctrlKey = evt.ctrlKey;
evt.preventDefault();
}
function scale_offset_freq_from_px(x, visible_range) {
if (typeof visible_range === "undefined") visible_range = get_visible_freq_range();
return (visible_range.start + visible_range.bw * (x / waterfallWidth())) - center_freq;
}
function scale_canvas_mousemove(evt) {
var event_handled = false;
var i;
var demodulators = getDemodulators();
if (scale_canvas_drag_params.mouse_down && !scale_canvas_drag_params.drag && Math.abs(evt.pageX - scale_canvas_drag_params.start_x) > canvas_drag_min_delta)
//we can use the main drag_min_delta thing of the main canvas
{
scale_canvas_drag_params.drag = true;
//call the drag_start for all demodulators (and they will decide if they're dragged, based on X coordinate)
for (i = 0; i < demodulators.length; i++) event_handled |= demodulators[i].envelope.drag_start(evt.pageX, scale_canvas_drag_params.key_modifiers);
scale_canvas.style.cursor = "move";
}
else if (scale_canvas_drag_params.drag) {
//call the drag_move for all demodulators (and they will decide if they're dragged)
for (i = 0; i < demodulators.length; i++) event_handled |= demodulators[i].envelope.drag_move(evt.pageX);
if (!event_handled) demodulators[0].set_offset_frequency(scale_offset_freq_from_px(evt.pageX));
}
}
function frequency_container_mousemove(evt) {
var frequency = center_freq + scale_offset_freq_from_px(evt.pageX);
$('.webrx-mouse-freq').frequencyDisplay().setFrequency(frequency);
}
function scale_canvas_end_drag(x) {
scale_canvas.style.cursor = "default";
scale_canvas_drag_params.drag = false;
scale_canvas_drag_params.mouse_down = false;
var event_handled = false;
var demodulators = getDemodulators();
for (var i = 0; i < demodulators.length; i++) event_handled |= demodulators[i].envelope.drag_end();
if (!event_handled) demodulators[0].set_offset_frequency(scale_offset_freq_from_px(x));
}
function scale_canvas_mouseup(evt) {
scale_canvas_end_drag(evt.pageX);
}
function scale_px_from_freq(f, range) {
return Math.round(((f - range.start) / range.bw) * waterfallWidth());
}
function get_visible_freq_range() {
var out = {};
var fcalc = function (x) {
var canvasWidth = waterfallWidth() * zoom_levels[zoom_level];
return Math.round(((-zoom_offset_px + x) / canvasWidth) * bandwidth) + (center_freq - bandwidth / 2);
};
out.start = fcalc(0);
out.center = fcalc(waterfallWidth() / 2);
out.end = fcalc(waterfallWidth());
out.bw = out.end - out.start;
out.hps = out.bw / waterfallWidth();
return out;
}
var scale_markers_levels = [
{
"large_marker_per_hz": 10000000, //large
"estimated_text_width": 70,
"format": "{x} MHz",
"pre_divide": 1000000,
"decimals": 0
},
{
"large_marker_per_hz": 5000000,
"estimated_text_width": 70,
"format": "{x} MHz",
"pre_divide": 1000000,
"decimals": 0
},
{
"large_marker_per_hz": 1000000,
"estimated_text_width": 70,
"format": "{x} MHz",
"pre_divide": 1000000,
"decimals": 0
},
{
"large_marker_per_hz": 500000,
"estimated_text_width": 70,
"format": "{x} MHz",
"pre_divide": 1000000,
"decimals": 1
},
{
"large_marker_per_hz": 100000,
"estimated_text_width": 70,
"format": "{x} MHz",
"pre_divide": 1000000,
"decimals": 1
},
{
"large_marker_per_hz": 50000,
"estimated_text_width": 70,
"format": "{x} MHz",
"pre_divide": 1000000,
"decimals": 2
},
{
"large_marker_per_hz": 10000,
"estimated_text_width": 70,
"format": "{x} MHz",
"pre_divide": 1000000,
"decimals": 2
},
{
"large_marker_per_hz": 5000,
"estimated_text_width": 70,
"format": "{x} MHz",
"pre_divide": 1000000,
"decimals": 3
},
{
"large_marker_per_hz": 1000,
"estimated_text_width": 70,
"format": "{x} MHz",
"pre_divide": 1000000,
"decimals": 1
}
];
var scale_min_space_bw_texts = 50;
var scale_min_space_bw_small_markers = 7;
function get_scale_mark_spacing(range) {
var out = {};
var fcalc = function (freq) {
out.numlarge = (range.bw / freq);
out.large = waterfallWidth() / out.numlarge; //distance between large markers (these have text)
out.ratio = 5; //(ratio-1) small markers exist per large marker
out.small = out.large / out.ratio; //distance between small markers
if (out.small < scale_min_space_bw_small_markers) return false;
if (out.small / 2 >= scale_min_space_bw_small_markers && freq.toString()[0] !== "5") {
out.small /= 2;
out.ratio *= 2;
}
out.smallbw = freq / out.ratio;
return true;
};
for (var i = scale_markers_levels.length - 1; i >= 0; i--) {
var mp = scale_markers_levels[i];
if (!fcalc(mp.large_marker_per_hz)) continue;
//console.log(mp.large_marker_per_hz);
//console.log(out);
if (out.large - mp.estimated_text_width > scale_min_space_bw_texts) break;
}
out.params = mp;
return out;
}
var range;
function mkscale() {
//clear the lower part of the canvas (where frequency scale resides; the upper part is used by filter envelopes):
range = get_visible_freq_range();
mkenvelopes(range); //when scale changes we will always have to redraw filter envelopes, too
scale_ctx.clearRect(0, 22, scale_ctx.canvas.width, scale_ctx.canvas.height - 22);
scale_ctx.strokeStyle = "#fff";
scale_ctx.font = "bold 11px sans-serif";
scale_ctx.textBaseline = "top";
scale_ctx.fillStyle = "#fff";
var spacing = get_scale_mark_spacing(range);
//console.log(spacing);
var marker_hz = Math.ceil(range.start / spacing.smallbw) * spacing.smallbw;
var text_h_pos = 22 + 10 + ((is_firefox) ? 3 : 0);
var text_to_draw = '';
var ftext = function (f) {
text_to_draw = format_frequency(spacing.params.format, f, spacing.params.pre_divide, spacing.params.decimals);
};
var last_large;
var x;
for (; ;) {
x = scale_px_from_freq(marker_hz, range);
if (x > window.innerWidth) break;
scale_ctx.beginPath();
scale_ctx.moveTo(x, 22);
if (marker_hz % spacing.params.large_marker_per_hz === 0) { //large marker
if (typeof first_large === "undefined") var first_large = marker_hz;
last_large = marker_hz;
scale_ctx.lineWidth = 3.5;
scale_ctx.lineTo(x, 22 + 11);
ftext(marker_hz);
var text_measured = scale_ctx.measureText(text_to_draw);
scale_ctx.textAlign = "center";
//advanced text drawing begins
if (zoom_level === 0 && (range.start + spacing.smallbw * spacing.ratio > marker_hz) && (x < text_measured.width / 2)) { //if this is the first overall marker when zoomed out... and if it would be clipped off the screen...
if (scale_px_from_freq(marker_hz + spacing.smallbw * spacing.ratio, range) - text_measured.width >= scale_min_space_bw_texts) { //and if we have enough space to draw it correctly without clipping
scale_ctx.textAlign = "left";
scale_ctx.fillText(text_to_draw, 0, text_h_pos);
}
}
else if (zoom_level === 0 && (range.end - spacing.smallbw * spacing.ratio < marker_hz) && (x > window.innerWidth - text_measured.width / 2)) { // if this is the last overall marker when zoomed out... and if it would be clipped off the screen...
if (window.innerWidth - text_measured.width - scale_px_from_freq(marker_hz - spacing.smallbw * spacing.ratio, range) >= scale_min_space_bw_texts) { //and if we have enough space to draw it correctly without clipping
scale_ctx.textAlign = "right";
scale_ctx.fillText(text_to_draw, window.innerWidth, text_h_pos);
}
}
else scale_ctx.fillText(text_to_draw, x, text_h_pos); //draw text normally
}
else { //small marker
scale_ctx.lineWidth = 2;
scale_ctx.lineTo(x, 22 + 8);
}
marker_hz += spacing.smallbw;
scale_ctx.stroke();
}
if (zoom_level !== 0) { // if zoomed, we don't want the texts to disappear because their markers can't be seen
// on the left side
scale_ctx.textAlign = "center";
var f = first_large - spacing.smallbw * spacing.ratio;
x = scale_px_from_freq(f, range);
ftext(f);
var w = scale_ctx.measureText(text_to_draw).width;
if (x + w / 2 > 0) scale_ctx.fillText(text_to_draw, x, 22 + 10);
// on the right side
f = last_large + spacing.smallbw * spacing.ratio;
x = scale_px_from_freq(f, range);
ftext(f);
w = scale_ctx.measureText(text_to_draw).width;
if (x - w / 2 < window.innerWidth) scale_ctx.fillText(text_to_draw, x, 22 + 10);
}
}
function resize_scale() {
var ratio = window.devicePixelRatio || 1;
var w = window.innerWidth;
var h = 47;
scale_canvas.style.width = w + "px";
scale_canvas.style.height = h + "px";
w *= ratio;
h *= ratio;
scale_canvas.width = w;
scale_canvas.height = h;
scale_ctx.scale(ratio, ratio);
mkscale();
bookmarks.position();
}
function canvas_get_freq_offset(relativeX) {
var rel = (relativeX / canvases[0].clientWidth);
return Math.round((bandwidth * rel) - (bandwidth / 2));
}
function canvas_get_frequency(relativeX) {
return center_freq + canvas_get_freq_offset(relativeX);
}
function format_frequency(format, freq_hz, pre_divide, decimals) {
var out = format.replace("{x}", (freq_hz / pre_divide).toFixed(decimals));
var at = out.indexOf(".") + 4;
while (decimals > 3) {
out = out.substr(0, at) + "," + out.substr(at);
at += 4;
decimals -= 3;
}
return out;
}
var canvas_drag = false;
var canvas_drag_min_delta = 1;
var canvas_mouse_down = false;
var canvas_drag_last_x;
var canvas_drag_last_y;
var canvas_drag_start_x;
var canvas_drag_start_y;
function canvas_mousedown(evt) {
canvas_mouse_down = true;
canvas_drag = false;
canvas_drag_last_x = canvas_drag_start_x = evt.pageX;
canvas_drag_last_y = canvas_drag_start_y = evt.pageY;
evt.preventDefault(); //don't show text selection mouse pointer
}
function canvas_mousemove(evt) {
if (!waterfall_setup_done) return;
var relativeX = get_relative_x(evt);
if (canvas_mouse_down) {
if (!canvas_drag && Math.abs(evt.pageX - canvas_drag_start_x) > canvas_drag_min_delta) {
canvas_drag = true;
canvas_container.style.cursor = "move";
}
if (canvas_drag) {
var deltaX = canvas_drag_last_x - evt.pageX;
var dpx = range.hps * deltaX;
if (
!(zoom_center_rel + dpx > (bandwidth / 2 - waterfallWidth() * (1 - zoom_center_where) * range.hps)) &&
!(zoom_center_rel + dpx < -bandwidth / 2 + waterfallWidth() * zoom_center_where * range.hps)
) {
zoom_center_rel += dpx;
}
resize_canvases(false);
canvas_drag_last_x = evt.pageX;
canvas_drag_last_y = evt.pageY;
mkscale();
bookmarks.position();
}
} else {
$('.webrx-mouse-freq').frequencyDisplay().setFrequency(canvas_get_frequency(relativeX));
}
}
function canvas_container_mouseleave() {
canvas_end_drag();
}
function canvas_mouseup(evt) {
if (!waterfall_setup_done) return;
var relativeX = get_relative_x(evt);
if (!canvas_drag) {
$('#openwebrx-panel-receiver').demodulatorPanel().getDemodulator().set_offset_frequency(canvas_get_freq_offset(relativeX));
}
else {
canvas_end_drag();
}
canvas_mouse_down = false;
}
function canvas_end_drag() {
canvas_container.style.cursor = "crosshair";
canvas_mouse_down = false;
}
function zoom_center_where_calc(screenposX) {
return screenposX / waterfallWidth();
}
function get_relative_x(evt) {
var relativeX = evt.offsetX || evt.layerX;
if ($(evt.target).closest(canvas_container).length) return relativeX;
// compensate for the frequency scale, since that is not resized by the browser.
var relatives = $(evt.target).closest('#openwebrx-frequency-container').map(function(){
return evt.pageX - this.offsetLeft;
});
if (relatives.length) relativeX = relatives[0];
return relativeX - zoom_offset_px;
}
function canvas_mousewheel(evt) {
if (!waterfall_setup_done) return;
var relativeX = get_relative_x(evt);
var dir = (evt.deltaY / Math.abs(evt.deltaY)) > 0;
zoom_step(dir, relativeX, zoom_center_where_calc(evt.pageX));
evt.preventDefault();
}
var zoom_max_level_hps = 33; //Hz/pixel
var zoom_levels_count = 14;
function get_zoom_coeff_from_hps(hps) {
var shown_bw = (window.innerWidth * hps);
return bandwidth / shown_bw;
}
var zoom_levels = [1];
var zoom_level = 0;
var zoom_offset_px = 0;
var zoom_center_rel = 0;
var zoom_center_where = 0;
var smeter_level = 0;
function mkzoomlevels() {
zoom_levels = [1];
var maxc = get_zoom_coeff_from_hps(zoom_max_level_hps);
if (maxc < 1) return;
// logarithmic interpolation
var zoom_ratio = Math.pow(maxc, 1 / zoom_levels_count);
for (var i = 1; i < zoom_levels_count; i++)
zoom_levels.push(Math.pow(zoom_ratio, i));
}
function zoom_step(out, where, onscreen) {
if ((out && zoom_level === 0) || (!out && zoom_level >= zoom_levels_count - 1)) return;
if (out) --zoom_level;
else ++zoom_level;
zoom_center_rel = canvas_get_freq_offset(where);
//console.log("zoom_step || zlevel: "+zoom_level.toString()+" zlevel_val: "+zoom_levels[zoom_level].toString()+" zoom_center_rel: "+zoom_center_rel.toString());
zoom_center_where = onscreen;
//console.log(zoom_center_where, zoom_center_rel, where);
resize_canvases(true);
mkscale();
bookmarks.position();
}
function zoom_set(level) {
if (!(level >= 0 && level <= zoom_levels.length - 1)) return;
level = parseInt(level);
zoom_level = level;
//zoom_center_rel=canvas_get_freq_offset(-canvases[0].offsetLeft+waterfallWidth()/2); //zoom to screen center instead of demod envelope
zoom_center_rel = $('#openwebrx-panel-receiver').demodulatorPanel().getDemodulator().get_offset_frequency();
zoom_center_where = 0.5 + (zoom_center_rel / bandwidth); //this is a kind of hack
resize_canvases(true);
mkscale();
bookmarks.position();
}
function zoom_calc() {
var winsize = waterfallWidth();
var canvases_new_width = winsize * zoom_levels[zoom_level];
zoom_offset_px = -((canvases_new_width * (0.5 + zoom_center_rel / bandwidth)) - (winsize * zoom_center_where));
if (zoom_offset_px > 0) zoom_offset_px = 0;
if (zoom_offset_px < winsize - canvases_new_width)
zoom_offset_px = winsize - canvases_new_width;
}
var networkSpeedMeasurement;
var currentprofile;
var COMPRESS_FFT_PAD_N = 10; //should be the same as in csdr.c
function on_ws_recv(evt) {
if (typeof evt.data === 'string') {
// text messages
networkSpeedMeasurement.add(evt.data.length);
if (evt.data.substr(0, 16) === "CLIENT DE SERVER") {
divlog("Server acknowledged WebSocket connection.");
} else {
try {
var json = JSON.parse(evt.data);
switch (json.type) {
case "config":
var config = json['value'];
waterfall_colors = buildWaterfallColors(config['waterfall_colors']);
waterfall_min_level_default = config['waterfall_min_level'];
waterfall_max_level_default = config['waterfall_max_level'];
waterfall_auto_level_margin = config['waterfall_auto_level_margin'];
waterfallColorsDefault();
var initial_demodulator_params = {
mod: config['start_mod'],
offset_frequency: config['start_offset_freq'],
squelch_level: Number.isInteger(config['initial_squelch_level']) ? config['initial_squelch_level'] : -150
};
bandwidth = config['samp_rate'];
center_freq = config['center_freq'];
fft_size = config['fft_size'];
var audio_compression = config['audio_compression'];
audioEngine.setCompression(audio_compression);
divlog("Audio stream is " + ((audio_compression === "adpcm") ? "compressed" : "uncompressed") + ".");
fft_compression = config['fft_compression'];
divlog("FFT stream is " + ((fft_compression === "adpcm") ? "compressed" : "uncompressed") + ".");
$('#openwebrx-bar-clients').progressbar().setMaxClients(config['max_clients']);
waterfall_init();
var demodulatorPanel = $('#openwebrx-panel-receiver').demodulatorPanel();
demodulatorPanel.setInitialParams(initial_demodulator_params);
demodulatorPanel.setCenterFrequency(center_freq);
bookmarks.loadLocalBookmarks();
waterfall_clear();
currentprofile = config['sdr_id'] + '|' + config['profile_id'];
$('#openwebrx-sdr-profiles-listbox').val(currentprofile);
break;
case "secondary_config":
var s = json['value'];
window.secondary_fft_size = s['secondary_fft_size'];
window.secondary_bw = s['secondary_bw'];
window.if_samp_rate = s['if_samp_rate'];
secondary_demod_init_canvases();
break;
case "receiver_details":
$('#webrx-top-container').header().setDetails(json['value']);
break;
case "smeter":
smeter_level = json['value'];
setSmeterAbsoluteValue(smeter_level);
break;
case "cpuusage":
$('#openwebrx-bar-server-cpu').progressbar().setUsage(json['value']);
break;
case "clients":
$('#openwebrx-bar-clients').progressbar().setClients(json['value']);
break;
case "profiles":
var listbox = e("openwebrx-sdr-profiles-listbox");
listbox.innerHTML = json['value'].map(function (profile) {
return '<option value="' + profile['id'] + '">' + profile['name'] + "</option>";
}).join("");
if (currentprofile) {
$('#openwebrx-sdr-profiles-listbox').val(currentprofile);
}
break;
case "features":
Modes.setFeatures(json['value']);
break;
case "metadata":
update_metadata(json['value']);
break;
case "js8_message":
$("#openwebrx-panel-js8-message").js8().pushMessage(json['value']);
break;
case "wsjt_message":
update_wsjt_panel(json['value']);
break;
case "dial_frequencies":
var as_bookmarks = json['value'].map(function (d) {
return {
name: d['mode'].toUpperCase(),
modulation: d['mode'],
frequency: d['frequency']
};
});
bookmarks.replace_bookmarks(as_bookmarks, 'dial_frequencies');
break;
case "aprs_data":
update_packet_panel(json['value']);
break;
case "bookmarks":
bookmarks.replace_bookmarks(json['value'], "server");
break;
case "sdr_error":
divlog(json['value'], true);
var $overlay = $('#openwebrx-error-overlay');
$overlay.find('.errormessage').text(json['value']);
$overlay.show();
break;
case 'secondary_demod':
secondary_demod_push_data(json['value']);
break;
case 'log_message':
divlog(json['value'], true);
break;
case 'pocsag_data':
update_pocsag_panel(json['value']);
break;
case 'backoff':
divlog("Server is currently busy: " + json['reason'], true);
var $overlay = $('#openwebrx-error-overlay');
$overlay.find('.errormessage').text(json['reason']);
$overlay.show();
// set a higher reconnection timeout right away to avoid additional load
reconnect_timeout = 16000;
break;
case 'modes':
Modes.setModes(json['value']);
break;
default:
console.warn('received message of unknown type: ' + json['type']);
}
} catch (e) {
// don't lose exception
console.error(e)
}
}
} else if (evt.data instanceof ArrayBuffer) {
// binary messages
networkSpeedMeasurement.add(evt.data.byteLength);
var type = new Uint8Array(evt.data, 0, 1)[0];
var data = evt.data.slice(1);
var waterfall_i16;
var waterfall_f32;
var i;
switch (type) {
case 1:
// FFT data
if (fft_compression === "none") {
waterfall_add(new Float32Array(data));
} else if (fft_compression === "adpcm") {
fft_codec.reset();
waterfall_i16 = fft_codec.decode(new Uint8Array(data));
waterfall_f32 = new Float32Array(waterfall_i16.length - COMPRESS_FFT_PAD_N);
for (i = 0; i < waterfall_i16.length; i++) waterfall_f32[i] = waterfall_i16[i + COMPRESS_FFT_PAD_N] / 100;
waterfall_add(waterfall_f32);
}
break;
case 2:
// audio data
audioEngine.pushAudio(data);
break;
case 3:
// secondary FFT
if (fft_compression === "none") {
secondary_demod_waterfall_add(new Float32Array(data));
} else if (fft_compression === "adpcm") {
fft_codec.reset();
waterfall_i16 = fft_codec.decode(new Uint8Array(data));
waterfall_f32 = new Float32Array(waterfall_i16.length - COMPRESS_FFT_PAD_N);
for (i = 0; i < waterfall_i16.length; i++) waterfall_f32[i] = waterfall_i16[i + COMPRESS_FFT_PAD_N] / 100;
secondary_demod_waterfall_add(waterfall_f32);
}
break;
case 4:
// hd audio data
audioEngine.pushHdAudio(data);
break;
default:
console.warn('unknown type of binary message: ' + type)
}
}
}
function update_metadata(meta) {
var el;
if (meta['protocol']) switch (meta['protocol']) {
case 'DMR':
if (meta['slot']) {
el = $("#openwebrx-panel-metadata-dmr").find(".openwebrx-dmr-timeslot-panel").get(meta['slot']);
var id = "";
var name = "";
var target = "";
var group = false;
$(el)[meta['sync'] ? "addClass" : "removeClass"]("sync");
if (meta['sync'] && meta['sync'] === "voice") {
id = (meta['additional'] && meta['additional']['callsign']) || meta['source'] || "";
name = (meta['additional'] && meta['additional']['fname']) || "";
if (meta['type'] === "group") {
target = "Talkgroup: ";
group = true;
}
if (meta['type'] === "direct") target = "Direct: ";
target += meta['target'] || "";
$(el).addClass("active");
} else {
$(el).removeClass("active");
}
$(el).find(".openwebrx-dmr-id").text(id);
$(el).find(".openwebrx-dmr-name").text(name);
$(el).find(".openwebrx-dmr-target").text(target);
$(el).find(".openwebrx-meta-user-image")[group ? "addClass" : "removeClass"]("group");
} else {
clear_metadata();
}
break;
case 'YSF':
el = $("#openwebrx-panel-metadata-ysf");
var mode = " ";
var source = "";
var up = "";
var down = "";
if (meta['mode'] && meta['mode'] !== "") {
mode = "Mode: " + meta['mode'];
source = meta['source'] || "";
if (meta['lat'] && meta['lon'] && meta['source']) {
source = "<a class=\"openwebrx-maps-pin\" href=\"map?callsign=" + meta['source'] + "\" target=\"_blank\"></a>" + source;
}
up = meta['up'] ? "Up: " + meta['up'] : "";
down = meta['down'] ? "Down: " + meta['down'] : "";
$(el).find(".openwebrx-meta-slot").addClass("active");
} else {
$(el).find(".openwebrx-meta-slot").removeClass("active");
}
$(el).find(".openwebrx-ysf-mode").text(mode);
$(el).find(".openwebrx-ysf-source").html(source);
$(el).find(".openwebrx-ysf-up").text(up);
$(el).find(".openwebrx-ysf-down").text(down);
break;
} else {
clear_metadata();
}
}
function html_escape(input) {
return $('<div/>').text(input).html()
}
function update_wsjt_panel(msg) {
var $b = $('#openwebrx-panel-wsjt-message').find('tbody');
var t = new Date(msg['timestamp']);
var pad = function (i) {
return ('' + i).padStart(2, "0");
};
var linkedmsg = msg['msg'];
var matches;
if (['FT8', 'JT65', 'JT9', 'FT4'].indexOf(msg['mode']) >= 0) {
matches = linkedmsg.match(/(.*\s[A-Z0-9]+\s)([A-R]{2}[0-9]{2})$/);
if (matches && matches[2] !== 'RR73') {
linkedmsg = html_escape(matches[1]) + '<a href="map?locator=' + matches[2] + '" target="openwebrx-map">' + matches[2] + '</a>';
} else {
linkedmsg = html_escape(linkedmsg);
}
} else if (msg['mode'] === 'WSPR') {
matches = linkedmsg.match(/([A-Z0-9]*\s)([A-R]{2}[0-9]{2})(\s[0-9]+)/);
if (matches) {
linkedmsg = html_escape(matches[1]) + '<a href="map?locator=' + matches[2] + '" target="openwebrx-map">' + matches[2] + '</a>' + html_escape(matches[3]);
} else {
linkedmsg = html_escape(linkedmsg);
}
}
$b.append($(
'<tr data-timestamp="' + msg['timestamp'] + '">' +
'<td>' + pad(t.getUTCHours()) + pad(t.getUTCMinutes()) + pad(t.getUTCSeconds()) + '</td>' +
'<td class="decimal">' + msg['db'] + '</td>' +
'<td class="decimal">' + msg['dt'] + '</td>' +
'<td class="decimal freq">' + msg['freq'] + '</td>' +
'<td class="message">' + linkedmsg + '</td>' +
'</tr>'
));
$b.scrollTop($b[0].scrollHeight);
}
var digital_removal_interval;
// remove old wsjt messages in fixed intervals
function init_digital_removal_timer() {
if (digital_removal_interval) clearInterval(digital_removal_interval);
digital_removal_interval = setInterval(function () {
['#openwebrx-panel-wsjt-message', '#openwebrx-panel-packet-message'].forEach(function (root) {
var $elements = $(root + ' tbody tr');
// limit to 1000 entries in the list since browsers get laggy at some point
var toRemove = $elements.length - 1000;
if (toRemove <= 0) return;
$elements.slice(0, toRemove).remove();
});
}, 15000);
}
function update_packet_panel(msg) {
var $b = $('#openwebrx-panel-packet-message').find('tbody');
var pad = function (i) {