Skip to main content

linux_media/
media_entity.rs

1use std::ffi::CStr;
2use std::ops::{BitAnd, BitOr};
3
4use bitflags;
5use derive_more::{From, Into};
6use linux_media_sys as media;
7use serde::{Deserialize, Serialize};
8
9use crate::error;
10use crate::MediaEntityDesc;
11use crate::Version;
12
13#[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Eq, Ord, Serialize, Deserialize)]
14pub enum MediaEntityFunctions {
15    /// Unknown entity. That generally indicates that a driver didn’t initialize properly the entity, which is a Kernel bug
16    Unknown,
17    /// Unknown entity. That generally indicates that a driver didn’t initialize properly the entity, which is a Kernel bug
18    V4L2SubdevUnknown,
19    /// Data streaming input and/or output entity.
20    IoV4L,
21    /// V4L VBI streaming input or output entity
22    IoVBI,
23    /// V4L Software Digital Radio (SDR) streaming input or output entity
24    IoSWRadio,
25    /// DVB Digital TV streaming input or output entity
26    IoDTV,
27    /// Digital TV demodulator entity.
28    DTVDemod,
29    /// MPEG Transport stream demux entity. Could be implemented on hardware or in Kernelspace by the Linux DVB subsystem.
30    TSDemux,
31    /// Digital TV Conditional Access module (CAM) entity
32    DTVCondAccess,
33    /// Digital TV network ULE/MLE desencapsulation entity. Could be implemented on hardware or in Kernelspace
34    DTVNetDecap,
35    /// Connector for a Radio Frequency (RF) signal.
36    #[cfg(has_linux_media_sys__MEDIA_ENT_F_CONN_RF)]
37    ConnRF,
38    /// Connector for a S-Video signal.
39    #[cfg(has_linux_media_sys__MEDIA_ENT_F_CONN_SVIDEO)]
40    ConnSVideo,
41    /// Connector for a RGB composite signal.
42    #[cfg(has_linux_media_sys__MEDIA_ENT_F_CONN_COMPOSITE)]
43    ConnComposite,
44    /// Camera video sensor entity.
45    CAMSensor,
46    /// Flash controller entity.
47    Flash,
48    /// Lens controller entity.
49    Lens,
50    /// Analog video decoder, the basic function of the video decoder is to accept analogue video from a wide variety of sources such as broadcast, DVD players, cameras and video cassette recorders, in either NTSC, PAL, SECAM or HD format, separating the stream into its component parts, luminance and chrominance, and output it in some digital video standard, with appropriate timing signals.
51    ATVDecoder,
52    /// Digital TV, analog TV, radio and/or software radio tuner, with consists on a PLL tuning stage that converts radio frequency (RF) signal into an Intermediate Frequency (IF). Modern tuners have internally IF-PLL decoders for audio and video, but older models have those stages implemented on separate entities.
53    Tuner,
54    /// IF-PLL video decoder. It receives the IF from a PLL and decodes the analog TV video signal. This is commonly found on some very old analog tuners, like Philips MK3 designs. They all contain a tda9887 (or some software compatible similar chip, like tda9885). Those devices use a different I2C address than the tuner PLL.
55    IFVIDDecoder,
56    /// IF-PLL sound decoder. It receives the IF from a PLL and decodes the analog TV audio signal. This is commonly found on some very old analog hardware, like Micronas msp3400, Philips tda9840, tda985x, etc. Those devices use a different I2C address than the tuner PLL and should be controlled together with the IF-PLL video decoder.
57    IFAUDDecoder,
58    /// Audio Capture Function Entity.
59    AudioCapture,
60    /// Audio Playback Function Entity.
61    AudioPlayback,
62    /// Audio Mixer Function Entity.
63    AudioMixer,
64    /// Video composer (blender). An entity capable of video composing must have at least two sink pads and one source pad, and composes input video frames onto output video frames. Composition can be performed using alpha blending, color keying, raster operations (ROP), stitching or any other means.
65    ProcVideoComposer,
66    /// Video pixel formatter. An entity capable of pixel formatting must have at least one sink pad and one source pad. Read pixel formatters read pixels from memory and perform a subset of unpacking, cropping, color keying, alpha multiplication and pixel encoding conversion. Write pixel formatters perform a subset of dithering, pixel encoding conversion and packing and write pixels to memory.
67    ProcVideoPixelFormatter,
68    /// Video pixel encoding converter. An entity capable of pixel enconding 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.
69    ProcVideoPixelEncConv,
70    /// Video look-up table. An entity capable of video lookup table processing must have one sink pad and one source pad. It uses the values of the pixels received on its sink pad to look up entries in internal tables and output them on its source pad. The lookup processing can be performed on all components separately or combine them for multi-dimensional table lookups.
71    ProcVideoLUT,
72    /// Video scaler. An entity capable of video scaling must have at least one sink pad and one source pad, and scale the video frame(s) received on its sink pad(s) to a different resolution output on its source pad(s). The range of supported scaling ratios is entity-specific and can differ between the horizontal and vertical directions (in particular scaling can be supported in one direction only). Binning and sub-sampling (occasionally also referred to as skipping) are considered as scaling.
73    ProcVideoScaler,
74    /// Video statistics computation (histogram, 3A, etc.). An entity capable of statistics computation must have one sink pad and one source pad. It computes statistics over the frames received on its sink pad and outputs the statistics data on its source pad.
75    ProcVideoStatistics,
76    /// Video (MPEG, HEVC, VPx, etc.) encoder. An entity capable of compressing video frames. Must have one sink pad and at least one source pad.
77    ProcVideoEncoder,
78    /// Video (MPEG, HEVC, VPx, etc.) decoder. An entity capable of decompressing a compressed video stream into uncompressed video frames. Must have one sink pad and at least one source pad.
79    ProcVideoDecoder,
80    /// Video multiplexer. An entity capable of multiplexing must have at least two sink pads and one source pad, and must pass the video frame(s) received from the active sink pad to the source pad.
81    VIDMux,
82    /// Video interface bridge. A video interface bridge entity must have at least one sink pad and at least one source pad. It receives video frames on its sink pad from an input video bus of one type (HDMI, eDP, MIPI CSI-2, etc.), and outputs them on its source pad to an output video bus of another type (eDP, MIPI CSI-2, parallel, etc.).
83    VIDIFBridge,
84    /// Digital video decoder. The basic function of the video decoder is to accept digital video from a wide variety of sources and output it in some digital video standard, with appropriate timing signals.
85    DVDecoder,
86    /// Digital video encoder. The basic function of the video encoder is to accept digital video from some digital video standard with appropriate timing signals (usually a parallel video bus with sync signals) and output this to a digital video output connector such as HDMI or DisplayPort.
87    DVEncoder,
88}
89
90impl TryFrom<u32> for MediaEntityFunctions {
91    type Error = error::Error;
92    fn try_from(v: u32) -> error::Result<Self> {
93        use MediaEntityFunctions::*;
94        match v {
95            media::MEDIA_ENT_F_UNKNOWN => Ok(Unknown),
96            media::MEDIA_ENT_F_V4L2_SUBDEV_UNKNOWN => Ok(V4L2SubdevUnknown),
97            media::MEDIA_ENT_F_IO_V4L => Ok(IoV4L),
98            media::MEDIA_ENT_F_IO_VBI => Ok(IoVBI),
99            media::MEDIA_ENT_F_IO_SWRADIO => Ok(IoSWRadio),
100            media::MEDIA_ENT_F_IO_DTV => Ok(IoDTV),
101            media::MEDIA_ENT_F_DTV_DEMOD => Ok(DTVDemod),
102            media::MEDIA_ENT_F_TS_DEMUX => Ok(TSDemux),
103            media::MEDIA_ENT_F_DTV_CA => Ok(DTVCondAccess),
104            media::MEDIA_ENT_F_DTV_NET_DECAP => Ok(DTVNetDecap),
105            #[cfg(has_linux_media_sys__MEDIA_ENT_F_CONN_RF)]
106            media::MEDIA_ENT_F_CONN_RF => Ok(ConnRF),
107            #[cfg(has_linux_media_sys__MEDIA_ENT_F_CONN_SVIDEO)]
108            media::MEDIA_ENT_F_CONN_SVIDEO => Ok(ConnSvideo),
109            #[cfg(has_linux_media_sys__MEDIA_ENT_F_CONN_COMPOSITE)]
110            media::MEDIA_ENT_F_CONN_COMPOSITE => Ok(ConnComposite),
111            media::MEDIA_ENT_F_CAM_SENSOR => Ok(CAMSensor),
112            media::MEDIA_ENT_F_FLASH => Ok(Flash),
113            media::MEDIA_ENT_F_LENS => Ok(Lens),
114            media::MEDIA_ENT_F_ATV_DECODER => Ok(ATVDecoder),
115            media::MEDIA_ENT_F_TUNER => Ok(Tuner),
116            media::MEDIA_ENT_F_IF_VID_DECODER => Ok(IFVIDDecoder),
117            media::MEDIA_ENT_F_IF_AUD_DECODER => Ok(IFAUDDecoder),
118            media::MEDIA_ENT_F_AUDIO_CAPTURE => Ok(AudioCapture),
119            media::MEDIA_ENT_F_AUDIO_PLAYBACK => Ok(AudioPlayback),
120            media::MEDIA_ENT_F_AUDIO_MIXER => Ok(AudioMixer),
121            media::MEDIA_ENT_F_PROC_VIDEO_COMPOSER => Ok(ProcVideoComposer),
122            media::MEDIA_ENT_F_PROC_VIDEO_PIXEL_FORMATTER => Ok(ProcVideoPixelFormatter),
123            media::MEDIA_ENT_F_PROC_VIDEO_PIXEL_ENC_CONV => Ok(ProcVideoPixelEncConv),
124            media::MEDIA_ENT_F_PROC_VIDEO_LUT => Ok(ProcVideoLUT),
125            media::MEDIA_ENT_F_PROC_VIDEO_SCALER => Ok(ProcVideoScaler),
126            media::MEDIA_ENT_F_PROC_VIDEO_STATISTICS => Ok(ProcVideoStatistics),
127            media::MEDIA_ENT_F_PROC_VIDEO_ENCODER => Ok(ProcVideoEncoder),
128            media::MEDIA_ENT_F_PROC_VIDEO_DECODER => Ok(ProcVideoDecoder),
129            media::MEDIA_ENT_F_VID_MUX => Ok(VIDMux),
130            media::MEDIA_ENT_F_VID_IF_BRIDGE => Ok(VIDIFBridge),
131            media::MEDIA_ENT_F_DV_DECODER => Ok(DVDecoder),
132            media::MEDIA_ENT_F_DV_ENCODER => Ok(DVEncoder),
133            other => Err(error::Error::EntityFunctionsParseError { from: other }),
134        }
135    }
136}
137
138bitflags::bitflags! {
139    /// Media entity flags
140    #[derive(Debug, Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Serialize, Deserialize)]
141    pub struct MediaEntityFlags: u32 {
142        /// Default entity for its type. Used to discover the default audio, VBI and video devices, the default camera sensor, etc.
143        const Default = media::MEDIA_ENT_FL_DEFAULT;
144        /// The entity represents a connector.
145        const Connector = media::MEDIA_ENT_FL_CONNECTOR;
146    }
147}
148
149impl TryFrom<u32> for MediaEntityFlags {
150    type Error = error::Error;
151    fn try_from(v: u32) -> error::Result<Self> {
152        MediaEntityFlags::from_bits(v)
153            .ok_or_else(|| error::Error::EntityFlagsParseError { from: v })
154    }
155}
156
157#[derive(
158    Debug, Copy, Clone, PartialEq, PartialOrd, Eq, Ord, From, Into, Serialize, Deserialize,
159)]
160pub struct EntityId(u32);
161
162/// for or'ing with linux_media_sys::MEDIA_ENT_ID_FLAG_NEXT.
163impl BitOr for EntityId {
164    type Output = Self;
165
166    fn bitor(self, rhs: Self) -> Self::Output {
167        EntityId(self.0 | rhs.0)
168    }
169}
170
171/// for clearing linux_media_sys::MEDIA_ENT_ID_FLAG_NEXT.
172impl BitAnd for EntityId {
173    type Output = Self;
174
175    fn bitand(self, rhs: Self) -> Self::Output {
176        EntityId(self.0 & rhs.0)
177    }
178}
179
180#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Serialize, Deserialize)]
181pub struct MediaEntity {
182    id: EntityId,
183    name: String,
184    function: MediaEntityFunctions,
185    /// media entity flags.
186    /// Only `Some` if `has_flags` return true.
187    flags: Option<MediaEntityFlags>,
188}
189
190impl MediaEntity {
191    pub fn has_flags(version: Version) -> bool {
192        media::MEDIA_V2_ENTITY_HAS_FLAGS(<Version as Into<u32>>::into(version).into())
193    }
194
195    pub fn id(&self) -> EntityId {
196        self.id
197    }
198
199    pub fn name(&self) -> &str {
200        &self.name
201    }
202
203    pub fn function(&self) -> MediaEntityFunctions {
204        self.function
205    }
206
207    pub fn flags(&self) -> Option<MediaEntityFlags> {
208        self.flags
209    }
210
211    pub fn from_raw_entity(version: Version, entity: media::media_v2_entity) -> Self {
212        let id = EntityId::from(entity.id);
213        let name = unsafe { CStr::from_ptr(entity.name.as_ptr()) }
214            .to_string_lossy()
215            .to_string();
216        let function: MediaEntityFunctions = entity.function.try_into().unwrap();
217        let flags: Option<MediaEntityFlags> = if Self::has_flags(version) {
218            Some(entity.flags.try_into().unwrap())
219        } else {
220            None
221        };
222        Self {
223            id,
224            name,
225            function,
226            flags,
227        }
228    }
229
230    pub fn from_desc(version: Version, desc: MediaEntityDesc) -> Self {
231        Self {
232            id: desc.id,
233            name: desc.name,
234            function: desc.r#type,
235            flags: if Self::has_flags(version) {
236                Some(desc.flags)
237            } else {
238                None
239            },
240        }
241    }
242}