trustformers-wasm 0.2.0

WebAssembly bindings for TrustformeRS transformer library
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
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
#![allow(dead_code)]
use js_sys::{Array, Function, Object, Promise, Uint8Array};
use serde::{Deserialize, Serialize};
use std::collections::VecDeque;
use std::string::String;
use std::vec::Vec;
use wasm_bindgen::prelude::*;
use wasm_bindgen::{closure::Closure, JsCast};
use web_sys::{
    window, CanvasRenderingContext2d, HtmlCanvasElement, HtmlVideoElement, ImageData,
    MediaDeviceInfo, MediaDeviceKind, MediaStream, MediaStreamConstraints, MediaStreamTrack,
    OffscreenCanvas, VideoTrack, Worker,
};

// Import our tensor operations for ML integration
use crate::core::tensor::WasmTensor;
use crate::core::utils::get_current_time_ms;

#[wasm_bindgen]
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
pub enum CameraFacing {
    User,        // Front-facing camera
    Environment, // Back-facing camera
    Unknown,
}

#[wasm_bindgen]
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
pub enum CameraResolution {
    Low,       // 320x240
    Medium,    // 640x480
    High,      // 1280x720
    UltraHigh, // 1920x1080
    Custom,    // Custom resolution
}

#[wasm_bindgen]
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
pub enum CameraState {
    Idle,
    Initializing,
    Active,
    Paused,
    Error,
    Stopped,
}

#[wasm_bindgen]
#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
pub struct FrameQuality {
    pub brightness: f64,
    pub contrast: f64,
    pub sharpness: f64,
    pub is_blurry: bool,
}

#[wasm_bindgen]
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CameraCapabilities {
    pub has_camera: bool,
    pub has_multiple_cameras: bool,
    pub supports_user_facing: bool,
    pub supports_environment_facing: bool,
    pub max_width: u32,
    pub max_height: u32,
    pub(crate) supported_resolutions: Vec<String>,
    pub supports_torch: bool,
    pub supports_zoom: bool,
    pub supports_focus: bool,
}

#[wasm_bindgen]
impl CameraCapabilities {
    #[wasm_bindgen(getter)]
    pub fn has_camera(&self) -> bool {
        self.has_camera
    }

    #[wasm_bindgen(getter)]
    pub fn has_multiple_cameras(&self) -> bool {
        self.has_multiple_cameras
    }

    #[wasm_bindgen(getter)]
    pub fn supports_user_facing(&self) -> bool {
        self.supports_user_facing
    }

    #[wasm_bindgen(getter)]
    pub fn supports_environment_facing(&self) -> bool {
        self.supports_environment_facing
    }

    #[wasm_bindgen(getter)]
    pub fn max_width(&self) -> u32 {
        self.max_width
    }

    #[wasm_bindgen(getter)]
    pub fn max_height(&self) -> u32 {
        self.max_height
    }

    #[wasm_bindgen(getter)]
    pub fn supports_torch(&self) -> bool {
        self.supports_torch
    }

    #[wasm_bindgen(getter)]
    pub fn supports_zoom(&self) -> bool {
        self.supports_zoom
    }

    #[wasm_bindgen(getter)]
    pub fn supports_focus(&self) -> bool {
        self.supports_focus
    }
}

#[wasm_bindgen]
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CameraConfig {
    pub facing: CameraFacing,
    pub resolution: CameraResolution,
    pub width: u32,
    pub height: u32,
    pub frame_rate: f64,
    pub auto_focus: bool,
    pub torch: bool,
    pub zoom: f64,
    pub(crate) device_id: Option<String>,
}

impl Default for CameraConfig {
    fn default() -> Self {
        Self {
            facing: CameraFacing::User,
            resolution: CameraResolution::Medium,
            width: 640,
            height: 480,
            frame_rate: 30.0,
            auto_focus: true,
            torch: false,
            zoom: 1.0,
            device_id: None,
        }
    }
}

#[wasm_bindgen]
impl CameraConfig {
    #[wasm_bindgen(constructor)]
    pub fn new() -> Self {
        Self::default()
    }

    #[wasm_bindgen(getter)]
    pub fn facing(&self) -> CameraFacing {
        self.facing
    }

    #[wasm_bindgen(setter)]
    pub fn set_facing(&mut self, facing: CameraFacing) {
        self.facing = facing;
    }

    #[wasm_bindgen(getter)]
    pub fn resolution(&self) -> CameraResolution {
        self.resolution
    }

    #[wasm_bindgen(setter)]
    pub fn set_resolution(&mut self, resolution: CameraResolution) {
        self.resolution = resolution;
        // Update width/height based on resolution preset
        match resolution {
            CameraResolution::Low => {
                self.width = 320;
                self.height = 240;
            },
            CameraResolution::Medium => {
                self.width = 640;
                self.height = 480;
            },
            CameraResolution::High => {
                self.width = 1280;
                self.height = 720;
            },
            CameraResolution::UltraHigh => {
                self.width = 1920;
                self.height = 1080;
            },
            CameraResolution::Custom => {}, // Keep current width/height
        }
    }

    #[wasm_bindgen(getter)]
    pub fn width(&self) -> u32 {
        self.width
    }

    #[wasm_bindgen(setter)]
    pub fn set_width(&mut self, width: u32) {
        self.width = width;
        self.resolution = CameraResolution::Custom;
    }

    #[wasm_bindgen(getter)]
    pub fn height(&self) -> u32 {
        self.height
    }

    #[wasm_bindgen(setter)]
    pub fn set_height(&mut self, height: u32) {
        self.height = height;
        self.resolution = CameraResolution::Custom;
    }

    #[wasm_bindgen(getter)]
    pub fn frame_rate(&self) -> f64 {
        self.frame_rate
    }

    #[wasm_bindgen(setter)]
    pub fn set_frame_rate(&mut self, rate: f64) {
        self.frame_rate = rate;
    }

    #[wasm_bindgen(getter)]
    pub fn auto_focus(&self) -> bool {
        self.auto_focus
    }

    #[wasm_bindgen(setter)]
    pub fn set_auto_focus(&mut self, auto_focus: bool) {
        self.auto_focus = auto_focus;
    }

    #[wasm_bindgen(getter)]
    pub fn torch(&self) -> bool {
        self.torch
    }

    #[wasm_bindgen(setter)]
    pub fn set_torch(&mut self, torch: bool) {
        self.torch = torch;
    }

    #[wasm_bindgen(getter)]
    pub fn zoom(&self) -> f64 {
        self.zoom
    }

    #[wasm_bindgen(setter)]
    pub fn set_zoom(&mut self, zoom: f64) {
        self.zoom = zoom;
    }

    pub fn set_device_id(&mut self, device_id: Option<String>) {
        self.device_id = device_id;
    }

    pub fn get_device_id(&self) -> Option<String> {
        self.device_id.clone()
    }
}

#[wasm_bindgen]
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FrameData {
    pub width: u32,
    pub height: u32,
    pub timestamp: f64,
    pub(crate) format: String,
    pub frame_number: u64,
    pub quality_score: f64,
    pub brightness: f64,
    pub contrast: f64,
    pub is_blurry: bool,
}

#[wasm_bindgen]
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ProcessingStats {
    pub frames_processed: u64,
    pub frames_dropped: u64,
    pub average_processing_time: f64,
    pub average_frame_rate: f64,
    pub buffer_utilization: f64,
    pub ml_inference_time: f64,
}

#[wasm_bindgen]
impl FrameData {
    #[wasm_bindgen(constructor)]
    pub fn new(width: u32, height: u32, timestamp: f64, format: String) -> Self {
        Self {
            width,
            height,
            timestamp,
            format,
            frame_number: 0,
            quality_score: 1.0,
            brightness: 0.5,
            contrast: 1.0,
            is_blurry: false,
        }
    }

    #[allow(clippy::too_many_arguments)] // reason: distinct configuration parameters; a struct would not simplify the wasm-bindgen API
    pub fn new_with_analysis(
        width: u32,
        height: u32,
        timestamp: f64,
        format: String,
        frame_number: u64,
        quality_score: f64,
        brightness: f64,
        contrast: f64,
        is_blurry: bool,
    ) -> Self {
        Self {
            width,
            height,
            timestamp,
            format,
            frame_number,
            quality_score,
            brightness,
            contrast,
            is_blurry,
        }
    }

    #[wasm_bindgen(getter)]
    pub fn width(&self) -> u32 {
        self.width
    }

    #[wasm_bindgen(getter)]
    pub fn height(&self) -> u32 {
        self.height
    }

    #[wasm_bindgen(getter)]
    pub fn timestamp(&self) -> f64 {
        self.timestamp
    }

    #[wasm_bindgen(getter)]
    pub fn format(&self) -> String {
        self.format.clone()
    }

    #[wasm_bindgen(getter)]
    pub fn frame_number(&self) -> u64 {
        self.frame_number
    }

    #[wasm_bindgen(getter)]
    pub fn quality_score(&self) -> f64 {
        self.quality_score
    }

    #[wasm_bindgen(getter)]
    pub fn brightness(&self) -> f64 {
        self.brightness
    }

    #[wasm_bindgen(getter)]
    pub fn contrast(&self) -> f64 {
        self.contrast
    }

    #[wasm_bindgen(getter)]
    pub fn is_blurry(&self) -> bool {
        self.is_blurry
    }
}

#[wasm_bindgen]
pub struct CameraManager {
    config: CameraConfig,
    state: CameraState,
    stream: Option<MediaStream>,
    video_element: Option<HtmlVideoElement>,
    canvas_element: Option<HtmlCanvasElement>,
    offscreen_canvas: Option<OffscreenCanvas>,
    capabilities: Option<CameraCapabilities>,
    frame_callbacks: Object,
    available_devices: Vec<String>,
    current_device_id: Option<String>,
    is_recording: bool,
    frame_count: u64,
    last_frame_time: f64,
    frame_rate_actual: f64,
    // Enhanced features
    frame_buffer: VecDeque<ImageData>,
    processing_stats: ProcessingStats,
    max_buffer_size: usize,
    auto_focus_enabled: bool,
    exposure_compensation: f64,
    white_balance_mode: String,
    noise_reduction_enabled: bool,
    image_stabilization_enabled: bool,
    ml_preprocessing_enabled: bool,
    adaptive_quality_enabled: bool,
    processing_worker: Option<Worker>,
}

#[wasm_bindgen]
impl CameraManager {
    #[wasm_bindgen(constructor)]
    pub fn new(config: CameraConfig) -> Self {
        Self {
            config,
            state: CameraState::Idle,
            stream: None,
            video_element: None,
            canvas_element: None,
            offscreen_canvas: None,
            capabilities: None,
            frame_callbacks: Object::new(),
            available_devices: Vec::new(),
            current_device_id: None,
            is_recording: false,
            frame_count: 0,
            last_frame_time: 0.0,
            frame_rate_actual: 0.0,
            // Enhanced features
            frame_buffer: VecDeque::new(),
            processing_stats: ProcessingStats {
                frames_processed: 0,
                frames_dropped: 0,
                average_processing_time: 0.0,
                average_frame_rate: 0.0,
                buffer_utilization: 0.0,
                ml_inference_time: 0.0,
            },
            max_buffer_size: 10,
            auto_focus_enabled: true,
            exposure_compensation: 0.0,
            white_balance_mode: "auto".to_string(),
            noise_reduction_enabled: true,
            image_stabilization_enabled: true,
            ml_preprocessing_enabled: false,
            adaptive_quality_enabled: true,
            processing_worker: None,
        }
    }

    pub async fn initialize(&mut self) -> Result<(), JsValue> {
        self.state = CameraState::Initializing;

        // Check for camera support
        self.check_camera_support().await?;

        // Enumerate available devices
        self.enumerate_devices().await?;

        // Create video and canvas elements
        self.create_media_elements()?;

        self.state = CameraState::Idle;
        Ok(())
    }

    async fn check_camera_support(&mut self) -> Result<(), JsValue> {
        let window = window().ok_or("No window object")?;
        let navigator = window.navigator();

        // Check for getUserMedia support
        let media_devices = navigator
            .media_devices()
            .map_err(|_| JsValue::from_str("MediaDevices API not supported"))?;

        // Try to enumerate devices to check camera availability
        let devices_promise = media_devices.enumerate_devices()?;
        let devices_result = wasm_bindgen_futures::JsFuture::from(devices_promise).await?;
        let devices: Array = devices_result.dyn_into()?;

        let mut has_camera = false;
        let mut supports_user_facing = false;
        let mut supports_environment_facing = false;
        let mut camera_count = 0;

        for i in 0..devices.length() {
            if let Ok(device) = devices.get(i).dyn_into::<MediaDeviceInfo>() {
                if device.kind() == MediaDeviceKind::Videoinput {
                    has_camera = true;
                    camera_count += 1;

                    let label = device.label();
                    if label.to_lowercase().contains("front")
                        || label.to_lowercase().contains("user")
                    {
                        supports_user_facing = true;
                    }
                    if label.to_lowercase().contains("back")
                        || label.to_lowercase().contains("environment")
                    {
                        supports_environment_facing = true;
                    }
                }
            }
        }

        let has_multiple_cameras = camera_count > 1;

        self.capabilities = Some(CameraCapabilities {
            has_camera,
            has_multiple_cameras,
            supports_user_facing,
            supports_environment_facing,
            max_width: 1920,
            max_height: 1080,
            supported_resolutions: vec![
                "320x240".to_string(),
                "640x480".to_string(),
                "1280x720".to_string(),
                "1920x1080".to_string(),
            ],
            supports_torch: true, // Most modern devices support torch
            supports_zoom: true,  // Most modern devices support zoom
            supports_focus: true, // Most modern devices support auto-focus
        });

        if !has_camera {
            return Err(JsValue::from_str("No camera devices found"));
        }

        Ok(())
    }

    async fn enumerate_devices(&mut self) -> Result<(), JsValue> {
        let window = window().ok_or("No window object")?;
        let navigator = window.navigator();
        let media_devices = navigator.media_devices().map_err(|_| "MediaDevices not available")?;

        let devices_promise = media_devices.enumerate_devices()?;
        let devices_result = wasm_bindgen_futures::JsFuture::from(devices_promise).await?;
        let devices: Array = devices_result.dyn_into()?;

        self.available_devices.clear();

        for i in 0..devices.length() {
            if let Ok(device) = devices.get(i).dyn_into::<MediaDeviceInfo>() {
                if device.kind() == MediaDeviceKind::Videoinput {
                    self.available_devices.push(device.device_id());
                }
            }
        }

        Ok(())
    }

    fn create_media_elements(&mut self) -> Result<(), JsValue> {
        let window = window().ok_or("No window object")?;
        let document = window.document().ok_or("No document object")?;

        // Create video element
        let video = document.create_element("video")?.dyn_into::<HtmlVideoElement>()?;
        video.set_autoplay(true);
        video.set_muted(true);
        // Use Reflect to set playsInline attribute
        let _ = js_sys::Reflect::set(
            &video,
            &JsValue::from_str("playsInline"),
            &JsValue::from_bool(true),
        );
        video.set_width(self.config.width);
        video.set_height(self.config.height);

        // Create canvas element for frame capture
        let canvas = document.create_element("canvas")?.dyn_into::<HtmlCanvasElement>()?;
        canvas.set_width(self.config.width);
        canvas.set_height(self.config.height);

        self.video_element = Some(video);
        self.canvas_element = Some(canvas);

        Ok(())
    }

    pub async fn start_camera(&mut self) -> Result<(), JsValue> {
        if self.state == CameraState::Active {
            return Ok(());
        }

        let window = window().ok_or("No window object")?;
        let navigator = window.navigator();
        let media_devices = navigator.media_devices().map_err(|_| "MediaDevices not available")?;

        // Create constraints
        let constraints = self.create_media_constraints()?;

        // Get user media
        let media_promise = media_devices.get_user_media_with_constraints(&constraints)?;
        let stream_result = wasm_bindgen_futures::JsFuture::from(media_promise).await;

        match stream_result {
            Ok(stream_value) => {
                let stream: MediaStream = stream_value.dyn_into()?;

                // Set stream to video element
                if let Some(video) = &self.video_element {
                    video.set_src_object(Some(&stream));
                }

                self.stream = Some(stream);
                self.state = CameraState::Active;
                self.frame_count = 0;
                self.last_frame_time = get_current_time();

                // Start frame processing loop
                self.start_frame_processing_loop();

                Ok(())
            },
            Err(error) => {
                self.state = CameraState::Error;
                Err(error)
            },
        }
    }

    fn create_media_constraints(&self) -> Result<MediaStreamConstraints, JsValue> {
        let constraints = MediaStreamConstraints::new();

        // Video constraints
        let video_constraints = Object::new();

        // Set resolution
        js_sys::Reflect::set(
            &video_constraints,
            &"width".into(),
            &JsValue::from(self.config.width),
        )?;
        js_sys::Reflect::set(
            &video_constraints,
            &"height".into(),
            &JsValue::from(self.config.height),
        )?;

        // Set frame rate
        js_sys::Reflect::set(
            &video_constraints,
            &"frameRate".into(),
            &JsValue::from(self.config.frame_rate),
        )?;

        // Set facing mode
        let facing_mode = match self.config.facing {
            CameraFacing::User => "user",
            CameraFacing::Environment => "environment",
            CameraFacing::Unknown => "user", // Default to user
        };
        js_sys::Reflect::set(
            &video_constraints,
            &"facingMode".into(),
            &JsValue::from_str(facing_mode),
        )?;

        // Set device ID if specified
        if let Some(device_id) = &self.config.device_id {
            js_sys::Reflect::set(
                &video_constraints,
                &"deviceId".into(),
                &JsValue::from_str(device_id),
            )?;
        }

        constraints.set_video(&video_constraints.into());
        constraints.set_audio(&JsValue::FALSE); // Only video for now

        Ok(constraints)
    }

    fn start_frame_processing_loop(&self) {
        let Some(window_obj) = window() else { return };

        // Clone necessary data for the closure
        let video_element = self.video_element.clone();
        let canvas_element = self.canvas_element.clone();

        let frame_callback = Closure::wrap(Box::new(move || {
            // Process current frame if video and canvas are available
            if let (Some(video), Some(canvas)) = (&video_element, &canvas_element) {
                if let Ok(Some(context)) = canvas.get_context("2d") {
                    let context: CanvasRenderingContext2d = context.unchecked_into();

                    // Set canvas size to match video
                    let video_width = video.video_width();
                    let video_height = video.video_height();

                    if video_width > 0 && video_height > 0 {
                        canvas.set_width(video_width);
                        canvas.set_height(video_height);

                        // Draw current video frame to canvas
                        let _ = context.draw_image_with_html_video_element_and_dw_and_dh(
                            video,
                            0.0,
                            0.0,
                            video_width as f64,
                            video_height as f64,
                        );

                        // Get image data for analysis
                        if let Ok(_image_data) = context.get_image_data(
                            0.0,
                            0.0,
                            video_width as f64,
                            video_height as f64,
                        ) {
                            // Frame quality analysis would be done here
                            // (Note: This would need access to self for analyze_frame_quality)
                            // For now, we just demonstrate the frame capture process

                            // Schedule next frame
                            // Note: This would need proper closure handling for recursive scheduling
                            // For now, we skip the recursive frame request to avoid complexity
                        }
                    }
                }
            }
        }) as Box<dyn FnMut()>);

        // Use requestAnimationFrame for smooth frame processing
        let _ = window_obj.request_animation_frame(frame_callback.as_ref().unchecked_ref());

        frame_callback.forget();
    }

    pub fn capture_frame(&mut self) -> Result<FrameData, JsValue> {
        if self.state != CameraState::Active {
            return Err(JsValue::from_str("Camera is not active"));
        }

        let video = self.video_element.as_ref().ok_or("No video element")?;
        let canvas = self.canvas_element.as_ref().ok_or("No canvas element")?;

        let context = canvas
            .get_context("2d")?
            .ok_or("Failed to get 2D context")?
            .dyn_into::<CanvasRenderingContext2d>()?;

        // Draw video frame to canvas
        context.draw_image_with_html_video_element_and_dw_and_dh(
            video,
            0.0,
            0.0,
            self.config.width as f64,
            self.config.height as f64,
        )?;

        let current_time = get_current_time();

        // Update frame rate calculation
        if self.last_frame_time > 0.0 {
            let time_delta = current_time - self.last_frame_time;
            self.frame_rate_actual = 1000.0 / time_delta; // Convert to FPS
        }

        self.last_frame_time = current_time;
        self.frame_count += 1;

        let frame_data = FrameData::new(
            self.config.width,
            self.config.height,
            current_time,
            "rgb".to_string(),
        );

        // Call frame callbacks
        self.call_frame_callbacks(&frame_data);

        Ok(frame_data)
    }

    pub fn capture_frame_as_image_data(&self) -> Result<ImageData, JsValue> {
        if self.state != CameraState::Active {
            return Err(JsValue::from_str("Camera is not active"));
        }

        let canvas = self.canvas_element.as_ref().ok_or("No canvas element")?;

        let context = canvas
            .get_context("2d")?
            .ok_or("Failed to get 2D context")?
            .dyn_into::<CanvasRenderingContext2d>()?;

        context.get_image_data(
            0.0,
            0.0,
            self.config.width as f64,
            self.config.height as f64,
        )
    }

    pub fn capture_frame_as_blob(&self) -> Result<Promise, JsValue> {
        if self.state != CameraState::Active {
            return Err(JsValue::from_str("Camera is not active"));
        }

        let canvas = self.canvas_element.as_ref().ok_or("No canvas element")?;

        // Create a promise that wraps the to_blob callback
        let promise = Promise::new(&mut |resolve, reject| {
            let resolve = resolve.clone();
            let reject_clone = reject.clone();
            let reject_for_closure = reject.clone();

            let callback = Closure::once(move |blob: JsValue| {
                if blob.is_null() || blob.is_undefined() {
                    let _ = reject_for_closure
                        .call1(&JsValue::NULL, &JsValue::from_str("Failed to create blob"));
                } else {
                    let _ = resolve.call1(&JsValue::NULL, &blob);
                }
            });

            if let Err(e) = canvas.to_blob(callback.as_ref().unchecked_ref()) {
                let _ = reject_clone.call1(&JsValue::NULL, &e);
            }

            callback.forget(); // Prevent closure from being dropped
        });

        Ok(promise)
    }

    pub fn capture_frame_as_data_url(&self) -> Result<String, JsValue> {
        if self.state != CameraState::Active {
            return Err(JsValue::from_str("Camera is not active"));
        }

        let canvas = self.canvas_element.as_ref().ok_or("No canvas element")?;

        canvas.to_data_url()
    }

    pub fn stop_camera(&mut self) -> Result<(), JsValue> {
        if let Some(stream) = &self.stream {
            let tracks = stream.get_tracks();
            for i in 0..tracks.length() {
                if let Ok(track) = tracks.get(i).dyn_into::<MediaStreamTrack>() {
                    track.stop();
                }
            }
        }

        if let Some(video) = &self.video_element {
            video.set_src_object(None);
        }

        self.stream = None;
        self.state = CameraState::Stopped;
        self.frame_count = 0;
        self.last_frame_time = 0.0;
        self.frame_rate_actual = 0.0;

        Ok(())
    }

    pub fn pause_camera(&mut self) -> Result<(), JsValue> {
        if self.state == CameraState::Active {
            if let Some(video) = &self.video_element {
                video.pause()?;
            }
            self.state = CameraState::Paused;
        }
        Ok(())
    }

    pub fn resume_camera(&mut self) -> Result<(), JsValue> {
        if self.state == CameraState::Paused {
            if let Some(video) = &self.video_element {
                let _ = video.play()?;
            }
            self.state = CameraState::Active;
        }
        Ok(())
    }

    pub async fn switch_camera(&mut self, facing: CameraFacing) -> Result<(), JsValue> {
        let was_active = self.state == CameraState::Active;

        if was_active {
            self.stop_camera()?;
        }

        self.config.facing = facing;
        self.config.device_id = None; // Reset device ID to use facing mode

        if was_active {
            self.start_camera().await?;
        }

        Ok(())
    }

    pub async fn switch_to_device(&mut self, device_id: String) -> Result<(), JsValue> {
        let was_active = self.state == CameraState::Active;

        if was_active {
            self.stop_camera()?;
        }

        self.config.device_id = Some(device_id);

        if was_active {
            self.start_camera().await?;
        }

        Ok(())
    }

    pub fn set_frame_callback(&mut self, callback: &Function) {
        let _ = js_sys::Reflect::set(&self.frame_callbacks, &"frame".into(), callback);
    }

    pub fn set_error_callback(&mut self, callback: &Function) {
        let _ = js_sys::Reflect::set(&self.frame_callbacks, &"error".into(), callback);
    }

    fn call_frame_callbacks(&self, frame_data: &FrameData) {
        if let Ok(callback) = js_sys::Reflect::get(&self.frame_callbacks, &"frame".into()) {
            if let Ok(function) = callback.dyn_into::<Function>() {
                let frame_js =
                    serde_wasm_bindgen::to_value(frame_data).unwrap_or(JsValue::UNDEFINED);
                let _ = function.call1(&JsValue::NULL, &frame_js);
            }
        }
    }

    pub fn apply_torch(&mut self, enable: bool) -> Result<(), JsValue> {
        if let Some(stream) = &self.stream {
            let tracks = stream.get_video_tracks();
            if tracks.length() > 0 {
                if let Ok(track) = tracks.get(0).dyn_into::<VideoTrack>() {
                    // Try to apply torch constraint
                    let constraints = Object::new();
                    let advanced = Array::new();
                    let torch_constraint = Object::new();
                    js_sys::Reflect::set(
                        &torch_constraint,
                        &"torch".into(),
                        &JsValue::from(enable),
                    )?;
                    advanced.push(&torch_constraint);
                    js_sys::Reflect::set(&constraints, &"advanced".into(), &advanced)?;

                    // Apply constraints (this may not work on all browsers/devices)
                    // Use Reflect to call applyConstraints
                    if let Ok(apply_fn) =
                        js_sys::Reflect::get(&track, &JsValue::from_str("applyConstraints"))
                    {
                        if let Ok(apply_fn) = apply_fn.dyn_into::<js_sys::Function>() {
                            let _ = apply_fn.call1(&track, &constraints);
                        }
                    }
                }
            }
        }

        self.config.torch = enable;
        Ok(())
    }

    pub fn apply_zoom(&mut self, zoom_level: f64) -> Result<(), JsValue> {
        if let Some(stream) = &self.stream {
            let tracks = stream.get_video_tracks();
            if tracks.length() > 0 {
                if let Ok(track) = tracks.get(0).dyn_into::<VideoTrack>() {
                    // Try to apply zoom constraint
                    let constraints = Object::new();
                    let advanced = Array::new();
                    let zoom_constraint = Object::new();
                    js_sys::Reflect::set(
                        &zoom_constraint,
                        &"zoom".into(),
                        &JsValue::from(zoom_level),
                    )?;
                    advanced.push(&zoom_constraint);
                    js_sys::Reflect::set(&constraints, &"advanced".into(), &advanced)?;

                    // Apply constraints (this may not work on all browsers/devices)
                    // Use Reflect to call applyConstraints
                    if let Ok(apply_fn) =
                        js_sys::Reflect::get(&track, &JsValue::from_str("applyConstraints"))
                    {
                        if let Ok(apply_fn) = apply_fn.dyn_into::<js_sys::Function>() {
                            let _ = apply_fn.call1(&track, &constraints);
                        }
                    }
                }
            }
        }

        self.config.zoom = zoom_level;
        Ok(())
    }

    #[wasm_bindgen(getter)]
    pub fn state(&self) -> CameraState {
        self.state
    }

    #[wasm_bindgen(getter)]
    pub fn capabilities(&self) -> Option<CameraCapabilities> {
        self.capabilities.clone()
    }

    #[wasm_bindgen(getter)]
    pub fn config(&self) -> CameraConfig {
        self.config.clone()
    }

    #[wasm_bindgen(getter)]
    pub fn frame_count(&self) -> u64 {
        self.frame_count
    }

    #[wasm_bindgen(getter)]
    pub fn actual_frame_rate(&self) -> f64 {
        self.frame_rate_actual
    }

    #[wasm_bindgen(getter)]
    pub fn is_active(&self) -> bool {
        self.state == CameraState::Active
    }

    pub fn get_available_devices(&self) -> Array {
        let array = Array::new();
        for device_id in &self.available_devices {
            array.push(&JsValue::from_str(device_id));
        }
        array
    }

    pub fn export_camera_info(&self) -> Result<String, JsValue> {
        let info = serde_json::json!({
            "state": self.state,
            "config": self.config,
            "capabilities": self.capabilities,
            "available_devices": self.available_devices,
            "current_device_id": self.current_device_id,
            "frame_count": self.frame_count,
            "actual_frame_rate": self.frame_rate_actual,
            "is_recording": self.is_recording,
            "processing_stats": self.processing_stats,
            "buffer_size": self.frame_buffer.len(),
            "ml_preprocessing_enabled": self.ml_preprocessing_enabled,
        });

        serde_json::to_string_pretty(&info).map_err(|e| JsValue::from_str(&e.to_string()))
    }

    // Enhanced ML Integration Methods
    pub fn enable_ml_preprocessing(&mut self, enable: bool) {
        self.ml_preprocessing_enabled = enable;
    }

    pub fn capture_frame_as_tensor(&mut self) -> Result<WasmTensor, JsValue> {
        let image_data = self.capture_frame_as_image_data()?;
        let data = image_data.data();

        // Convert RGBA to RGB and normalize to [0, 1]
        let mut rgb_data = Vec::new();
        let data_vec = data.to_vec();
        for i in (0..data_vec.len()).step_by(4) {
            let r = data_vec[i] as f32 / 255.0;
            let g = data_vec[i + 1] as f32 / 255.0;
            let b = data_vec[i + 2] as f32 / 255.0;
            rgb_data.push(r);
            rgb_data.push(g);
            rgb_data.push(b);
        }

        WasmTensor::new(
            rgb_data,
            vec![self.config.height as usize, self.config.width as usize, 3],
        )
    }

    pub fn capture_frame_as_normalized_tensor(
        &mut self,
        mean: &[f32],
        std: &[f32],
    ) -> Result<WasmTensor, JsValue> {
        let tensor = self.capture_frame_as_tensor()?;

        // Get the data and apply normalization
        let mut data = tensor.data();
        for (i, value) in data.iter_mut().enumerate() {
            let channel = i % 3;
            *value = (*value - mean[channel]) / std[channel];
        }

        // Create a new tensor with normalized data
        WasmTensor::new(data, tensor.shape())
    }

    // Frame Quality Analysis
    pub fn analyze_frame_quality(&self, image_data: &ImageData) -> FrameQuality {
        let data = image_data.data();
        let data_vec = data.to_vec();
        let pixel_count = (data_vec.len() / 4) as f64;

        let mut brightness_sum = 0.0;
        let contrast_sum = 0.0;
        let mut edge_strength = 0.0;

        // Simple quality analysis
        for i in (0..data_vec.len()).step_by(4) {
            let r = data_vec[i] as f64;
            let g = data_vec[i + 1] as f64;
            let b = data_vec[i + 2] as f64;

            // Calculate brightness (luminance)
            let luminance = 0.299 * r + 0.587 * g + 0.114 * b;
            brightness_sum += luminance;

            // Simple edge detection for blur estimation
            if i >= 4 {
                let prev_lum = 0.299 * data_vec[i - 4] as f64
                    + 0.587 * data_vec[i - 3] as f64
                    + 0.114 * data_vec[i - 2] as f64;
                edge_strength += (luminance - prev_lum).abs();
            }
        }

        let brightness = brightness_sum / pixel_count / 255.0;
        let contrast = contrast_sum / pixel_count;
        let sharpness = edge_strength / pixel_count;
        let is_blurry = sharpness < 10.0; // Threshold for blur detection

        FrameQuality {
            brightness,
            contrast,
            sharpness,
            is_blurry,
        }
    }

    // Enhanced frame capture with quality analysis
    pub fn capture_analyzed_frame(&mut self) -> Result<FrameData, JsValue> {
        let image_data = self.capture_frame_as_image_data()?;
        let quality = self.analyze_frame_quality(&image_data);

        let current_time = get_current_time_ms();
        self.frame_count += 1;

        // Update processing stats
        self.processing_stats.frames_processed += 1;
        if self.last_frame_time > 0.0 {
            let time_delta = current_time - self.last_frame_time;
            self.frame_rate_actual = 1000.0 / time_delta;
        }
        self.last_frame_time = current_time;

        // Quality score based on multiple factors
        let quality_score = (quality.sharpness / 50.0).min(1.0)
            * (1.0 - (quality.brightness - 0.5).abs() * 2.0).max(0.0);

        let frame_data = FrameData::new_with_analysis(
            self.config.width,
            self.config.height,
            current_time,
            "rgb".to_string(),
            self.frame_count,
            quality_score,
            quality.brightness,
            quality.contrast,
            quality.is_blurry,
        );

        // Buffer management
        if self.frame_buffer.len() >= self.max_buffer_size {
            self.frame_buffer.pop_front();
        }
        self.frame_buffer.push_back(image_data);

        self.processing_stats.buffer_utilization =
            self.frame_buffer.len() as f64 / self.max_buffer_size as f64;

        Ok(frame_data)
    }

    // Mobile-specific optimizations
    pub fn enable_mobile_optimizations(&mut self, enable: bool) {
        if enable {
            // Reduce buffer size for memory constraints
            self.max_buffer_size = 5;
            // Enable adaptive quality
            self.adaptive_quality_enabled = true;
            // Enable noise reduction for better image quality
            self.noise_reduction_enabled = true;
        } else {
            self.max_buffer_size = 10;
            self.adaptive_quality_enabled = false;
        }
    }

    pub fn set_adaptive_quality(&mut self, enable: bool) {
        self.adaptive_quality_enabled = enable;
    }

    pub fn adjust_quality_based_on_performance(&mut self) {
        if !self.adaptive_quality_enabled {
            return;
        }

        // If frame rate is too low, reduce quality
        if self.frame_rate_actual < self.config.frame_rate * 0.8 {
            if self.config.resolution != CameraResolution::Low {
                match self.config.resolution {
                    CameraResolution::UltraHigh => {
                        self.config.set_resolution(CameraResolution::High)
                    },
                    CameraResolution::High => self.config.set_resolution(CameraResolution::Medium),
                    CameraResolution::Medium => self.config.set_resolution(CameraResolution::Low),
                    _ => {},
                }
            }
        }
        // If frame rate is consistently high, try to increase quality
        else if self.frame_rate_actual > self.config.frame_rate * 1.2
            && self.config.resolution != CameraResolution::UltraHigh
        {
            match self.config.resolution {
                CameraResolution::Low => self.config.set_resolution(CameraResolution::Medium),
                CameraResolution::Medium => self.config.set_resolution(CameraResolution::High),
                CameraResolution::High => self.config.set_resolution(CameraResolution::UltraHigh),
                _ => {},
            }
        }
    }

    // Advanced camera controls
    pub fn set_exposure_compensation(&mut self, compensation: f64) -> Result<(), JsValue> {
        self.exposure_compensation = compensation.clamp(-2.0, 2.0);

        if let Some(stream) = &self.stream {
            let tracks = stream.get_video_tracks();
            if tracks.length() > 0 {
                if let Ok(track) = tracks.get(0).dyn_into::<VideoTrack>() {
                    let constraints = Object::new();
                    let advanced = Array::new();
                    let exposure_constraint = Object::new();
                    js_sys::Reflect::set(
                        &exposure_constraint,
                        &"exposureCompensation".into(),
                        &JsValue::from(compensation),
                    )?;
                    advanced.push(&exposure_constraint);
                    js_sys::Reflect::set(&constraints, &"advanced".into(), &advanced)?;
                    // Use Reflect to call applyConstraints
                    if let Ok(apply_fn) =
                        js_sys::Reflect::get(&track, &JsValue::from_str("applyConstraints"))
                    {
                        if let Ok(apply_fn) = apply_fn.dyn_into::<js_sys::Function>() {
                            let _ = apply_fn.call1(&track, &constraints);
                        }
                    }
                }
            }
        }

        Ok(())
    }

    pub fn set_white_balance_mode(&mut self, mode: String) -> Result<(), JsValue> {
        self.white_balance_mode = mode.clone();

        if let Some(stream) = &self.stream {
            let tracks = stream.get_video_tracks();
            if tracks.length() > 0 {
                if let Ok(track) = tracks.get(0).dyn_into::<VideoTrack>() {
                    let constraints = Object::new();
                    let advanced = Array::new();
                    let wb_constraint = Object::new();
                    js_sys::Reflect::set(
                        &wb_constraint,
                        &"whiteBalanceMode".into(),
                        &JsValue::from_str(&mode),
                    )?;
                    advanced.push(&wb_constraint);
                    js_sys::Reflect::set(&constraints, &"advanced".into(), &advanced)?;
                    // Use Reflect to call applyConstraints
                    if let Ok(apply_fn) =
                        js_sys::Reflect::get(&track, &JsValue::from_str("applyConstraints"))
                    {
                        if let Ok(apply_fn) = apply_fn.dyn_into::<js_sys::Function>() {
                            let _ = apply_fn.call1(&track, &constraints);
                        }
                    }
                }
            }
        }

        Ok(())
    }

    // Processing statistics
    #[wasm_bindgen(getter)]
    pub fn processing_stats(&self) -> ProcessingStats {
        self.processing_stats.clone()
    }

    pub fn reset_processing_stats(&mut self) {
        self.processing_stats = ProcessingStats {
            frames_processed: 0,
            frames_dropped: 0,
            average_processing_time: 0.0,
            average_frame_rate: 0.0,
            buffer_utilization: 0.0,
            ml_inference_time: 0.0,
        };
    }

    // Buffer management
    pub fn set_max_buffer_size(&mut self, size: usize) {
        self.max_buffer_size = size;
        while self.frame_buffer.len() > size {
            self.frame_buffer.pop_front();
        }
    }

    pub fn clear_frame_buffer(&mut self) {
        self.frame_buffer.clear();
    }

    pub fn get_buffered_frame_count(&self) -> usize {
        self.frame_buffer.len()
    }
}

// Utility functions
fn get_current_time() -> f64 {
    if let Some(window) = window() {
        if let Some(performance) = window.performance() {
            performance.now()
        } else {
            js_sys::Date::now()
        }
    } else {
        0.0
    }
}

// Factory functions for easy creation
#[wasm_bindgen]
pub async fn create_camera_manager() -> Result<CameraManager, JsValue> {
    let config = CameraConfig::default();
    let mut manager = CameraManager::new(config);
    manager.initialize().await?;
    Ok(manager)
}

#[wasm_bindgen]
pub async fn create_camera_manager_with_config(
    config: CameraConfig,
) -> Result<CameraManager, JsValue> {
    let mut manager = CameraManager::new(config);
    manager.initialize().await?;
    Ok(manager)
}

// Quick setup functions
#[wasm_bindgen]
pub async fn setup_front_camera() -> Result<CameraManager, JsValue> {
    let config = CameraConfig {
        facing: CameraFacing::User,
        ..Default::default()
    };
    create_camera_manager_with_config(config).await
}

#[wasm_bindgen]
pub async fn setup_back_camera() -> Result<CameraManager, JsValue> {
    let config = CameraConfig {
        facing: CameraFacing::Environment,
        ..Default::default()
    };
    create_camera_manager_with_config(config).await
}

#[wasm_bindgen]
pub async fn setup_hd_camera() -> Result<CameraManager, JsValue> {
    let config = CameraConfig {
        resolution: CameraResolution::High,
        ..Default::default()
    };
    create_camera_manager_with_config(config).await
}

// Camera capability detection utilities
#[wasm_bindgen]
pub async fn check_camera_support() -> Result<bool, JsValue> {
    let window = window().ok_or("No window object")?;
    let navigator = window.navigator();

    if let Ok(media_devices) = navigator.media_devices() {
        // Try to enumerate devices
        let devices_promise = media_devices.enumerate_devices()?;
        let devices_result = wasm_bindgen_futures::JsFuture::from(devices_promise).await?;
        let devices: Array = devices_result.dyn_into()?;

        for i in 0..devices.length() {
            if let Ok(device) = devices.get(i).dyn_into::<MediaDeviceInfo>() {
                if device.kind() == MediaDeviceKind::Videoinput {
                    return Ok(true);
                }
            }
        }
    }

    Ok(false)
}

#[wasm_bindgen]
pub async fn get_camera_count() -> Result<u32, JsValue> {
    let window = window().ok_or("No window object")?;
    let navigator = window.navigator();

    if let Ok(media_devices) = navigator.media_devices() {
        let devices_promise = media_devices.enumerate_devices()?;
        let devices_result = wasm_bindgen_futures::JsFuture::from(devices_promise).await?;
        let devices: Array = devices_result.dyn_into()?;

        let mut count = 0;
        for i in 0..devices.length() {
            if let Ok(device) = devices.get(i).dyn_into::<MediaDeviceInfo>() {
                if device.kind() == MediaDeviceKind::Videoinput {
                    count += 1;
                }
            }
        }
        Ok(count)
    } else {
        Ok(0)
    }
}

#[wasm_bindgen]
pub async fn get_available_cameras() -> Result<Array, JsValue> {
    let window = window().ok_or("No window object")?;
    let navigator = window.navigator();
    let array = Array::new();

    if let Ok(media_devices) = navigator.media_devices() {
        let devices_promise = media_devices.enumerate_devices()?;
        let devices_result = wasm_bindgen_futures::JsFuture::from(devices_promise).await?;
        let devices: Array = devices_result.dyn_into()?;

        for i in 0..devices.length() {
            if let Ok(device) = devices.get(i).dyn_into::<MediaDeviceInfo>() {
                if device.kind() == MediaDeviceKind::Videoinput {
                    let camera_info = Object::new();
                    js_sys::Reflect::set(
                        &camera_info,
                        &"deviceId".into(),
                        &JsValue::from_str(&device.device_id()),
                    )?;
                    js_sys::Reflect::set(
                        &camera_info,
                        &"label".into(),
                        &JsValue::from_str(&device.label()),
                    )?;
                    js_sys::Reflect::set(
                        &camera_info,
                        &"groupId".into(),
                        &JsValue::from_str(&device.group_id()),
                    )?;
                    array.push(&camera_info);
                }
            }
        }
    }

    Ok(array)
}

#[wasm_bindgen]
pub fn is_camera_permission_granted() -> bool {
    // Check if camera permission is granted using the Permissions API
    if let Some(window) = window() {
        let navigator = window.navigator();

        // Try to access navigator.permissions
        if let Ok(permissions) = js_sys::Reflect::get(&navigator, &"permissions".into()) {
            if !permissions.is_undefined() {
                // Check if we have camera permissions
                // Note: This is a synchronous check - for async permission checking,
                // you'd want to use a different function that returns a Promise

                // Try to detect if getUserMedia is available as a fallback
                if let Ok(get_user_media) = js_sys::Reflect::get(&navigator, &"getUserMedia".into())
                {
                    return !get_user_media.is_undefined();
                }

                if let Ok(media_devices) = js_sys::Reflect::get(&navigator, &"mediaDevices".into())
                {
                    if let Ok(get_user_media) =
                        js_sys::Reflect::get(&media_devices, &"getUserMedia".into())
                    {
                        return !get_user_media.is_undefined();
                    }
                }
            }
        }
    }
    false
}

// Image processing utilities for captured frames
#[wasm_bindgen]
pub fn convert_frame_to_tensor_data(frame_data: &ImageData) -> Result<Uint8Array, JsValue> {
    let data = frame_data.data();
    let array = Uint8Array::new_with_length(data.len() as u32);
    array.copy_from(&data);
    Ok(array)
}

#[wasm_bindgen]
pub fn resize_frame_data(
    frame_data: &ImageData,
    new_width: u32,
    new_height: u32,
) -> Result<ImageData, JsValue> {
    let window = window().ok_or("No window object")?;
    let document = window.document().ok_or("No document object")?;

    // Create temporary canvas for resizing
    let temp_canvas = document.create_element("canvas")?.dyn_into::<HtmlCanvasElement>()?;
    temp_canvas.set_width(new_width);
    temp_canvas.set_height(new_height);

    let context = temp_canvas
        .get_context("2d")?
        .ok_or("Failed to get 2D context")?
        .dyn_into::<CanvasRenderingContext2d>()?;

    // Put original image data on a temporary canvas
    let src_canvas = document.create_element("canvas")?.dyn_into::<HtmlCanvasElement>()?;
    src_canvas.set_width(frame_data.width());
    src_canvas.set_height(frame_data.height());

    let src_context = src_canvas
        .get_context("2d")?
        .ok_or("Failed to get 2D context")?
        .dyn_into::<CanvasRenderingContext2d>()?;

    src_context.put_image_data(frame_data, 0.0, 0.0)?;

    // Resize by drawing to the new canvas
    context.draw_image_with_html_canvas_element_and_dw_and_dh(
        &src_canvas,
        0.0,
        0.0,
        new_width as f64,
        new_height as f64,
    )?;

    // Get the resized image data
    context.get_image_data(0.0, 0.0, new_width as f64, new_height as f64)
}