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
//! Representation of [MediaDevices][0].
//!
//! [0]: https://w3.org/TR/mediacapture-streams#mediadevices

use medea_macro::dart_bridge;
use tracerr::Traced;

use crate::{
    media::MediaSourceKind,
    platform::{
        dart::utils::{
            dart_future::FutureFromDart, handle::DartHandle, list::DartList,
            string_into_c_str,
        },
        utils::callback::Callback,
        Error, GetUserMediaError,
    },
};

use super::{
    constraints::{DisplayMediaStreamConstraints, MediaStreamConstraints},
    media_device_info::MediaDeviceInfo,
    media_display_info::MediaDisplayInfo,
    media_track::MediaStreamTrack,
};

#[dart_bridge("flutter/lib/src/native/platform/media_devices.g.dart")]
mod media_devices {
    use std::{os::raw::c_char, ptr};

    use dart_sys::Dart_Handle;

    use crate::platform::Error;

    extern "C" {
        /// Returns information about available media input devices.
        pub fn enumerate_devices() -> Result<Dart_Handle, Error>;

        /// Returns information about available displays.
        pub fn enumerate_displays() -> Result<Dart_Handle, Error>;

        /// Prompts a user for permissions to use a media input device,
        /// producing a vector of [MediaStreamTrack][1]s containing the
        /// requested types of media.
        ///
        /// [1]: https://w3.org/TR/mediacapture-streams#mediastreamtrack
        pub fn get_user_media(
            constraints: Dart_Handle,
        ) -> Result<Dart_Handle, Error>;

        /// Prompts a user to select and grant permissions to capture contents
        /// of a display or portion thereof (such as a single window), producing
        /// a vector of [MediaStreamTrack][1]s containing the requested types
        /// of media.
        ///
        /// [1]: https://w3.org/TR/mediacapture-streams#mediastreamtrack
        pub fn get_display_media(
            constraints: Dart_Handle,
        ) -> Result<Dart_Handle, Error>;

        /// Switches the current output audio device to the device with the
        /// provided `device_id`.
        pub fn set_output_audio_id(
            device_id: ptr::NonNull<c_char>,
        ) -> Result<Dart_Handle, Error>;

        /// Indicates whether it's possible to access microphone volume
        /// settings.
        pub fn microphone_volume_is_available() -> Result<Dart_Handle, Error>;

        /// Returns the current microphone volume level in percents.
        pub fn microphone_volume() -> Result<Dart_Handle, Error>;

        /// Sets the microphone volume level in percents.
        pub fn set_microphone_volume(level: i64) -> Result<Dart_Handle, Error>;

        /// Subscribes onto the `MediaDevices`'s `devicechange` event.
        pub fn on_device_change(cb: Dart_Handle) -> Result<(), Error>;

        /// Returns the kind of the Dart side `GetMediaException`.
        pub fn get_media_exception_kind(
            exception: Dart_Handle,
        ) -> Result<i64, Error>;
    }
}

#[expect(clippy::fallible_impl_from, reason = "FFI error is unexpected")]
impl From<Error> for GetUserMediaError {
    fn from(err: Error) -> Self {
        let kind = unsafe {
            media_devices::get_media_exception_kind(err.get_handle())
        }
        .unwrap();

        match kind {
            0 => Self::Audio(err),
            1 => Self::Video(err),
            _ => Self::Unknown(err),
        }
    }
}

/// Media devices controller.
#[derive(Clone, Copy, Debug, Default)]
pub struct MediaDevices;

impl MediaDevices {
    /// Collects information about available media input devices.
    ///
    /// Adapter for the [MediaDevices.enumerateDevices()][1] function.
    ///
    /// # Errors
    ///
    /// If [MediaDevices.enumerateDevices()][1] errors itself or unable to get
    /// [MediaDevices][2].
    ///
    /// [1]: https://tinyurl.com/w3-streams#dom-mediadevices-enumeratedevices
    /// [2]: https://w3.org/TR/mediacapture-streams#mediadevices
    pub async fn enumerate_devices(
        &self,
    ) -> Result<Vec<MediaDeviceInfo>, Traced<Error>> {
        let fut = unsafe { media_devices::enumerate_devices() }.unwrap();
        let devices = unsafe { FutureFromDart::execute::<DartHandle>(fut) }
            .await
            .map(DartList::from)
            .map_err(tracerr::wrap!())?;

        let len = devices.length();
        let mut result = Vec::with_capacity(len);
        for i in 0..len {
            let val = devices.get(i).unwrap();
            if let Ok(v) = val.try_into() {
                result.push(v);
            }
        }
        Ok(result)
    }

    /// Collects information about available displays.
    ///
    /// # Errors
    ///
    /// If platform call returns error.
    pub async fn enumerate_displays(
        &self,
    ) -> Result<Vec<MediaDisplayInfo>, Traced<Error>> {
        let fut = unsafe { media_devices::enumerate_displays() }.unwrap();
        let displays = unsafe { FutureFromDart::execute::<DartHandle>(fut) }
            .await
            .map(DartList::from)
            .map_err(tracerr::from_and_wrap!())?;

        let len = displays.length();
        let mut result = Vec::with_capacity(len);
        for i in 0..len {
            let val = displays.get(i).unwrap();
            result.push(MediaDisplayInfo::from(val));
        }

        Ok(result)
    }

    /// Prompts a user for permissions to use a media input device, producing
    /// [`MediaStreamTrack`]s containing the requested types of media.
    ///
    /// Adapter for the [MediaDevices.getUserMedia()][1] function.
    ///
    /// # Errors
    ///
    /// If [MediaDevices.getUserMedia()][1] errors itself or unable to get
    /// [MediaDevices][2].
    ///
    /// [1]: https://tinyurl.com/w3-streams#dom-mediadevices-getusermedia
    /// [2]: https://w3.org/TR/mediacapture-streams#mediadevices
    pub async fn get_user_media(
        &self,
        caps: MediaStreamConstraints,
    ) -> Result<Vec<MediaStreamTrack>, Traced<GetUserMediaError>> {
        let fut =
            unsafe { media_devices::get_user_media(caps.into()) }.unwrap();
        let tracks = unsafe { FutureFromDart::execute::<DartHandle>(fut) }
            .await
            .map_err(tracerr::from_and_wrap!())?;

        let tracks = Vec::from(DartList::from(tracks))
            .into_iter()
            .map(|track| {
                MediaStreamTrack::new(track, Some(MediaSourceKind::Device))
            })
            .collect();

        Ok(tracks)
    }

    /// Prompts a user to select and grant permissions to capture contents of a
    /// display or portion thereof (such as a single window), producing
    /// [`MediaStreamTrack`]s containing the requested types of media.
    ///
    /// Adapter for a [MediaDevices.getDisplayMedia()][1] function.
    ///
    /// # Errors
    ///
    /// If [MediaDevices.getDisplayMedia()][1] errors itself or unable to get
    /// [MediaDevices][2].
    ///
    /// [1]: https://w3.org/TR/screen-capture#dom-mediadevices-getdisplaymedia
    /// [2]: https://w3.org/TR/mediacapture-streams#mediadevices
    pub async fn get_display_media(
        &self,
        caps: DisplayMediaStreamConstraints,
    ) -> Result<Vec<MediaStreamTrack>, Traced<Error>> {
        let fut =
            unsafe { media_devices::get_display_media(caps.into()) }.unwrap();
        let tracks = unsafe { FutureFromDart::execute::<DartHandle>(fut) }
            .await
            .map_err(tracerr::wrap!())?;

        let tracks = Vec::from(DartList::from(tracks))
            .into_iter()
            .map(|track| {
                MediaStreamTrack::new(track, Some(MediaSourceKind::Display))
            })
            .collect();

        Ok(tracks)
    }

    /// Switches the current output audio device to the device with the provided
    /// `device_id`.
    ///
    /// # Errors
    ///
    /// If output audio device with the provided `device_id` is not available.
    pub async fn set_output_audio_id(
        &self,
        device_id: String,
    ) -> Result<(), Traced<Error>> {
        let fut = unsafe {
            media_devices::set_output_audio_id(string_into_c_str(device_id))
        }
        .unwrap();
        unsafe { FutureFromDart::execute::<()>(fut) }
            .await
            .map_err(tracerr::wrap!())
    }

    /// Indicates whether it's possible to access microphone volume settings.
    pub async fn microphone_volume_is_available(&self) -> bool {
        let fut =
            unsafe { media_devices::microphone_volume_is_available() }.unwrap();
        let result = unsafe { FutureFromDart::execute::<i64>(fut) }
            .await
            .unwrap();

        result == 1
    }

    /// Returns the current microphone volume level in percents.
    ///
    /// # Errors
    ///
    /// If it the "Audio Device Module" is not initialized or there is no
    /// connected audio input devices.
    pub async fn microphone_volume(&self) -> Result<i64, Traced<Error>> {
        let fut = unsafe { media_devices::microphone_volume() }.unwrap();
        unsafe { FutureFromDart::execute::<i64>(fut) }
            .await
            .map_err(tracerr::wrap!())
    }

    /// Sets the microphone volume level in percents.
    ///
    /// # Errors
    ///
    /// If it the "Audio Device Module" is not initialized or there is no
    /// connected audio input devices.
    pub async fn set_microphone_volume(
        &self,
        level: i64,
    ) -> Result<(), Traced<Error>> {
        let fut =
            unsafe { media_devices::set_microphone_volume(level) }.unwrap();
        unsafe { FutureFromDart::execute::<()>(fut) }
            .await
            .map_err(tracerr::wrap!())
    }

    /// Subscribes onto the [`MediaDevices`]'s `devicechange` event.
    pub fn on_device_change<F>(&self, handler: Option<F>)
    where
        F: 'static + FnMut(),
    {
        if let Some(mut h) = handler {
            unsafe {
                media_devices::on_device_change(
                    Callback::from_fn_mut(move |(): ()| {
                        h();
                    })
                    .into_dart(),
                )
            }
            .unwrap();
        }
    }
}