media_subsystem/
lib.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
/*
 * SPDX-FileCopyrightText: 2024 DorotaC
 *
 * SPDX-License-Identifier: MPL-2.0 OR LGPL-2.1-or-later
 */

/*! A safe wrapper around Linux Media device interface. */

/// The unsafe wrapper
#[allow(non_camel_case_types)]
#[allow(non_snake_case)]
pub mod sys;

use bitflags::bitflags;
use const_enum::const_enum_camel;
use sys::media_pad_desc;
use sys::media_v2_intf_devnode;
use std::ffi::CStr;
use std::fmt;
use std::mem;
use std::io;
use std::os::fd::RawFd;
use std::str;
use sys::{media_v2_entity, media_v2_link, media_v2_pad, media_v2_topology, media_v2_interface, media_link_desc};

/// Skips newlines while pretty-printing a newtype
macro_rules! id_debug {
    ($newtype:ident) => {
        impl std::fmt::Debug for $newtype {
            fn fmt(&self, formatter: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {
                formatter.write_fmt(format_args!("{}({})", stringify!($newtype), self.0))
            }
        }
    };
}

pub trait Zeroed where Self: Sized {
    fn zeroed() -> Self {
        unsafe { mem::zeroed() }
    }
}

// I already did the work with nicely documenting this struct, so let it be.
/// https://kernel.org/doc/html/v6.2/userspace-api/media/mediactl/media-ioc-device-info.html
#[repr(C)]
#[repr(packed)]
pub struct MediaDeviceInfo {
    /// ASCII
    driver_name: [u8; 16],
    /// UTF-8
    device_name: [u8; 32],
    /// ASCII
    serial_number: [u8; 40],
    /// ASCII
    bus_info: [u8; 32],
    media_version: u32,
    hardware_device_version: u32,
    driver_version: u32,
    reserved: [u32; 31],
}


impl Zeroed for MediaDeviceInfo {}

impl fmt::Debug for MediaDeviceInfo {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("MediaDeviceInfo")
            .field("driver", &self.get_driver())
            .field("device", &self.get_device())
            .finish()
    }
}

fn str_from_slice(s: &[u8]) -> &str {
    let full = str::from_utf8(s).unwrap();
    let end_byte = full.char_indices()
        .find(|(_i, c)| *c == '\0')
        .map(|(i, _c)| i)
        .unwrap_or(full.len());
    full.split_at(end_byte).0
}

impl MediaDeviceInfo {
    pub fn get_driver(&self) -> &str {
        str_from_slice(&self.driver_name)
    }
    pub fn get_device(&self) -> &str {
        str_from_slice(&self.device_name)
    }
}

// https://elixir.bootlin.com/linux/latest/source/include/uapi/linux/media.h#L371
nix::ioctl_readwrite!(media_ioc_device_info, b'|', 0x00, MediaDeviceInfo);


impl Zeroed for media_v2_topology {}

impl media_v2_topology {
    pub fn set_entities(&mut self, entities: &mut Vec<media_v2_entity>) {
        self.num_entities = entities.len() as u32;
        self.ptr_entities = entities.as_mut_ptr() as u64;
    }
    pub fn set_links(&mut self, links: &mut Vec<media_v2_link>) {
        self.num_links = links.len() as u32;
        self.ptr_links = links.as_mut_ptr() as u64;
    }
    pub fn set_interfaces(&mut self, arr: &mut Vec<media_v2_interface>) {
        self.num_interfaces = arr.len() as u32;
        self.ptr_interfaces = arr.as_mut_ptr() as u64;
    }
    pub fn set_pads(&mut self, arr: &mut Vec<media_v2_pad>) {
        self.num_pads = arr.len() as u32;
        self.ptr_pads = arr.as_mut_ptr() as u64;
    }
}

#[derive(PartialEq, Eq, Clone, Copy, Hash)]
pub struct EntityId(pub u32);

id_debug!(EntityId);

#[derive(PartialEq, Eq, Clone, Debug)]
pub enum EntityName {
    Text(String),
    Bytes([::std::os::raw::c_char; 64usize]),
}

const_enum_camel! {
    enum MediaEntF, sys, MEDIA_ENT_F_ {
        UNKNOWN,
        V4L2_SUBDEV_UNKNOWN,
        DTV_DEMOD,
        TS_DEMUX,
        DTV_CA,
        DTV_NET_DECAP,
        /// Data streaming input and/or output entity.
        IO_V4L,
        IO_DTV,
        IO_VBI,
        IO_SWRADIO,
        /// Camera video sensor entity.
        CAM_SENSOR,
        FLASH,
        /// Lens motor entity (seen used for focus adjustment)
        LENS,
        TUNER,
        IF_VID_DECODER,
        IF_AUD_DECODER,
        AUDIO_CAPTURE,
        AUDIO_PLAYBACK,
        AUDIO_MIXER,
        PROC_VIDEO_COMPOSER,
        /// Video pixel encoding converter. An entity capable of pixel encoding conversion must have at least one sink pad and one source pad, and convert the encoding of pixels received on its sink pad(s) to a different encoding output on its source pad(s). Pixel encoding conversion includes but isn’t limited to RGB to/from HSV, RGB to/from YUV and CFA (Bayer) to RGB conversions.
        PROC_VIDEO_PIXEL_FORMATTER,
        PROC_VIDEO_PIXEL_ENC_CONV,
        PROC_VIDEO_LUT,
        PROC_VIDEO_SCALER,
        PROC_VIDEO_STATISTICS,
        PROC_VIDEO_ENCODER,
        PROC_VIDEO_DECODER,
        PROC_VIDEO_ISP,
        VID_MUX,
        VID_IF_BRIDGE,
        ATV_DECODER,
        DV_DECODER,
        DV_ENCODER,
    }
}

bitflags! {
    #[derive(Debug, Clone, Copy)]
    pub struct MediaEntFl: u32 {
        const DEFAULT = sys::MEDIA_ENT_FL_DEFAULT;
        const CONNECTOR = sys::MEDIA_ENT_FL_CONNECTOR;
    }
}

#[derive(Debug, Clone)]
pub struct MediaV2Entity {
    /// Unique ID for the entity. Do not expect that the ID will always be the same for each instance of the device. In other words, do not hardcode entity IDs in an application.
    pub id: EntityId,
    /// This name must be unique within the media topology.
    /// (In practice, this is false with my integrated USB camera with 2 interfaces called "Integrated Camera: Integrated C\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0".
    /// If the name can be expressed as a valid String, it will be. Otherwise, the raw form is used.
    pub name: EntityName,
    /// Main function of the entity
    pub function: MediaEntF, 
    pub flags: MediaEntFl,
}

impl From<media_v2_entity> for MediaV2Entity {
    fn from(v: media_v2_entity) -> Self {
        let name: &[u8; 64] = unsafe { mem::transmute(&v.name) };
        let name = CStr::from_bytes_until_nul(name).ok()
            .and_then(|name| name.to_str().ok())
            .map(String::from)
            .ok_or_else(|| v.name.clone());
        Self {
            id: EntityId(v.id),
            name: match name {
                Ok(n) => EntityName::Text(n),
                Err(b) => EntityName::Bytes(b),
            },
            function: v.function.into(),
            flags: MediaEntFl::from_bits_retain(v.flags),
        }
    }
}

impl Zeroed for media_v2_entity {}

#[derive(PartialEq, Eq, Clone, Copy)]
pub struct InterfaceId(pub u32);

id_debug!(InterfaceId);

const_enum_camel! {
    enum MediaIntfT, sys, MEDIA_INTF_T_ {
        DVB_FE,
        DVB_DEMUX,
        DVB_DVR,
        DVB_CA,
        DVB_NET,
        /// Device node interface for video (V4L)
        /// typically, /dev/video?
        V4L_VIDEO,
        V4L_VBI,
        V4L_RADIO,
        /// Device node interface for a V4L subdevice
        /// typically, /dev/v4l-subdev?
        V4L_SUBDEV,
        V4L_SWRADIO,
        V4L_TOUCH,
        ALSA_PCM_CAPTURE,
        ALSA_PCM_PLAYBACK,
        ALSA_CONTROL,
    }
}

#[derive(Debug, Clone)]
pub struct MediaV2Interface {
    /// Unique ID for the interface. Do not expect that the ID will always be the same for each instance of the device. In other words, do not hardcode interface IDs in an application.
    pub id: InterfaceId,
    pub intf_type: MediaIntfT,
    /// Currently unused.
    pub flags: u32,
    /// Used only for device node interfaces
    pub devnode: media_v2_intf_devnode,
}

impl From<&media_v2_interface> for MediaV2Interface {
    fn from(v: &media_v2_interface) -> Self {
        MediaV2Interface {
            id: InterfaceId(v.id),
            intf_type: v.intf_type.into(),
            flags: v.flags,
            devnode: unsafe { v.__bindgen_anon_1.devnode },
        }
    }
}

impl Zeroed for media_v2_interface {}

#[repr(C)]
#[repr(packed)]
#[derive(Clone, Copy, Debug)]
pub struct MediaV2IntfDevnode {
    pub major: u32,
    pub minor: u32,
}

#[derive(Debug, Clone)]
pub struct MediaV2Link {
    pub id: u32,
    pub flags: MediaLnkFl,
    pub connection: MediaLinkType,
}

/// Defines the type of the link. Based on MEDIA_LNK_FL_LINK_TYPE
#[derive(Debug, Clone)]
pub enum MediaLinkType {
    /// links that represent a data connection between two pads.
    Data {
        source: PadId,
        sink: PadId,
    },
    /// links that associate an entity to its interface.
    Interface {
        interface: InterfaceId,
        entity: EntityId,
    },
    /// links that represent a physical relationship between two entities. The link may or may not be immutable, so applications must not assume either case.
    Ancillary {
        source: EntityId,
        sink: EntityId,
    },
    /// Unknown
    Other {
        typ: u32,
        source: u32,
        sink: u32
    },
}

bitflags! {
    /// Link flags, excluding link type
    #[derive(Debug, PartialEq, Clone, Copy)]
    pub struct MediaLnkFl: u32 {
        /// The link is enabled and can be used to transfer media data. When two or more links target a sink pad, only one of them can be enabled at a time.
        const ENABLED = sys::MEDIA_LNK_FL_ENABLED;
        /// The link enabled state can’t be modified at runtime. An immutable link is always enabled.
        const IMMUTABLE = sys::MEDIA_LNK_FL_IMMUTABLE;
        /// The link enabled state can be modified during streaming. This flag is set by drivers and is read-only for applications.
        const DYNAMIC = sys::MEDIA_LNK_FL_DYNAMIC;
    }
}

impl From<media_v2_link> for MediaV2Link {
    fn from(v: media_v2_link) ->Self {
        Self {
            id: v.id,
            flags: MediaLnkFl::from_bits_retain(v.flags & !sys::MEDIA_LNK_FL_LINK_TYPE),
            connection: match v.flags & sys::MEDIA_LNK_FL_LINK_TYPE {
                sys::MEDIA_LNK_FL_DATA_LINK => MediaLinkType::Data {
                    source: PadId(v.source_id),
                    sink: PadId(v.sink_id),
                },
                    sys::MEDIA_LNK_FL_INTERFACE_LINK => MediaLinkType::Interface {
                    interface: InterfaceId(v.source_id),
                    entity: EntityId(v.sink_id),
                },
                sys::MEDIA_LNK_FL_ANCILLARY_LINK => MediaLinkType::Ancillary  {
                    source: EntityId(v.source_id),
                    sink:  EntityId(v.sink_id),
                },
                other => MediaLinkType::Other {
                    typ: other,
                    source: v.source_id,
                    sink: v.sink_id,
                }
            },
        }
    }
}

impl Zeroed for media_v2_link {}

#[derive(PartialEq, Eq, Clone, Copy, Hash)]
pub struct PadId(pub u32);

id_debug!(PadId);

#[derive(Debug, Copy, Clone)]
pub struct MediaV2Pad {
    /// Unique ID for the pad. Do not expect that the ID will always be the same for each instance of the device. In other words, do not hardcode pad IDs in an application.
    pub id: PadId,
    /// Unique ID for the entity where this pad belongs.
    pub entity_id: EntityId,
    pub role: PadRole,
    pub must_connect: bool,
    /// Pad index, starts at 0. Only valid if MEDIA_V2_PAD_HAS_INDEX(media_version) returns true.
    pub index: u32,
}

#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub enum PadRole {
    Sink,
    Source,
}

impl From<media_v2_pad> for MediaV2Pad {
    fn from(v: media_v2_pad) ->Self {
        Self {
            id: PadId(v.id),
            entity_id: EntityId(v.entity_id),
            // Pad must have exactly one role.
            // This could use tracing for buggy kernels, but this is simpler.
            role: if v.flags & sys::MEDIA_PAD_FL_SINK != 0 {
                PadRole::Sink
            } else {
                PadRole::Source
            },
            must_connect: v.flags & sys::MEDIA_PAD_FL_MUST_CONNECT != 0,
            index: v.index,
        }
    }
}

impl Zeroed for media_v2_pad {}

// https://elixir.bootlin.com/linux/latest/source/include/uapi/linux/media.h#L375
nix::ioctl_readwrite!(media_ioc_g_topology, b'|', 0x04, media_v2_topology);

#[derive(Debug, Clone)]
pub struct MediaV2Topology {
    pub version: sys::__u64,
    pub links: Vec<MediaV2Link>,
    pub entities: Vec<MediaV2Entity>,
    pub interfaces: Vec<MediaV2Interface>,
    pub pads: Vec<MediaV2Pad>,
}

impl MediaV2Topology {
    pub fn read_from_rawfd(fd: RawFd) -> io::Result<Self> {
        let mut topology = media_v2_topology::zeroed();
        unsafe {
            media_ioc_g_topology(fd, &mut topology)
        }?;
        let mut links: Vec<_> = (0..topology.num_links)
            .map(|_| media_v2_link::zeroed())
            .collect();
        let mut entities: Vec<_> = (0..topology.num_entities)
            .map(|_| media_v2_entity::zeroed())
            .collect();
        let mut interfaces: Vec<_> = (0..topology.num_interfaces)
            .map(|_| media_v2_interface::zeroed())
            .collect();
        let mut pads: Vec<_> = (0..topology.num_pads)
            .map(|_| Zeroed::zeroed())
            .collect();
        let mut topology = media_v2_topology::zeroed();
        topology.set_links(&mut links);
        topology.set_entities(&mut entities);
        topology.set_interfaces(&mut interfaces);
        topology.set_pads(&mut pads);
        unsafe {
            media_ioc_g_topology(fd, &mut topology)
        }?;
        
        Ok(MediaV2Topology {
            version: topology.topology_version,
            links: links.into_iter().map(MediaV2Link::from).collect(),
            interfaces: interfaces.iter().map(MediaV2Interface::from).collect(),
            entities: entities.into_iter().map(MediaV2Entity::from).collect(),
            pads: pads.into_iter().map(MediaV2Pad::from).collect(),
        })
    }
}

nix::ioctl_readwrite!(media_ioc_setup_link, b'|', 0x03, media_link_desc);

impl Zeroed for media_link_desc {}

#[derive(Debug, Clone)]
pub struct MediaLinkDesc {
    pub source: MediaPadDesc,
    pub sink: MediaPadDesc,
    pub state: LinkEnabled,
}

impl From<MediaLinkDesc> for media_link_desc {
    fn from(value: MediaLinkDesc) -> Self {
        Self {
            source: value.source.into(),
            sink: value.sink.into(),
            flags: match value.state {
                LinkEnabled::Enabled => MediaLnkFl::ENABLED.bits(),
                LinkEnabled::Disabled => 0,
            },
            // For the reserved fields
            ..Self::zeroed()
        }
    }
}

#[derive(Debug, Clone)]
pub enum LinkEnabled {
    Enabled,
    Disabled,
}

impl Zeroed for media_pad_desc {}

#[derive(Debug, Clone)]
pub struct MediaPadDesc {
    pub entity: EntityId,
    pub index: u16,
}

impl From<MediaPadDesc> for media_pad_desc {
    fn from(value: MediaPadDesc) -> Self {
        Self {
            entity: value.entity.0,
            index: value.index,
            // No word on whether flags are even supported on https://docs.kernel.org/userspace-api/media/mediactl/media-ioc-setup-link.html
            // It doesn't make sense to set flags here, either.
            flags: 0,
            // For the reserved fields
            ..Self::zeroed()
        }
    }
}

#[cfg(test)]
mod test {
    use super::*;
    #[test]
    fn entity_bad_string() {
        // fill entity with garbage
        let v = [0xfeu8; mem::size_of::<media_v2_entity>()];
        dbg!(v.len());
        let entity: media_v2_entity = unsafe { mem::transmute_copy(&v) };
        let entity = MediaV2Entity::from(entity);
        match entity.name {
            EntityName::Bytes(_) => {},
            EntityName::Text(_) => panic!("bad string should not get accepted"),
        }
    }
}