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
/* Copyright (C) 2024 DorotaC
 * SPDX-License-Identifier: LGPL-2.1-or-later OR MPL-2.0
 */

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

#[allow(non_camel_case_types)]
#[allow(non_snake_case)]
pub mod sys;

use bitflags::bitflags;
use const_enum::const_enum;
use std::ffi::CStr;
use std::fmt;
use std::mem;
use std::str;
use sys::{media_v2_entity, media_v2_link};


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);


/// https://docs.kernel.org/userspace-api/media/mediactl/media-ioc-g-topology.html
#[repr(C)]
#[repr(packed)]
#[derive(Debug)]
pub struct media_v2_topology {
    topology_version: u64,
	pub num_entities: u32,
    reserved1: u32,
    ptr_entities: u64,

    pub num_interfaces: u32,
    reserved2: u32,
    ptr_interfaces: u64,

    num_pads: u32,
    reserved3: u32,
    ptr_pads: u64,

    pub num_links: u32,
    reserved4: u32,
    pub ptr_links: u64,
}

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_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;
    }
}


const_enum! {
    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,
        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)]
    pub struct MediaEntFl: u32 {
        const DEFAULT = sys::MEDIA_ENT_FL_DEFAULT;
        const CONNECTOR = sys::MEDIA_ENT_FL_CONNECTOR;
    }
}

#[derive(Debug)]
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: u32,
    /// 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: Result<String, [::std::os::raw::c_char; 64usize]>,
    /// 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: v.id,
            name,
            function: v.function.into(),
            flags: MediaEntFl::from_bits_retain(v.flags),
        }
    }
}

impl Zeroed for media_v2_entity {}

#[repr(C)]
#[repr(packed)]
union MediaV2Interface_devnode {
    devnode: MediaV2IntfDevnode,
    raw: [u32; 16],
}

#[repr(C)]
#[repr(packed)]
pub struct media_v2_interface {
    id: u32,
    intf_type: u32,
    flags: u32,
    reserved: [u32; 9],
    devnode: MediaV2Interface_devnode,
}

const_enum! {
    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)]
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: u32,
    pub intf_type: MediaIntfT,
    /// Currently unused.
    pub flags: u32,
    /// Used only for device node interfaces
    pub devnode: MediaV2IntfDevnode,
}

impl From<&media_v2_interface> for MediaV2Interface {
    fn from(v: &media_v2_interface) -> Self {
        MediaV2Interface {
            id: v.id,
            intf_type: v.intf_type.into(),
            flags: v.flags,
            devnode: unsafe { v.devnode.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)]
pub struct MediaV2Link {
    id: u32,
    source_id: u32,
    sink_id: u32,
    flags: MediaLnkFl,
}

bitflags! {
    #[derive(Debug)]
    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;
        /// This is a bitmask that defines the type of the link.
        const LINK_TYPE = sys::MEDIA_LNK_FL_LINK_TYPE;
        /// links that represent a data connection between two pads.
        const DATA_LINK = sys::MEDIA_LNK_FL_DATA_LINK;
        /// links that associate an entity to its interface.
        const INTERFACE_LINK = sys::MEDIA_LNK_FL_INTERFACE_LINK;
        /// links that represent a physical relationship between two entities. The link may or may not be immutable, so applications must not assume either case.
        const ANCILLARY_LINK = sys::MEDIA_LNK_FL_ANCILLARY_LINK;
    }
}

impl From<media_v2_link> for MediaV2Link {
    fn from(v: media_v2_link) ->Self {
        Self {
            id: v.id,
            source_id: v.source_id,
            sink_id: v.sink_id,
            flags: MediaLnkFl::from_bits_retain(v.flags),
        }
    }
}

impl Zeroed for media_v2_link {}

// 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);


#[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 {
            Err(_) => {},
            Ok(_) => panic!("bad string should not get accepted"),
        }
    }
}