forked from l1npengtul/nokhwa
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathjs_camera.rs
2725 lines (2481 loc) · 106 KB
/
js_camera.rs
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
/*
* Copyright 2022 l1npengtul <[email protected]> / The Nokhwa Contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
//! This contains all the code for using webcams in the browser.
//!
//! Anything starting with `js` is meant as a binding, a.k.a. not meant for consumption.
//!
//! This assumes that you are running a modern browser on the desktop.
use image::{buffer::ConvertBuffer, ImageBuffer, Rgb, RgbImage, Rgba};
#[cfg(feature = "output-wasm")]
use js_sys::{Array, JsString, Map, Object, Promise};
use nokhwa_core::{
error::NokhwaError,
types::{CameraIndex, CameraInfo, Resolution},
};
use std::{
borrow::{Borrow, Cow},
convert::TryFrom,
fmt::{Debug, Display, Formatter},
ops::Deref,
};
#[cfg(feature = "output-wasm")]
use wasm_bindgen::{prelude::wasm_bindgen, JsCast, JsValue};
#[cfg(feature = "output-wasm")]
use wasm_bindgen_futures::JsFuture;
#[cfg(feature = "output-wasm")]
use web_sys::{
console::log_1, CanvasRenderingContext2d, Document, Element, HtmlCanvasElement,
HtmlVideoElement, ImageData, MediaDeviceInfo, MediaDeviceKind, MediaDevices, MediaStream,
MediaStreamConstraints, MediaStreamTrack, MediaStreamTrackState, Navigator, Node, Window,
};
#[cfg(feature = "output-wgpu")]
use wgpu::{
Device, Extent3d, ImageCopyTexture, ImageDataLayout, Queue, Texture, TextureAspect,
TextureDescriptor, TextureDimension, TextureFormat, TextureUsages,
};
// why no code completion
// big sadger
// intellij 2021.2 review: i like structure window, 4 pengs / 5 pengs
macro_rules! jsv {
($value:expr) => {{
JsValue::from($value)
}};
}
macro_rules! obj {
($(($key:expr, $value:expr)),+ ) => {{
use js_sys::{Map, Object};
use wasm_bindgen::JsValue;
let map = Map::new();
$(
map.set(&jsv!($key), &jsv!($value));
)+
Object::from(map)
}};
($object:expr, $(($key:expr, $value:expr)),+ ) => {{
use js_sys::{Map, Object};
use wasm_bindgen::JsValue;
let map = Map::new();
$(
map.set(&jsv!($key), &jsv!($value));
)+
let o = Object::from(map);
Object::assign(&$object, &o)
}};
}
fn window() -> Result<Window, NokhwaError> {
match web_sys::window() {
Some(win) => Ok(win),
None => Err(NokhwaError::StructureError {
structure: "web_sys Window".to_string(),
error: "None".to_string(),
}),
}
}
fn media_devices(navigator: &Navigator) -> Result<MediaDevices, NokhwaError> {
match navigator.media_devices() {
Ok(media) => Ok(media),
Err(why) => Err(NokhwaError::StructureError {
structure: "MediaDevices".to_string(),
error: format!("{:?}", why),
}),
}
}
fn document(window: &Window) -> Result<Document, NokhwaError> {
match window.document() {
Some(doc) => Ok(doc),
None => Err(NokhwaError::StructureError {
structure: "web_sys Document".to_string(),
error: "None".to_string(),
}),
}
}
fn document_select_elem(doc: &Document, element: &str) -> Result<Element, NokhwaError> {
match doc.get_element_by_id(element) {
Some(elem) => Ok(elem),
None => {
return Err(NokhwaError::StructureError {
structure: format!("Document {}", element),
error: "None".to_string(),
})
}
}
}
fn element_cast<T: JsCast, U: JsCast>(from: T, name: &str) -> Result<U, NokhwaError> {
if !from.has_type::<U>() {
return Err(NokhwaError::StructureError {
structure: name.to_string(),
error: "Cannot Cast - No Subtype".to_string(),
});
}
let casted = match from.dyn_into::<U>() {
Ok(cast) => cast,
Err(_) => {
return Err(NokhwaError::StructureError {
structure: name.to_string(),
error: "Casting Error".to_string(),
});
}
};
Ok(casted)
}
fn element_cast_ref<'a, T: JsCast, U: JsCast>(
from: &'a T,
name: &'a str,
) -> Result<&'a U, NokhwaError> {
if !from.has_type::<U>() {
return Err(NokhwaError::StructureError {
structure: name.to_string(),
error: "Cannot Cast - No Subtype".to_string(),
});
}
match from.dyn_ref::<U>() {
Some(v_e) => Ok(v_e),
None => Err(NokhwaError::StructureError {
structure: name.to_string(),
error: "Cannot Cast".to_string(),
}),
}
}
fn create_element(doc: &Document, element: &str) -> Result<Element, NokhwaError> {
match Document::create_element(doc, element) {
// ???? thank you intellij
Ok(new_element) => Ok(new_element),
Err(why) => Err(NokhwaError::StructureError {
structure: "Document Video Element".to_string(),
error: format!("{:?}", why.as_string()),
}),
}
}
fn set_autoplay_inline(element: &Element) -> Result<(), NokhwaError> {
if let Err(why) = element.set_attribute("autoplay", "autoplay") {
return Err(NokhwaError::SetPropertyError {
property: "Video-autoplay".to_string(),
value: "autoplay".to_string(),
error: format!("{:?}", why),
});
}
if let Err(why) = element.set_attribute("playsinline", "playsinline") {
return Err(NokhwaError::SetPropertyError {
property: "Video-playsinline".to_string(),
value: "playsinline".to_string(),
error: format!("{:?}", why),
});
}
Ok(())
}
/// Requests Webcam permissions from the browser using [`MediaDevices::get_user_media()`](https://rustwasm.github.io/wasm-bindgen/api/web_sys/struct.MediaDevices.html#method.get_user_media) [MDN](https://developer.mozilla.org/en-US/docs/Web/API/MediaDevices/getUserMedia)
/// # Errors
/// This will error if there is no valid web context or the web API is not supported
pub async fn request_permission() -> Result<(), NokhwaError> {
let window: Window = window()?;
let navigator = window.navigator();
let media_devices = media_devices(&navigator)?;
match media_devices.get_user_media_with_constraints(
MediaStreamConstraints::new()
.video(&JsValue::from_bool(true))
.audio(&JsValue::from_bool(false)),
) {
Ok(promise) => {
let js_future = JsFuture::from(promise);
match js_future.await {
Ok(stream) => {
let media_stream = MediaStream::from(stream);
media_stream
.get_tracks()
.iter()
.for_each(|track| MediaStreamTrack::from(track).stop());
Ok(())
}
Err(why) => Err(NokhwaError::OpenStreamError(format!("{:?}", why))),
}
}
Err(why) => Err(NokhwaError::StructureError {
structure: "UserMediaPermission".to_string(),
error: format!("{:?}", why),
}),
}
}
/// Requests Webcam permissions from the browser using [`MediaDevices::get_user_media()`](https://rustwasm.github.io/wasm-bindgen/api/web_sys/struct.MediaDevices.html#method.get_user_media) [MDN](https://developer.mozilla.org/en-US/docs/Web/API/MediaDevices/getUserMedia)
/// # Errors
/// This will error if there is no valid web context or the web API is not supported
/// # JS-WASM
/// In exported JS bindings, the name of the function is `requestPermissions`. It may throw an exception.
#[cfg(feature = "output-wasm")]
#[cfg_attr(feature = "output-wasm", wasm_bindgen(js_name = requestPermissions))]
pub async fn js_request_permission() -> Result<(), JsValue> {
if let Err(why) = request_permission().await {
return Err(JsValue::from(why.to_string()));
}
Ok(())
}
/// Queries Cameras using [`MediaDevices::enumerate_devices()`](https://rustwasm.github.io/wasm-bindgen/api/web_sys/struct.MediaDevices.html#method.enumerate_devices) [MDN](https://developer.mozilla.org/en-US/docs/Web/API/MediaDevices/enumerateDevices)
/// # Errors
/// This will error if there is no valid web context or the web API is not supported
pub async fn query_js_cameras() -> Result<Vec<CameraInfo>, NokhwaError> {
let window: Window = window()?;
let navigator = window.navigator();
let media_devices = media_devices(&navigator)?;
match media_devices.enumerate_devices() {
Ok(prom) => {
let prom: Promise = prom;
let future = JsFuture::from(prom);
match future.await {
Ok(v) => {
let array: Array = Array::from(&v);
let mut device_list = vec![];
request_permission().await.unwrap_or(()); // swallow errors
for idx_device in 0_u32..array.length() {
if MediaDeviceInfo::instanceof(&array.get(idx_device)) {
let media_device_info =
MediaDeviceInfo::unchecked_from_js(array.get(idx_device));
if media_device_info.kind() == MediaDeviceKind::Videoinput {
match media_devices.get_user_media_with_constraints(
MediaStreamConstraints::new()
.audio(&jsv!(false))
.video(&jsv!(obj!((
"deviceId",
media_device_info.device_id()
)))),
) {
Ok(promised_stream) => {
let future_stream = JsFuture::from(promised_stream);
if let Ok(stream) = future_stream.await {
let stream = MediaStream::from(stream);
let tracks = stream.get_video_tracks();
let first = tracks.get(0);
let name = if first.is_undefined() {
format!(
"{:?}#{}",
media_device_info.kind(),
idx_device
)
} else {
MediaStreamTrack::from(first).label()
};
device_list.push(CameraInfo::new(
&name,
&format!("{:?}", media_device_info.kind()),
&format!(
"{} {}",
media_device_info.group_id(),
media_device_info.device_id()
),
CameraIndex::String(format!(
"{} {}",
media_device_info.group_id(),
media_device_info.device_id()
)),
));
tracks
.iter()
.for_each(|t| MediaStreamTrack::from(t).stop());
}
}
Err(_) => {
device_list.push(CameraInfo::new(
&format!(
"{:?}#{}",
media_device_info.kind(),
idx_device
),
&format!("{:?}", media_device_info.kind()),
&format!(
"{} {}",
media_device_info.group_id(),
media_device_info.device_id()
),
CameraIndex::String(format!(
"{} {}",
media_device_info.group_id(),
media_device_info.device_id()
)),
));
}
}
}
}
}
Ok(device_list)
}
Err(why) => Err(NokhwaError::StructureError {
structure: "EnumerateDevicesFuture".to_string(),
error: format!("{:?}", why),
}),
}
}
Err(why) => Err(NokhwaError::StructureError {
structure: "EnumerateDevices".to_string(),
error: format!("{:?}", why),
}),
}
}
/// Queries Cameras using [`MediaDevices::enumerate_devices()`](https://rustwasm.github.io/wasm-bindgen/api/web_sys/struct.MediaDevices.html#method.enumerate_devices) [MDN](https://developer.mozilla.org/en-US/docs/Web/API/MediaDevices/enumerateDevices)
/// # Errors
/// This will error if there is no valid web context or the web API is not supported
/// # JS-WASM
/// This is exported as `queryCameras`. It may throw an exception.
#[cfg(feature = "output-wasm")]
#[cfg_attr(feature = "output-wasm", wasm_bindgen(js_name = queryCameras))]
pub async fn js_query_js_cameras() -> Result<Array, JsValue> {
match query_js_cameras().await {
Ok(cameras) => Ok(cameras.into_iter().map(JsValue::from).collect()),
Err(why) => Err(JsValue::from(why.to_string())),
}
}
/// Queries the browser's supported constraints using [`navigator.mediaDevices.getSupportedConstraints()`](https://developer.mozilla.org/en-US/docs/Web/API/MediaDevices/getSupportedConstraints)
/// # Errors
/// This will error if there is no valid web context or the web API is not supported
pub fn query_supported_constraints() -> Result<Vec<JSCameraSupportedCapabilities>, NokhwaError> {
let window: Window = window()?;
let navigator = window.navigator();
let media_devices = media_devices(&navigator)?;
let supported_constraints = JsValue::from(media_devices.get_supported_constraints());
let dict_supported_constraints = Object::from(supported_constraints);
let mut capabilities_vec = vec![];
for constraint in Object::keys(&dict_supported_constraints).iter() {
let constraint_str = JsValue::from(JsString::from(constraint))
.as_string()
.unwrap_or_default();
// swallow errors
if let Ok(cap) = JSCameraSupportedCapabilities::try_from(constraint_str) {
capabilities_vec.push(cap);
}
}
Ok(capabilities_vec)
}
/// Queries the browser's supported constraints using [`navigator.mediaDevices.getSupportedConstraints()`](https://developer.mozilla.org/en-US/docs/Web/API/MediaDevices/getSupportedConstraints)
/// # Errors
/// This will error if there is no valid web context or the web API is not supported
/// # JS-WASM
/// This is exported as `queryConstraints` and returns an array of strings.
#[cfg_attr(feature = "output-wasm", wasm_bindgen(js_name = queryConstraints))]
pub fn query_supported_constraints_js() -> Result<Array, JsValue> {
match query_supported_constraints() {
Ok(constraints) => Ok(constraints
.into_iter()
.map(|c| JsValue::from(c.to_string()))
.collect()),
Err(why) => Err(JsValue::from(why.to_string())),
}
}
/// The enum describing the possible constraints for video in the browser.
/// - `DeviceID`: The ID of the device
/// - `GroupID`: The ID of the group that the device is in
/// - `AspectRatio`: The Aspect Ratio of the final stream
/// - `FacingMode`: What direction the camera is facing. This is more common on mobile. See [`JSCameraFacingMode`]
/// - `FrameRate`: The Frame Rate of the final stream
/// - `Height`: The height of the final stream in pixels
/// - `Width`: The width of the final stream in pixels
/// - `ResizeMode`: Whether the client can crop and/or scale the stream to match the resolution (width, height). See [`JSCameraResizeMode`]
/// See More: [`MediaTrackConstraints`](https://developer.mozilla.org/en-US/docs/Web/API/MediaTrackConstraints) [`Capabilities, constraints, and settings`](https://developer.mozilla.org/en-US/docs/Web/API/Media_Streams_API/Constraints)
/// # JS-WASM
/// This is exported as `CameraSupportedCapabilities`.
#[cfg_attr(feature = "output-wasm", wasm_bindgen(js_name = CameraSupportedCapabilities))]
#[derive(Copy, Clone, Hash, Ord, PartialOrd, Eq, PartialEq)]
pub enum JSCameraSupportedCapabilities {
DeviceID,
GroupID,
AspectRatio,
FacingMode,
FrameRate,
Height,
Width,
ResizeMode,
}
impl Display for JSCameraSupportedCapabilities {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
let cap = match self {
JSCameraSupportedCapabilities::DeviceID => "deviceId",
JSCameraSupportedCapabilities::GroupID => "groupId",
JSCameraSupportedCapabilities::AspectRatio => "aspectRatio",
JSCameraSupportedCapabilities::FacingMode => "facingMode",
JSCameraSupportedCapabilities::FrameRate => "frameRate",
JSCameraSupportedCapabilities::Height => "height",
JSCameraSupportedCapabilities::Width => "width",
JSCameraSupportedCapabilities::ResizeMode => "resizeMode",
};
write!(f, "{}", cap)
}
}
impl Debug for JSCameraSupportedCapabilities {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
let str = self.to_string();
write!(f, "{}", str)
}
}
impl TryFrom<String> for JSCameraSupportedCapabilities {
type Error = NokhwaError;
fn try_from(value: String) -> Result<Self, Self::Error> {
let value = value.as_str();
let result = match value {
"deviceId" => JSCameraSupportedCapabilities::DeviceID,
"groupId" => JSCameraSupportedCapabilities::GroupID,
"aspectRatio" => JSCameraSupportedCapabilities::AspectRatio,
"facingMode" => JSCameraSupportedCapabilities::FacingMode,
"frameRate" => JSCameraSupportedCapabilities::FrameRate,
"height" => JSCameraSupportedCapabilities::Height,
"width" => JSCameraSupportedCapabilities::Width,
"resizeMode" => JSCameraSupportedCapabilities::ResizeMode,
_ => {
return Err(NokhwaError::StructureError {
structure: "JSCameraSupportedCapabilities".to_string(),
error: "No Match Str".to_string(),
})
}
};
Ok(result)
}
}
/// The Facing Mode of the camera
/// - Any: Make no particular choice.
/// - Environment: The camera that shows the user's environment, such as the back camera of a smartphone
/// - User: The camera that shows the user, such as the front camera of a smartphone
/// - Left: The camera that shows the user but to their left, such as a camera that shows a user but to their left shoulder
/// - Right: The camera that shows the user but to their right, such as a camera that shows a user but to their right shoulder
/// See More: [`facingMode`](https://developer.mozilla.org/en-US/docs/Web/API/MediaTrackConstraints/facingMode)
/// # JS-WASM
/// This is exported as `CameraFacingMode`.
#[cfg_attr(feature = "output-wasm", wasm_bindgen(js_name = CameraFacingMode))]
#[derive(Copy, Clone, Hash, Ord, PartialOrd, Eq, PartialEq)]
pub enum JSCameraFacingMode {
Any,
Environment,
User,
Left,
Right,
}
impl Display for JSCameraFacingMode {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
let cap = match self {
JSCameraFacingMode::Environment => "environment",
JSCameraFacingMode::User => "user",
JSCameraFacingMode::Left => "left",
JSCameraFacingMode::Right => "right",
JSCameraFacingMode::Any => "any",
};
write!(f, "{}", cap)
}
}
impl Debug for JSCameraFacingMode {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
let str = self.to_string();
write!(f, "{}", str)
}
}
/// Whether the browser can crop and/or scale to match the requested resolution.
/// - `Any`: Make no particular choice.
/// - `None`: Do not crop and/or scale.
/// - `CropAndScale`: Crop and/or scale to match the requested resolution.
/// See More: [`resizeMode`](https://developer.mozilla.org/en-US/docs/Web/API/MediaTrackConstraints#resizemode)
/// # JS-WASM
/// This is exported as `CameraResizeMode`.
#[cfg_attr(feature = "output-wasm", wasm_bindgen(js_name = CameraResizeMode))]
#[derive(Copy, Clone, Hash, Ord, PartialOrd, Eq, PartialEq)]
pub enum JSCameraResizeMode {
Any,
None,
CropAndScale,
}
impl Display for JSCameraResizeMode {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
let cap = match self {
JSCameraResizeMode::None => "none",
JSCameraResizeMode::CropAndScale => "crop-and-scale",
JSCameraResizeMode::Any => "",
};
write!(f, "{}", cap)
}
}
impl Debug for JSCameraResizeMode {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
let str = self.to_string();
write!(f, "{}", str)
}
}
/// A builder that builds a [`JSCameraConstraints`] that is used to construct a [`JSCamera`].
/// See More: [`Constraints MDN`](https://developer.mozilla.org/en-US/docs/Web/API/Media_Streams_API/Constraints), [`Properties of Media Tracks MDN`](https://developer.mozilla.org/en-US/docs/Web/API/MediaTrackConstraints)
/// # JS-WASM
/// This is exported as `CameraConstraintsBuilder`.
#[cfg_attr(feature = "output-wasm", wasm_bindgen(js_name = CameraConstraintsBuilder))]
#[derive(Clone, Debug)]
#[allow(clippy::struct_excessive_bools)]
pub struct JSCameraConstraintsBuilder {
pub(crate) min_resolution: Option<Resolution>,
pub(crate) preferred_resolution: Resolution,
pub(crate) max_resolution: Option<Resolution>,
pub(crate) resolution_exact: bool,
pub(crate) min_aspect_ratio: Option<f64>,
pub(crate) aspect_ratio: f64,
pub(crate) max_aspect_ratio: Option<f64>,
pub(crate) aspect_ratio_exact: bool,
pub(crate) facing_mode: JSCameraFacingMode,
pub(crate) facing_mode_exact: bool,
pub(crate) min_frame_rate: Option<u32>,
pub(crate) frame_rate: u32,
pub(crate) max_frame_rate: Option<u32>,
pub(crate) frame_rate_exact: bool,
pub(crate) resize_mode: JSCameraResizeMode,
pub(crate) resize_mode_exact: bool,
pub(crate) device_id: String,
pub(crate) device_id_exact: bool,
pub(crate) group_id: String,
pub(crate) group_id_exact: bool,
}
#[cfg_attr(feature = "output-wasm", wasm_bindgen(js_class = CameraConstraintsBuilder))]
impl JSCameraConstraintsBuilder {
/// Constructs a default [`JSCameraConstraintsBuilder`].
/// The constructed default [`JSCameraConstraintsBuilder`] has these settings:
/// - 480x234 min, 640x360 ideal, 1920x1080 max
/// - 10 FPS min, 15 FPS ideal, 30 FPS max
/// - 1.0 aspect ratio min, 1.77777777778 aspect ratio ideal, 2.0 aspect ratio max
/// - No `exact`s
/// # JS-WASM
/// This is exported as a constructor.
#[must_use]
#[cfg_attr(feature = "output-wasm", wasm_bindgen(constructor))]
pub fn new() -> Self {
JSCameraConstraintsBuilder::default()
}
/// Sets the minimum resolution for the [`JSCameraConstraintsBuilder`].
///
/// Sets [`width`](https://developer.mozilla.org/en-US/docs/Web/API/MediaTrackConstraints/width) and [`height`](https://developer.mozilla.org/en-US/docs/Web/API/MediaTrackConstraints/height).
/// # JS-WASM
/// This is exported as `set_MinResolution`.
#[must_use]
#[cfg_attr(
feature = "output-wasm",
wasm_bindgen(js_name = MinResolution)
)]
pub fn min_resolution(mut self, min_resolution: Resolution) -> JSCameraConstraintsBuilder {
self.min_resolution = Some(min_resolution);
self
}
/// Sets the preferred resolution for the [`JSCameraConstraintsBuilder`].
///
/// Sets [`width`](https://developer.mozilla.org/en-US/docs/Web/API/MediaTrackConstraints/width) and [`height`](https://developer.mozilla.org/en-US/docs/Web/API/MediaTrackConstraints/height).
/// # JS-WASM
/// This is exported as `set_Resolution`.
#[must_use]
#[cfg_attr(
feature = "output-wasm",
wasm_bindgen(js_name = Resolution)
)]
pub fn resolution(mut self, new_resolution: Resolution) -> JSCameraConstraintsBuilder {
self.preferred_resolution = new_resolution;
self
}
/// Sets the maximum resolution for the [`JSCameraConstraintsBuilder`].
///
/// Sets [`width`](https://developer.mozilla.org/en-US/docs/Web/API/MediaTrackConstraints/width) and [`height`](https://developer.mozilla.org/en-US/docs/Web/API/MediaTrackConstraints/height).
/// # JS-WASM
/// This is exported as `set_MaxResolution`.
#[must_use]
#[cfg_attr(
feature = "output-wasm",
wasm_bindgen(js_name = MaxResolution)
)]
pub fn max_resolution(mut self, max_resolution: Resolution) -> JSCameraConstraintsBuilder {
self.min_resolution = Some(max_resolution);
self
}
/// Sets whether the resolution fields ([`width`](https://developer.mozilla.org/en-US/docs/Web/API/MediaTrackConstraints/width), [`height`](https://developer.mozilla.org/en-US/docs/Web/API/MediaTrackConstraints/height)/[`resolution`](crate::js_camera::JSCameraConstraintsBuilder::resolution))
/// should use [`exact`](https://developer.mozilla.org/en-US/docs/Web/API/MediaTrackConstraints#constraints).
/// Note that this will make the builder ignore [`min_resolution`](crate::js_camera::JSCameraConstraintsBuilder::min_resolution) and [`max_resolution`](crate::js_camera::JSCameraConstraintsBuilder::max_resolution).
/// # JS-WASM
/// This is exported as `set_ResolutionExact`.
#[must_use]
#[cfg_attr(
feature = "output-wasm",
wasm_bindgen(js_name = ResolutionExact)
)]
pub fn resolution_exact(mut self, value: bool) -> JSCameraConstraintsBuilder {
self.resolution_exact = value;
self
}
/// Sets the minimum aspect ratio of the resulting constraint for the [`JSCameraConstraintsBuilder`].
///
/// Sets [`aspectRatio`](https://developer.mozilla.org/en-US/docs/Web/API/MediaTrackConstraints/aspectRatio).
/// # JS-WASM
/// This is exported as `set_MinAspectRatio`.
#[must_use]
#[cfg_attr(
feature = "output-wasm",
wasm_bindgen(js_name = MinAspectRatio)
)]
pub fn min_aspect_ratio(mut self, ratio: f64) -> JSCameraConstraintsBuilder {
self.min_aspect_ratio = Some(ratio);
self
}
/// Sets the aspect ratio of the resulting constraint for the [`JSCameraConstraintsBuilder`].
///
/// Sets [`aspectRatio`](https://developer.mozilla.org/en-US/docs/Web/API/MediaTrackConstraints/aspectRatio).
/// # JS-WASM
/// This is exported as `set_AspectRatio`.
#[must_use]
#[cfg_attr(
feature = "output-wasm",
wasm_bindgen(js_name = AspectRatio)
)]
pub fn aspect_ratio(mut self, ratio: f64) -> JSCameraConstraintsBuilder {
self.aspect_ratio = ratio;
self
}
/// Sets the maximum aspect ratio of the resulting constraint for the [`JSCameraConstraintsBuilder`].
///
/// Sets [`aspectRatio`](https://developer.mozilla.org/en-US/docs/Web/API/MediaTrackConstraints/aspectRatio).
/// # JS-WASM
/// This is exported as `set_MaxAspectRatio`.
#[must_use]
#[cfg_attr(
feature = "output-wasm",
wasm_bindgen(js_name = MaxAspectRatio)
)]
pub fn max_aspect_ratio(mut self, ratio: f64) -> JSCameraConstraintsBuilder {
self.max_aspect_ratio = Some(ratio);
self
}
/// Sets whether the [`aspect_ratio`](crate::js_camera::JSCameraConstraintsBuilder::aspect_ratio) field should use [`exact`](https://developer.mozilla.org/en-US/docs/Web/API/MediaTrackConstraints#constraints).
/// Note that this will make the builder ignore [`min_aspect_ratio`](crate::js_camera::JSCameraConstraintsBuilder::min_aspect_ratio) and [`max_aspect_ratio`](crate::js_camera::JSCameraConstraintsBuilder::max_aspect_ratio).
/// # JS-WASM
/// This is exported as `set_AspectRatioExact`.
#[must_use]
#[cfg_attr(
feature = "output-wasm",
wasm_bindgen(js_name = AspectRatioExact)
)]
pub fn aspect_ratio_exact(mut self, value: bool) -> JSCameraConstraintsBuilder {
self.aspect_ratio_exact = value;
self
}
/// Sets the facing mode of the resulting constraint for the [`JSCameraConstraintsBuilder`].
///
/// Sets [`facingMode`](https://developer.mozilla.org/en-US/docs/Web/API/MediaTrackConstraints/facingMode).
/// # JS-WASM
/// This is exported as `set_FacingMode`.
#[must_use]
#[cfg_attr(
feature = "output-wasm",
wasm_bindgen(js_name = FacingMode)
)]
pub fn facing_mode(mut self, facing_mode: JSCameraFacingMode) -> JSCameraConstraintsBuilder {
self.facing_mode = facing_mode;
self
}
/// Sets whether the [`facing_mode`](crate::js_camera::JSCameraConstraintsBuilder::facing_mode) field should use [`exact`](https://developer.mozilla.org/en-US/docs/Web/API/MediaTrackConstraints#constraints).
/// # JS-WASM
/// This is exported as `set_FacingModeExact`.
#[must_use]
#[cfg_attr(
feature = "output-wasm",
wasm_bindgen(js_name = FacingModeExact)
)]
pub fn facing_mode_exact(mut self, value: bool) -> JSCameraConstraintsBuilder {
self.facing_mode_exact = value;
self
}
/// Sets the minimum frame rate of the resulting constraint for the [`JSCameraConstraintsBuilder`].
///
/// Sets [`frameRate`](https://developer.mozilla.org/en-US/docs/Web/API/MediaTrackConstraints/frameRate).
/// # JS-WASM
/// This is exported as `set_MinFrameRate`.
#[must_use]
#[cfg_attr(
feature = "output-wasm",
wasm_bindgen(js_name = MinFrameRate)
)]
pub fn min_frame_rate(mut self, fps: u32) -> JSCameraConstraintsBuilder {
self.min_frame_rate = Some(fps);
self
}
/// Sets the frame rate of the resulting constraint for the [`JSCameraConstraintsBuilder`].
///
/// Sets [`frameRate`](https://developer.mozilla.org/en-US/docs/Web/API/MediaTrackConstraints/frameRate).
/// # JS-WASM
/// This is exported as `set_FrameRate`.
#[must_use]
#[cfg_attr(
feature = "output-wasm",
wasm_bindgen(js_name = FrameRate)
)]
pub fn frame_rate(mut self, fps: u32) -> JSCameraConstraintsBuilder {
self.frame_rate = fps;
self
}
/// Sets the maximum frame rate of the resulting constraint for the [`JSCameraConstraintsBuilder`].
///
/// Sets [`frameRate`](https://developer.mozilla.org/en-US/docs/Web/API/MediaTrackConstraints/frameRate).
/// # JS-WASM
/// This is exported as `set_MaxFrameRate`.
#[must_use]
#[cfg_attr(
feature = "output-wasm",
wasm_bindgen(js_name = MaxFrameRate)
)]
pub fn max_frame_rate(mut self, fps: u32) -> JSCameraConstraintsBuilder {
self.max_frame_rate = Some(fps);
self
}
/// Sets whether the [`frame_rate`](crate::js_camera::JSCameraConstraintsBuilder::frame_rate) field should use [`exact`](https://developer.mozilla.org/en-US/docs/Web/API/MediaTrackConstraints#constraints).
/// Note that this will make the builder ignore [`min_frame_rate`](crate::js_camera::JSCameraConstraintsBuilder::min_frame_rate) and [`max_frame_rate`](crate::js_camera::JSCameraConstraintsBuilder::max_frame_rate).
/// # JS-WASM
/// This is exported as `set_FrameRateExact`.
#[must_use]
#[cfg_attr(
feature = "output-wasm",
wasm_bindgen(js_name = FrameRateExact)
)]
pub fn frame_rate_exact(mut self, value: bool) -> JSCameraConstraintsBuilder {
self.frame_rate_exact = value;
self
}
/// Sets the resize mode of the resulting constraint for the [`JSCameraConstraintsBuilder`].
///
/// Sets [`resizeMode`](https://developer.mozilla.org/en-US/docs/Web/API/MediaTrackConstraints#resizemode).
/// # JS-WASM
/// This is exported as `set_ResizeMode`.
#[must_use]
#[cfg_attr(
feature = "output-wasm",
wasm_bindgen(js_name = ResizeMode)
)]
pub fn resize_mode(mut self, resize_mode: JSCameraResizeMode) -> JSCameraConstraintsBuilder {
self.resize_mode = resize_mode;
self
}
/// Sets whether the [`resize_mode`](crate::js_camera::JSCameraConstraintsBuilder::resize_mode) field should use [`exact`](https://developer.mozilla.org/en-US/docs/Web/API/MediaTrackConstraints#constraints).
/// # JS-WASM
/// This is exported as `set_ResizeModeExact`.
#[must_use]
#[cfg_attr(
feature = "output-wasm",
wasm_bindgen(js_name = ResizeModeExact)
)]
pub fn resize_mode_exact(mut self, value: bool) -> JSCameraConstraintsBuilder {
self.resize_mode_exact = value;
self
}
/// Sets the device ID of the resulting constraint for the [`JSCameraConstraintsBuilder`].
///
/// Sets [`deviceId`](https://developer.mozilla.org/en-US/docs/Web/API/MediaTrackConstraints/deviceId).
/// # JS-WASM
/// This is exported as `set_DeviceId`.
#[must_use]
#[cfg_attr(
feature = "output-wasm",
wasm_bindgen(js_name = DeviceId)
)]
pub fn device_id(mut self, id: &str) -> JSCameraConstraintsBuilder {
self.device_id = id.to_string();
self
}
/// Sets whether the [`device_id`](crate::js_camera::JSCameraConstraintsBuilder::device_id) field should use [`exact`](https://developer.mozilla.org/en-US/docs/Web/API/MediaTrackConstraints#constraints).
/// # JS-WASM
/// This is exported as `set_DeviceIdExact`.
#[must_use]
#[cfg_attr(
feature = "output-wasm",
wasm_bindgen(js_name = DeviceIdExact)
)]
pub fn device_id_exact(mut self, value: bool) -> JSCameraConstraintsBuilder {
self.device_id_exact = value;
self
}
/// Sets the group ID of the resulting constraint for the [`JSCameraConstraintsBuilder`].
///
/// Sets [`groupId`](https://developer.mozilla.org/en-US/docs/Web/API/MediaTrackConstraints/groupId).
/// # JS-WASM
/// This is exported as `set_GroupId`.
#[must_use]
#[cfg_attr(feature = "output-wasm", wasm_bindgen(js_name = GroupId))]
pub fn group_id(mut self, id: &str) -> JSCameraConstraintsBuilder {
self.group_id = id.to_string();
self
}
/// Sets whether the [`group_id`](crate::js_camera::JSCameraConstraintsBuilder::group_id) field should use [`exact`](https://developer.mozilla.org/en-US/docs/Web/API/MediaTrackConstraints#constraints).
/// # JS-WASM
/// This is exported as `set_GroupIdExact`.
#[must_use]
#[cfg_attr(
feature = "output-wasm",
wasm_bindgen(js_name = GroupIdExact)
)]
pub fn group_id_exact(mut self, value: bool) -> JSCameraConstraintsBuilder {
self.group_id_exact = value;
self
}
/// Builds the [`JSCameraConstraints`]. Wrapper for [`build`](crate::js_camera::JSCameraConstraintsBuilder::build)
///
/// Fields that use exact are marked `exact`, otherwise are marked with `ideal`. If min-max are involved, they will use `min` and `max` accordingly.
/// # JS-WASM
/// This is exported as `buildCameraConstraints`.
#[cfg(feature = "output-wasm")]
#[cfg_attr(
feature = "output-wasm",
wasm_bindgen(js_name = buildCameraConstraints)
)]
#[must_use]
pub fn js_build(self) -> JSCameraConstraints {
self.build()
}
}
impl JSCameraConstraintsBuilder {
/// Builds the [`JSCameraConstraints`]
#[allow(clippy::too_many_lines)]
#[must_use]
pub fn build(self) -> JSCameraConstraints {
let null_resolution = Resolution::default();
let null_string = String::new();
let mut video_object = Object::new();
// width
if self.resolution_exact {
if self.preferred_resolution != null_resolution {
video_object = obj!(
video_object,
("width", obj!(("exact", self.preferred_resolution.width())))
);
}
} else {
let mut width_object = Object::new();
if let Some(min_res) = self.min_resolution {
width_object = obj!(width_object, ("min", min_res.width()));
}
width_object = obj!(width_object, ("ideal", self.preferred_resolution.width()));
if let Some(max_res) = self.max_resolution {
width_object = obj!(width_object, ("max", max_res.width()));
}
video_object = obj!(video_object, ("width", width_object));
}
// height
if self.resolution_exact {
if self.preferred_resolution != null_resolution {
video_object = obj!(
video_object,
(
"height",
obj!(("exact", self.preferred_resolution.height()))
)
);
}
} else {
let mut height_object = Object::new();
if let Some(min_res) = self.min_resolution {
height_object = obj!(height_object, ("min", min_res.height()));
}
height_object = obj!(height_object, ("ideal", self.preferred_resolution.height()));
if let Some(max_res) = self.max_resolution {
height_object = obj!(height_object, ("max", max_res.height()));
}
video_object = obj!(video_object, ("height", height_object));
}
// aspect ratio
if self.aspect_ratio_exact {
if self.aspect_ratio != 0_f64 {
video_object = obj!(
video_object,
("aspectRatio", obj!(("exact", self.aspect_ratio)))
);
}
} else {
let mut aspect_ratio_object = Object::new();
if let Some(min_ratio) = self.min_aspect_ratio {
aspect_ratio_object = obj!(aspect_ratio_object, ("min", min_ratio));
}
aspect_ratio_object = obj!(aspect_ratio_object, ("ideal", self.aspect_ratio));
if let Some(max_ratio) = self.max_aspect_ratio {
aspect_ratio_object = obj!(aspect_ratio_object, ("max", max_ratio));
}
video_object = obj!(video_object, ("aspectRatio", aspect_ratio_object));
}
if self.facing_mode != JSCameraFacingMode::Any && self.facing_mode_exact {
video_object = obj!(
video_object,
("facingMode", obj!(("exact", self.facing_mode.to_string())))
);
} else if self.facing_mode != JSCameraFacingMode::Any {
video_object = obj!(
video_object,
("facingMode", obj!(("ideal", self.facing_mode.to_string())))
);
}
// aspect ratio
if self.frame_rate_exact {
if self.frame_rate != 0 {
video_object = obj!(