openipc-web 0.1.11

WebAssembly bindings for openipc-rs
Documentation
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
use js_sys::{Array, Object, Reflect, Uint8Array};
use openipc_core::ieee80211::WifiFrame;
use openipc_core::realtek::{parse_rx_aggregate, RxPacketType};
#[cfg(target_arch = "wasm32")]
use openipc_core::realtek_tx::RealtekTxOptions;
use openipc_core::{
    AdaptiveLinkSender, ChannelId, Codec, DepacketizedFrame, FecCounters, FrameLayout,
    PipelineEvent, RadioPort, ReceiverPipeline, WfbKeypair, WfbTxKeypair,
};
#[cfg(target_arch = "wasm32")]
use openipc_rtl88xx::{ChannelWidth, InitReport, InitStatus, RadioConfig, RealtekDevice};
use wasm_bindgen::prelude::*;

#[wasm_bindgen(typescript_custom_section)]
const OPENIPC_VIDEO_FRAME_TYPES: &'static str = r#"
export type OpenIpcVideoFrame = {
    data: Uint8Array;
    codec: "h264" | "h265";
    codecString: string;
    isKeyFrame: boolean;
    timestamp: number;
};

export type OpenIpcRxTransferProfile = {
    frames: OpenIpcVideoFrame[];
    transferBytes: number;
    packets: number;
    acceptedPackets: number;
    droppedPackets: number;
    crcDropped: number;
    icvDropped: number;
    reportDropped: number;
    ignoredFrames: number;
    sessions: number;
    wfbPayloads: number;
    rtpPackets: number;
    videoFrames: number;
    parseMs: number;
    pipelineMs: number;
    totalMs: number;
};
"#;

#[wasm_bindgen]
pub struct OpenIpcReceiver {
    pipeline: ReceiverPipeline,
}

#[wasm_bindgen]
impl OpenIpcReceiver {
    #[wasm_bindgen(constructor)]
    pub fn new() -> Result<OpenIpcReceiver, JsValue> {
        Self::with_channel_id(openipc_core::channel::DEFAULT_LINK_ID << 8, 1, 5)
    }

    #[wasm_bindgen(js_name = withChannelId)]
    pub fn with_channel_id(
        channel_id: u32,
        fec_k: usize,
        fec_n: usize,
    ) -> Result<OpenIpcReceiver, JsValue> {
        let pipeline = ReceiverPipeline::new(
            ChannelId::new(channel_id),
            FrameLayout::WithFcs,
            fec_k,
            fec_n,
        )
        .map_err(|err| JsValue::from_str(&format!("invalid receiver config: {err:?}")))?;
        Ok(Self { pipeline })
    }

    #[wasm_bindgen(js_name = withKeypair)]
    pub fn with_keypair(
        channel_id: u32,
        keypair: &[u8],
        minimum_epoch: u64,
    ) -> Result<OpenIpcReceiver, JsValue> {
        let keypair = WfbKeypair::from_bytes(keypair)
            .map_err(|err| JsValue::from_str(&format!("invalid WFB keypair: {err}")))?;
        let pipeline = ReceiverPipeline::with_keypair(
            ChannelId::new(channel_id),
            FrameLayout::WithFcs,
            keypair,
            minimum_epoch,
        )
        .map_err(|err| JsValue::from_str(&format!("invalid encrypted receiver config: {err}")))?;
        Ok(Self { pipeline })
    }

    #[wasm_bindgen(js_name = pushRtpPacket)]
    pub fn push_rtp_packet(&mut self, data: &[u8]) -> Option<Uint8Array> {
        self.pipeline
            .push_rtp(data)
            .map(|frame| Uint8Array::from(frame.data.as_slice()))
    }

    #[wasm_bindgen(
        js_name = pushRtpPacketDetailed,
        unchecked_return_type = "OpenIpcVideoFrame | null"
    )]
    pub fn push_rtp_packet_detailed(&mut self, data: &[u8]) -> Result<JsValue, JsValue> {
        match self.pipeline.push_rtp(data) {
            Some(frame) => Ok(video_frame_object(frame)?.into()),
            None => Ok(JsValue::NULL),
        }
    }

    #[wasm_bindgen(js_name = pushDecryptedFragment)]
    pub fn push_decrypted_fragment(
        &mut self,
        data_nonce_hex: &str,
        fragment: &[u8],
    ) -> Result<Array, JsValue> {
        let data_nonce = parse_hex_u64(data_nonce_hex)?;
        let events = self
            .pipeline
            .push_decrypted_fragment(data_nonce, fragment)
            .map_err(|err| JsValue::from_str(&format!("WFB fragment rejected: {err:?}")))?;

        let frames = Array::new();
        for event in events {
            if let PipelineEvent::VideoFrame(frame) = event {
                frames.push(&Uint8Array::from(frame.data.as_slice()));
            }
        }
        Ok(frames)
    }

    #[wasm_bindgen(js_name = pushDecrypted80211Frame)]
    pub fn push_decrypted_80211_frame(
        &mut self,
        frame: &[u8],
        fragment: &[u8],
    ) -> Result<Array, JsValue> {
        let events = self
            .pipeline
            .push_decrypted_80211_frame(frame, fragment)
            .map_err(|err| JsValue::from_str(&format!("802.11 frame rejected: {err:?}")))?;
        let frames = Array::new();
        for event in events {
            if let PipelineEvent::VideoFrame(frame) = event {
                frames.push(&Uint8Array::from(frame.data.as_slice()));
            }
        }
        Ok(frames)
    }

    #[wasm_bindgen(js_name = pushEncrypted80211Frame)]
    pub fn push_encrypted_80211_frame(&mut self, frame: &[u8]) -> Result<Array, JsValue> {
        let events = self
            .pipeline
            .push_80211_frame(frame)
            .map_err(|err| JsValue::from_str(&format!("802.11 frame rejected: {err}")))?;
        Ok(video_frames_from_events(events))
    }

    #[wasm_bindgen(js_name = pushRxTransfer)]
    pub fn push_rx_transfer(&mut self, transfer: &[u8]) -> Result<Array, JsValue> {
        let packets = parse_rx_aggregate(transfer)
            .map_err(|err| JsValue::from_str(&format!("Realtek RX aggregate rejected: {err}")))?;
        let frames = Array::new();
        for packet in packets {
            if packet.attrib.crc_err
                || packet.attrib.icv_err
                || packet.attrib.pkt_rpt_type != RxPacketType::NormalRx
            {
                continue;
            }
            let events = self
                .pipeline
                .push_80211_frame(packet.data)
                .map_err(|err| JsValue::from_str(&format!("OpenIPC frame rejected: {err}")))?;
            append_video_frames(&frames, events);
        }
        Ok(frames)
    }

    #[wasm_bindgen(
        js_name = pushRxTransferDetailed,
        unchecked_return_type = "OpenIpcVideoFrame[]"
    )]
    pub fn push_rx_transfer_detailed(&mut self, transfer: &[u8]) -> Result<Array, JsValue> {
        let packets = parse_rx_aggregate(transfer)
            .map_err(|err| JsValue::from_str(&format!("Realtek RX aggregate rejected: {err}")))?;
        let frames = Array::new();
        for packet in packets {
            if packet.attrib.crc_err
                || packet.attrib.icv_err
                || packet.attrib.pkt_rpt_type != RxPacketType::NormalRx
            {
                continue;
            }
            let events = self
                .pipeline
                .push_80211_frame(packet.data)
                .map_err(|err| JsValue::from_str(&format!("OpenIPC frame rejected: {err}")))?;
            append_video_frame_objects(&frames, events)?;
        }
        Ok(frames)
    }

    #[wasm_bindgen(
        js_name = pushRxTransferProfiled,
        unchecked_return_type = "OpenIpcRxTransferProfile"
    )]
    pub fn push_rx_transfer_profiled(&mut self, transfer: &[u8]) -> Result<Object, JsValue> {
        let total_start = now_ms();
        let parse_start = now_ms();
        let packets = parse_rx_aggregate(transfer)
            .map_err(|err| JsValue::from_str(&format!("Realtek RX aggregate rejected: {err}")))?;
        let parse_ms = elapsed_ms(parse_start);

        let frames = Array::new();
        let mut accepted_packets = 0usize;
        let mut crc_dropped = 0usize;
        let mut icv_dropped = 0usize;
        let mut report_dropped = 0usize;
        let mut ignored_frames = 0usize;
        let mut sessions = 0usize;
        let mut wfb_payloads = 0usize;
        let mut rtp_packets = 0usize;
        let mut video_frames = 0usize;

        let pipeline_start = now_ms();
        let packet_count = packets.len();
        for packet in packets {
            if packet.attrib.crc_err {
                crc_dropped += 1;
                continue;
            }
            if packet.attrib.icv_err {
                icv_dropped += 1;
                continue;
            }
            if packet.attrib.pkt_rpt_type != RxPacketType::NormalRx {
                report_dropped += 1;
                continue;
            }
            accepted_packets += 1;
            let events = self
                .pipeline
                .push_80211_frame(packet.data)
                .map_err(|err| JsValue::from_str(&format!("OpenIPC frame rejected: {err}")))?;
            for event in events {
                match event {
                    PipelineEvent::IgnoredFrame => ignored_frames += 1,
                    PipelineEvent::SessionEstablished { .. } => sessions += 1,
                    PipelineEvent::WfbPayload { .. } => wfb_payloads += 1,
                    PipelineEvent::RtpPacket { .. } => rtp_packets += 1,
                    PipelineEvent::VideoFrame(frame) => {
                        video_frames += 1;
                        frames.push(&video_frame_object(frame)?.into());
                    }
                }
            }
        }
        let pipeline_ms = elapsed_ms(pipeline_start);

        let object = Object::new();
        Reflect::set(&object, &JsValue::from_str("frames"), &frames)?;
        set_number(&object, "transferBytes", transfer.len() as f64)?;
        set_number(&object, "packets", packet_count as f64)?;
        set_number(&object, "acceptedPackets", accepted_packets as f64)?;
        set_number(
            &object,
            "droppedPackets",
            (crc_dropped + icv_dropped + report_dropped) as f64,
        )?;
        set_number(&object, "crcDropped", crc_dropped as f64)?;
        set_number(&object, "icvDropped", icv_dropped as f64)?;
        set_number(&object, "reportDropped", report_dropped as f64)?;
        set_number(&object, "ignoredFrames", ignored_frames as f64)?;
        set_number(&object, "sessions", sessions as f64)?;
        set_number(&object, "wfbPayloads", wfb_payloads as f64)?;
        set_number(&object, "rtpPackets", rtp_packets as f64)?;
        set_number(&object, "videoFrames", video_frames as f64)?;
        set_number(&object, "parseMs", parse_ms)?;
        set_number(&object, "pipelineMs", pipeline_ms)?;
        set_number(&object, "totalMs", elapsed_ms(total_start))?;
        Ok(object)
    }

    #[wasm_bindgen(js_name = fecCounters)]
    pub fn fec_counters(&self) -> String {
        counters_json(self.pipeline.fec_counters())
    }
}

#[wasm_bindgen]
pub struct OpenIpcAdaptiveLink {
    sender: AdaptiveLinkSender,
    last_counters: FecCounters,
    rx_channel_id: ChannelId,
}

#[wasm_bindgen]
impl OpenIpcAdaptiveLink {
    #[wasm_bindgen(constructor)]
    pub fn new(
        link_id: u32,
        keypair: &[u8],
        epoch: u64,
        fec_k: usize,
        fec_n: usize,
    ) -> Result<OpenIpcAdaptiveLink, JsValue> {
        let keypair = WfbTxKeypair::from_bytes(keypair)
            .map_err(|err| JsValue::from_str(&format!("invalid adaptive-link keypair: {err}")))?;
        let sender = AdaptiveLinkSender::new(link_id, keypair, epoch, fec_k, fec_n)
            .map_err(|err| JsValue::from_str(&format!("invalid adaptive-link config: {err}")))?;
        Ok(Self {
            sender,
            last_counters: FecCounters::default(),
            rx_channel_id: ChannelId::from_link_port(link_id, RadioPort::Video),
        })
    }

    #[wasm_bindgen(js_name = recordRx)]
    pub fn record_rx(&mut self, now_ms: f64, rssi0: u8, rssi1: u8, snr0: i8, snr1: i8) {
        self.sender
            .link_mut()
            .record_rx(ms_from_js(now_ms), rssi0, rssi1, snr0, snr1);
    }

    #[wasm_bindgen(js_name = recordRxTransfer)]
    pub fn record_rx_transfer(&mut self, transfer: &[u8], now_ms: f64) -> Result<(), JsValue> {
        let packets = parse_rx_aggregate(transfer)
            .map_err(|err| JsValue::from_str(&format!("Realtek RX aggregate rejected: {err}")))?;
        let now_ms = ms_from_js(now_ms);
        for packet in packets {
            if packet.attrib.crc_err
                || packet.attrib.icv_err
                || packet.attrib.pkt_rpt_type != RxPacketType::NormalRx
            {
                continue;
            }
            if !WifiFrame::parse(packet.data, FrameLayout::WithFcs)
                .map(|frame| frame.matches_channel_id(self.rx_channel_id))
                .unwrap_or(false)
            {
                continue;
            }
            self.sender
                .record_rx_paths(now_ms, packet.attrib.rssi, packet.attrib.snr);
        }
        Ok(())
    }

    #[wasm_bindgen(js_name = recordReceiverCounters)]
    pub fn record_receiver_counters(&mut self, receiver: &OpenIpcReceiver, now_ms: f64) {
        self.record_counter_delta(ms_from_js(now_ms), receiver.pipeline.fec_counters());
    }

    #[wasm_bindgen(js_name = recordFec)]
    pub fn record_fec(&mut self, now_ms: f64, total: u32, recovered: u32, lost: u32) {
        self.sender
            .record_fec(ms_from_js(now_ms), total, recovered, lost);
    }

    #[wasm_bindgen(js_name = requestKeyframe)]
    pub fn request_keyframe(&mut self) {
        self.sender.link_mut().request_keyframe();
    }

    #[wasm_bindgen(js_name = setKeyframeRequestMessages)]
    pub fn set_keyframe_request_messages(&mut self, messages: u32) {
        self.sender
            .link_mut()
            .set_keyframe_request_messages(messages);
    }

    #[wasm_bindgen(js_name = setVideoStartIdleMs)]
    pub fn set_video_start_idle_ms(&mut self, idle_ms: u32) {
        self.sender
            .link_mut()
            .set_video_start_idle_ms(idle_ms as u64);
    }

    #[wasm_bindgen(js_name = tick)]
    pub fn tick(&mut self, now_ms: f64) -> Result<Array, JsValue> {
        let frames = self
            .sender
            .tick(ms_from_js(now_ms))
            .map_err(|err| JsValue::from_str(&format!("adaptive-link tick failed: {err}")))?;
        let out = Array::new();
        for frame in frames {
            out.push(&Uint8Array::from(frame.as_slice()));
        }
        Ok(out)
    }

    #[wasm_bindgen(js_name = counters)]
    pub fn counters(&self) -> String {
        counters_json(self.last_counters)
    }

    #[wasm_bindgen(js_name = quality)]
    pub fn quality(&mut self, now_ms: f64) -> String {
        let quality = self.sender.link_mut().quality(ms_from_js(now_ms));
        format!(
            r#"{{"lostLastSecond":{},"recoveredLastSecond":{},"totalLastSecond":{},"rssi":[{},{}],"snr":[{},{}],"linkScore":[{},{}],"idrCode":"{}"}}"#,
            quality.lost_last_second,
            quality.recovered_last_second,
            quality.total_last_second,
            quality.rssi[0],
            quality.rssi[1],
            quality.snr[0],
            quality.snr[1],
            quality.link_score[0],
            quality.link_score[1],
            escape_json_str(&quality.idr_code),
        )
    }

    fn record_counter_delta(&mut self, now_ms: u64, counters: FecCounters) {
        let total = counters
            .total_packets
            .saturating_sub(self.last_counters.total_packets);
        let recovered = counters
            .recovered_packets
            .saturating_sub(self.last_counters.recovered_packets);
        let lost = counters
            .lost_packets
            .saturating_sub(self.last_counters.lost_packets);
        self.last_counters = counters;
        self.sender.record_fec(
            now_ms,
            total.min(u32::MAX as u64) as u32,
            recovered.min(u32::MAX as u64) as u32,
            lost.min(u32::MAX as u64) as u32,
        );
    }
}

#[cfg(target_arch = "wasm32")]
#[wasm_bindgen]
impl OpenIpcAdaptiveLink {
    #[wasm_bindgen(js_name = tickAndSend)]
    pub async fn tick_and_send(
        &mut self,
        device: &WebUsbRealtekDevice,
        now_ms: f64,
        current_channel: u8,
    ) -> Result<usize, JsValue> {
        let frames = self
            .sender
            .tick(ms_from_js(now_ms))
            .map_err(|err| JsValue::from_str(&format!("adaptive-link tick failed: {err}")))?;
        let count = frames.len();
        for frame in frames {
            device.send_packet(&frame, current_channel).await?;
        }
        Ok(count)
    }
}

#[cfg(target_arch = "wasm32")]
#[wasm_bindgen]
pub struct WebUsbRealtekDevice {
    driver: RealtekDevice,
}

#[cfg(target_arch = "wasm32")]
#[wasm_bindgen]
impl WebUsbRealtekDevice {
    #[wasm_bindgen(js_name = fromWebUsbDevice)]
    pub async fn from_web_usb_device(
        device: web_sys::UsbDevice,
    ) -> Result<WebUsbRealtekDevice, JsValue> {
        let driver = RealtekDevice::from_web_usb_device(device)
            .await
            .map_err(driver_error)?;
        Ok(Self { driver })
    }

    #[wasm_bindgen(js_name = bulkInEndpoint)]
    pub fn bulk_in_endpoint(&self) -> u8 {
        self.driver.bulk_in_ep
    }

    #[wasm_bindgen(js_name = bulkOutEndpoint)]
    pub fn bulk_out_endpoint(&self) -> u8 {
        self.driver.bulk_out_ep
    }

    #[wasm_bindgen(js_name = initializeMonitor)]
    pub async fn initialize_monitor(
        &self,
        channel: u8,
        channel_width_mhz: u16,
        channel_offset: u8,
    ) -> Result<String, JsValue> {
        let radio = RadioConfig {
            channel,
            channel_offset,
            channel_width: parse_channel_width(channel_width_mhz)?,
        };
        let report = self
            .driver
            .initialize_monitor_async(radio, false)
            .await
            .map_err(driver_error)?;
        Ok(init_report_json(&report))
    }

    #[wasm_bindgen(js_name = readRxTransfer)]
    pub async fn read_rx_transfer(&self, length: usize) -> Result<Uint8Array, JsValue> {
        let bytes = self
            .driver
            .read_rx_transfer_async(length)
            .await
            .map_err(driver_error)?;
        Ok(Uint8Array::from(bytes.as_slice()))
    }

    #[wasm_bindgen(js_name = writeTxTransfer)]
    pub async fn write_tx_transfer(&self, transfer: &[u8]) -> Result<usize, JsValue> {
        self.driver
            .write_tx_transfer_async(transfer)
            .await
            .map_err(driver_error)
    }

    #[wasm_bindgen(js_name = sendPacket)]
    pub async fn send_packet(
        &self,
        radiotap_packet: &[u8],
        current_channel: u8,
    ) -> Result<usize, JsValue> {
        let chip = self.driver.probe_chip_async().await.map_err(driver_error)?;
        self.driver
            .send_packet_async(
                radiotap_packet,
                RealtekTxOptions {
                    current_channel,
                    is_8814a: chip.family == openipc_rtl88xx::ChipFamily::Rtl8814,
                },
            )
            .await
            .map_err(driver_error)
    }

    #[wasm_bindgen(js_name = setTxPowerOverride)]
    pub async fn set_tx_power_override(
        &self,
        current_channel: u8,
        power: u8,
    ) -> Result<(), JsValue> {
        self.driver
            .set_tx_power_override_async(current_channel, power)
            .await
            .map_err(driver_error)
    }

    #[wasm_bindgen(js_name = readRegisterU8)]
    pub async fn read_register_u8(&self, register: u16) -> Result<u8, JsValue> {
        self.driver
            .read_u8_async(register)
            .await
            .map_err(driver_error)
    }

    #[wasm_bindgen(js_name = readRegisterU32)]
    pub async fn read_register_u32(&self, register: u16) -> Result<u32, JsValue> {
        self.driver
            .read_u32_async(register)
            .await
            .map_err(driver_error)
    }
}

#[cfg(target_arch = "wasm32")]
fn parse_channel_width(width_mhz: u16) -> Result<ChannelWidth, JsValue> {
    match width_mhz {
        20 => Ok(ChannelWidth::Mhz20),
        40 => Ok(ChannelWidth::Mhz40),
        80 => Ok(ChannelWidth::Mhz80),
        _ => Err(JsValue::from_str(
            "unsupported channel width; expected 20, 40, or 80 MHz",
        )),
    }
}

#[cfg(target_arch = "wasm32")]
fn init_report_json(report: &InitReport) -> String {
    let status = match report.status {
        InitStatus::AlreadyRunning => "already_running",
        InitStatus::Initialized => "initialized",
    };
    format!(
        r#"{{"chip":"{}","rfPaths":{},"cutVersion":{},"status":"{}","firmwareDownloaded":{}}}"#,
        report.chip.family.name(),
        report.chip.total_rf_paths(),
        report.chip.cut_version,
        status,
        report.firmware_downloaded
    )
}

#[cfg(target_arch = "wasm32")]
fn driver_error(err: impl std::fmt::Display) -> JsValue {
    JsValue::from_str(&err.to_string())
}

fn video_frames_from_events(events: Vec<PipelineEvent>) -> Array {
    let frames = Array::new();
    append_video_frames(&frames, events);
    frames
}

fn append_video_frames(frames: &Array, events: Vec<PipelineEvent>) {
    for event in events {
        if let PipelineEvent::VideoFrame(frame) = event {
            frames.push(&Uint8Array::from(frame.data.as_slice()));
        }
    }
}

fn append_video_frame_objects(frames: &Array, events: Vec<PipelineEvent>) -> Result<(), JsValue> {
    for event in events {
        if let PipelineEvent::VideoFrame(frame) = event {
            frames.push(&video_frame_object(frame)?.into());
        }
    }
    Ok(())
}

fn video_frame_object(frame: DepacketizedFrame) -> Result<Object, JsValue> {
    let object = Object::new();
    let codec_string = codec_string(&frame);
    Reflect::set(
        &object,
        &JsValue::from_str("data"),
        &Uint8Array::from(frame.data.as_slice()),
    )?;
    Reflect::set(
        &object,
        &JsValue::from_str("codec"),
        &JsValue::from_str(codec_name(frame.codec)),
    )?;
    Reflect::set(
        &object,
        &JsValue::from_str("codecString"),
        &JsValue::from_str(&codec_string),
    )?;
    Reflect::set(
        &object,
        &JsValue::from_str("isKeyFrame"),
        &JsValue::from_bool(frame.is_keyframe),
    )?;
    Reflect::set(
        &object,
        &JsValue::from_str("timestamp"),
        &JsValue::from_f64(f64::from(frame.timestamp)),
    )?;
    Ok(object)
}

fn codec_name(codec: Codec) -> &'static str {
    match codec {
        Codec::H264 => "h264",
        Codec::H265 => "h265",
    }
}

fn codec_string(frame: &DepacketizedFrame) -> String {
    match frame.codec {
        Codec::H264 => h264_codec_string(&frame.data).unwrap_or_else(|| "avc1.42E01E".to_owned()),
        Codec::H265 => "hev1.1.6.L93.B0".to_owned(),
    }
}

fn h264_codec_string(frame: &[u8]) -> Option<String> {
    for unit in annex_b_units(frame) {
        let nalu = &frame[unit.start..unit.end];
        if nalu.len() >= 4 && nalu[0] & 0x1f == 7 {
            return Some(format!(
                "avc1.{}{}{}",
                hex_byte(nalu[1]),
                hex_byte(nalu[2]),
                hex_byte(nalu[3])
            ));
        }
    }
    None
}

#[derive(Debug, Clone, Copy)]
struct AnnexBUnit {
    start: usize,
    end: usize,
}

fn annex_b_units(frame: &[u8]) -> Vec<AnnexBUnit> {
    let mut starts = Vec::new();
    let mut index = 0;
    while index + 3 < frame.len() {
        let len = start_code_len(frame, index);
        if len > 0 {
            starts.push(index);
            index += len;
        } else {
            index += 1;
        }
    }
    if starts.is_empty() && !frame.is_empty() {
        return vec![AnnexBUnit {
            start: 0,
            end: frame.len(),
        }];
    }
    starts
        .iter()
        .enumerate()
        .map(|(index, start)| AnnexBUnit {
            start: start + start_code_len(frame, *start),
            end: starts.get(index + 1).copied().unwrap_or(frame.len()),
        })
        .collect()
}

fn start_code_len(frame: &[u8], offset: usize) -> usize {
    if frame.get(offset) != Some(&0) || frame.get(offset + 1) != Some(&0) {
        return 0;
    }
    if frame.get(offset + 2) == Some(&1) {
        return 3;
    }
    if frame.get(offset + 2) == Some(&0) && frame.get(offset + 3) == Some(&1) {
        return 4;
    }
    0
}

fn hex_byte(value: u8) -> String {
    format!("{value:02X}")
}

fn set_number(object: &Object, key: &str, value: f64) -> Result<(), JsValue> {
    Reflect::set(object, &JsValue::from_str(key), &JsValue::from_f64(value))?;
    Ok(())
}

fn now_ms() -> f64 {
    #[cfg(target_arch = "wasm32")]
    {
        web_sys::window()
            .and_then(|window| window.performance())
            .map(|performance| performance.now())
            .unwrap_or_else(js_sys::Date::now)
    }
    #[cfg(not(target_arch = "wasm32"))]
    {
        0.0
    }
}

fn elapsed_ms(start_ms: f64) -> f64 {
    let elapsed = now_ms() - start_ms;
    if elapsed.is_finite() && elapsed >= 0.0 {
        elapsed
    } else {
        0.0
    }
}

fn counters_json(counters: FecCounters) -> String {
    format!(
        r#"{{"totalPackets":{},"recoveredPackets":{},"lostPackets":{},"badPackets":{}}}"#,
        counters.total_packets,
        counters.recovered_packets,
        counters.lost_packets,
        counters.bad_packets
    )
}

fn escape_json_str(value: &str) -> String {
    let mut out = String::with_capacity(value.len());
    for ch in value.chars() {
        match ch {
            '"' => out.push_str("\\\""),
            '\\' => out.push_str("\\\\"),
            '\n' => out.push_str("\\n"),
            '\r' => out.push_str("\\r"),
            '\t' => out.push_str("\\t"),
            _ => out.push(ch),
        }
    }
    out
}

fn ms_from_js(now_ms: f64) -> u64 {
    if now_ms.is_finite() && now_ms > 0.0 {
        now_ms.min(u64::MAX as f64) as u64
    } else {
        0
    }
}

#[wasm_bindgen(js_name = supportedUsbFilters)]
pub fn supported_usb_filters() -> String {
    // Kept as JSON to avoid forcing web-sys types into the Rust API.
    r#"[{"vendorId":3034,"productId":34834},{"vendorId":3034,"productId":2065},{"vendorId":3034,"productId":43025},{"vendorId":3034,"productId":47121},{"vendorId":3034,"productId":34835},{"vendorId":9047,"productId":288}]"#.to_owned()
}

#[cfg(target_arch = "wasm32")]
#[wasm_bindgen(js_name = listAuthorizedUsbDevices)]
pub async fn list_authorized_usb_devices() -> Result<Array, JsValue> {
    let devices = nusb::list_devices()
        .await
        .map_err(|err| JsValue::from_str(&format!("nusb list_devices failed: {err}")))?;

    let out = Array::new();
    for device in devices {
        let obj = Object::new();
        Reflect::set(
            &obj,
            &JsValue::from_str("vendorId"),
            &JsValue::from_f64(device.vendor_id() as f64),
        )?;
        Reflect::set(
            &obj,
            &JsValue::from_str("productId"),
            &JsValue::from_f64(device.product_id() as f64),
        )?;
        if let Some(product) = device.product_string() {
            Reflect::set(
                &obj,
                &JsValue::from_str("product"),
                &JsValue::from_str(product),
            )?;
        }
        if let Some(manufacturer) = device.manufacturer_string() {
            Reflect::set(
                &obj,
                &JsValue::from_str("manufacturer"),
                &JsValue::from_str(manufacturer),
            )?;
        }
        out.push(&obj);
    }
    Ok(out)
}

fn parse_hex_u64(input: &str) -> Result<u64, JsValue> {
    let trimmed = input.trim();
    let hex = trimmed
        .strip_prefix("0x")
        .or_else(|| trimmed.strip_prefix("0X"))
        .unwrap_or(trimmed);
    u64::from_str_radix(hex, 16)
        .map_err(|err| JsValue::from_str(&format!("invalid nonce hex: {err}")))
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn h264_codec_string_comes_from_annex_b_sps() {
        let frame = [0, 0, 0, 1, 0x67, 0x64, 0x00, 0x1f, 0xac, 0xd9];
        assert_eq!(h264_codec_string(&frame).as_deref(), Some("avc1.64001F"));
    }
}