formats: add some helper functions and make formaton and chromaton fields public
[nihav.git] / nihav-core / src / formats.rs
1 use std::str::FromStr;
2 use std::string::*;
3 use std::fmt;
4
5 #[derive(Debug,Copy,Clone,PartialEq)]
6 pub struct NASoniton {
7 bits: u8,
8 be: bool,
9 packed: bool,
10 planar: bool,
11 float: bool,
12 signed: bool,
13 }
14
15 pub const SONITON_FLAG_BE :u32 = 0x01;
16 pub const SONITON_FLAG_PACKED :u32 = 0x02;
17 pub const SONITON_FLAG_PLANAR :u32 = 0x04;
18 pub const SONITON_FLAG_FLOAT :u32 = 0x08;
19 pub const SONITON_FLAG_SIGNED :u32 = 0x10;
20
21 pub const SND_U8_FORMAT: NASoniton = NASoniton { bits: 8, be: false, packed: false, planar: false, float: false, signed: false };
22 pub const SND_S16_FORMAT: NASoniton = NASoniton { bits: 16, be: false, packed: false, planar: false, float: false, signed: true };
23 pub const SND_S16P_FORMAT: NASoniton = NASoniton { bits: 16, be: false, packed: false, planar: true, float: false, signed: true };
24 pub const SND_F32P_FORMAT: NASoniton = NASoniton { bits: 32, be: false, packed: false, planar: true, float: true, signed: true };
25
26 impl NASoniton {
27 pub fn new(bits: u8, flags: u32) -> Self {
28 let is_be = (flags & SONITON_FLAG_BE) != 0;
29 let is_pk = (flags & SONITON_FLAG_PACKED) != 0;
30 let is_pl = (flags & SONITON_FLAG_PLANAR) != 0;
31 let is_fl = (flags & SONITON_FLAG_FLOAT) != 0;
32 let is_sg = (flags & SONITON_FLAG_SIGNED) != 0;
33 NASoniton { bits: bits, be: is_be, packed: is_pk, planar: is_pl, float: is_fl, signed: is_sg }
34 }
35
36 pub fn get_bits(&self) -> u8 { self.bits }
37 pub fn is_be(&self) -> bool { self.be }
38 pub fn is_packed(&self) -> bool { self.packed }
39 pub fn is_planar(&self) -> bool { self.planar }
40 pub fn is_float(&self) -> bool { self.float }
41 pub fn is_signed(&self) -> bool { self.signed }
42
43 pub fn get_audio_size(&self, length: u64) -> usize {
44 if self.packed {
45 ((length * (self.bits as u64) + 7) >> 3) as usize
46 } else {
47 (length * (((self.bits + 7) >> 3) as u64)) as usize
48 }
49 }
50 }
51
52 impl fmt::Display for NASoniton {
53 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
54 let fmt = if self.float { "float" } else if self.signed { "int" } else { "uint" };
55 let end = if self.be { "BE" } else { "LE" };
56 write!(f, "({} bps, {} planar: {} packed: {} {})", self.bits, end, self.packed, self.planar, fmt)
57 }
58 }
59
60 #[derive(Debug,Clone,Copy,PartialEq)]
61 pub enum NAChannelType {
62 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
63 }
64
65 impl NAChannelType {
66 pub fn is_center(&self) -> bool {
67 match *self {
68 NAChannelType::C => true, NAChannelType::Ch => true,
69 NAChannelType::Cl => true, NAChannelType::Ov => true,
70 NAChannelType::LFE => true, NAChannelType::LFE2 => true,
71 NAChannelType::Cs => true, NAChannelType::Chs => true,
72 _ => false,
73 }
74 }
75 pub fn is_left(&self) -> bool {
76 match *self {
77 NAChannelType::L => true, NAChannelType::Ls => true,
78 NAChannelType::Lss => true, NAChannelType::Lc => true,
79 NAChannelType::Lh => true, NAChannelType::Lw => true,
80 NAChannelType::Lhs => true, NAChannelType::Ll => true,
81 NAChannelType::Lt => true, NAChannelType::Lo => true,
82 _ => false,
83 }
84 }
85 pub fn is_right(&self) -> bool {
86 match *self {
87 NAChannelType::R => true, NAChannelType::Rs => true,
88 NAChannelType::Rss => true, NAChannelType::Rc => true,
89 NAChannelType::Rh => true, NAChannelType::Rw => true,
90 NAChannelType::Rhs => true, NAChannelType::Rl => true,
91 NAChannelType::Rt => true, NAChannelType::Ro => true,
92 _ => false,
93 }
94 }
95 }
96
97 #[derive(Clone,Copy,Debug,PartialEq)]
98 pub struct ChannelParseError {}
99
100 impl FromStr for NAChannelType {
101 type Err = ChannelParseError;
102
103 fn from_str(s: &str) -> Result<Self, Self::Err> {
104 match s {
105 "C" => Ok(NAChannelType::C),
106 "L" => Ok(NAChannelType::L),
107 "R" => Ok(NAChannelType::R),
108 "Cs" => Ok(NAChannelType::Cs),
109 "Ls" => Ok(NAChannelType::Ls),
110 "Rs" => Ok(NAChannelType::Rs),
111 "Lss" => Ok(NAChannelType::Lss),
112 "Rss" => Ok(NAChannelType::Rss),
113 "LFE" => Ok(NAChannelType::LFE),
114 "Lc" => Ok(NAChannelType::Lc),
115 "Rc" => Ok(NAChannelType::Rc),
116 "Lh" => Ok(NAChannelType::Lh),
117 "Rh" => Ok(NAChannelType::Rh),
118 "Ch" => Ok(NAChannelType::Ch),
119 "LFE2" => Ok(NAChannelType::LFE2),
120 "Lw" => Ok(NAChannelType::Lw),
121 "Rw" => Ok(NAChannelType::Rw),
122 "Ov" => Ok(NAChannelType::Ov),
123 "Lhs" => Ok(NAChannelType::Lhs),
124 "Rhs" => Ok(NAChannelType::Rhs),
125 "Chs" => Ok(NAChannelType::Chs),
126 "Ll" => Ok(NAChannelType::Ll),
127 "Rl" => Ok(NAChannelType::Rl),
128 "Cl" => Ok(NAChannelType::Cl),
129 "Lt" => Ok(NAChannelType::Lt),
130 "Rt" => Ok(NAChannelType::Rt),
131 "Lo" => Ok(NAChannelType::Lo),
132 "Ro" => Ok(NAChannelType::Ro),
133 _ => Err(ChannelParseError{}),
134 }
135 }
136 }
137
138 impl fmt::Display for NAChannelType {
139 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
140 let name = match *self {
141 NAChannelType::C => "C".to_string(),
142 NAChannelType::L => "L".to_string(),
143 NAChannelType::R => "R".to_string(),
144 NAChannelType::Cs => "Cs".to_string(),
145 NAChannelType::Ls => "Ls".to_string(),
146 NAChannelType::Rs => "Rs".to_string(),
147 NAChannelType::Lss => "Lss".to_string(),
148 NAChannelType::Rss => "Rss".to_string(),
149 NAChannelType::LFE => "LFE".to_string(),
150 NAChannelType::Lc => "Lc".to_string(),
151 NAChannelType::Rc => "Rc".to_string(),
152 NAChannelType::Lh => "Lh".to_string(),
153 NAChannelType::Rh => "Rh".to_string(),
154 NAChannelType::Ch => "Ch".to_string(),
155 NAChannelType::LFE2 => "LFE2".to_string(),
156 NAChannelType::Lw => "Lw".to_string(),
157 NAChannelType::Rw => "Rw".to_string(),
158 NAChannelType::Ov => "Ov".to_string(),
159 NAChannelType::Lhs => "Lhs".to_string(),
160 NAChannelType::Rhs => "Rhs".to_string(),
161 NAChannelType::Chs => "Chs".to_string(),
162 NAChannelType::Ll => "Ll".to_string(),
163 NAChannelType::Rl => "Rl".to_string(),
164 NAChannelType::Cl => "Cl".to_string(),
165 NAChannelType::Lt => "Lt".to_string(),
166 NAChannelType::Rt => "Rt".to_string(),
167 NAChannelType::Lo => "Lo".to_string(),
168 NAChannelType::Ro => "Ro".to_string(),
169 };
170 write!(f, "{}", name)
171 }
172 }
173
174 #[derive(Clone)]
175 pub struct NAChannelMap {
176 ids: Vec<NAChannelType>,
177 }
178
179 const MS_CHANNEL_MAP: [NAChannelType; 11] = [
180 NAChannelType::L,
181 NAChannelType::R,
182 NAChannelType::C,
183 NAChannelType::LFE,
184 NAChannelType::Ls,
185 NAChannelType::Rs,
186 NAChannelType::Lss,
187 NAChannelType::Rss,
188 NAChannelType::Cs,
189 NAChannelType::Lc,
190 NAChannelType::Rc,
191 ];
192
193 impl NAChannelMap {
194 pub fn new() -> Self { NAChannelMap { ids: Vec::new() } }
195 pub fn add_channel(&mut self, ch: NAChannelType) {
196 self.ids.push(ch);
197 }
198 pub fn add_channels(&mut self, chs: &[NAChannelType]) {
199 for i in 0..chs.len() {
200 self.ids.push(chs[i]);
201 }
202 }
203 pub fn num_channels(&self) -> usize {
204 self.ids.len()
205 }
206 pub fn get_channel(&self, idx: usize) -> NAChannelType {
207 self.ids[idx]
208 }
209 pub fn find_channel_id(&self, t: NAChannelType) -> Option<u8> {
210 for i in 0..self.ids.len() {
211 if self.ids[i] as i32 == t as i32 { return Some(i as u8); }
212 }
213 None
214 }
215 pub fn from_ms_mapping(chmap: u32) -> Self {
216 let mut cm = NAChannelMap::new();
217 for i in 0..MS_CHANNEL_MAP.len() {
218 if ((chmap >> i) & 1) != 0 {
219 cm.add_channel(MS_CHANNEL_MAP[i]);
220 }
221 }
222 cm
223 }
224 }
225
226 impl fmt::Display for NAChannelMap {
227 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
228 let mut map = String::new();
229 for el in self.ids.iter() {
230 if map.len() > 0 { map.push(','); }
231 map.push_str(&*el.to_string());
232 }
233 write!(f, "{}", map)
234 }
235 }
236
237 impl FromStr for NAChannelMap {
238 type Err = ChannelParseError;
239
240 fn from_str(s: &str) -> Result<Self, Self::Err> {
241 let mut chm = NAChannelMap::new();
242 for tok in s.split(',') {
243 chm.add_channel(NAChannelType::from_str(tok)?);
244 }
245 Ok(chm)
246 }
247 }
248
249 #[derive(Debug,Clone,Copy,PartialEq)]
250 pub enum RGBSubmodel {
251 RGB,
252 SRGB,
253 }
254
255 impl fmt::Display for RGBSubmodel {
256 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
257 let name = match *self {
258 RGBSubmodel::RGB => "RGB".to_string(),
259 RGBSubmodel::SRGB => "sRGB".to_string(),
260 };
261 write!(f, "{}", name)
262 }
263 }
264
265 #[derive(Debug,Clone,Copy,PartialEq)]
266 pub enum YUVSubmodel {
267 YCbCr,
268 YIQ,
269 YUVJ,
270 }
271
272 impl fmt::Display for YUVSubmodel {
273 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
274 let name = match *self {
275 YUVSubmodel::YCbCr => "YCbCr".to_string(),
276 YUVSubmodel::YIQ => "YIQ".to_string(),
277 YUVSubmodel::YUVJ => "YUVJ".to_string(),
278 };
279 write!(f, "{}", name)
280 }
281 }
282
283 #[derive(Debug, Clone,Copy,PartialEq)]
284 pub enum ColorModel {
285 RGB(RGBSubmodel),
286 YUV(YUVSubmodel),
287 CMYK,
288 HSV,
289 LAB,
290 XYZ,
291 }
292
293 impl ColorModel {
294 pub fn get_default_components(&self) -> usize {
295 match *self {
296 ColorModel::CMYK => 4,
297 _ => 3,
298 }
299 }
300 pub fn is_rgb(&self) -> bool {
301 match *self {
302 ColorModel::RGB(_) => true,
303 _ => false,
304 }
305 }
306 pub fn is_yuv(&self) -> bool {
307 match *self {
308 ColorModel::YUV(_) => true,
309 _ => false,
310 }
311 }
312 }
313
314 impl fmt::Display for ColorModel {
315 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
316 let name = match *self {
317 ColorModel::RGB(fmt) => format!("RGB({})", fmt).to_string(),
318 ColorModel::YUV(fmt) => format!("YUV({})", fmt).to_string(),
319 ColorModel::CMYK => "CMYK".to_string(),
320 ColorModel::HSV => "HSV".to_string(),
321 ColorModel::LAB => "LAB".to_string(),
322 ColorModel::XYZ => "XYZ".to_string(),
323 };
324 write!(f, "{}", name)
325 }
326 }
327
328 #[derive(Clone,Copy,PartialEq)]
329 pub struct NAPixelChromaton {
330 pub h_ss: u8,
331 pub v_ss: u8,
332 pub packed: bool,
333 pub depth: u8,
334 pub shift: u8,
335 pub comp_offs: u8,
336 pub next_elem: u8,
337 }
338
339 pub const FORMATON_FLAG_BE :u32 = 0x01;
340 pub const FORMATON_FLAG_ALPHA :u32 = 0x02;
341 pub const FORMATON_FLAG_PALETTE :u32 = 0x04;
342
343
344 #[derive(Clone,Copy,PartialEq)]
345 pub struct NAPixelFormaton {
346 pub model: ColorModel,
347 pub components: u8,
348 pub comp_info: [Option<NAPixelChromaton>; 5],
349 pub elem_size: u8,
350 pub be: bool,
351 pub alpha: bool,
352 pub palette: bool,
353 }
354
355 macro_rules! chromaton {
356 ($hs: expr, $vs: expr, $pck: expr, $d: expr, $sh: expr, $co: expr, $ne: expr) => ({
357 Some(NAPixelChromaton{ h_ss: $hs, v_ss: $vs, packed: $pck, depth: $d, shift: $sh, comp_offs: $co, next_elem: $ne })
358 });
359 (yuv8; $hs: expr, $vs: expr, $co: expr) => ({
360 Some(NAPixelChromaton{ h_ss: $hs, v_ss: $vs, packed: false, depth: 8, shift: 0, comp_offs: $co, next_elem: 1 })
361 });
362 (packrgb; $d: expr, $s: expr, $co: expr, $ne: expr) => ({
363 Some(NAPixelChromaton{ h_ss: 0, v_ss: 0, packed: true, depth: $d, shift: $s, comp_offs: $co, next_elem: $ne })
364 });
365 (pal8; $co: expr) => ({
366 Some(NAPixelChromaton{ h_ss: 0, v_ss: 0, packed: true, depth: 8, shift: 0, comp_offs: $co, next_elem: 3 })
367 });
368 }
369
370 pub const YUV420_FORMAT: NAPixelFormaton = NAPixelFormaton { model: ColorModel::YUV(YUVSubmodel::YUVJ), components: 3,
371 comp_info: [
372 chromaton!(0, 0, false, 8, 0, 0, 1),
373 chromaton!(yuv8; 1, 1, 1),
374 chromaton!(yuv8; 1, 1, 2),
375 None, None],
376 elem_size: 0, be: false, alpha: false, palette: false };
377
378 pub const YUV410_FORMAT: NAPixelFormaton = NAPixelFormaton { model: ColorModel::YUV(YUVSubmodel::YUVJ), components: 3,
379 comp_info: [
380 chromaton!(0, 0, false, 8, 0, 0, 1),
381 chromaton!(yuv8; 2, 2, 1),
382 chromaton!(yuv8; 2, 2, 2),
383 None, None],
384 elem_size: 0, be: false, alpha: false, palette: false };
385 pub const YUVA410_FORMAT: NAPixelFormaton = NAPixelFormaton { model: ColorModel::YUV(YUVSubmodel::YUVJ), components: 4,
386 comp_info: [
387 chromaton!(0, 0, false, 8, 0, 0, 1),
388 chromaton!(yuv8; 2, 2, 1),
389 chromaton!(yuv8; 2, 2, 2),
390 chromaton!(0, 0, false, 8, 0, 3, 1),
391 None],
392 elem_size: 0, be: false, alpha: true, palette: false };
393
394 pub const PAL8_FORMAT: NAPixelFormaton = NAPixelFormaton { model: ColorModel::RGB(RGBSubmodel::RGB), components: 3,
395 comp_info: [
396 chromaton!(pal8; 0),
397 chromaton!(pal8; 1),
398 chromaton!(pal8; 2),
399 None, None],
400 elem_size: 3, be: false, alpha: false, palette: true };
401
402 pub const RGB565_FORMAT: NAPixelFormaton = NAPixelFormaton { model: ColorModel::RGB(RGBSubmodel::RGB), components: 3,
403 comp_info: [
404 chromaton!(packrgb; 5, 11, 0, 2),
405 chromaton!(packrgb; 6, 5, 0, 2),
406 chromaton!(packrgb; 5, 0, 0, 2),
407 None, None],
408 elem_size: 2, be: false, alpha: false, palette: false };
409
410 pub const RGB24_FORMAT: NAPixelFormaton = NAPixelFormaton { model: ColorModel::RGB(RGBSubmodel::RGB), components: 3,
411 comp_info: [
412 chromaton!(packrgb; 8, 0, 2, 3),
413 chromaton!(packrgb; 8, 0, 1, 3),
414 chromaton!(packrgb; 8, 0, 0, 3),
415 None, None],
416 elem_size: 3, be: false, alpha: false, palette: false };
417
418 impl NAPixelChromaton {
419 pub fn new(h_ss: u8, v_ss: u8, packed: bool, depth: u8, shift: u8, comp_offs: u8, next_elem: u8) -> Self {
420 Self { h_ss, v_ss, packed, depth, shift, comp_offs, next_elem }
421 }
422 pub fn get_subsampling(&self) -> (u8, u8) { (self.h_ss, self.v_ss) }
423 pub fn is_packed(&self) -> bool { self.packed }
424 pub fn get_depth(&self) -> u8 { self.depth }
425 pub fn get_shift(&self) -> u8 { self.shift }
426 pub fn get_offset(&self) -> u8 { self.comp_offs }
427 pub fn get_step(&self) -> u8 { self.next_elem }
428
429 pub fn get_width(&self, width: usize) -> usize {
430 (width + ((1 << self.h_ss) - 1)) >> self.h_ss
431 }
432 pub fn get_height(&self, height: usize) -> usize {
433 (height + ((1 << self.v_ss) - 1)) >> self.v_ss
434 }
435 pub fn get_linesize(&self, width: usize) -> usize {
436 let d = self.depth as usize;
437 if self.packed {
438 (self.get_width(width) * d + d - 1) >> 3
439 } else {
440 self.get_width(width)
441 }
442 }
443 pub fn get_data_size(&self, width: usize, height: usize) -> usize {
444 let nh = (height + ((1 << self.v_ss) - 1)) >> self.v_ss;
445 self.get_linesize(width) * nh
446 }
447 }
448
449 impl fmt::Display for NAPixelChromaton {
450 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
451 let pfmt = if self.packed {
452 let mask = ((1 << self.depth) - 1) << self.shift;
453 format!("packed(+{},{:X}, step {})", self.comp_offs, mask, self.next_elem)
454 } else {
455 format!("planar({},{})", self.comp_offs, self.next_elem)
456 };
457 write!(f, "({}x{}, {})", self.h_ss, self.v_ss, pfmt)
458 }
459 }
460
461 impl NAPixelFormaton {
462 pub fn new(model: ColorModel,
463 comp1: Option<NAPixelChromaton>,
464 comp2: Option<NAPixelChromaton>,
465 comp3: Option<NAPixelChromaton>,
466 comp4: Option<NAPixelChromaton>,
467 comp5: Option<NAPixelChromaton>,
468 flags: u32, elem_size: u8) -> Self {
469 let mut chromatons: [Option<NAPixelChromaton>; 5] = [None; 5];
470 let mut ncomp = 0;
471 let be = (flags & FORMATON_FLAG_BE) != 0;
472 let alpha = (flags & FORMATON_FLAG_ALPHA) != 0;
473 let palette = (flags & FORMATON_FLAG_PALETTE) != 0;
474 if let Some(c) = comp1 { chromatons[0] = Some(c); ncomp += 1; }
475 if let Some(c) = comp2 { chromatons[1] = Some(c); ncomp += 1; }
476 if let Some(c) = comp3 { chromatons[2] = Some(c); ncomp += 1; }
477 if let Some(c) = comp4 { chromatons[3] = Some(c); ncomp += 1; }
478 if let Some(c) = comp5 { chromatons[4] = Some(c); ncomp += 1; }
479 NAPixelFormaton { model: model,
480 components: ncomp,
481 comp_info: chromatons,
482 elem_size: elem_size,
483 be: be, alpha: alpha, palette: palette }
484 }
485
486 pub fn get_model(&self) -> ColorModel { self.model }
487 pub fn get_num_comp(&self) -> usize { self.components as usize }
488 pub fn get_chromaton(&self, idx: usize) -> Option<NAPixelChromaton> {
489 if idx < self.comp_info.len() { return self.comp_info[idx]; }
490 None
491 }
492 pub fn is_be(&self) -> bool { self.be }
493 pub fn has_alpha(&self) -> bool { self.alpha }
494 pub fn is_paletted(&self) -> bool { self.palette }
495 pub fn get_elem_size(&self) -> u8 { self.elem_size }
496 }
497
498 impl fmt::Display for NAPixelFormaton {
499 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
500 let end = if self.be { "BE" } else { "LE" };
501 let palstr = if self.palette { "palette " } else { "" };
502 let astr = if self.alpha { "alpha " } else { "" };
503 let mut str = format!("Formaton for {} ({}{}elem {} size {}): ", self.model, palstr, astr,end, self.elem_size);
504 for i in 0..self.comp_info.len() {
505 if let Some(chr) = self.comp_info[i] {
506 str = format!("{} {}", str, chr);
507 }
508 }
509 write!(f, "[{}]", str)
510 }
511 }
512
513 #[cfg(test)]
514 mod test {
515 use super::*;
516
517 #[test]
518 fn test_fmt() {
519 println!("{}", SND_S16_FORMAT);
520 println!("{}", SND_U8_FORMAT);
521 println!("{}", SND_F32P_FORMAT);
522 println!("formaton yuv- {}", YUV420_FORMAT);
523 println!("formaton pal- {}", PAL8_FORMAT);
524 println!("formaton rgb565- {}", RGB565_FORMAT);
525 }
526 }