core/formats: add NAPixelFormaton::get_total_depth()
[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
33b5689a
KS
10/// Audio format definition.
11///
12/// The structure describes how audio samples are stored and what characteristics they have.
b68ff5ae 13#[derive(Debug,Copy,Clone,PartialEq)]
fba6f8e4 14pub struct NASoniton {
33b5689a 15 /// Bits per sample.
a92a5113 16 pub bits: u8,
33b5689a 17 /// Audio format is big-endian.
a92a5113 18 pub be: bool,
33b5689a 19 /// Audio samples are packed (e.g. 20-bit audio samples).
a92a5113 20 pub packed: bool,
33b5689a 21 /// Audio data is stored in planar format instead of interleaving samples for different channels.
a92a5113 22 pub planar: bool,
33b5689a 23 /// Audio data is in floating point format.
a92a5113 24 pub float: bool,
33b5689a 25 /// Audio data is signed (usually only 8-bit audio is unsigned).
a92a5113 26 pub signed: bool,
fba6f8e4
KS
27}
28
33b5689a
KS
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
9e9a3af1 33pub const SONITON_FLAG_BE :u32 = 0x01;
33b5689a
KS
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
9e9a3af1 38pub const SONITON_FLAG_PACKED :u32 = 0x02;
33b5689a
KS
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
9e9a3af1 43pub const SONITON_FLAG_PLANAR :u32 = 0x04;
33b5689a
KS
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
9e9a3af1 48pub const SONITON_FLAG_FLOAT :u32 = 0x08;
33b5689a
KS
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
9e9a3af1 53pub const SONITON_FLAG_SIGNED :u32 = 0x10;
fba6f8e4 54
33b5689a 55/// Predefined format for interleaved 8-bit unsigned audio.
fba6f8e4 56pub const SND_U8_FORMAT: NASoniton = NASoniton { bits: 8, be: false, packed: false, planar: false, float: false, signed: false };
33b5689a 57/// Predefined format for interleaved 16-bit signed audio.
fba6f8e4 58pub const SND_S16_FORMAT: NASoniton = NASoniton { bits: 16, be: false, packed: false, planar: false, float: false, signed: true };
33b5689a 59/// Predefined format for planar 16-bit signed audio.
49fde921 60pub const SND_S16P_FORMAT: NASoniton = NASoniton { bits: 16, be: false, packed: false, planar: true, float: false, signed: true };
33b5689a 61/// Predefined format for planar 32-bit floating point audio.
126b7eb8 62pub const SND_F32P_FORMAT: NASoniton = NASoniton { bits: 32, be: false, packed: false, planar: true, float: true, signed: true };
fba6f8e4
KS
63
64impl NASoniton {
33b5689a
KS
65 /// Constructs a new audio format definition using flags like [`SONITON_FLAG_BE`].
66 ///
67 /// [`SONITON_FLAG_BE`]: ./constant.SONITON_FLAG_BE.html
9e9a3af1
KS
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;
e243ceb4 74 NASoniton { bits, be: is_be, packed: is_pk, planar: is_pl, float: is_fl, signed: is_sg }
fba6f8e4
KS
75 }
76
33b5689a 77 /// Returns the number of bits per sample.
e243ceb4 78 pub fn get_bits(self) -> u8 { self.bits }
33b5689a 79 /// Reports whether the format is big-endian.
e243ceb4 80 pub fn is_be(self) -> bool { self.be }
33b5689a 81 /// Reports whether the format has packed samples.
e243ceb4 82 pub fn is_packed(self) -> bool { self.packed }
33b5689a 83 /// Reports whether audio data is planar instead of interleaved.
e243ceb4 84 pub fn is_planar(self) -> bool { self.planar }
33b5689a 85 /// Reports whether audio samples are in floating point format.
e243ceb4 86 pub fn is_float(self) -> bool { self.float }
33b5689a 87 /// Reports whether audio samples are signed.
e243ceb4 88 pub fn is_signed(self) -> bool { self.signed }
15e41b31 89
33b5689a 90 /// Returns the amount of bytes needed to store the audio of requested length (in samples).
e243ceb4 91 pub fn get_audio_size(self, length: u64) -> usize {
15e41b31 92 if self.packed {
e243ceb4 93 ((length * u64::from(self.bits) + 7) >> 3) as usize
15e41b31 94 } else {
e243ceb4 95 (length * u64::from((self.bits + 7) >> 3)) as usize
15e41b31
KS
96 }
97 }
fba6f8e4
KS
98}
99
100impl 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
33b5689a 108/// Known channel types.
10a00d52 109#[derive(Debug,Clone,Copy,PartialEq)]
fba6f8e4
KS
110pub 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
114impl NAChannelType {
33b5689a 115 /// Reports whether this is some center channel.
e243ceb4
KS
116 pub fn is_center(self) -> bool {
117 match self {
fba6f8e4
KS
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 }
33b5689a 125 /// Reports whether this is some left channel.
e243ceb4
KS
126 pub fn is_left(self) -> bool {
127 match self {
fba6f8e4
KS
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 }
33b5689a 136 /// Reports whether this is some right channel.
e243ceb4
KS
137 pub fn is_right(self) -> bool {
138 match self {
fba6f8e4
KS
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
33b5689a 149/// Generic channel configuration parsing error.
32ce974d
KS
150#[derive(Clone,Copy,Debug,PartialEq)]
151pub struct ChannelParseError {}
152
153impl 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{}),
1a151e53 187 }
32ce974d
KS
188 }
189}
190
fba6f8e4
KS
191impl 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
33b5689a
KS
227/// Channel map.
228///
229/// This is essentially an ordered sequence of channels.
e243ceb4 230#[derive(Clone,Default)]
fba6f8e4
KS
231pub struct NAChannelMap {
232 ids: Vec<NAChannelType>,
233}
234
62b33487
KS
235const 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
fba6f8e4 249impl NAChannelMap {
33b5689a 250 /// Constructs a new `NAChannelMap` instance.
fba6f8e4 251 pub fn new() -> Self { NAChannelMap { ids: Vec::new() } }
33b5689a 252 /// Adds a new channel to the map.
fba6f8e4
KS
253 pub fn add_channel(&mut self, ch: NAChannelType) {
254 self.ids.push(ch);
255 }
33b5689a 256 /// Adds several channels to the map at once.
10a00d52 257 pub fn add_channels(&mut self, chs: &[NAChannelType]) {
e243ceb4
KS
258 for e in chs.iter() {
259 self.ids.push(*e);
10a00d52
KS
260 }
261 }
33b5689a 262 /// Returns the total number of channels.
fba6f8e4
KS
263 pub fn num_channels(&self) -> usize {
264 self.ids.len()
265 }
33b5689a 266 /// Reports channel type for a requested index.
fba6f8e4
KS
267 pub fn get_channel(&self, idx: usize) -> NAChannelType {
268 self.ids[idx]
269 }
33b5689a 270 /// Tries to find position of the channel with requested type.
fba6f8e4
KS
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 }
33b5689a 277 /// Creates a new `NAChannelMap` using the channel mapping flags from WAVE format.
62b33487
KS
278 pub fn from_ms_mapping(chmap: u32) -> Self {
279 let mut cm = NAChannelMap::new();
e243ceb4 280 for (i, ch) in MS_CHANNEL_MAP.iter().enumerate() {
62b33487 281 if ((chmap >> i) & 1) != 0 {
e243ceb4 282 cm.add_channel(*ch);
62b33487
KS
283 }
284 }
285 cm
286 }
fba6f8e4
KS
287}
288
32ce974d
KS
289impl 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() {
e243ceb4 293 if !map.is_empty() { map.push(','); }
32ce974d
KS
294 map.push_str(&*el.to_string());
295 }
296 write!(f, "{}", map)
297 }
298}
299
300impl 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
33b5689a 312/// A list of RGB colour model variants.
b68ff5ae 313#[derive(Debug,Clone,Copy,PartialEq)]
fba6f8e4
KS
314pub enum RGBSubmodel {
315 RGB,
316 SRGB,
317}
318
319impl 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
33b5689a 329/// A list of YUV colour model variants.
b68ff5ae 330#[derive(Debug,Clone,Copy,PartialEq)]
fba6f8e4
KS
331pub enum YUVSubmodel {
332 YCbCr,
33b5689a 333 /// NTSC variant.
fba6f8e4 334 YIQ,
33b5689a 335 /// The YUV variant used by JPEG.
fba6f8e4
KS
336 YUVJ,
337}
338
339impl 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
33b5689a 350/// A list of known colour models.
b68ff5ae 351#[derive(Debug, Clone,Copy,PartialEq)]
fba6f8e4
KS
352pub enum ColorModel {
353 RGB(RGBSubmodel),
354 YUV(YUVSubmodel),
355 CMYK,
356 HSV,
357 LAB,
358 XYZ,
359}
360
361impl ColorModel {
33b5689a
KS
362 /// Returns the number of colour model components.
363 ///
364 /// The actual image may have more components e.g. alpha component.
e243ceb4
KS
365 pub fn get_default_components(self) -> usize {
366 match self {
fba6f8e4
KS
367 ColorModel::CMYK => 4,
368 _ => 3,
369 }
370 }
33b5689a 371 /// Reports whether the current colour model is RGB.
e243ceb4
KS
372 pub fn is_rgb(self) -> bool {
373 match self {
386957f1
KS
374 ColorModel::RGB(_) => true,
375 _ => false,
376 }
377 }
33b5689a 378 /// Reports whether the current colour model is YUV.
e243ceb4
KS
379 pub fn is_yuv(self) -> bool {
380 match self {
386957f1
KS
381 ColorModel::YUV(_) => true,
382 _ => false,
383 }
384 }
33b5689a 385 /// Returns short name for the current colour mode.
e243ceb4
KS
386 pub fn get_short_name(self) -> &'static str {
387 match self {
8efb7386
KS
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 }
fba6f8e4
KS
396}
397
398impl 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
33b5689a
KS
412/// Single colourspace component definition.
413///
414/// This structure defines how components of a colourspace are subsampled and where and how they are stored.
b68ff5ae 415#[derive(Clone,Copy,PartialEq)]
fba6f8e4 416pub struct NAPixelChromaton {
33b5689a 417 /// Horizontal subsampling in power of two (e.g. `0` = no subsampling, `1` = only every second value is stored).
386957f1 418 pub h_ss: u8,
33b5689a 419 /// Vertial subsampling in power of two (e.g. `0` = no subsampling, `1` = only every second value is stored).
386957f1 420 pub v_ss: u8,
33b5689a 421 /// A flag to signal that component is packed.
386957f1 422 pub packed: bool,
33b5689a 423 /// Bit depth of current component.
386957f1 424 pub depth: u8,
33b5689a 425 /// Shift for packed components.
386957f1 426 pub shift: u8,
33b5689a 427 /// Component offset for byte-packed components.
386957f1 428 pub comp_offs: u8,
33b5689a 429 /// The distance to the next packed element in bytes.
386957f1 430 pub next_elem: u8,
fba6f8e4
KS
431}
432
33b5689a
KS
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
9e9a3af1 437pub const FORMATON_FLAG_BE :u32 = 0x01;
33b5689a
KS
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
9e9a3af1 442pub const FORMATON_FLAG_ALPHA :u32 = 0x02;
33b5689a
KS
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
9e9a3af1 447pub const FORMATON_FLAG_PALETTE :u32 = 0x04;
fba6f8e4 448
33b5689a 449/// The current limit on number of components in image colourspace model (including alpha component).
8efb7386 450pub const MAX_CHROMATONS: usize = 5;
fba6f8e4 451
33b5689a
KS
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.
b68ff5ae 456#[derive(Clone,Copy,PartialEq)]
fba6f8e4 457pub struct NAPixelFormaton {
33b5689a 458 /// Image colour model.
386957f1 459 pub model: ColorModel,
33b5689a 460 /// Actual number of components present.
386957f1 461 pub components: u8,
33b5689a 462 /// Format definition for each component.
8efb7386 463 pub comp_info: [Option<NAPixelChromaton>; MAX_CHROMATONS],
33b5689a 464 /// Single pixel size for packed formats.
386957f1 465 pub elem_size: u8,
33b5689a 466 /// A flag signalling that data is stored as big-endian.
386957f1 467 pub be: bool,
33b5689a 468 /// A flag signalling that image has alpha component.
386957f1 469 pub alpha: bool,
33b5689a
KS
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.
386957f1 473 pub palette: bool,
fba6f8e4
KS
474}
475
476macro_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
33b5689a 491/// Predefined format for planar 8-bit YUV with 4:2:0 subsampling.
fba6f8e4
KS
492pub 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
33b5689a 500/// Predefined format for planar 8-bit YUV with 4:1:0 subsampling.
b68ff5ae
KS
501pub 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 };
33b5689a 508/// Predefined format for planar 8-bit YUV with 4:1:0 subsampling and alpha component.
a2a9732a
KS
509pub 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 };
b68ff5ae 517
33b5689a 518/// Predefined format with RGB24 palette.
fba6f8e4
KS
519pub 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
33b5689a 527/// Predefined format for RGB565 packed video.
fba6f8e4
KS
528pub 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
33b5689a 536/// Predefined format for RGB24.
653e5afd
KS
537pub const RGB24_FORMAT: NAPixelFormaton = NAPixelFormaton { model: ColorModel::RGB(RGBSubmodel::RGB), components: 3,
538 comp_info: [
653e5afd 539 chromaton!(packrgb; 8, 0, 0, 3),
c6297d1f
KS
540 chromaton!(packrgb; 8, 0, 1, 3),
541 chromaton!(packrgb; 8, 0, 2, 3),
653e5afd
KS
542 None, None],
543 elem_size: 3, be: false, alpha: false, palette: false };
544
fba6f8e4 545impl NAPixelChromaton {
33b5689a 546 /// Constructs a new `NAPixelChromaton` instance.
0cc09358
KS
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 }
33b5689a 550 /// Returns subsampling for the current component.
e243ceb4 551 pub fn get_subsampling(self) -> (u8, u8) { (self.h_ss, self.v_ss) }
33b5689a 552 /// Reports whether current component is packed.
e243ceb4 553 pub fn is_packed(self) -> bool { self.packed }
33b5689a 554 /// Returns bit depth of current component.
e243ceb4 555 pub fn get_depth(self) -> u8 { self.depth }
33b5689a 556 /// Returns bit shift for packed component.
e243ceb4 557 pub fn get_shift(self) -> u8 { self.shift }
33b5689a 558 /// Returns byte offset for packed component.
e243ceb4 559 pub fn get_offset(self) -> u8 { self.comp_offs }
33b5689a 560 /// Returns byte offset to the next element of current packed component.
e243ceb4 561 pub fn get_step(self) -> u8 { self.next_elem }
b68ff5ae 562
33b5689a 563 /// Calculates the width for current component from general image width.
e243ceb4 564 pub fn get_width(self, width: usize) -> usize {
15e41b31
KS
565 (width + ((1 << self.h_ss) - 1)) >> self.h_ss
566 }
33b5689a 567 /// Calculates the height for current component from general image height.
e243ceb4 568 pub fn get_height(self, height: usize) -> usize {
15e41b31
KS
569 (height + ((1 << self.v_ss) - 1)) >> self.v_ss
570 }
33b5689a 571 /// Calculates the minimal stride for current component from general image width.
e243ceb4 572 pub fn get_linesize(self, width: usize) -> usize {
b68ff5ae 573 let d = self.depth as usize;
6c8e5c40
KS
574 if self.packed {
575 (self.get_width(width) * d + d - 1) >> 3
576 } else {
577 self.get_width(width)
578 }
b68ff5ae 579 }
33b5689a 580 /// Calculates the required image size in pixels for current component from general image width.
e243ceb4 581 pub fn get_data_size(self, width: usize, height: usize) -> usize {
b68ff5ae
KS
582 let nh = (height + ((1 << self.v_ss) - 1)) >> self.v_ss;
583 self.get_linesize(width) * nh
584 }
fba6f8e4
KS
585}
586
587impl 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
599impl NAPixelFormaton {
33b5689a 600 /// Constructs a new instance of `NAPixelFormaton`.
fba6f8e4
KS
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>,
9e9a3af1 607 flags: u32, elem_size: u8) -> Self {
8efb7386 608 let mut chromatons: [Option<NAPixelChromaton>; MAX_CHROMATONS] = [None; MAX_CHROMATONS];
fba6f8e4 609 let mut ncomp = 0;
9e9a3af1
KS
610 let be = (flags & FORMATON_FLAG_BE) != 0;
611 let alpha = (flags & FORMATON_FLAG_ALPHA) != 0;
612 let palette = (flags & FORMATON_FLAG_PALETTE) != 0;
fba6f8e4
KS
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; }
e243ceb4 618 NAPixelFormaton { model,
fba6f8e4
KS
619 components: ncomp,
620 comp_info: chromatons,
e243ceb4
KS
621 elem_size,
622 be, alpha, palette }
fba6f8e4
KS
623 }
624
33b5689a 625 /// Returns current colour model.
fba6f8e4 626 pub fn get_model(&self) -> ColorModel { self.model }
33b5689a 627 /// Returns the number of components.
b68ff5ae 628 pub fn get_num_comp(&self) -> usize { self.components as usize }
33b5689a 629 /// Returns selected component information.
fba6f8e4
KS
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 }
33b5689a 634 /// Reports whether the packing format is big-endian.
e243ceb4 635 pub fn is_be(self) -> bool { self.be }
33b5689a 636 /// Reports whether colourspace has alpha component.
e243ceb4 637 pub fn has_alpha(self) -> bool { self.alpha }
33b5689a 638 /// Reports whether this is paletted format.
e243ceb4 639 pub fn is_paletted(self) -> bool { self.palette }
33b5689a 640 /// Returns single packed pixel size.
e243ceb4 641 pub fn get_elem_size(self) -> u8 { self.elem_size }
33b5689a 642 /// Reports whether the format is not packed.
8efb7386 643 pub fn is_unpacked(&self) -> bool {
c7d8d948 644 if self.palette { return false; }
8efb7386
KS
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 }
33b5689a 652 /// Returns the maximum component bit depth.
8efb7386
KS
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 }
8b746bf7
KS
662 /// Returns the total amount of bits needed for components.
663 pub fn get_total_depth(&self) -> u8 {
664 let mut depth = 0;
665 for chr in self.comp_info.iter() {
666 if let Some(ref chromaton) = chr {
667 depth += chromaton.depth;
668 }
669 }
670 depth
671 }
33b5689a 672 /// Returns the maximum component subsampling.
8efb7386
KS
673 pub fn get_max_subsampling(&self) -> u8 {
674 let mut ssamp = 0;
675 for chr in self.comp_info.iter() {
676 if let Some(ref chromaton) = chr {
677 let (ss_v, ss_h) = chromaton.get_subsampling();
678 ssamp = ssamp.max(ss_v).max(ss_h);
679 }
680 }
681 ssamp
682 }
fba6f8e4
KS
683}
684
685impl fmt::Display for NAPixelFormaton {
686 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
687 let end = if self.be { "BE" } else { "LE" };
688 let palstr = if self.palette { "palette " } else { "" };
689 let astr = if self.alpha { "alpha " } else { "" };
690 let mut str = format!("Formaton for {} ({}{}elem {} size {}): ", self.model, palstr, astr,end, self.elem_size);
691 for i in 0..self.comp_info.len() {
692 if let Some(chr) = self.comp_info[i] {
693 str = format!("{} {}", str, chr);
694 }
695 }
696 write!(f, "[{}]", str)
697 }
698}
699
700#[cfg(test)]
701mod test {
702 use super::*;
703
704 #[test]
705 fn test_fmt() {
706 println!("{}", SND_S16_FORMAT);
707 println!("{}", SND_U8_FORMAT);
126b7eb8 708 println!("{}", SND_F32P_FORMAT);
fba6f8e4
KS
709 println!("formaton yuv- {}", YUV420_FORMAT);
710 println!("formaton pal- {}", PAL8_FORMAT);
711 println!("formaton rgb565- {}", RGB565_FORMAT);
712 }
713}