176f8d613f32a0fd782ea4569a1076c8343ebee7
[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 /// Audio format definition.
11 ///
12 /// The structure describes how audio samples are stored and what characteristics they have.
13 #[derive(Debug,Copy,Clone,PartialEq)]
14 pub struct NASoniton {
15 /// Bits per sample.
16 pub bits: u8,
17 /// Audio format is big-endian.
18 pub be: bool,
19 /// Audio samples are packed (e.g. 20-bit audio samples).
20 pub packed: bool,
21 /// Audio data is stored in planar format instead of interleaving samples for different channels.
22 pub planar: bool,
23 /// Audio data is in floating point format.
24 pub float: bool,
25 /// Audio data is signed (usually only 8-bit audio is unsigned).
26 pub signed: bool,
27 }
28
29 /// Flag for specifying that audio format is big-endian in `NASoniton::`[`new`]`()`. Related to [`be`] field of `NASoniton`.
30 ///
31 /// [`new`]: ./struct.NASoniton.html#method.new
32 /// [`be`]: ./struct.NASoniton.html#structfield.be
33 pub const SONITON_FLAG_BE :u32 = 0x01;
34 /// Flag for specifying that audio format has packed samples in `NASoniton::`[`new`]`()`. Related to [`packed`] field of `NASoniton`.
35 ///
36 /// [`new`]: ./struct.NASoniton.html#method.new
37 /// [`packed`]: ./struct.NASoniton.html#structfield.packed
38 pub const SONITON_FLAG_PACKED :u32 = 0x02;
39 /// Flag for specifying that audio data is stored as planar in `NASoniton::`[`new`]`()`. Related to [`planar`] field of `NASoniton`.
40 ///
41 /// [`new`]: ./struct.NASoniton.html#method.new
42 /// [`planar`]: ./struct.NASoniton.html#structfield.planar
43 pub const SONITON_FLAG_PLANAR :u32 = 0x04;
44 /// Flag for specifying that audio samples are in floating point format in `NASoniton::`[`new`]`()`. Related to [`float`] field of `NASoniton`.
45 ///
46 /// [`new`]: ./struct.NASoniton.html#method.new
47 /// [`float`]: ./struct.NASoniton.html#structfield.float
48 pub const SONITON_FLAG_FLOAT :u32 = 0x08;
49 /// Flag for specifying that audio format is signed in `NASoniton::`[`new`]`()`. Related to [`signed`] field of `NASoniton`.
50 ///
51 /// [`new`]: ./struct.NASoniton.html#method.new
52 /// [`signed`]: ./struct.NASoniton.html#structfield.signed
53 pub const SONITON_FLAG_SIGNED :u32 = 0x10;
54
55 /// Predefined format for interleaved 8-bit unsigned audio.
56 pub const SND_U8_FORMAT: NASoniton = NASoniton { bits: 8, be: false, packed: false, planar: false, float: false, signed: false };
57 /// Predefined format for interleaved 16-bit signed audio.
58 pub const SND_S16_FORMAT: NASoniton = NASoniton { bits: 16, be: false, packed: false, planar: false, float: false, signed: true };
59 /// Predefined format for planar 16-bit signed audio.
60 pub const SND_S16P_FORMAT: NASoniton = NASoniton { bits: 16, be: false, packed: false, planar: true, float: false, signed: true };
61 /// Predefined format for planar 32-bit floating point audio.
62 pub const SND_F32P_FORMAT: NASoniton = NASoniton { bits: 32, be: false, packed: false, planar: true, float: true, signed: true };
63
64 impl NASoniton {
65 /// Constructs a new audio format definition using flags like [`SONITON_FLAG_BE`].
66 ///
67 /// [`SONITON_FLAG_BE`]: ./constant.SONITON_FLAG_BE.html
68 pub fn new(bits: u8, flags: u32) -> Self {
69 let is_be = (flags & SONITON_FLAG_BE) != 0;
70 let is_pk = (flags & SONITON_FLAG_PACKED) != 0;
71 let is_pl = (flags & SONITON_FLAG_PLANAR) != 0;
72 let is_fl = (flags & SONITON_FLAG_FLOAT) != 0;
73 let is_sg = (flags & SONITON_FLAG_SIGNED) != 0;
74 NASoniton { bits, be: is_be, packed: is_pk, planar: is_pl, float: is_fl, signed: is_sg }
75 }
76
77 /// Returns the number of bits per sample.
78 pub fn get_bits(self) -> u8 { self.bits }
79 /// Reports whether the format is big-endian.
80 pub fn is_be(self) -> bool { self.be }
81 /// Reports whether the format has packed samples.
82 pub fn is_packed(self) -> bool { self.packed }
83 /// Reports whether audio data is planar instead of interleaved.
84 pub fn is_planar(self) -> bool { self.planar }
85 /// Reports whether audio samples are in floating point format.
86 pub fn is_float(self) -> bool { self.float }
87 /// Reports whether audio samples are signed.
88 pub fn is_signed(self) -> bool { self.signed }
89
90 /// Returns the amount of bytes needed to store the audio of requested length (in samples).
91 pub fn get_audio_size(self, length: u64) -> usize {
92 if self.packed {
93 ((length * u64::from(self.bits) + 7) >> 3) as usize
94 } else {
95 (length * u64::from((self.bits + 7) >> 3)) as usize
96 }
97 }
98 }
99
100 impl fmt::Display for NASoniton {
101 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
102 let fmt = if self.float { "float" } else if self.signed { "int" } else { "uint" };
103 let end = if self.be { "BE" } else { "LE" };
104 write!(f, "({} bps, {} planar: {} packed: {} {})", self.bits, end, self.packed, self.planar, fmt)
105 }
106 }
107
108 /// Known channel types.
109 #[derive(Debug,Clone,Copy,PartialEq)]
110 pub enum NAChannelType {
111 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
112 }
113
114 impl NAChannelType {
115 /// Reports whether this is some center channel.
116 pub fn is_center(self) -> bool {
117 match self {
118 NAChannelType::C => true, NAChannelType::Ch => true,
119 NAChannelType::Cl => true, NAChannelType::Ov => true,
120 NAChannelType::LFE => true, NAChannelType::LFE2 => true,
121 NAChannelType::Cs => true, NAChannelType::Chs => true,
122 _ => false,
123 }
124 }
125 /// Reports whether this is some left channel.
126 pub fn is_left(self) -> bool {
127 match self {
128 NAChannelType::L => true, NAChannelType::Ls => true,
129 NAChannelType::Lss => true, NAChannelType::Lc => true,
130 NAChannelType::Lh => true, NAChannelType::Lw => true,
131 NAChannelType::Lhs => true, NAChannelType::Ll => true,
132 NAChannelType::Lt => true, NAChannelType::Lo => true,
133 _ => false,
134 }
135 }
136 /// Reports whether this is some right channel.
137 pub fn is_right(self) -> bool {
138 match self {
139 NAChannelType::R => true, NAChannelType::Rs => true,
140 NAChannelType::Rss => true, NAChannelType::Rc => true,
141 NAChannelType::Rh => true, NAChannelType::Rw => true,
142 NAChannelType::Rhs => true, NAChannelType::Rl => true,
143 NAChannelType::Rt => true, NAChannelType::Ro => true,
144 _ => false,
145 }
146 }
147 }
148
149 /// Generic channel configuration parsing error.
150 #[derive(Clone,Copy,Debug,PartialEq)]
151 pub struct ChannelParseError {}
152
153 impl FromStr for NAChannelType {
154 type Err = ChannelParseError;
155
156 fn from_str(s: &str) -> Result<Self, Self::Err> {
157 match s {
158 "C" => Ok(NAChannelType::C),
159 "L" => Ok(NAChannelType::L),
160 "R" => Ok(NAChannelType::R),
161 "Cs" => Ok(NAChannelType::Cs),
162 "Ls" => Ok(NAChannelType::Ls),
163 "Rs" => Ok(NAChannelType::Rs),
164 "Lss" => Ok(NAChannelType::Lss),
165 "Rss" => Ok(NAChannelType::Rss),
166 "LFE" => Ok(NAChannelType::LFE),
167 "Lc" => Ok(NAChannelType::Lc),
168 "Rc" => Ok(NAChannelType::Rc),
169 "Lh" => Ok(NAChannelType::Lh),
170 "Rh" => Ok(NAChannelType::Rh),
171 "Ch" => Ok(NAChannelType::Ch),
172 "LFE2" => Ok(NAChannelType::LFE2),
173 "Lw" => Ok(NAChannelType::Lw),
174 "Rw" => Ok(NAChannelType::Rw),
175 "Ov" => Ok(NAChannelType::Ov),
176 "Lhs" => Ok(NAChannelType::Lhs),
177 "Rhs" => Ok(NAChannelType::Rhs),
178 "Chs" => Ok(NAChannelType::Chs),
179 "Ll" => Ok(NAChannelType::Ll),
180 "Rl" => Ok(NAChannelType::Rl),
181 "Cl" => Ok(NAChannelType::Cl),
182 "Lt" => Ok(NAChannelType::Lt),
183 "Rt" => Ok(NAChannelType::Rt),
184 "Lo" => Ok(NAChannelType::Lo),
185 "Ro" => Ok(NAChannelType::Ro),
186 _ => Err(ChannelParseError{}),
187 }
188 }
189 }
190
191 impl fmt::Display for NAChannelType {
192 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
193 let name = match *self {
194 NAChannelType::C => "C".to_string(),
195 NAChannelType::L => "L".to_string(),
196 NAChannelType::R => "R".to_string(),
197 NAChannelType::Cs => "Cs".to_string(),
198 NAChannelType::Ls => "Ls".to_string(),
199 NAChannelType::Rs => "Rs".to_string(),
200 NAChannelType::Lss => "Lss".to_string(),
201 NAChannelType::Rss => "Rss".to_string(),
202 NAChannelType::LFE => "LFE".to_string(),
203 NAChannelType::Lc => "Lc".to_string(),
204 NAChannelType::Rc => "Rc".to_string(),
205 NAChannelType::Lh => "Lh".to_string(),
206 NAChannelType::Rh => "Rh".to_string(),
207 NAChannelType::Ch => "Ch".to_string(),
208 NAChannelType::LFE2 => "LFE2".to_string(),
209 NAChannelType::Lw => "Lw".to_string(),
210 NAChannelType::Rw => "Rw".to_string(),
211 NAChannelType::Ov => "Ov".to_string(),
212 NAChannelType::Lhs => "Lhs".to_string(),
213 NAChannelType::Rhs => "Rhs".to_string(),
214 NAChannelType::Chs => "Chs".to_string(),
215 NAChannelType::Ll => "Ll".to_string(),
216 NAChannelType::Rl => "Rl".to_string(),
217 NAChannelType::Cl => "Cl".to_string(),
218 NAChannelType::Lt => "Lt".to_string(),
219 NAChannelType::Rt => "Rt".to_string(),
220 NAChannelType::Lo => "Lo".to_string(),
221 NAChannelType::Ro => "Ro".to_string(),
222 };
223 write!(f, "{}", name)
224 }
225 }
226
227 /// Channel map.
228 ///
229 /// This is essentially an ordered sequence of channels.
230 #[derive(Clone,Default)]
231 pub struct NAChannelMap {
232 ids: Vec<NAChannelType>,
233 }
234
235 const MS_CHANNEL_MAP: [NAChannelType; 11] = [
236 NAChannelType::L,
237 NAChannelType::R,
238 NAChannelType::C,
239 NAChannelType::LFE,
240 NAChannelType::Ls,
241 NAChannelType::Rs,
242 NAChannelType::Lss,
243 NAChannelType::Rss,
244 NAChannelType::Cs,
245 NAChannelType::Lc,
246 NAChannelType::Rc,
247 ];
248
249 impl NAChannelMap {
250 /// Constructs a new `NAChannelMap` instance.
251 pub fn new() -> Self { NAChannelMap { ids: Vec::new() } }
252 /// Adds a new channel to the map.
253 pub fn add_channel(&mut self, ch: NAChannelType) {
254 self.ids.push(ch);
255 }
256 /// Adds several channels to the map at once.
257 pub fn add_channels(&mut self, chs: &[NAChannelType]) {
258 for e in chs.iter() {
259 self.ids.push(*e);
260 }
261 }
262 /// Returns the total number of channels.
263 pub fn num_channels(&self) -> usize {
264 self.ids.len()
265 }
266 /// Reports channel type for a requested index.
267 pub fn get_channel(&self, idx: usize) -> NAChannelType {
268 self.ids[idx]
269 }
270 /// Tries to find position of the channel with requested type.
271 pub fn find_channel_id(&self, t: NAChannelType) -> Option<u8> {
272 for i in 0..self.ids.len() {
273 if self.ids[i] as i32 == t as i32 { return Some(i as u8); }
274 }
275 None
276 }
277 /// Creates a new `NAChannelMap` using the channel mapping flags from WAVE format.
278 pub fn from_ms_mapping(chmap: u32) -> Self {
279 let mut cm = NAChannelMap::new();
280 for (i, ch) in MS_CHANNEL_MAP.iter().enumerate() {
281 if ((chmap >> i) & 1) != 0 {
282 cm.add_channel(*ch);
283 }
284 }
285 cm
286 }
287 }
288
289 impl fmt::Display for NAChannelMap {
290 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
291 let mut map = String::new();
292 for el in self.ids.iter() {
293 if !map.is_empty() { map.push(','); }
294 map.push_str(&*el.to_string());
295 }
296 write!(f, "{}", map)
297 }
298 }
299
300 impl FromStr for NAChannelMap {
301 type Err = ChannelParseError;
302
303 fn from_str(s: &str) -> Result<Self, Self::Err> {
304 let mut chm = NAChannelMap::new();
305 for tok in s.split(',') {
306 chm.add_channel(NAChannelType::from_str(tok)?);
307 }
308 Ok(chm)
309 }
310 }
311
312 /// A list of RGB colour model variants.
313 #[derive(Debug,Clone,Copy,PartialEq)]
314 pub enum RGBSubmodel {
315 RGB,
316 SRGB,
317 }
318
319 impl fmt::Display for RGBSubmodel {
320 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
321 let name = match *self {
322 RGBSubmodel::RGB => "RGB".to_string(),
323 RGBSubmodel::SRGB => "sRGB".to_string(),
324 };
325 write!(f, "{}", name)
326 }
327 }
328
329 /// A list of YUV colour model variants.
330 #[derive(Debug,Clone,Copy,PartialEq)]
331 pub enum YUVSubmodel {
332 YCbCr,
333 /// NTSC variant.
334 YIQ,
335 /// The YUV variant used by JPEG.
336 YUVJ,
337 }
338
339 impl fmt::Display for YUVSubmodel {
340 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
341 let name = match *self {
342 YUVSubmodel::YCbCr => "YCbCr".to_string(),
343 YUVSubmodel::YIQ => "YIQ".to_string(),
344 YUVSubmodel::YUVJ => "YUVJ".to_string(),
345 };
346 write!(f, "{}", name)
347 }
348 }
349
350 /// A list of known colour models.
351 #[derive(Debug, Clone,Copy,PartialEq)]
352 pub enum ColorModel {
353 RGB(RGBSubmodel),
354 YUV(YUVSubmodel),
355 CMYK,
356 HSV,
357 LAB,
358 XYZ,
359 }
360
361 impl ColorModel {
362 /// Returns the number of colour model components.
363 ///
364 /// The actual image may have more components e.g. alpha component.
365 pub fn get_default_components(self) -> usize {
366 match self {
367 ColorModel::CMYK => 4,
368 _ => 3,
369 }
370 }
371 /// Reports whether the current colour model is RGB.
372 pub fn is_rgb(self) -> bool {
373 match self {
374 ColorModel::RGB(_) => true,
375 _ => false,
376 }
377 }
378 /// Reports whether the current colour model is YUV.
379 pub fn is_yuv(self) -> bool {
380 match self {
381 ColorModel::YUV(_) => true,
382 _ => false,
383 }
384 }
385 /// Returns short name for the current colour mode.
386 pub fn get_short_name(self) -> &'static str {
387 match self {
388 ColorModel::RGB(_) => "rgb",
389 ColorModel::YUV(_) => "yuv",
390 ColorModel::CMYK => "cmyk",
391 ColorModel::HSV => "hsv",
392 ColorModel::LAB => "lab",
393 ColorModel::XYZ => "xyz",
394 }
395 }
396 }
397
398 impl fmt::Display for ColorModel {
399 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
400 let name = match *self {
401 ColorModel::RGB(fmt) => format!("RGB({})", fmt).to_string(),
402 ColorModel::YUV(fmt) => format!("YUV({})", fmt).to_string(),
403 ColorModel::CMYK => "CMYK".to_string(),
404 ColorModel::HSV => "HSV".to_string(),
405 ColorModel::LAB => "LAB".to_string(),
406 ColorModel::XYZ => "XYZ".to_string(),
407 };
408 write!(f, "{}", name)
409 }
410 }
411
412 /// Single colourspace component definition.
413 ///
414 /// This structure defines how components of a colourspace are subsampled and where and how they are stored.
415 #[derive(Clone,Copy,PartialEq)]
416 pub struct NAPixelChromaton {
417 /// Horizontal subsampling in power of two (e.g. `0` = no subsampling, `1` = only every second value is stored).
418 pub h_ss: u8,
419 /// Vertial subsampling in power of two (e.g. `0` = no subsampling, `1` = only every second value is stored).
420 pub v_ss: u8,
421 /// A flag to signal that component is packed.
422 pub packed: bool,
423 /// Bit depth of current component.
424 pub depth: u8,
425 /// Shift for packed components.
426 pub shift: u8,
427 /// Component offset for byte-packed components.
428 pub comp_offs: u8,
429 /// The distance to the next packed element in bytes.
430 pub next_elem: u8,
431 }
432
433 /// Flag for specifying that image data is stored big-endian in `NAPixelFormaton::`[`new`]`()`. Related to its [`be`] field.
434 ///
435 /// [`new`]: ./struct.NAPixelFormaton.html#method.new
436 /// [`be`]: ./struct.NAPixelFormaton.html#structfield.new
437 pub const FORMATON_FLAG_BE :u32 = 0x01;
438 /// Flag for specifying that image data has alpha plane in `NAPixelFormaton::`[`new`]`()`. Related to its [`alpha`] field.
439 ///
440 /// [`new`]: ./struct.NAPixelFormaton.html#method.new
441 /// [`alpha`]: ./struct.NAPixelFormaton.html#structfield.alpha
442 pub const FORMATON_FLAG_ALPHA :u32 = 0x02;
443 /// Flag for specifying that image data is stored in paletted form for `NAPixelFormaton::`[`new`]`()`. Related to its [`palette`] field.
444 ///
445 /// [`new`]: ./struct.NAPixelFormaton.html#method.new
446 /// [`palette`]: ./struct.NAPixelFormaton.html#structfield.palette
447 pub const FORMATON_FLAG_PALETTE :u32 = 0x04;
448
449 /// The current limit on number of components in image colourspace model (including alpha component).
450 pub const MAX_CHROMATONS: usize = 5;
451
452 /// Image colourspace representation.
453 ///
454 /// This structure includes both definitions for each component and some common definitions.
455 /// For example the format can be paletted and then components describe the palette storage format while actual data is 8-bit palette indices.
456 #[derive(Clone,Copy,PartialEq)]
457 pub struct NAPixelFormaton {
458 /// Image colour model.
459 pub model: ColorModel,
460 /// Actual number of components present.
461 pub components: u8,
462 /// Format definition for each component.
463 pub comp_info: [Option<NAPixelChromaton>; MAX_CHROMATONS],
464 /// Single pixel size for packed formats.
465 pub elem_size: u8,
466 /// A flag signalling that data is stored as big-endian.
467 pub be: bool,
468 /// A flag signalling that image has alpha component.
469 pub alpha: bool,
470 /// A flag signalling that data is paletted.
471 ///
472 /// 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.
473 pub palette: bool,
474 }
475
476 macro_rules! chromaton {
477 ($hs: expr, $vs: expr, $pck: expr, $d: expr, $sh: expr, $co: expr, $ne: expr) => ({
478 Some(NAPixelChromaton{ h_ss: $hs, v_ss: $vs, packed: $pck, depth: $d, shift: $sh, comp_offs: $co, next_elem: $ne })
479 });
480 (yuv8; $hs: expr, $vs: expr, $co: expr) => ({
481 Some(NAPixelChromaton{ h_ss: $hs, v_ss: $vs, packed: false, depth: 8, shift: 0, comp_offs: $co, next_elem: 1 })
482 });
483 (packrgb; $d: expr, $s: expr, $co: expr, $ne: expr) => ({
484 Some(NAPixelChromaton{ h_ss: 0, v_ss: 0, packed: true, depth: $d, shift: $s, comp_offs: $co, next_elem: $ne })
485 });
486 (pal8; $co: expr) => ({
487 Some(NAPixelChromaton{ h_ss: 0, v_ss: 0, packed: true, depth: 8, shift: 0, comp_offs: $co, next_elem: 3 })
488 });
489 }
490
491 /// Predefined format for planar 8-bit YUV with 4:2:0 subsampling.
492 pub const YUV420_FORMAT: NAPixelFormaton = NAPixelFormaton { model: ColorModel::YUV(YUVSubmodel::YUVJ), components: 3,
493 comp_info: [
494 chromaton!(0, 0, false, 8, 0, 0, 1),
495 chromaton!(yuv8; 1, 1, 1),
496 chromaton!(yuv8; 1, 1, 2),
497 None, None],
498 elem_size: 0, be: false, alpha: false, palette: false };
499
500 /// Predefined format for planar 8-bit YUV with 4:1:0 subsampling.
501 pub const YUV410_FORMAT: NAPixelFormaton = NAPixelFormaton { model: ColorModel::YUV(YUVSubmodel::YUVJ), components: 3,
502 comp_info: [
503 chromaton!(0, 0, false, 8, 0, 0, 1),
504 chromaton!(yuv8; 2, 2, 1),
505 chromaton!(yuv8; 2, 2, 2),
506 None, None],
507 elem_size: 0, be: false, alpha: false, palette: false };
508 /// Predefined format for planar 8-bit YUV with 4:1:0 subsampling and alpha component.
509 pub const YUVA410_FORMAT: NAPixelFormaton = NAPixelFormaton { model: ColorModel::YUV(YUVSubmodel::YUVJ), components: 4,
510 comp_info: [
511 chromaton!(0, 0, false, 8, 0, 0, 1),
512 chromaton!(yuv8; 2, 2, 1),
513 chromaton!(yuv8; 2, 2, 2),
514 chromaton!(0, 0, false, 8, 0, 3, 1),
515 None],
516 elem_size: 0, be: false, alpha: true, palette: false };
517
518 /// Predefined format with RGB24 palette.
519 pub const PAL8_FORMAT: NAPixelFormaton = NAPixelFormaton { model: ColorModel::RGB(RGBSubmodel::RGB), components: 3,
520 comp_info: [
521 chromaton!(pal8; 0),
522 chromaton!(pal8; 1),
523 chromaton!(pal8; 2),
524 None, None],
525 elem_size: 3, be: false, alpha: false, palette: true };
526
527 /// Predefined format for RGB565 packed video.
528 pub const RGB565_FORMAT: NAPixelFormaton = NAPixelFormaton { model: ColorModel::RGB(RGBSubmodel::RGB), components: 3,
529 comp_info: [
530 chromaton!(packrgb; 5, 11, 0, 2),
531 chromaton!(packrgb; 6, 5, 0, 2),
532 chromaton!(packrgb; 5, 0, 0, 2),
533 None, None],
534 elem_size: 2, be: false, alpha: false, palette: false };
535
536 /// Predefined format for RGB24.
537 pub const RGB24_FORMAT: NAPixelFormaton = NAPixelFormaton { model: ColorModel::RGB(RGBSubmodel::RGB), components: 3,
538 comp_info: [
539 chromaton!(packrgb; 8, 0, 0, 3),
540 chromaton!(packrgb; 8, 0, 1, 3),
541 chromaton!(packrgb; 8, 0, 2, 3),
542 None, None],
543 elem_size: 3, be: false, alpha: false, palette: false };
544
545 impl NAPixelChromaton {
546 /// Constructs a new `NAPixelChromaton` instance.
547 pub fn new(h_ss: u8, v_ss: u8, packed: bool, depth: u8, shift: u8, comp_offs: u8, next_elem: u8) -> Self {
548 Self { h_ss, v_ss, packed, depth, shift, comp_offs, next_elem }
549 }
550 /// Returns subsampling for the current component.
551 pub fn get_subsampling(self) -> (u8, u8) { (self.h_ss, self.v_ss) }
552 /// Reports whether current component is packed.
553 pub fn is_packed(self) -> bool { self.packed }
554 /// Returns bit depth of current component.
555 pub fn get_depth(self) -> u8 { self.depth }
556 /// Returns bit shift for packed component.
557 pub fn get_shift(self) -> u8 { self.shift }
558 /// Returns byte offset for packed component.
559 pub fn get_offset(self) -> u8 { self.comp_offs }
560 /// Returns byte offset to the next element of current packed component.
561 pub fn get_step(self) -> u8 { self.next_elem }
562
563 /// Calculates the width for current component from general image width.
564 pub fn get_width(self, width: usize) -> usize {
565 (width + ((1 << self.h_ss) - 1)) >> self.h_ss
566 }
567 /// Calculates the height for current component from general image height.
568 pub fn get_height(self, height: usize) -> usize {
569 (height + ((1 << self.v_ss) - 1)) >> self.v_ss
570 }
571 /// Calculates the minimal stride for current component from general image width.
572 pub fn get_linesize(self, width: usize) -> usize {
573 let d = self.depth as usize;
574 if self.packed {
575 (self.get_width(width) * d + d - 1) >> 3
576 } else {
577 self.get_width(width)
578 }
579 }
580 /// Calculates the required image size in pixels for current component from general image width.
581 pub fn get_data_size(self, width: usize, height: usize) -> usize {
582 let nh = (height + ((1 << self.v_ss) - 1)) >> self.v_ss;
583 self.get_linesize(width) * nh
584 }
585 }
586
587 impl fmt::Display for NAPixelChromaton {
588 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
589 let pfmt = if self.packed {
590 let mask = ((1 << self.depth) - 1) << self.shift;
591 format!("packed(+{},{:X}, step {})", self.comp_offs, mask, self.next_elem)
592 } else {
593 format!("planar({},{})", self.comp_offs, self.next_elem)
594 };
595 write!(f, "({}x{}, {})", self.h_ss, self.v_ss, pfmt)
596 }
597 }
598
599 impl NAPixelFormaton {
600 /// Constructs a new instance of `NAPixelFormaton`.
601 pub fn new(model: ColorModel,
602 comp1: Option<NAPixelChromaton>,
603 comp2: Option<NAPixelChromaton>,
604 comp3: Option<NAPixelChromaton>,
605 comp4: Option<NAPixelChromaton>,
606 comp5: Option<NAPixelChromaton>,
607 flags: u32, elem_size: u8) -> Self {
608 let mut chromatons: [Option<NAPixelChromaton>; MAX_CHROMATONS] = [None; MAX_CHROMATONS];
609 let mut ncomp = 0;
610 let be = (flags & FORMATON_FLAG_BE) != 0;
611 let alpha = (flags & FORMATON_FLAG_ALPHA) != 0;
612 let palette = (flags & FORMATON_FLAG_PALETTE) != 0;
613 if let Some(c) = comp1 { chromatons[0] = Some(c); ncomp += 1; }
614 if let Some(c) = comp2 { chromatons[1] = Some(c); ncomp += 1; }
615 if let Some(c) = comp3 { chromatons[2] = Some(c); ncomp += 1; }
616 if let Some(c) = comp4 { chromatons[3] = Some(c); ncomp += 1; }
617 if let Some(c) = comp5 { chromatons[4] = Some(c); ncomp += 1; }
618 NAPixelFormaton { model,
619 components: ncomp,
620 comp_info: chromatons,
621 elem_size,
622 be, alpha, palette }
623 }
624
625 /// Returns current colour model.
626 pub fn get_model(&self) -> ColorModel { self.model }
627 /// Returns the number of components.
628 pub fn get_num_comp(&self) -> usize { self.components as usize }
629 /// Returns selected component information.
630 pub fn get_chromaton(&self, idx: usize) -> Option<NAPixelChromaton> {
631 if idx < self.comp_info.len() { return self.comp_info[idx]; }
632 None
633 }
634 /// Reports whether the packing format is big-endian.
635 pub fn is_be(self) -> bool { self.be }
636 /// Reports whether colourspace has alpha component.
637 pub fn has_alpha(self) -> bool { self.alpha }
638 /// Reports whether this is paletted format.
639 pub fn is_paletted(self) -> bool { self.palette }
640 /// Returns single packed pixel size.
641 pub fn get_elem_size(self) -> u8 { self.elem_size }
642 /// Reports whether the format is not packed.
643 pub fn is_unpacked(&self) -> bool {
644 if self.palette { return false; }
645 for chr in self.comp_info.iter() {
646 if let Some(ref chromaton) = chr {
647 if chromaton.is_packed() { return false; }
648 }
649 }
650 true
651 }
652 /// Returns the maximum component bit depth.
653 pub fn get_max_depth(&self) -> u8 {
654 let mut mdepth = 0;
655 for chr in self.comp_info.iter() {
656 if let Some(ref chromaton) = chr {
657 mdepth = mdepth.max(chromaton.depth);
658 }
659 }
660 mdepth
661 }
662 /// Returns the maximum component subsampling.
663 pub fn get_max_subsampling(&self) -> u8 {
664 let mut ssamp = 0;
665 for chr in self.comp_info.iter() {
666 if let Some(ref chromaton) = chr {
667 let (ss_v, ss_h) = chromaton.get_subsampling();
668 ssamp = ssamp.max(ss_v).max(ss_h);
669 }
670 }
671 ssamp
672 }
673 }
674
675 impl fmt::Display for NAPixelFormaton {
676 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
677 let end = if self.be { "BE" } else { "LE" };
678 let palstr = if self.palette { "palette " } else { "" };
679 let astr = if self.alpha { "alpha " } else { "" };
680 let mut str = format!("Formaton for {} ({}{}elem {} size {}): ", self.model, palstr, astr,end, self.elem_size);
681 for i in 0..self.comp_info.len() {
682 if let Some(chr) = self.comp_info[i] {
683 str = format!("{} {}", str, chr);
684 }
685 }
686 write!(f, "[{}]", str)
687 }
688 }
689
690 #[cfg(test)]
691 mod test {
692 use super::*;
693
694 #[test]
695 fn test_fmt() {
696 println!("{}", SND_S16_FORMAT);
697 println!("{}", SND_U8_FORMAT);
698 println!("{}", SND_F32P_FORMAT);
699 println!("formaton yuv- {}", YUV420_FORMAT);
700 println!("formaton pal- {}", PAL8_FORMAT);
701 println!("formaton rgb565- {}", RGB565_FORMAT);
702 }
703 }