leptos_use/
use_user_media.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
use crate::core::MaybeRwSignal;
use default_struct_builder::DefaultBuilder;
use js_sys::{Object, Reflect};
use leptos::*;
use wasm_bindgen::{JsCast, JsValue};

/// Reactive [`mediaDevices.getUserMedia`](https://developer.mozilla.org/en-US/docs/Web/API/MediaDevices/getUserMedia) streaming.
///
/// ## Demo
///
/// [Link to Demo](https://github.com/Synphonyte/leptos-use/tree/main/examples/use_user_media)
///
/// ## Usage
///
/// ```
/// # use leptos::*;
/// # use leptos_use::{use_user_media, UseUserMediaReturn};
/// #
/// # #[component]
/// # fn Demo() -> impl IntoView {
/// let video_ref = create_node_ref::<leptos::html::Video>();
///
/// let UseUserMediaReturn { stream, start, .. } = use_user_media();
///
/// start();
///
/// create_effect(move |_|
///     video_ref.get().map(|v| {
///         match stream.get() {
///             Some(Ok(s)) => v.set_src_object(Some(&s)),
///             Some(Err(e)) => logging::error!("Failed to get media stream: {:?}", e),
///             None => logging::log!("No stream yet"),
///         }
///     })
/// );
///
/// view! { <video node_ref=video_ref controls=false autoplay=true muted=true></video> }
/// # }
/// ```
///
/// ## Server-Side Rendering
///
/// On the server calls to `start` or any other way to enable the stream will be ignored
/// and the stream will always be `None`.
pub fn use_user_media() -> UseUserMediaReturn<impl Fn() + Clone, impl Fn() + Clone> {
    use_user_media_with_options(UseUserMediaOptions::default())
}

/// Version of [`use_user_media`] that takes a `UseUserMediaOptions`. See [`use_user_media`] for how to use.
pub fn use_user_media_with_options(
    options: UseUserMediaOptions,
) -> UseUserMediaReturn<impl Fn() + Clone, impl Fn() + Clone> {
    let UseUserMediaOptions {
        enabled,
        video,
        audio,
        ..
    } = options;

    let (enabled, set_enabled) = enabled.into_signal();

    let (stream, set_stream) = create_signal(None::<Result<web_sys::MediaStream, JsValue>>);

    let _start = {
        let audio = audio.clone();
        let video = video.clone();

        move || async move {
            #[cfg(not(feature = "ssr"))]
            {
                if stream.get_untracked().is_some() {
                    return;
                }

                let stream = create_media(Some(video), Some(audio)).await;

                set_stream.update(|s| *s = Some(stream));
            }

            #[cfg(feature = "ssr")]
            {
                let _ = video;
                let _ = audio;
            }
        }
    };

    let _stop = move || {
        if let Some(Ok(stream)) = stream.get_untracked() {
            for track in stream.get_tracks() {
                track.unchecked_ref::<web_sys::MediaStreamTrack>().stop();
            }
        }

        set_stream.set(None);
    };

    let start = {
        let _start = _start.clone();
        move || {
            #[cfg(not(feature = "ssr"))]
            {
                spawn_local({
                    let _start = _start.clone();
                    async move {
                        _start().await;
                        stream.with_untracked(move |stream| {
                            if let Some(Ok(_)) = stream {
                                set_enabled.set(true);
                            }
                        });
                    }
                });
            }
        }
    };

    let stop = move || {
        _stop();
        set_enabled.set(false);
    };

    let _ = {
        watch(
            move || enabled.get(),
            move |enabled, _, _| {
                if *enabled {
                    spawn_local({
                        let _start = _start.clone();
                        async move {
                            _start().await;
                        }
                    });
                } else {
                    _stop();
                }
            },
            true,
        )
    };
    UseUserMediaReturn {
        stream: stream.into(),
        start,
        stop,
        enabled,
        set_enabled,
    }
}

#[cfg(not(feature = "ssr"))]
async fn create_media(
    video: Option<VideoConstraints>,
    audio: Option<AudioConstraints>,
) -> Result<web_sys::MediaStream, JsValue> {
    use crate::js_fut;
    use crate::use_window::use_window;
    use js_sys::Array;

    let media = use_window()
        .navigator()
        .ok_or_else(|| JsValue::from_str("Failed to access window.navigator"))
        .and_then(|n| n.media_devices())?;

    let constraints = web_sys::MediaStreamConstraints::new();
    if let Some(video_shadow_constraints) = video {
        match video_shadow_constraints {
            VideoConstraints::Bool(b) => constraints.set_video(&JsValue::from(b)),
            VideoConstraints::Constraints(boxed_constraints) => {
                let VideoTrackConstraints {
                    device_id,
                    facing_mode,
                    frame_rate,
                    height,
                    width,
                    viewport_height,
                    viewport_width,
                    viewport_offset_x,
                    viewport_offset_y,
                } = *boxed_constraints;

                let video_constraints = web_sys::MediaTrackConstraints::new();

                if !device_id.is_empty() {
                    video_constraints.set_device_id(
                        &Array::from_iter(device_id.into_iter().map(JsValue::from)).into(),
                    );
                }

                if let Some(value) = facing_mode {
                    video_constraints.set_facing_mode(&value.to_jsvalue());
                }

                if let Some(value) = frame_rate {
                    video_constraints.set_frame_rate(&value.to_jsvalue());
                }

                if let Some(value) = height {
                    video_constraints.set_height(&value.to_jsvalue());
                }

                if let Some(value) = width {
                    video_constraints.set_width(&value.to_jsvalue());
                }

                if let Some(value) = viewport_height {
                    video_constraints.set_viewport_height(&value.to_jsvalue());
                }

                if let Some(value) = viewport_width {
                    video_constraints.set_viewport_width(&value.to_jsvalue());
                }
                if let Some(value) = viewport_offset_x {
                    video_constraints.set_viewport_offset_x(&value.to_jsvalue());
                }

                if let Some(value) = viewport_offset_y {
                    video_constraints.set_viewport_offset_y(&value.to_jsvalue());
                }

                constraints.set_video(&JsValue::from(video_constraints));
            }
        }
    }
    if let Some(audio_shadow_constraints) = audio {
        match audio_shadow_constraints {
            AudioConstraints::Bool(b) => constraints.set_audio(&JsValue::from(b)),
            AudioConstraints::Constraints(boxed_constraints) => {
                let AudioTrackConstraints {
                    device_id,
                    auto_gain_control,
                    channel_count,
                    echo_cancellation,
                    noise_suppression,
                } = *boxed_constraints;

                let audio_constraints = web_sys::MediaTrackConstraints::new();

                if !device_id.is_empty() {
                    audio_constraints.set_device_id(
                        &Array::from_iter(device_id.into_iter().map(JsValue::from)).into(),
                    );
                }
                if let Some(value) = auto_gain_control {
                    audio_constraints.set_auto_gain_control(&JsValue::from(&value.to_jsvalue()));
                }
                if let Some(value) = channel_count {
                    audio_constraints.set_channel_count(&JsValue::from(&value.to_jsvalue()));
                }
                if let Some(value) = echo_cancellation {
                    audio_constraints.set_echo_cancellation(&JsValue::from(&value.to_jsvalue()));
                }
                if let Some(value) = noise_suppression {
                    audio_constraints.set_noise_suppression(&JsValue::from(&value.to_jsvalue()));
                }

                constraints.set_audio(&JsValue::from(audio_constraints));
            }
        }
    }

    let promise = media.get_user_media_with_constraints(&constraints)?;
    let res = js_fut!(promise).await?;

    Ok::<_, JsValue>(web_sys::MediaStream::unchecked_from_js(res))
}

/// Options for [`use_user_media_with_options`].
///
/// Either or both constraints must be specified.
/// If the browser cannot find all media tracks with the specified types that meet the constraints given,
/// then the returned promise is rejected with `NotFoundError`
#[derive(DefaultBuilder, Clone, Debug)]
pub struct UseUserMediaOptions {
    /// If the stream is enabled. Defaults to `false`.
    enabled: MaybeRwSignal<bool>,
    /// Constraint parameter describing video media type requested
    /// The default value is `true`.
    #[builder(into)]
    video: VideoConstraints,
    /// Constraint parameter describing audio media type requested
    /// The default value is `false`.
    #[builder(into)]
    audio: AudioConstraints,
}

impl Default for UseUserMediaOptions {
    fn default() -> Self {
        Self {
            enabled: false.into(),
            video: true.into(),
            audio: false.into(),
        }
    }
}

/// Return type of [`use_user_media`].
#[derive(Clone)]
pub struct UseUserMediaReturn<StartFn, StopFn>
where
    StartFn: Fn() + Clone,
    StopFn: Fn() + Clone,
{
    /// The current [`MediaStream`](https://developer.mozilla.org/en-US/docs/Web/API/MediaStream) if it exists.
    /// Initially this is `None` until `start` resolved successfully.
    /// In case the stream couldn't be started, for example because the user didn't grant permission,
    /// this has the value `Some(Err(...))`.
    pub stream: Signal<Option<Result<web_sys::MediaStream, JsValue>>>,

    /// Starts the screen streaming. Triggers the ask for permission if not already granted.
    pub start: StartFn,

    /// Stops the screen streaming
    pub stop: StopFn,

    /// A value of `true` indicates that the returned [`MediaStream`](https://developer.mozilla.org/en-US/docs/Web/API/MediaStream)
    /// has resolved successfully and thus the stream is enabled.
    pub enabled: Signal<bool>,

    /// A value of `true` is the same as calling `start()` whereas `false` is the same as calling `stop()`.
    pub set_enabled: WriteSignal<bool>,
}

#[derive(Clone, Debug)]
pub enum ConstraintExactIdeal<T> {
    Single(Option<T>),
    ExactIdeal { exact: Option<T>, ideal: Option<T> },
}

impl<T> Default for ConstraintExactIdeal<T>
where
    T: Default,
{
    fn default() -> Self {
        ConstraintExactIdeal::Single(Some(T::default()))
    }
}

impl<T> ConstraintExactIdeal<T> {
    pub fn exact(mut self, value: T) -> Self {
        if let ConstraintExactIdeal::ExactIdeal {
            exact: ref mut e, ..
        } = &mut self
        {
            *e = Some(value);
        }

        self
    }

    pub fn ideal(mut self, value: T) -> Self {
        if let ConstraintExactIdeal::ExactIdeal {
            ideal: ref mut i, ..
        } = &mut self
        {
            *i = Some(value);
        }

        self
    }
}

impl<T> ConstraintExactIdeal<T>
where
    T: Into<JsValue> + Clone,
{
    pub fn to_jsvalue(&self) -> JsValue {
        match self {
            ConstraintExactIdeal::Single(value) => value.clone().unwrap().into(),
            ConstraintExactIdeal::ExactIdeal { exact, ideal } => {
                let obj = Object::new();

                if let Some(value) = exact {
                    Reflect::set(&obj, &JsValue::from_str("exact"), &value.clone().into()).unwrap();
                }
                if let Some(value) = ideal {
                    Reflect::set(&obj, &JsValue::from_str("ideal"), &value.clone().into()).unwrap();
                }

                JsValue::from(obj)
            }
        }
    }
}

impl From<&'static str> for ConstraintExactIdeal<&'static str> {
    fn from(value: &'static str) -> Self {
        ConstraintExactIdeal::Single(Some(value))
    }
}

#[derive(Clone, Debug)]
pub enum ConstraintRange<T> {
    Single(Option<T>),
    Range {
        min: Option<T>,
        max: Option<T>,
        exact: Option<T>,
        ideal: Option<T>,
    },
}

impl<T> Default for ConstraintRange<T>
where
    T: Default,
{
    fn default() -> Self {
        ConstraintRange::Single(Some(T::default()))
    }
}

impl<T> ConstraintRange<T>
where
    T: Clone + std::fmt::Debug,
{
    pub fn new(value: Option<T>) -> Self {
        ConstraintRange::Single(value)
    }

    pub fn min(mut self, value: T) -> Self {
        if let ConstraintRange::Range { ref mut min, .. } = self {
            *min = Some(value);
        }
        self
    }

    pub fn max(mut self, value: T) -> Self {
        if let ConstraintRange::Range { ref mut max, .. } = self {
            *max = Some(value);
        }
        self
    }

    pub fn exact(mut self, value: T) -> Self {
        if let ConstraintRange::Range { ref mut exact, .. } = &mut self {
            *exact = Some(value);
        }

        self
    }

    pub fn ideal(mut self, value: T) -> Self {
        if let ConstraintRange::Range { ref mut ideal, .. } = &mut self {
            *ideal = Some(value);
        }

        self
    }
}

impl<T> ConstraintRange<T>
where
    T: Into<JsValue> + Clone,
{
    pub fn to_jsvalue(&self) -> JsValue {
        match self {
            ConstraintRange::Single(value) => value.clone().unwrap().into(),
            ConstraintRange::Range {
                min,
                max,
                exact,
                ideal,
            } => {
                let obj = Object::new();

                if let Some(min_value) = min {
                    Reflect::set(&obj, &JsValue::from_str("min"), &min_value.clone().into())
                        .unwrap();
                }
                if let Some(max_value) = max {
                    Reflect::set(&obj, &JsValue::from_str("max"), &max_value.clone().into())
                        .unwrap();
                }
                if let Some(value) = exact {
                    Reflect::set(&obj, &JsValue::from_str("exact"), &value.clone().into()).unwrap();
                }
                if let Some(value) = ideal {
                    Reflect::set(&obj, &JsValue::from_str("ideal"), &value.clone().into()).unwrap();
                }

                JsValue::from(obj)
            }
        }
    }
}

impl From<f64> for ConstraintDouble {
    fn from(value: f64) -> Self {
        ConstraintRange::Single(Some(value))
    }
}

impl From<u32> for ConstraintULong {
    fn from(value: u32) -> Self {
        ConstraintRange::Single(Some(value))
    }
}

pub type ConstraintBool = ConstraintExactIdeal<bool>;

impl From<bool> for ConstraintBool {
    fn from(value: bool) -> Self {
        ConstraintExactIdeal::Single(Some(value))
    }
}

pub type ConstraintDouble = ConstraintRange<f64>;
pub type ConstraintULong = ConstraintRange<u32>;

#[derive(Clone, Copy, Debug)]
pub enum FacingMode {
    User,
    Environment,
    Left,
    Right,
}

impl FacingMode {
    pub fn as_str(self) -> &'static str {
        match self {
            FacingMode::User => "user",
            FacingMode::Environment => "environment",
            FacingMode::Left => "left",
            FacingMode::Right => "right",
        }
    }
}

pub type ConstraintFacingMode = ConstraintExactIdeal<FacingMode>;

impl From<FacingMode> for ConstraintFacingMode {
    fn from(value: FacingMode) -> Self {
        ConstraintFacingMode::Single(Some(value))
    }
}

impl ConstraintFacingMode {
    pub fn to_jsvalue(&self) -> JsValue {
        match self {
            ConstraintExactIdeal::Single(value) => JsValue::from_str((*value).unwrap().as_str()),
            ConstraintExactIdeal::ExactIdeal { exact, ideal } => {
                let obj = Object::new();

                if let Some(value) = exact {
                    Reflect::set(
                        &obj,
                        &JsValue::from_str("exact"),
                        &JsValue::from_str(value.as_str()),
                    )
                    .unwrap();
                }
                if let Some(value) = ideal {
                    Reflect::set(
                        &obj,
                        &JsValue::from_str("ideal"),
                        &JsValue::from_str(value.as_str()),
                    )
                    .unwrap();
                }

                JsValue::from(obj)
            }
        }
    }
}

#[derive(Clone, Debug)]
pub enum AudioConstraints {
    Bool(bool),
    Constraints(Box<AudioTrackConstraints>),
}

impl From<bool> for AudioConstraints {
    fn from(value: bool) -> Self {
        AudioConstraints::Bool(value)
    }
}

impl From<AudioTrackConstraints> for AudioConstraints {
    fn from(value: AudioTrackConstraints) -> Self {
        AudioConstraints::Constraints(Box::new(value))
    }
}

#[derive(Clone, Debug)]
pub enum VideoConstraints {
    Bool(bool),
    Constraints(Box<VideoTrackConstraints>),
}

impl From<bool> for VideoConstraints {
    fn from(value: bool) -> Self {
        VideoConstraints::Bool(value)
    }
}

impl From<VideoTrackConstraints> for VideoConstraints {
    fn from(value: VideoTrackConstraints) -> Self {
        VideoConstraints::Constraints(Box::new(value))
    }
}

pub trait IntoDeviceIds<M> {
    fn into_device_ids(self) -> Vec<String>;
}

impl<T> IntoDeviceIds<String> for T
where
    T: Into<String>,
{
    fn into_device_ids(self) -> Vec<String> {
        vec![self.into()]
    }
}

pub struct VecMarker;

impl<T, I> IntoDeviceIds<VecMarker> for T
where
    T: IntoIterator<Item = I>,
    I: Into<String>,
{
    fn into_device_ids(self) -> Vec<String> {
        self.into_iter().map(Into::into).collect()
    }
}

#[derive(DefaultBuilder, Default, Clone, Debug)]
pub struct AudioTrackConstraints {
    #[builder(skip)]
    device_id: Vec<String>,

    #[builder(into)]
    auto_gain_control: Option<ConstraintBool>,
    #[builder(into)]
    channel_count: Option<ConstraintULong>,
    #[builder(into)]
    echo_cancellation: Option<ConstraintBool>,
    #[builder(into)]
    noise_suppression: Option<ConstraintBool>,
}

impl AudioTrackConstraints {
    pub fn new() -> Self {
        AudioTrackConstraints::default()
    }

    pub fn device_id<M>(mut self, value: impl IntoDeviceIds<M>) -> Self {
        self.device_id = value.into_device_ids();
        self
    }
}

#[derive(DefaultBuilder, Default, Clone, Debug)]
pub struct VideoTrackConstraints {
    #[builder(skip)]
    pub device_id: Vec<String>,

    #[builder(into)]
    pub facing_mode: Option<ConstraintFacingMode>,
    #[builder(into)]
    pub frame_rate: Option<ConstraintDouble>,
    #[builder(into)]
    pub height: Option<ConstraintULong>,
    #[builder(into)]
    pub width: Option<ConstraintULong>,
    #[builder(into)]
    pub viewport_offset_x: Option<ConstraintULong>,
    #[builder(into)]
    pub viewport_offset_y: Option<ConstraintULong>,
    #[builder(into)]
    pub viewport_height: Option<ConstraintULong>,
    #[builder(into)]
    pub viewport_width: Option<ConstraintULong>,
}

impl VideoTrackConstraints {
    pub fn new() -> Self {
        VideoTrackConstraints::default()
    }

    pub fn device_id<M>(mut self, value: impl IntoDeviceIds<M>) -> Self {
        self.device_id = value.into_device_ids();
        self
    }
}