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