]>
Commit | Line | Data |
---|---|---|
33b5689a KS |
1 | //! Audio and image sample format definitions. |
2 | //! | |
3 | //! NihAV does not have a fixed list of supported formats but rather accepts format definitions both for audio and video. | |
4 | //! In result exotic formats like YUV410+alpha plane that is used by Indeo 4 are supported without any additional case handing. | |
5 | //! Some common format definitions are provided as constants for convenience. | |
32ce974d | 6 | use std::str::FromStr; |
fba6f8e4 KS |
7 | use std::string::*; |
8 | use std::fmt; | |
9 | ||
f49e17fc KS |
10 | /// Generic format parsing error. |
11 | #[derive(Clone,Copy,Debug,PartialEq)] | |
12 | pub struct FormatParseError {} | |
13 | ||
33b5689a KS |
14 | /// Audio format definition. |
15 | /// | |
16 | /// The structure describes how audio samples are stored and what characteristics they have. | |
b68ff5ae | 17 | #[derive(Debug,Copy,Clone,PartialEq)] |
fba6f8e4 | 18 | pub struct NASoniton { |
33b5689a | 19 | /// Bits per sample. |
a92a5113 | 20 | pub bits: u8, |
33b5689a | 21 | /// Audio format is big-endian. |
a92a5113 | 22 | pub be: bool, |
33b5689a | 23 | /// Audio samples are packed (e.g. 20-bit audio samples). |
a92a5113 | 24 | pub packed: bool, |
33b5689a | 25 | /// Audio data is stored in planar format instead of interleaving samples for different channels. |
a92a5113 | 26 | pub planar: bool, |
33b5689a | 27 | /// Audio data is in floating point format. |
a92a5113 | 28 | pub float: bool, |
33b5689a | 29 | /// Audio data is signed (usually only 8-bit audio is unsigned). |
a92a5113 | 30 | pub signed: bool, |
fba6f8e4 KS |
31 | } |
32 | ||
33b5689a KS |
33 | /// Flag for specifying that audio format is big-endian in `NASoniton::`[`new`]`()`. Related to [`be`] field of `NASoniton`. |
34 | /// | |
35 | /// [`new`]: ./struct.NASoniton.html#method.new | |
36 | /// [`be`]: ./struct.NASoniton.html#structfield.be | |
9e9a3af1 | 37 | pub const SONITON_FLAG_BE :u32 = 0x01; |
33b5689a KS |
38 | /// Flag for specifying that audio format has packed samples in `NASoniton::`[`new`]`()`. Related to [`packed`] field of `NASoniton`. |
39 | /// | |
40 | /// [`new`]: ./struct.NASoniton.html#method.new | |
41 | /// [`packed`]: ./struct.NASoniton.html#structfield.packed | |
9e9a3af1 | 42 | pub const SONITON_FLAG_PACKED :u32 = 0x02; |
33b5689a KS |
43 | /// Flag for specifying that audio data is stored as planar in `NASoniton::`[`new`]`()`. Related to [`planar`] field of `NASoniton`. |
44 | /// | |
45 | /// [`new`]: ./struct.NASoniton.html#method.new | |
46 | /// [`planar`]: ./struct.NASoniton.html#structfield.planar | |
9e9a3af1 | 47 | pub const SONITON_FLAG_PLANAR :u32 = 0x04; |
33b5689a KS |
48 | /// Flag for specifying that audio samples are in floating point format in `NASoniton::`[`new`]`()`. Related to [`float`] field of `NASoniton`. |
49 | /// | |
50 | /// [`new`]: ./struct.NASoniton.html#method.new | |
51 | /// [`float`]: ./struct.NASoniton.html#structfield.float | |
9e9a3af1 | 52 | pub const SONITON_FLAG_FLOAT :u32 = 0x08; |
33b5689a KS |
53 | /// Flag for specifying that audio format is signed in `NASoniton::`[`new`]`()`. Related to [`signed`] field of `NASoniton`. |
54 | /// | |
55 | /// [`new`]: ./struct.NASoniton.html#method.new | |
56 | /// [`signed`]: ./struct.NASoniton.html#structfield.signed | |
9e9a3af1 | 57 | pub const SONITON_FLAG_SIGNED :u32 = 0x10; |
fba6f8e4 | 58 | |
33b5689a | 59 | /// Predefined format for interleaved 8-bit unsigned audio. |
fba6f8e4 | 60 | pub const SND_U8_FORMAT: NASoniton = NASoniton { bits: 8, be: false, packed: false, planar: false, float: false, signed: false }; |
33b5689a | 61 | /// Predefined format for interleaved 16-bit signed audio. |
fba6f8e4 | 62 | pub const SND_S16_FORMAT: NASoniton = NASoniton { bits: 16, be: false, packed: false, planar: false, float: false, signed: true }; |
33b5689a | 63 | /// Predefined format for planar 16-bit signed audio. |
49fde921 | 64 | pub const SND_S16P_FORMAT: NASoniton = NASoniton { bits: 16, be: false, packed: false, planar: true, float: false, signed: true }; |
002d2a48 KS |
65 | /// Predefined format for planar 32-bit signed audio. |
66 | pub const SND_S32P_FORMAT: NASoniton = NASoniton { bits: 32, be: false, packed: false, planar: true, float: false, signed: true }; | |
33b5689a | 67 | /// Predefined format for planar 32-bit floating point audio. |
126b7eb8 | 68 | pub const SND_F32P_FORMAT: NASoniton = NASoniton { bits: 32, be: false, packed: false, planar: true, float: true, signed: true }; |
fba6f8e4 KS |
69 | |
70 | impl NASoniton { | |
33b5689a KS |
71 | /// Constructs a new audio format definition using flags like [`SONITON_FLAG_BE`]. |
72 | /// | |
73 | /// [`SONITON_FLAG_BE`]: ./constant.SONITON_FLAG_BE.html | |
9e9a3af1 KS |
74 | pub fn new(bits: u8, flags: u32) -> Self { |
75 | let is_be = (flags & SONITON_FLAG_BE) != 0; | |
76 | let is_pk = (flags & SONITON_FLAG_PACKED) != 0; | |
77 | let is_pl = (flags & SONITON_FLAG_PLANAR) != 0; | |
78 | let is_fl = (flags & SONITON_FLAG_FLOAT) != 0; | |
79 | let is_sg = (flags & SONITON_FLAG_SIGNED) != 0; | |
e243ceb4 | 80 | NASoniton { bits, be: is_be, packed: is_pk, planar: is_pl, float: is_fl, signed: is_sg } |
fba6f8e4 KS |
81 | } |
82 | ||
33b5689a | 83 | /// Returns the number of bits per sample. |
e243ceb4 | 84 | pub fn get_bits(self) -> u8 { self.bits } |
33b5689a | 85 | /// Reports whether the format is big-endian. |
e243ceb4 | 86 | pub fn is_be(self) -> bool { self.be } |
33b5689a | 87 | /// Reports whether the format has packed samples. |
e243ceb4 | 88 | pub fn is_packed(self) -> bool { self.packed } |
33b5689a | 89 | /// Reports whether audio data is planar instead of interleaved. |
e243ceb4 | 90 | pub fn is_planar(self) -> bool { self.planar } |
33b5689a | 91 | /// Reports whether audio samples are in floating point format. |
e243ceb4 | 92 | pub fn is_float(self) -> bool { self.float } |
33b5689a | 93 | /// Reports whether audio samples are signed. |
e243ceb4 | 94 | pub fn is_signed(self) -> bool { self.signed } |
15e41b31 | 95 | |
33b5689a | 96 | /// Returns the amount of bytes needed to store the audio of requested length (in samples). |
e243ceb4 | 97 | pub fn get_audio_size(self, length: u64) -> usize { |
15e41b31 | 98 | if self.packed { |
e243ceb4 | 99 | ((length * u64::from(self.bits) + 7) >> 3) as usize |
15e41b31 | 100 | } else { |
e243ceb4 | 101 | (length * u64::from((self.bits + 7) >> 3)) as usize |
15e41b31 KS |
102 | } |
103 | } | |
11d889bb KS |
104 | |
105 | /// Returns soniton description as a short string. | |
73f0f89f | 106 | pub fn to_short_string(self) -> String { |
11d889bb KS |
107 | let ltype = if self.float { 'f' } else if self.signed { 's' } else { 'u' }; |
108 | let endianness = if self.bits == 8 { "" } else if self.be { "be" } else { "le" }; | |
109 | let planar = if self.planar { "p" } else { "" }; | |
110 | let packed = if self.packed { "x" } else { "" }; | |
111 | format!("{}{}{}{}{}", ltype, self.bits, endianness, planar, packed) | |
112 | } | |
fba6f8e4 KS |
113 | } |
114 | ||
115 | impl fmt::Display for NASoniton { | |
116 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { | |
117 | let fmt = if self.float { "float" } else if self.signed { "int" } else { "uint" }; | |
118 | let end = if self.be { "BE" } else { "LE" }; | |
8ea7e306 | 119 | write!(f, "({} bps, {} planar: {} packed: {} {})", self.bits, end, self.planar, self.packed, fmt) |
fba6f8e4 KS |
120 | } |
121 | } | |
122 | ||
11d889bb | 123 | impl FromStr for NASoniton { |
f49e17fc | 124 | type Err = FormatParseError; |
11d889bb KS |
125 | |
126 | fn from_str(s: &str) -> Result<Self, Self::Err> { | |
127 | match s { | |
128 | "u8" => Ok(NASoniton { bits: 8, be: true, packed: false, planar: false, float: false, signed: false }), | |
129 | "s16be" => Ok(NASoniton { bits: 16, be: true, packed: false, planar: false, float: false, signed: true }), | |
130 | "s16le" => Ok(NASoniton { bits: 16, be: false, packed: false, planar: false, float: false, signed: true }), | |
131 | "s24be" => Ok(NASoniton { bits: 24, be: true, packed: false, planar: false, float: false, signed: true }), | |
132 | "s24le" => Ok(NASoniton { bits: 24, be: false, packed: false, planar: false, float: false, signed: true }), | |
133 | "s32be" => Ok(NASoniton { bits: 32, be: true, packed: false, planar: false, float: false, signed: true }), | |
134 | "s32le" => Ok(NASoniton { bits: 32, be: false, packed: false, planar: false, float: false, signed: true }), | |
135 | "f32be" => Ok(NASoniton { bits: 32, be: true, packed: false, planar: false, float: true, signed: true }), | |
136 | "f32le" => Ok(NASoniton { bits: 32, be: false, packed: false, planar: false, float: true, signed: true }), | |
f49e17fc | 137 | _ => Err(FormatParseError{}), |
11d889bb KS |
138 | } |
139 | } | |
140 | } | |
141 | ||
33b5689a | 142 | /// Known channel types. |
10a00d52 | 143 | #[derive(Debug,Clone,Copy,PartialEq)] |
fba6f8e4 KS |
144 | pub enum NAChannelType { |
145 | C, L, R, Cs, Ls, Rs, Lss, Rss, LFE, Lc, Rc, Lh, Rh, Ch, LFE2, Lw, Rw, Ov, Lhs, Rhs, Chs, Ll, Rl, Cl, Lt, Rt, Lo, Ro | |
146 | } | |
147 | ||
148 | impl NAChannelType { | |
33b5689a | 149 | /// Reports whether this is some center channel. |
e243ceb4 | 150 | pub fn is_center(self) -> bool { |
6f263099 KS |
151 | matches!(self, |
152 | NAChannelType::C | NAChannelType::Ch | | |
153 | NAChannelType::Cl | NAChannelType::Ov | | |
154 | NAChannelType::LFE | NAChannelType::LFE2 | | |
155 | NAChannelType::Cs | NAChannelType::Chs) | |
fba6f8e4 | 156 | } |
33b5689a | 157 | /// Reports whether this is some left channel. |
e243ceb4 | 158 | pub fn is_left(self) -> bool { |
6f263099 KS |
159 | matches!(self, |
160 | NAChannelType::L | NAChannelType::Ls | | |
161 | NAChannelType::Lss | NAChannelType::Lc | | |
162 | NAChannelType::Lh | NAChannelType::Lw | | |
163 | NAChannelType::Lhs | NAChannelType::Ll | | |
164 | NAChannelType::Lt | NAChannelType::Lo) | |
fba6f8e4 | 165 | } |
33b5689a | 166 | /// Reports whether this is some right channel. |
e243ceb4 | 167 | pub fn is_right(self) -> bool { |
6f263099 KS |
168 | matches!(self, |
169 | NAChannelType::R | NAChannelType::Rs | | |
170 | NAChannelType::Rss | NAChannelType::Rc | | |
171 | NAChannelType::Rh | NAChannelType::Rw | | |
172 | NAChannelType::Rhs | NAChannelType::Rl | | |
173 | NAChannelType::Rt | NAChannelType::Ro) | |
fba6f8e4 KS |
174 | } |
175 | } | |
176 | ||
32ce974d | 177 | impl FromStr for NAChannelType { |
f49e17fc | 178 | type Err = FormatParseError; |
32ce974d KS |
179 | |
180 | fn from_str(s: &str) -> Result<Self, Self::Err> { | |
181 | match s { | |
182 | "C" => Ok(NAChannelType::C), | |
183 | "L" => Ok(NAChannelType::L), | |
184 | "R" => Ok(NAChannelType::R), | |
185 | "Cs" => Ok(NAChannelType::Cs), | |
186 | "Ls" => Ok(NAChannelType::Ls), | |
187 | "Rs" => Ok(NAChannelType::Rs), | |
188 | "Lss" => Ok(NAChannelType::Lss), | |
189 | "Rss" => Ok(NAChannelType::Rss), | |
190 | "LFE" => Ok(NAChannelType::LFE), | |
191 | "Lc" => Ok(NAChannelType::Lc), | |
192 | "Rc" => Ok(NAChannelType::Rc), | |
193 | "Lh" => Ok(NAChannelType::Lh), | |
194 | "Rh" => Ok(NAChannelType::Rh), | |
195 | "Ch" => Ok(NAChannelType::Ch), | |
196 | "LFE2" => Ok(NAChannelType::LFE2), | |
197 | "Lw" => Ok(NAChannelType::Lw), | |
198 | "Rw" => Ok(NAChannelType::Rw), | |
199 | "Ov" => Ok(NAChannelType::Ov), | |
200 | "Lhs" => Ok(NAChannelType::Lhs), | |
201 | "Rhs" => Ok(NAChannelType::Rhs), | |
202 | "Chs" => Ok(NAChannelType::Chs), | |
203 | "Ll" => Ok(NAChannelType::Ll), | |
204 | "Rl" => Ok(NAChannelType::Rl), | |
205 | "Cl" => Ok(NAChannelType::Cl), | |
206 | "Lt" => Ok(NAChannelType::Lt), | |
207 | "Rt" => Ok(NAChannelType::Rt), | |
208 | "Lo" => Ok(NAChannelType::Lo), | |
209 | "Ro" => Ok(NAChannelType::Ro), | |
f49e17fc | 210 | _ => Err(FormatParseError{}), |
1a151e53 | 211 | } |
32ce974d KS |
212 | } |
213 | } | |
214 | ||
c4699d66 KS |
215 | impl fmt::Display for NAChannelType { |
216 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { | |
217 | let name = match *self { | |
fba6f8e4 KS |
218 | NAChannelType::C => "C".to_string(), |
219 | NAChannelType::L => "L".to_string(), | |
220 | NAChannelType::R => "R".to_string(), | |
221 | NAChannelType::Cs => "Cs".to_string(), | |
222 | NAChannelType::Ls => "Ls".to_string(), | |
223 | NAChannelType::Rs => "Rs".to_string(), | |
224 | NAChannelType::Lss => "Lss".to_string(), | |
225 | NAChannelType::Rss => "Rss".to_string(), | |
226 | NAChannelType::LFE => "LFE".to_string(), | |
227 | NAChannelType::Lc => "Lc".to_string(), | |
228 | NAChannelType::Rc => "Rc".to_string(), | |
229 | NAChannelType::Lh => "Lh".to_string(), | |
230 | NAChannelType::Rh => "Rh".to_string(), | |
231 | NAChannelType::Ch => "Ch".to_string(), | |
232 | NAChannelType::LFE2 => "LFE2".to_string(), | |
233 | NAChannelType::Lw => "Lw".to_string(), | |
234 | NAChannelType::Rw => "Rw".to_string(), | |
235 | NAChannelType::Ov => "Ov".to_string(), | |
236 | NAChannelType::Lhs => "Lhs".to_string(), | |
237 | NAChannelType::Rhs => "Rhs".to_string(), | |
238 | NAChannelType::Chs => "Chs".to_string(), | |
239 | NAChannelType::Ll => "Ll".to_string(), | |
240 | NAChannelType::Rl => "Rl".to_string(), | |
241 | NAChannelType::Cl => "Cl".to_string(), | |
242 | NAChannelType::Lt => "Lt".to_string(), | |
243 | NAChannelType::Rt => "Rt".to_string(), | |
244 | NAChannelType::Lo => "Lo".to_string(), | |
245 | NAChannelType::Ro => "Ro".to_string(), | |
c4699d66 KS |
246 | }; |
247 | write!(f, "{}", name) | |
fba6f8e4 KS |
248 | } |
249 | } | |
250 | ||
33b5689a KS |
251 | /// Channel map. |
252 | /// | |
253 | /// This is essentially an ordered sequence of channels. | |
e243ceb4 | 254 | #[derive(Clone,Default)] |
fba6f8e4 KS |
255 | pub struct NAChannelMap { |
256 | ids: Vec<NAChannelType>, | |
257 | } | |
258 | ||
62b33487 KS |
259 | const MS_CHANNEL_MAP: [NAChannelType; 11] = [ |
260 | NAChannelType::L, | |
261 | NAChannelType::R, | |
262 | NAChannelType::C, | |
263 | NAChannelType::LFE, | |
264 | NAChannelType::Ls, | |
265 | NAChannelType::Rs, | |
266 | NAChannelType::Lss, | |
267 | NAChannelType::Rss, | |
268 | NAChannelType::Cs, | |
269 | NAChannelType::Lc, | |
270 | NAChannelType::Rc, | |
271 | ]; | |
272 | ||
fba6f8e4 | 273 | impl NAChannelMap { |
33b5689a | 274 | /// Constructs a new `NAChannelMap` instance. |
fba6f8e4 | 275 | pub fn new() -> Self { NAChannelMap { ids: Vec::new() } } |
33b5689a | 276 | /// Adds a new channel to the map. |
fba6f8e4 KS |
277 | pub fn add_channel(&mut self, ch: NAChannelType) { |
278 | self.ids.push(ch); | |
279 | } | |
33b5689a | 280 | /// Adds several channels to the map at once. |
10a00d52 | 281 | pub fn add_channels(&mut self, chs: &[NAChannelType]) { |
e243ceb4 KS |
282 | for e in chs.iter() { |
283 | self.ids.push(*e); | |
10a00d52 KS |
284 | } |
285 | } | |
33b5689a | 286 | /// Returns the total number of channels. |
fba6f8e4 KS |
287 | pub fn num_channels(&self) -> usize { |
288 | self.ids.len() | |
289 | } | |
33b5689a | 290 | /// Reports channel type for a requested index. |
fba6f8e4 KS |
291 | pub fn get_channel(&self, idx: usize) -> NAChannelType { |
292 | self.ids[idx] | |
293 | } | |
33b5689a | 294 | /// Tries to find position of the channel with requested type. |
fba6f8e4 KS |
295 | pub fn find_channel_id(&self, t: NAChannelType) -> Option<u8> { |
296 | for i in 0..self.ids.len() { | |
297 | if self.ids[i] as i32 == t as i32 { return Some(i as u8); } | |
298 | } | |
299 | None | |
300 | } | |
33b5689a | 301 | /// Creates a new `NAChannelMap` using the channel mapping flags from WAVE format. |
62b33487 KS |
302 | pub fn from_ms_mapping(chmap: u32) -> Self { |
303 | let mut cm = NAChannelMap::new(); | |
e243ceb4 | 304 | for (i, ch) in MS_CHANNEL_MAP.iter().enumerate() { |
62b33487 | 305 | if ((chmap >> i) & 1) != 0 { |
e243ceb4 | 306 | cm.add_channel(*ch); |
62b33487 KS |
307 | } |
308 | } | |
309 | cm | |
310 | } | |
fba6f8e4 KS |
311 | } |
312 | ||
32ce974d KS |
313 | impl fmt::Display for NAChannelMap { |
314 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { | |
315 | let mut map = String::new(); | |
316 | for el in self.ids.iter() { | |
e243ceb4 | 317 | if !map.is_empty() { map.push(','); } |
32ce974d KS |
318 | map.push_str(&*el.to_string()); |
319 | } | |
320 | write!(f, "{}", map) | |
321 | } | |
322 | } | |
323 | ||
324 | impl FromStr for NAChannelMap { | |
f49e17fc | 325 | type Err = FormatParseError; |
32ce974d KS |
326 | |
327 | fn from_str(s: &str) -> Result<Self, Self::Err> { | |
328 | let mut chm = NAChannelMap::new(); | |
329 | for tok in s.split(',') { | |
330 | chm.add_channel(NAChannelType::from_str(tok)?); | |
331 | } | |
332 | Ok(chm) | |
333 | } | |
334 | } | |
335 | ||
33b5689a | 336 | /// A list of RGB colour model variants. |
b68ff5ae | 337 | #[derive(Debug,Clone,Copy,PartialEq)] |
fba6f8e4 KS |
338 | pub enum RGBSubmodel { |
339 | RGB, | |
340 | SRGB, | |
341 | } | |
342 | ||
343 | impl fmt::Display for RGBSubmodel { | |
344 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { | |
345 | let name = match *self { | |
346 | RGBSubmodel::RGB => "RGB".to_string(), | |
347 | RGBSubmodel::SRGB => "sRGB".to_string(), | |
348 | }; | |
349 | write!(f, "{}", name) | |
350 | } | |
351 | } | |
352 | ||
33b5689a | 353 | /// A list of YUV colour model variants. |
b68ff5ae | 354 | #[derive(Debug,Clone,Copy,PartialEq)] |
fba6f8e4 KS |
355 | pub enum YUVSubmodel { |
356 | YCbCr, | |
33b5689a | 357 | /// NTSC variant. |
fba6f8e4 | 358 | YIQ, |
33b5689a | 359 | /// The YUV variant used by JPEG. |
fba6f8e4 KS |
360 | YUVJ, |
361 | } | |
362 | ||
363 | impl fmt::Display for YUVSubmodel { | |
364 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { | |
365 | let name = match *self { | |
366 | YUVSubmodel::YCbCr => "YCbCr".to_string(), | |
367 | YUVSubmodel::YIQ => "YIQ".to_string(), | |
368 | YUVSubmodel::YUVJ => "YUVJ".to_string(), | |
369 | }; | |
370 | write!(f, "{}", name) | |
371 | } | |
372 | } | |
373 | ||
33b5689a | 374 | /// A list of known colour models. |
b68ff5ae | 375 | #[derive(Debug, Clone,Copy,PartialEq)] |
fba6f8e4 KS |
376 | pub enum ColorModel { |
377 | RGB(RGBSubmodel), | |
378 | YUV(YUVSubmodel), | |
379 | CMYK, | |
380 | HSV, | |
381 | LAB, | |
382 | XYZ, | |
383 | } | |
384 | ||
385 | impl ColorModel { | |
33b5689a KS |
386 | /// Returns the number of colour model components. |
387 | /// | |
388 | /// The actual image may have more components e.g. alpha component. | |
e243ceb4 KS |
389 | pub fn get_default_components(self) -> usize { |
390 | match self { | |
fba6f8e4 KS |
391 | ColorModel::CMYK => 4, |
392 | _ => 3, | |
393 | } | |
394 | } | |
33b5689a | 395 | /// Reports whether the current colour model is RGB. |
e243ceb4 | 396 | pub fn is_rgb(self) -> bool { |
6f263099 | 397 | matches!(self, ColorModel::RGB(_)) |
386957f1 | 398 | } |
33b5689a | 399 | /// Reports whether the current colour model is YUV. |
e243ceb4 | 400 | pub fn is_yuv(self) -> bool { |
6f263099 | 401 | matches!(self, ColorModel::YUV(_)) |
386957f1 | 402 | } |
33b5689a | 403 | /// Returns short name for the current colour mode. |
e243ceb4 KS |
404 | pub fn get_short_name(self) -> &'static str { |
405 | match self { | |
8efb7386 KS |
406 | ColorModel::RGB(_) => "rgb", |
407 | ColorModel::YUV(_) => "yuv", | |
408 | ColorModel::CMYK => "cmyk", | |
409 | ColorModel::HSV => "hsv", | |
410 | ColorModel::LAB => "lab", | |
411 | ColorModel::XYZ => "xyz", | |
412 | } | |
413 | } | |
fba6f8e4 KS |
414 | } |
415 | ||
416 | impl fmt::Display for ColorModel { | |
417 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { | |
418 | let name = match *self { | |
b7c882c1 KS |
419 | ColorModel::RGB(fmt) => format!("RGB({})", fmt), |
420 | ColorModel::YUV(fmt) => format!("YUV({})", fmt), | |
fba6f8e4 KS |
421 | ColorModel::CMYK => "CMYK".to_string(), |
422 | ColorModel::HSV => "HSV".to_string(), | |
423 | ColorModel::LAB => "LAB".to_string(), | |
424 | ColorModel::XYZ => "XYZ".to_string(), | |
425 | }; | |
426 | write!(f, "{}", name) | |
427 | } | |
428 | } | |
429 | ||
33b5689a KS |
430 | /// Single colourspace component definition. |
431 | /// | |
432 | /// This structure defines how components of a colourspace are subsampled and where and how they are stored. | |
b68ff5ae | 433 | #[derive(Clone,Copy,PartialEq)] |
fba6f8e4 | 434 | pub struct NAPixelChromaton { |
33b5689a | 435 | /// Horizontal subsampling in power of two (e.g. `0` = no subsampling, `1` = only every second value is stored). |
386957f1 | 436 | pub h_ss: u8, |
33b5689a | 437 | /// Vertial subsampling in power of two (e.g. `0` = no subsampling, `1` = only every second value is stored). |
386957f1 | 438 | pub v_ss: u8, |
33b5689a | 439 | /// A flag to signal that component is packed. |
386957f1 | 440 | pub packed: bool, |
33b5689a | 441 | /// Bit depth of current component. |
386957f1 | 442 | pub depth: u8, |
33b5689a | 443 | /// Shift for packed components. |
386957f1 | 444 | pub shift: u8, |
33b5689a | 445 | /// Component offset for byte-packed components. |
386957f1 | 446 | pub comp_offs: u8, |
33b5689a | 447 | /// The distance to the next packed element in bytes. |
386957f1 | 448 | pub next_elem: u8, |
fba6f8e4 KS |
449 | } |
450 | ||
33b5689a KS |
451 | /// Flag for specifying that image data is stored big-endian in `NAPixelFormaton::`[`new`]`()`. Related to its [`be`] field. |
452 | /// | |
453 | /// [`new`]: ./struct.NAPixelFormaton.html#method.new | |
454 | /// [`be`]: ./struct.NAPixelFormaton.html#structfield.new | |
9e9a3af1 | 455 | pub const FORMATON_FLAG_BE :u32 = 0x01; |
33b5689a KS |
456 | /// Flag for specifying that image data has alpha plane in `NAPixelFormaton::`[`new`]`()`. Related to its [`alpha`] field. |
457 | /// | |
458 | /// [`new`]: ./struct.NAPixelFormaton.html#method.new | |
459 | /// [`alpha`]: ./struct.NAPixelFormaton.html#structfield.alpha | |
9e9a3af1 | 460 | pub const FORMATON_FLAG_ALPHA :u32 = 0x02; |
33b5689a KS |
461 | /// Flag for specifying that image data is stored in paletted form for `NAPixelFormaton::`[`new`]`()`. Related to its [`palette`] field. |
462 | /// | |
463 | /// [`new`]: ./struct.NAPixelFormaton.html#method.new | |
464 | /// [`palette`]: ./struct.NAPixelFormaton.html#structfield.palette | |
9e9a3af1 | 465 | pub const FORMATON_FLAG_PALETTE :u32 = 0x04; |
fba6f8e4 | 466 | |
33b5689a | 467 | /// The current limit on number of components in image colourspace model (including alpha component). |
8efb7386 | 468 | pub const MAX_CHROMATONS: usize = 5; |
fba6f8e4 | 469 | |
33b5689a KS |
470 | /// Image colourspace representation. |
471 | /// | |
472 | /// This structure includes both definitions for each component and some common definitions. | |
473 | /// For example the format can be paletted and then components describe the palette storage format while actual data is 8-bit palette indices. | |
b68ff5ae | 474 | #[derive(Clone,Copy,PartialEq)] |
fba6f8e4 | 475 | pub struct NAPixelFormaton { |
33b5689a | 476 | /// Image colour model. |
386957f1 | 477 | pub model: ColorModel, |
33b5689a | 478 | /// Actual number of components present. |
386957f1 | 479 | pub components: u8, |
33b5689a | 480 | /// Format definition for each component. |
8efb7386 | 481 | pub comp_info: [Option<NAPixelChromaton>; MAX_CHROMATONS], |
33b5689a | 482 | /// Single pixel size for packed formats. |
386957f1 | 483 | pub elem_size: u8, |
33b5689a | 484 | /// A flag signalling that data is stored as big-endian. |
386957f1 | 485 | pub be: bool, |
33b5689a | 486 | /// A flag signalling that image has alpha component. |
386957f1 | 487 | pub alpha: bool, |
33b5689a KS |
488 | /// A flag signalling that data is paletted. |
489 | /// | |
490 | /// This means that image data is stored as 8-bit indices (in the first image component) for the palette stored as second component of the image and actual palette format is described in this structure. | |
386957f1 | 491 | pub palette: bool, |
fba6f8e4 KS |
492 | } |
493 | ||
494 | macro_rules! chromaton { | |
495 | ($hs: expr, $vs: expr, $pck: expr, $d: expr, $sh: expr, $co: expr, $ne: expr) => ({ | |
496 | Some(NAPixelChromaton{ h_ss: $hs, v_ss: $vs, packed: $pck, depth: $d, shift: $sh, comp_offs: $co, next_elem: $ne }) | |
497 | }); | |
498 | (yuv8; $hs: expr, $vs: expr, $co: expr) => ({ | |
499 | Some(NAPixelChromaton{ h_ss: $hs, v_ss: $vs, packed: false, depth: 8, shift: 0, comp_offs: $co, next_elem: 1 }) | |
500 | }); | |
501 | (packrgb; $d: expr, $s: expr, $co: expr, $ne: expr) => ({ | |
502 | Some(NAPixelChromaton{ h_ss: 0, v_ss: 0, packed: true, depth: $d, shift: $s, comp_offs: $co, next_elem: $ne }) | |
503 | }); | |
504 | (pal8; $co: expr) => ({ | |
505 | Some(NAPixelChromaton{ h_ss: 0, v_ss: 0, packed: true, depth: 8, shift: 0, comp_offs: $co, next_elem: 3 }) | |
506 | }); | |
507 | } | |
508 | ||
33b5689a | 509 | /// Predefined format for planar 8-bit YUV with 4:2:0 subsampling. |
fba6f8e4 KS |
510 | pub const YUV420_FORMAT: NAPixelFormaton = NAPixelFormaton { model: ColorModel::YUV(YUVSubmodel::YUVJ), components: 3, |
511 | comp_info: [ | |
512 | chromaton!(0, 0, false, 8, 0, 0, 1), | |
513 | chromaton!(yuv8; 1, 1, 1), | |
514 | chromaton!(yuv8; 1, 1, 2), | |
515 | None, None], | |
516 | elem_size: 0, be: false, alpha: false, palette: false }; | |
517 | ||
33b5689a | 518 | /// Predefined format for planar 8-bit YUV with 4:1:0 subsampling. |
b68ff5ae KS |
519 | pub const YUV410_FORMAT: NAPixelFormaton = NAPixelFormaton { model: ColorModel::YUV(YUVSubmodel::YUVJ), components: 3, |
520 | comp_info: [ | |
521 | chromaton!(0, 0, false, 8, 0, 0, 1), | |
522 | chromaton!(yuv8; 2, 2, 1), | |
523 | chromaton!(yuv8; 2, 2, 2), | |
524 | None, None], | |
525 | elem_size: 0, be: false, alpha: false, palette: false }; | |
33b5689a | 526 | /// Predefined format for planar 8-bit YUV with 4:1:0 subsampling and alpha component. |
a2a9732a KS |
527 | pub const YUVA410_FORMAT: NAPixelFormaton = NAPixelFormaton { model: ColorModel::YUV(YUVSubmodel::YUVJ), components: 4, |
528 | comp_info: [ | |
529 | chromaton!(0, 0, false, 8, 0, 0, 1), | |
530 | chromaton!(yuv8; 2, 2, 1), | |
531 | chromaton!(yuv8; 2, 2, 2), | |
532 | chromaton!(0, 0, false, 8, 0, 3, 1), | |
533 | None], | |
534 | elem_size: 0, be: false, alpha: true, palette: false }; | |
b68ff5ae | 535 | |
33b5689a | 536 | /// Predefined format with RGB24 palette. |
fba6f8e4 KS |
537 | pub const PAL8_FORMAT: NAPixelFormaton = NAPixelFormaton { model: ColorModel::RGB(RGBSubmodel::RGB), components: 3, |
538 | comp_info: [ | |
539 | chromaton!(pal8; 0), | |
540 | chromaton!(pal8; 1), | |
541 | chromaton!(pal8; 2), | |
542 | None, None], | |
543 | elem_size: 3, be: false, alpha: false, palette: true }; | |
544 | ||
33b5689a | 545 | /// Predefined format for RGB565 packed video. |
fba6f8e4 KS |
546 | pub const RGB565_FORMAT: NAPixelFormaton = NAPixelFormaton { model: ColorModel::RGB(RGBSubmodel::RGB), components: 3, |
547 | comp_info: [ | |
548 | chromaton!(packrgb; 5, 11, 0, 2), | |
549 | chromaton!(packrgb; 6, 5, 0, 2), | |
550 | chromaton!(packrgb; 5, 0, 0, 2), | |
551 | None, None], | |
552 | elem_size: 2, be: false, alpha: false, palette: false }; | |
553 | ||
33b5689a | 554 | /// Predefined format for RGB24. |
653e5afd KS |
555 | pub const RGB24_FORMAT: NAPixelFormaton = NAPixelFormaton { model: ColorModel::RGB(RGBSubmodel::RGB), components: 3, |
556 | comp_info: [ | |
653e5afd | 557 | chromaton!(packrgb; 8, 0, 0, 3), |
c6297d1f KS |
558 | chromaton!(packrgb; 8, 0, 1, 3), |
559 | chromaton!(packrgb; 8, 0, 2, 3), | |
653e5afd KS |
560 | None, None], |
561 | elem_size: 3, be: false, alpha: false, palette: false }; | |
562 | ||
fba6f8e4 | 563 | impl NAPixelChromaton { |
33b5689a | 564 | /// Constructs a new `NAPixelChromaton` instance. |
0cc09358 KS |
565 | pub fn new(h_ss: u8, v_ss: u8, packed: bool, depth: u8, shift: u8, comp_offs: u8, next_elem: u8) -> Self { |
566 | Self { h_ss, v_ss, packed, depth, shift, comp_offs, next_elem } | |
567 | } | |
33b5689a | 568 | /// Returns subsampling for the current component. |
e243ceb4 | 569 | pub fn get_subsampling(self) -> (u8, u8) { (self.h_ss, self.v_ss) } |
33b5689a | 570 | /// Reports whether current component is packed. |
e243ceb4 | 571 | pub fn is_packed(self) -> bool { self.packed } |
33b5689a | 572 | /// Returns bit depth of current component. |
e243ceb4 | 573 | pub fn get_depth(self) -> u8 { self.depth } |
33b5689a | 574 | /// Returns bit shift for packed component. |
e243ceb4 | 575 | pub fn get_shift(self) -> u8 { self.shift } |
33b5689a | 576 | /// Returns byte offset for packed component. |
e243ceb4 | 577 | pub fn get_offset(self) -> u8 { self.comp_offs } |
33b5689a | 578 | /// Returns byte offset to the next element of current packed component. |
e243ceb4 | 579 | pub fn get_step(self) -> u8 { self.next_elem } |
b68ff5ae | 580 | |
33b5689a | 581 | /// Calculates the width for current component from general image width. |
e243ceb4 | 582 | pub fn get_width(self, width: usize) -> usize { |
15e41b31 KS |
583 | (width + ((1 << self.h_ss) - 1)) >> self.h_ss |
584 | } | |
33b5689a | 585 | /// Calculates the height for current component from general image height. |
e243ceb4 | 586 | pub fn get_height(self, height: usize) -> usize { |
15e41b31 KS |
587 | (height + ((1 << self.v_ss) - 1)) >> self.v_ss |
588 | } | |
33b5689a | 589 | /// Calculates the minimal stride for current component from general image width. |
e243ceb4 | 590 | pub fn get_linesize(self, width: usize) -> usize { |
b68ff5ae | 591 | let d = self.depth as usize; |
6c8e5c40 KS |
592 | if self.packed { |
593 | (self.get_width(width) * d + d - 1) >> 3 | |
594 | } else { | |
595 | self.get_width(width) | |
596 | } | |
b68ff5ae | 597 | } |
33b5689a | 598 | /// Calculates the required image size in pixels for current component from general image width. |
e243ceb4 | 599 | pub fn get_data_size(self, width: usize, height: usize) -> usize { |
b68ff5ae KS |
600 | let nh = (height + ((1 << self.v_ss) - 1)) >> self.v_ss; |
601 | self.get_linesize(width) * nh | |
602 | } | |
fba6f8e4 KS |
603 | } |
604 | ||
605 | impl fmt::Display for NAPixelChromaton { | |
606 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { | |
607 | let pfmt = if self.packed { | |
608 | let mask = ((1 << self.depth) - 1) << self.shift; | |
609 | format!("packed(+{},{:X}, step {})", self.comp_offs, mask, self.next_elem) | |
610 | } else { | |
611 | format!("planar({},{})", self.comp_offs, self.next_elem) | |
612 | }; | |
613 | write!(f, "({}x{}, {})", self.h_ss, self.v_ss, pfmt) | |
614 | } | |
615 | } | |
616 | ||
617 | impl NAPixelFormaton { | |
33b5689a | 618 | /// Constructs a new instance of `NAPixelFormaton`. |
fba6f8e4 KS |
619 | pub fn new(model: ColorModel, |
620 | comp1: Option<NAPixelChromaton>, | |
621 | comp2: Option<NAPixelChromaton>, | |
622 | comp3: Option<NAPixelChromaton>, | |
623 | comp4: Option<NAPixelChromaton>, | |
624 | comp5: Option<NAPixelChromaton>, | |
9e9a3af1 | 625 | flags: u32, elem_size: u8) -> Self { |
8efb7386 | 626 | let mut chromatons: [Option<NAPixelChromaton>; MAX_CHROMATONS] = [None; MAX_CHROMATONS]; |
fba6f8e4 | 627 | let mut ncomp = 0; |
9e9a3af1 KS |
628 | let be = (flags & FORMATON_FLAG_BE) != 0; |
629 | let alpha = (flags & FORMATON_FLAG_ALPHA) != 0; | |
630 | let palette = (flags & FORMATON_FLAG_PALETTE) != 0; | |
fba6f8e4 KS |
631 | if let Some(c) = comp1 { chromatons[0] = Some(c); ncomp += 1; } |
632 | if let Some(c) = comp2 { chromatons[1] = Some(c); ncomp += 1; } | |
633 | if let Some(c) = comp3 { chromatons[2] = Some(c); ncomp += 1; } | |
634 | if let Some(c) = comp4 { chromatons[3] = Some(c); ncomp += 1; } | |
635 | if let Some(c) = comp5 { chromatons[4] = Some(c); ncomp += 1; } | |
e243ceb4 | 636 | NAPixelFormaton { model, |
fba6f8e4 KS |
637 | components: ncomp, |
638 | comp_info: chromatons, | |
e243ceb4 KS |
639 | elem_size, |
640 | be, alpha, palette } | |
fba6f8e4 KS |
641 | } |
642 | ||
33b5689a | 643 | /// Returns current colour model. |
fba6f8e4 | 644 | pub fn get_model(&self) -> ColorModel { self.model } |
33b5689a | 645 | /// Returns the number of components. |
b68ff5ae | 646 | pub fn get_num_comp(&self) -> usize { self.components as usize } |
33b5689a | 647 | /// Returns selected component information. |
fba6f8e4 KS |
648 | pub fn get_chromaton(&self, idx: usize) -> Option<NAPixelChromaton> { |
649 | if idx < self.comp_info.len() { return self.comp_info[idx]; } | |
650 | None | |
651 | } | |
33b5689a | 652 | /// Reports whether the packing format is big-endian. |
e243ceb4 | 653 | pub fn is_be(self) -> bool { self.be } |
33b5689a | 654 | /// Reports whether colourspace has alpha component. |
e243ceb4 | 655 | pub fn has_alpha(self) -> bool { self.alpha } |
33b5689a | 656 | /// Reports whether this is paletted format. |
e243ceb4 | 657 | pub fn is_paletted(self) -> bool { self.palette } |
33b5689a | 658 | /// Returns single packed pixel size. |
e243ceb4 | 659 | pub fn get_elem_size(self) -> u8 { self.elem_size } |
33b5689a | 660 | /// Reports whether the format is not packed. |
8efb7386 | 661 | pub fn is_unpacked(&self) -> bool { |
c7d8d948 | 662 | if self.palette { return false; } |
8efb7386 KS |
663 | for chr in self.comp_info.iter() { |
664 | if let Some(ref chromaton) = chr { | |
665 | if chromaton.is_packed() { return false; } | |
666 | } | |
667 | } | |
668 | true | |
669 | } | |
33b5689a | 670 | /// Returns the maximum component bit depth. |
8efb7386 KS |
671 | pub fn get_max_depth(&self) -> u8 { |
672 | let mut mdepth = 0; | |
673 | for chr in self.comp_info.iter() { | |
674 | if let Some(ref chromaton) = chr { | |
675 | mdepth = mdepth.max(chromaton.depth); | |
676 | } | |
677 | } | |
678 | mdepth | |
679 | } | |
8b746bf7 KS |
680 | /// Returns the total amount of bits needed for components. |
681 | pub fn get_total_depth(&self) -> u8 { | |
682 | let mut depth = 0; | |
683 | for chr in self.comp_info.iter() { | |
684 | if let Some(ref chromaton) = chr { | |
685 | depth += chromaton.depth; | |
686 | } | |
687 | } | |
688 | depth | |
689 | } | |
33b5689a | 690 | /// Returns the maximum component subsampling. |
8efb7386 KS |
691 | pub fn get_max_subsampling(&self) -> u8 { |
692 | let mut ssamp = 0; | |
693 | for chr in self.comp_info.iter() { | |
694 | if let Some(ref chromaton) = chr { | |
695 | let (ss_v, ss_h) = chromaton.get_subsampling(); | |
696 | ssamp = ssamp.max(ss_v).max(ss_h); | |
697 | } | |
698 | } | |
699 | ssamp | |
700 | } | |
b7c882c1 | 701 | #[allow(clippy::cognitive_complexity)] |
00eac62b KS |
702 | /// Returns a short string description of the format if possible. |
703 | pub fn to_short_string(&self) -> Option<String> { | |
704 | match self.model { | |
705 | ColorModel::RGB(_) => { | |
706 | if self.is_paletted() { | |
707 | if *self == PAL8_FORMAT { | |
708 | return Some("pal8".to_string()); | |
709 | } else { | |
710 | return None; | |
711 | } | |
712 | } | |
713 | let mut name = [b'z'; 4]; | |
714 | let planar = self.is_unpacked(); | |
715 | ||
716 | let mut start_off = 0; | |
717 | let mut start_shift = 0; | |
718 | let mut use_shift = true; | |
719 | for comp in self.comp_info.iter() { | |
720 | if let Some(comp) = comp { | |
721 | start_off = start_off.min(comp.comp_offs); | |
722 | start_shift = start_shift.min(comp.shift); | |
723 | if comp.comp_offs != 0 { use_shift = false; } | |
724 | } | |
725 | } | |
726 | for component in 0..(self.components as usize) { | |
727 | for (comp, cname) in self.comp_info.iter().zip(b"rgba".iter()) { | |
728 | if let Some(comp) = comp { | |
729 | if use_shift { | |
730 | if comp.shift == start_shift { | |
731 | name[component] = *cname; | |
732 | start_shift += comp.depth; | |
733 | } | |
734 | } else if comp.comp_offs == start_off { | |
735 | name[component] = *cname; | |
736 | if planar { | |
737 | start_off += 1; | |
738 | } else { | |
739 | start_off += (comp.depth + 7) / 8; | |
740 | } | |
741 | } | |
742 | } | |
743 | } | |
744 | } | |
745 | ||
746 | for (comp, cname) in self.comp_info.iter().zip(b"rgba".iter()) { | |
747 | if let Some(comp) = comp { | |
748 | name[comp.comp_offs as usize] = *cname; | |
749 | } else { | |
750 | break; | |
751 | } | |
752 | } | |
753 | let mut name = String::from_utf8(name[..self.components as usize].to_vec()).unwrap(); | |
754 | let depth = self.get_total_depth(); | |
755 | if depth == 15 || depth == 16 { | |
756 | for c in self.comp_info.iter() { | |
757 | if let Some(comp) = c { | |
758 | name.push((b'0' + comp.depth) as char); | |
759 | } else { | |
760 | break; | |
761 | } | |
762 | } | |
237cc1f9 | 763 | name += if self.be { "be" } else { "le" }; |
00eac62b KS |
764 | return Some(name); |
765 | } | |
766 | if depth == 24 || depth != 8 * self.components { | |
767 | name += depth.to_string().as_str(); | |
768 | } | |
769 | if planar { | |
770 | name.push('p'); | |
771 | } | |
772 | if self.get_max_depth() > 8 { | |
237cc1f9 | 773 | name += if self.be { "be" } else { "le" }; |
00eac62b KS |
774 | } |
775 | Some(name) | |
776 | }, | |
777 | ColorModel::YUV(_) => { | |
778 | let max_depth = self.get_max_depth(); | |
779 | if self.get_total_depth() != max_depth * self.components { | |
780 | return None; | |
781 | } | |
782 | if self.components < 3 { | |
783 | if self.components == 1 && max_depth == 8 { | |
784 | return Some("y8".to_string()); | |
785 | } | |
786 | if self.components == 2 && self.alpha && max_depth == 8 { | |
787 | return Some("y8a".to_string()); | |
788 | } | |
789 | return None; | |
790 | } | |
791 | let cu = self.comp_info[1].unwrap(); | |
792 | let cv = self.comp_info[2].unwrap(); | |
793 | if cu.h_ss != cv.h_ss || cu.v_ss != cv.v_ss || cu.h_ss > 2 || cu.v_ss > 2 { | |
794 | return None; | |
795 | } | |
796 | let mut name = "yuv".to_string(); | |
797 | if self.alpha { | |
798 | name.push('a'); | |
799 | } | |
800 | name.push('4'); | |
801 | let sch = b"421"[cu.h_ss as usize]; | |
802 | let tch = if cu.v_ss > 1 { b'0' } else { sch }; | |
803 | name.push(sch as char); | |
804 | name.push(tch as char); | |
805 | if self.is_unpacked() { | |
806 | name.push('p'); | |
807 | } | |
808 | if max_depth != 8 { | |
809 | name += max_depth.to_string().as_str(); | |
810 | } | |
811 | Some(name) | |
812 | }, | |
813 | _ => None, | |
814 | } | |
815 | } | |
fba6f8e4 KS |
816 | } |
817 | ||
818 | impl fmt::Display for NAPixelFormaton { | |
819 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { | |
820 | let end = if self.be { "BE" } else { "LE" }; | |
821 | let palstr = if self.palette { "palette " } else { "" }; | |
822 | let astr = if self.alpha { "alpha " } else { "" }; | |
823 | let mut str = format!("Formaton for {} ({}{}elem {} size {}): ", self.model, palstr, astr,end, self.elem_size); | |
824 | for i in 0..self.comp_info.len() { | |
825 | if let Some(chr) = self.comp_info[i] { | |
826 | str = format!("{} {}", str, chr); | |
827 | } | |
828 | } | |
829 | write!(f, "[{}]", str) | |
830 | } | |
831 | } | |
832 | ||
00eac62b KS |
833 | fn parse_rgb_format(s: &str) -> Result<NAPixelFormaton, FormatParseError> { |
834 | let mut order = [0; 4]; | |
835 | let mut is_be = s.ends_with("be"); | |
836 | let mut has_alpha = false; | |
837 | let mut pstate = 0; | |
838 | let mut bits = 0; | |
839 | let mut bits_start = 0; | |
840 | for (i, ch) in s.chars().enumerate() { | |
841 | match pstate { | |
842 | 0 => { | |
843 | if i > 4 { return Err(FormatParseError {}); } | |
844 | match ch { | |
845 | 'R' | 'r' => { order[0] = i; }, | |
846 | 'G' | 'g' => { order[1] = i; }, | |
847 | 'B' | 'b' => { order[2] = i; }, | |
848 | 'A' | 'a' => { order[3] = i; has_alpha = true; }, | |
849 | '0'..='9' => { | |
850 | pstate = 1; bits_start = i; | |
73f0f89f | 851 | bits = u32::from((ch as u8) - b'0'); |
00eac62b KS |
852 | }, |
853 | _ => return Err(FormatParseError {}), | |
854 | }; | |
855 | }, | |
856 | 1 => { | |
857 | if i > 4 + bits_start { return Err(FormatParseError {}); } | |
858 | match ch { | |
859 | '0'..='9' => { | |
73f0f89f | 860 | bits = (bits * 10) + u32::from((ch as u8) - b'0'); |
00eac62b KS |
861 | }, |
862 | 'B' | 'b' => { pstate = 2; } | |
863 | 'L' | 'l' => { pstate = 2; is_be = false; } | |
864 | _ => return Err(FormatParseError {}), | |
865 | } | |
866 | }, | |
867 | 2 => { | |
868 | if ch != 'e' && ch != 'E' { return Err(FormatParseError {}); } | |
869 | pstate = 3; | |
870 | }, | |
871 | _ => return Err(FormatParseError {}), | |
872 | }; | |
873 | } | |
874 | let components: u8 = if has_alpha { 4 } else { 3 }; | |
875 | for el in order.iter() { | |
876 | if *el >= (components as usize) { | |
877 | return Err(FormatParseError {}); | |
878 | } | |
879 | } | |
880 | if order[0] == order[1] || order[0] == order[2] || order[1] == order[2] { | |
881 | return Err(FormatParseError {}); | |
882 | } | |
883 | if has_alpha && order[0..3].contains(&order[3]) { | |
884 | return Err(FormatParseError {}); | |
885 | } | |
886 | let mut chromatons = [None; 5]; | |
887 | let elem_size = match bits { | |
888 | 0 | 24 => { | |
889 | for (chro, ord) in chromatons.iter_mut().take(components as usize).zip(order.iter()) { | |
890 | *chro = Some(NAPixelChromaton { h_ss: 0, v_ss: 0, packed: true, depth: 8, shift: 0, comp_offs: *ord as u8, next_elem: components }); | |
891 | } | |
892 | components | |
893 | }, | |
894 | 555 => { | |
895 | let rshift = (order[0] * 5) as u8; | |
896 | let gshift = (order[1] * 5) as u8; | |
897 | let bshift = (order[2] * 5) as u8; | |
898 | chromatons[0] = Some(NAPixelChromaton { h_ss: 0, v_ss: 0, packed: true, depth: 5, shift: rshift, comp_offs: 0, next_elem: 2 }); | |
899 | chromatons[1] = Some(NAPixelChromaton { h_ss: 0, v_ss: 0, packed: true, depth: 5, shift: gshift, comp_offs: 0, next_elem: 2 }); | |
900 | chromatons[2] = Some(NAPixelChromaton { h_ss: 0, v_ss: 0, packed: true, depth: 5, shift: bshift, comp_offs: 0, next_elem: 2 }); | |
901 | if has_alpha { return Err(FormatParseError {}); } | |
902 | 2 | |
903 | }, | |
904 | 565 => { | |
905 | let mut offs = [0; 3]; | |
906 | for (ord, off) in order.iter().zip(offs.iter_mut()) { | |
907 | *off = (*ord * 5) as u8; | |
908 | } | |
909 | match order[1] { | |
910 | 0 => { offs[0] += 1; offs[2] += 1; }, | |
911 | 1 => { for el in offs.iter_mut() { if *el == 10 { *el += 1; break; } } }, | |
912 | _ => {}, | |
913 | }; | |
914 | chromatons[0] = Some(NAPixelChromaton { h_ss: 0, v_ss: 0, packed: true, depth: 5, shift: offs[0], comp_offs: 0, next_elem: 2 }); | |
915 | chromatons[1] = Some(NAPixelChromaton { h_ss: 0, v_ss: 0, packed: true, depth: 6, shift: offs[1], comp_offs: 0, next_elem: 2 }); | |
916 | chromatons[2] = Some(NAPixelChromaton { h_ss: 0, v_ss: 0, packed: true, depth: 5, shift: offs[2], comp_offs: 0, next_elem: 2 }); | |
917 | if has_alpha { return Err(FormatParseError {}); } | |
918 | 2 | |
919 | }, | |
920 | 5551 => { | |
921 | let mut offs = [0; 4]; | |
922 | let depth = [ 5, 5, 5, 1 ]; | |
923 | let mut cur_off = 0; | |
924 | for comp in 0..4 { | |
925 | for (off, ord) in offs.iter_mut().zip(order.iter()) { | |
926 | if *ord == comp { | |
927 | *off = cur_off; | |
928 | cur_off += depth[comp]; | |
929 | break; | |
930 | } | |
931 | } | |
932 | } | |
933 | chromatons[0] = Some(NAPixelChromaton { h_ss: 0, v_ss: 0, packed: true, depth: 5, shift: offs[0], comp_offs: 0, next_elem: 2 }); | |
934 | chromatons[1] = Some(NAPixelChromaton { h_ss: 0, v_ss: 0, packed: true, depth: 5, shift: offs[1], comp_offs: 0, next_elem: 2 }); | |
935 | chromatons[2] = Some(NAPixelChromaton { h_ss: 0, v_ss: 0, packed: true, depth: 5, shift: offs[2], comp_offs: 0, next_elem: 2 }); | |
936 | chromatons[3] = Some(NAPixelChromaton { h_ss: 0, v_ss: 0, packed: true, depth: 1, shift: offs[3], comp_offs: 0, next_elem: 2 }); | |
937 | if !has_alpha { return Err(FormatParseError {}); } | |
938 | 2 | |
939 | }, | |
940 | _ => return Err(FormatParseError {}), | |
941 | }; | |
942 | Ok(NAPixelFormaton { model: ColorModel::RGB(RGBSubmodel::RGB), | |
943 | components, | |
944 | comp_info: chromatons, | |
945 | elem_size, | |
946 | be: is_be, alpha: has_alpha, palette: false }) | |
947 | } | |
948 | ||
949 | fn parse_yuv_format(s: &str) -> Result<NAPixelFormaton, FormatParseError> { | |
950 | match s { | |
951 | "y8" | "y400" | "gray" => { | |
952 | return Ok(NAPixelFormaton { | |
953 | model: ColorModel::YUV(YUVSubmodel::YUVJ), components: 1, | |
954 | comp_info: [ | |
c031f98d | 955 | Some(NAPixelChromaton{ h_ss: 0, v_ss: 0, packed: false, depth: 8, shift: 0, comp_offs: 0, next_elem: 1 }), |
00eac62b | 956 | None, None, None, None], |
c031f98d | 957 | elem_size: 1, be: true, alpha: false, palette: false }); |
00eac62b KS |
958 | }, |
959 | "y8a" | "y400a" | "graya" => { | |
960 | return Ok(NAPixelFormaton { | |
961 | model: ColorModel::YUV(YUVSubmodel::YUVJ), components: 2, | |
962 | comp_info: [ | |
c031f98d KS |
963 | Some(NAPixelChromaton{ h_ss: 0, v_ss: 0, packed: false, depth: 8, shift: 0, comp_offs: 0, next_elem: 2 }), |
964 | Some(NAPixelChromaton{ h_ss: 0, v_ss: 0, packed: false, depth: 8, shift: 0, comp_offs: 1, next_elem: 2 }), | |
00eac62b | 965 | None, None, None], |
c031f98d | 966 | elem_size: 1, be: true, alpha: true, palette: false }); |
00eac62b KS |
967 | }, |
968 | "uyvy" | "y422" => { | |
969 | return Ok(NAPixelFormaton { | |
970 | model: ColorModel::YUV(YUVSubmodel::YUVJ), components: 3, | |
971 | comp_info: [ | |
972 | Some(NAPixelChromaton{ h_ss: 0, v_ss: 0, packed: true, depth: 8, shift: 0, comp_offs: 1, next_elem: 2 }), | |
973 | Some(NAPixelChromaton{ h_ss: 1, v_ss: 0, packed: true, depth: 8, shift: 0, comp_offs: 0, next_elem: 4 }), | |
974 | Some(NAPixelChromaton{ h_ss: 1, v_ss: 0, packed: true, depth: 8, shift: 0, comp_offs: 2, next_elem: 4 }), | |
975 | None, None], | |
976 | elem_size: 4, be: false, alpha: false, palette: false }); | |
977 | }, | |
978 | "yuy2" | "yuyv" | "v422" => { | |
979 | return Ok(NAPixelFormaton { | |
980 | model: ColorModel::YUV(YUVSubmodel::YUVJ), components: 3, | |
981 | comp_info: [ | |
982 | Some(NAPixelChromaton{ h_ss: 0, v_ss: 0, packed: true, depth: 8, shift: 0, comp_offs: 0, next_elem: 2 }), | |
983 | Some(NAPixelChromaton{ h_ss: 1, v_ss: 0, packed: true, depth: 8, shift: 0, comp_offs: 1, next_elem: 4 }), | |
984 | Some(NAPixelChromaton{ h_ss: 1, v_ss: 0, packed: true, depth: 8, shift: 0, comp_offs: 3, next_elem: 4 }), | |
985 | None, None], | |
986 | elem_size: 4, be: false, alpha: false, palette: false }); | |
987 | }, | |
988 | "yvyu" => { | |
989 | return Ok(NAPixelFormaton { | |
990 | model: ColorModel::YUV(YUVSubmodel::YUVJ), components: 3, | |
991 | comp_info: [ | |
992 | Some(NAPixelChromaton{ h_ss: 0, v_ss: 0, packed: true, depth: 8, shift: 0, comp_offs: 0, next_elem: 2 }), | |
993 | Some(NAPixelChromaton{ h_ss: 1, v_ss: 0, packed: true, depth: 8, shift: 0, comp_offs: 3, next_elem: 4 }), | |
994 | Some(NAPixelChromaton{ h_ss: 1, v_ss: 0, packed: true, depth: 8, shift: 0, comp_offs: 1, next_elem: 4 }), | |
995 | None, None], | |
996 | elem_size: 4, be: false, alpha: false, palette: false }); | |
997 | }, | |
998 | "vyuy" => { | |
999 | return Ok(NAPixelFormaton { | |
1000 | model: ColorModel::YUV(YUVSubmodel::YUVJ), components: 3, | |
1001 | comp_info: [ | |
1002 | Some(NAPixelChromaton{ h_ss: 0, v_ss: 0, packed: true, depth: 8, shift: 0, comp_offs: 1, next_elem: 2 }), | |
1003 | Some(NAPixelChromaton{ h_ss: 1, v_ss: 0, packed: true, depth: 8, shift: 0, comp_offs: 2, next_elem: 4 }), | |
1004 | Some(NAPixelChromaton{ h_ss: 1, v_ss: 0, packed: true, depth: 8, shift: 0, comp_offs: 0, next_elem: 4 }), | |
1005 | None, None], | |
1006 | elem_size: 4, be: false, alpha: false, palette: false }); | |
1007 | }, | |
1008 | _ => {}, | |
1009 | }; | |
1010 | if !s.starts_with("yuv") { | |
1011 | return Err(FormatParseError {}); | |
1012 | } | |
1013 | let has_alpha = s.starts_with("yuva"); | |
1014 | let components: u8 = if has_alpha { 4 } else { 3 }; | |
1015 | let mut is_planar = false; | |
1016 | let mut format = 0; | |
1017 | let mut parse_end = components as usize; | |
1018 | for ch in s.chars().skip(components as usize) { | |
1019 | parse_end += 1; | |
6f263099 | 1020 | if ('0'..='9').contains(&ch) { |
73f0f89f | 1021 | format = format * 10 + u32::from((ch as u8) - b'0'); |
00eac62b KS |
1022 | if format > 444 { return Err(FormatParseError {}); } |
1023 | } else { | |
1024 | is_planar = ch == 'p'; | |
1025 | break; | |
1026 | } | |
1027 | } | |
1028 | if format == 0 { return Err(FormatParseError {}); } | |
1029 | let depth = if s.len() == parse_end { 8 } else { | |
1030 | let mut val = 0; | |
1031 | for ch in s.chars().skip(parse_end) { | |
6f263099 | 1032 | if ('0'..='9').contains(&ch) { |
00eac62b KS |
1033 | val = val * 10 + ((ch as u8) - b'0'); |
1034 | if val > 16 { return Err(FormatParseError {}); } | |
1035 | } else { | |
1036 | break; | |
1037 | } | |
1038 | } | |
1039 | val | |
1040 | }; | |
1041 | if depth == 0 { return Err(FormatParseError {}); } | |
1042 | let is_be = s.ends_with("be"); | |
1043 | ||
1044 | let mut chromatons = [None; 5]; | |
1045 | let next_elem = if is_planar { (depth + 7) >> 3 } else { | |
1046 | components * ((depth + 7) >> 3) }; | |
1047 | let subsamp: [[u8; 2]; 4] = match format { | |
1048 | 410 => [[0, 0], [2, 2], [2, 2], [0, 0]], | |
1049 | 411 => [[0, 0], [2, 0], [2, 0], [0, 0]], | |
1050 | 420 => [[0, 0], [1, 1], [1, 1], [0, 0]], | |
1051 | 422 => [[0, 0], [1, 0], [1, 0], [0, 0]], | |
1052 | 440 => [[0, 0], [0, 1], [0, 1], [0, 0]], | |
1053 | 444 => [[0, 0], [0, 0], [0, 0], [0, 0]], | |
1054 | _ => return Err(FormatParseError {}), | |
1055 | }; | |
9610895f KS |
1056 | for (i, (chro, ss)) in chromatons.iter_mut().take(components as usize).zip(subsamp.iter()).enumerate() { |
1057 | *chro = Some(NAPixelChromaton{ h_ss: ss[0], v_ss: ss[1], packed: !is_planar, depth, shift: 0, comp_offs: if is_planar { i as u8 } else { next_elem }, next_elem }); | |
00eac62b KS |
1058 | } |
1059 | Ok(NAPixelFormaton { model: ColorModel::YUV(YUVSubmodel::YUVJ), | |
1060 | components, | |
1061 | comp_info: chromatons, | |
1062 | elem_size: components, | |
1063 | be: is_be, alpha: has_alpha, palette: false }) | |
1064 | } | |
1065 | ||
1066 | impl FromStr for NAPixelFormaton { | |
1067 | type Err = FormatParseError; | |
1068 | ||
b7c882c1 | 1069 | #[allow(clippy::single_match)] |
00eac62b KS |
1070 | fn from_str(s: &str) -> Result<Self, Self::Err> { |
1071 | match s { | |
1072 | "pal8" => return Ok(PAL8_FORMAT), | |
1073 | _ => {}, | |
1074 | } | |
1075 | let ret = parse_rgb_format(s); | |
1076 | if ret.is_ok() { | |
1077 | return ret; | |
1078 | } | |
1079 | parse_yuv_format(s) | |
1080 | } | |
1081 | } | |
1082 | ||
fba6f8e4 KS |
1083 | #[cfg(test)] |
1084 | mod test { | |
1085 | use super::*; | |
1086 | ||
1087 | #[test] | |
1088 | fn test_fmt() { | |
1089 | println!("{}", SND_S16_FORMAT); | |
1090 | println!("{}", SND_U8_FORMAT); | |
126b7eb8 | 1091 | println!("{}", SND_F32P_FORMAT); |
11d889bb KS |
1092 | assert_eq!(SND_U8_FORMAT.to_short_string(), "u8"); |
1093 | assert_eq!(SND_F32P_FORMAT.to_short_string(), "f32lep"); | |
1094 | let s16fmt = SND_S16_FORMAT.to_short_string(); | |
1095 | assert_eq!(NASoniton::from_str(s16fmt.as_str()).unwrap(), SND_S16_FORMAT); | |
fba6f8e4 KS |
1096 | println!("formaton yuv- {}", YUV420_FORMAT); |
1097 | println!("formaton pal- {}", PAL8_FORMAT); | |
1098 | println!("formaton rgb565- {}", RGB565_FORMAT); | |
00eac62b KS |
1099 | |
1100 | let pfmt = NAPixelFormaton::from_str("rgb24").unwrap(); | |
1101 | assert!(pfmt == RGB24_FORMAT); | |
1102 | let pfmt = "gbra"; | |
1103 | assert_eq!(pfmt, NAPixelFormaton::from_str("gbra").unwrap().to_short_string().unwrap()); | |
1104 | let pfmt = NAPixelFormaton::from_str("yuv420").unwrap(); | |
1105 | println!("parsed pfmt as {} / {:?}", pfmt, pfmt.to_short_string()); | |
1106 | let pfmt = NAPixelFormaton::from_str("yuva420p12").unwrap(); | |
1107 | println!("parsed pfmt as {} / {:?}", pfmt, pfmt.to_short_string()); | |
1108 | ||
1109 | assert_eq!(RGB565_FORMAT.to_short_string().unwrap(), "bgr565le"); | |
1110 | assert_eq!(PAL8_FORMAT.to_short_string().unwrap(), "pal8"); | |
1111 | assert_eq!(YUV420_FORMAT.to_short_string().unwrap(), "yuv422p"); | |
1112 | assert_eq!(YUVA410_FORMAT.to_short_string().unwrap(), "yuva410p"); | |
fba6f8e4 KS |
1113 | } |
1114 | } |