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
#![forbid(future_incompatible)]
#![deny(bad_style/*, missing_docs*/)]
#![doc = include_str!("../README.md")]

use std::{
    fs::File,
    os::unix::io::{AsRawFd, RawFd},
};

pub use linux_video_core as types;
use linux_video_core::private::*;
use types::*;

use async_io::Async;
use async_std::{
    path::{Path, PathBuf},
    stream::StreamExt,
    task::spawn_blocking as asyncify,
};

/// Video device
pub struct Device {
    file: File,
}

impl AsRawFd for Device {
    fn as_raw_fd(&self) -> RawFd {
        self.file.as_raw_fd()
    }
}

impl Device {
    /// List video devices
    pub async fn list() -> Result<Devices> {
        Devices::new().await
    }

    /// Open video device
    pub async fn open(path: impl AsRef<Path>) -> Result<Self> {
        let path = path.as_ref().to_owned();
        let file = asyncify(move || open(path, true)).await?;
        //let file = File::from_file(file)?;

        Ok(Device { file })
    }

    /// Get capabilities
    pub async fn capabilities(&self) -> Result<Capability> {
        let fd = self.as_raw_fd();
        asyncify(move || Internal::<Capability>::query(fd).map(Internal::into_inner)).await
    }

    /// Get controls
    pub fn controls(&self, class: Option<CtrlClass>) -> Controls<'_> {
        let last_id = class.map(|c| c as _).unwrap_or_default();

        Controls {
            device: self,
            class,
            last_id,
        }
    }

    /// Get control by identifier
    pub async fn control(&self, id: impl Into<u32>) -> Result<Control> {
        let fd = self.as_raw_fd();
        let id = id.into();
        let ctrl = asyncify(move || Internal::<QueryExtCtrl>::query_fallback(fd, id)).await?;

        Ok(Control { ctrl })
    }

    /// Get control menu items
    pub fn control_items(&self, control: &Control) -> Option<MenuItems<'_>> {
        if control.is_menu() {
            Some(MenuItems {
                device: self,
                ctrl_type: control.type_(),
                ctrl_id: control.id(),
                index_iter: control.min() as _..=control.max() as _,
            })
        } else {
            None
        }
    }

    /// Get control value
    pub async fn get_control<T: GetValue>(&self, value: &mut T) -> Result<()> {
        //let fd = self.as_raw_fd();
        //asyncify(move || value.get(fd)).await
        value.get(self.as_raw_fd())
    }

    /// Set control value
    pub async fn set_control<T: SetValue>(&self, value: &T) -> Result<()> {
        value.set(self.as_raw_fd())
    }

    /// Get supported formats
    pub fn formats(&self, type_: BufferType) -> FmtDescs {
        FmtDescs {
            device: self,
            type_,
            index: 0,
        }
    }

    /// Get current format
    pub async fn format(&self, type_: BufferType) -> Result<Format> {
        let fd = self.as_raw_fd();
        asyncify(move || {
            let mut fmt = Format::from(type_);
            Internal::from(&mut fmt).get(fd)?;
            Ok(fmt)
        })
        .await
    }

    /// Get current format
    pub async fn get_format(&self, fmt: &mut Format) -> Result<()> {
        let fmt_ = self.format(fmt.type_()).await?;
        fmt.clone_from(&fmt_);
        Ok(())
    }

    /// Set current format
    pub async fn set_format(&self, fmt: &mut Format) -> Result<()> {
        let fd = self.as_raw_fd();
        let mut fmt2 = *fmt;
        *fmt = asyncify(move || -> Result<Format> {
            Internal::from(&mut fmt2).set(fd)?;
            Ok(fmt2)
        })
        .await?;
        Ok(())
    }

    /// Try format without set it
    pub async fn try_format(&self, fmt: &mut Format) -> Result<()> {
        let fd = self.as_raw_fd();
        let mut fmt2 = *fmt;
        *fmt = asyncify(move || -> Result<Format> {
            Internal::from(&mut fmt2).try_(fd)?;
            Ok(fmt2)
        })
        .await?;
        Ok(())
    }

    /// Get supported frame sizes
    pub fn sizes(&self, pixel_format: FourCc) -> FrmSizes {
        FrmSizes {
            device: self,
            pixel_format,
            index: 0,
        }
    }

    /// Get supported frame intervals
    pub fn intervals(&self, pixel_format: FourCc, width: u32, height: u32) -> FrmIvals {
        FrmIvals {
            device: self,
            pixel_format,
            width,
            height,
            index: 0,
        }
    }

    /// Create stream to input/output data
    pub fn stream<Dir: Direction, Met: Method>(
        &self,
        type_: ContentType,
        count: usize,
    ) -> Result<Stream<Dir, Met>> {
        Stream::new(self.file.try_clone()?, type_, count)
    }
}

/// The interface to get available devices
pub struct Devices {
    reader: async_std::fs::ReadDir,
}

impl Devices {
    async fn new() -> Result<Self> {
        async_std::fs::read_dir("/dev")
            .await
            .map(|reader| Devices { reader })
    }

    /// Get path of the next device
    pub async fn fetch_next(&mut self) -> Result<Option<PathBuf>> {
        use std::os::unix::fs::FileTypeExt;

        while let Some(entry) = self.reader.next().await {
            let entry = entry?;
            if let Some(file_name) = entry.file_name().to_str() {
                if check_dev_name(file_name).is_some() {
                    let file_type = entry.file_type().await?;
                    if file_type.is_char_device() {
                        return Ok(Some(entry.path()));
                    }
                }
            }
        }

        Ok(None)
    }
}

/// The interface to get device controls
pub struct Controls<'i> {
    device: &'i Device,
    class: Option<CtrlClass>,
    last_id: u32,
}

impl<'i> Controls<'i> {
    /// Get next control
    pub async fn fetch_next(&mut self) -> Result<Option<Control>> {
        if self.last_id == u32::MAX {
            return Ok(None);
        }

        let fd = self.device.as_raw_fd();
        let id = self.last_id;

        if let Some(ctrl) =
            asyncify(move || Internal::<QueryExtCtrl>::query_next_fallback(fd, id)).await?
        {
            if self
                .class
                .map(|class| class.fast_match(ctrl.id()))
                .unwrap_or(true)
            {
                self.last_id = ctrl.id();
                Ok(Some(Control { ctrl }))
            } else {
                self.last_id = u32::MAX;
                Ok(None)
            }
        } else {
            self.last_id = u32::MAX;
            Ok(None)
        }
    }
}

/// The control access interface
pub struct Control {
    ctrl: Internal<QueryExtCtrl>,
}

impl core::ops::Deref for Control {
    type Target = QueryExtCtrl;

    fn deref(&self) -> &Self::Target {
        &self.ctrl
    }
}

impl AsRef<QueryExtCtrl> for Control {
    fn as_ref(&self) -> &QueryExtCtrl {
        &self.ctrl
    }
}

impl core::fmt::Display for Control {
    fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
        self.ctrl.fmt(f)
    }
}

/// The interface to get menu items
pub struct MenuItems<'i> {
    device: &'i Device,
    ctrl_type: CtrlType,
    ctrl_id: u32,
    index_iter: core::ops::RangeInclusive<u32>,
}

impl<'i> MenuItems<'i> {
    /// Get next menu control item
    pub async fn fetch_next(&mut self) -> Result<Option<MenuItem>> {
        let fd = self.device.as_raw_fd();
        let type_ = self.ctrl_type;
        let id = self.ctrl_id;
        for index in &mut self.index_iter {
            if let Some(item) =
                asyncify(move || Internal::<MenuItem>::query(fd, type_, id, index)).await?
            {
                return Ok(Some(item.into_inner()));
            }
        }
        Ok(None)
    }
}

/// The interface to get format descriptions
pub struct FmtDescs<'i> {
    device: &'i Device,
    type_: BufferType,
    index: u32,
}

impl<'i> FmtDescs<'i> {
    /// Fetch next format description
    pub async fn fetch_next(&mut self) -> Result<Option<FmtDesc>> {
        if self.index == u32::MAX {
            return Ok(None);
        }

        let fd = self.device.as_raw_fd();
        let index = self.index;
        let type_ = self.type_;

        if let Some(desc) = asyncify(move || Internal::<FmtDesc>::query(fd, index, type_)).await? {
            self.index += 1;
            Ok(Some(desc.into_inner()))
        } else {
            self.index = u32::MAX;
            Ok(None)
        }
    }
}

/// The interface to get drame sizes
pub struct FrmSizes<'i> {
    device: &'i Device,
    pixel_format: FourCc,
    index: u32,
}

impl<'i> FrmSizes<'i> {
    /// Get next frame size value
    pub async fn fetch_next(&mut self) -> Result<Option<FrmSizeEnum>> {
        if self.index == u32::MAX {
            return Ok(None);
        }

        let fd = self.device.as_raw_fd();
        let index = self.index;
        let pixfmt = self.pixel_format;

        if let Some(size) =
            asyncify(move || Internal::<FrmSizeEnum>::query(fd, index, pixfmt)).await?
        {
            self.index += 1;
            Ok(Some(size.into_inner()))
        } else {
            self.index = u32::MAX;
            Ok(None)
        }
    }
}

/// The interface to get frame intervals
pub struct FrmIvals<'i> {
    device: &'i Device,
    pixel_format: FourCc,
    width: u32,
    height: u32,
    index: u32,
}

impl<'i> FrmIvals<'i> {
    /// Get next frame interval value
    pub async fn fetch_next(&mut self) -> Result<Option<FrmIvalEnum>> {
        if self.index == u32::MAX {
            return Ok(None);
        }

        let fd = self.device.as_raw_fd();
        let index = self.index;
        let pixfmt = self.pixel_format;
        let width = self.width;
        let height = self.height;

        if let Some(ival) =
            asyncify(move || Internal::<FrmIvalEnum>::query(fd, index, pixfmt, width, height))
                .await?
        {
            self.index += 1;
            Ok(Some(ival.into_inner()))
        } else {
            self.index = u32::MAX;
            Ok(None)
        }
    }
}

/// Data I/O queue
pub struct Stream<Dir, Met: Method> {
    file: File,
    queue: Internal<QueueData<Dir, Met>>,
}

impl<Dir, Met: Method> Drop for Stream<Dir, Met> {
    fn drop(&mut self) {
        let _ = self.queue.del(self.file.as_raw_fd());
    }
}

struct FdWrapper {
    fd: RawFd,
}

impl AsRawFd for FdWrapper {
    fn as_raw_fd(&self) -> RawFd {
        self.fd
    }
}

impl<Dir: Direction, Met: Method> Stream<Dir, Met> {
    fn new(file: File, type_: ContentType, count: usize) -> Result<Self> {
        let queue = Internal::<QueueData<Dir, Met>>::new(file.as_raw_fd(), type_, count as _)?;

        Ok(Self { file, queue })
    }

    /// Get next frame to write or read
    pub async fn next(&self) -> Result<BufferRef<Dir, Met>> {
        let fd = self.file.as_raw_fd();

        loop {
            match self.queue.next(fd) {
                Ok(buffer) => break Ok(buffer),
                Err(error) if error.kind() == std::io::ErrorKind::WouldBlock => {
                    let async_fd = Async::new(FdWrapper { fd })?;

                    core::future::poll_fn(|cx| {
                        if Dir::IN {
                            async_fd.poll_readable(cx)
                        } else {
                            async_fd.poll_writable(cx)
                        }
                    })
                    .await?;
                }
                Err(error) => break Err(error),
            }
        }
    }
}