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