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