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