edc8124e473c811b388ae74ecc9344da598523c4
[nihav.git] / nihav-commonfmt / src / codecs / pcm.rs
1 use std::rc::Rc;
2 use std::cell::RefCell;
3 use nihav_core::formats::*;
4 use nihav_core::codecs::*;
5
6 struct PCMDecoder { chmap: NAChannelMap }
7
8 impl PCMDecoder {
9 fn new() -> Self {
10 PCMDecoder { chmap: NAChannelMap::new() }
11 }
12 }
13
14 const CHMAP_MONO: [NAChannelType; 1] = [NAChannelType::C];
15 const CHMAP_STEREO: [NAChannelType; 2] = [NAChannelType::L, NAChannelType::R];
16
17 fn get_default_chmap(nch: u8) -> NAChannelMap {
18 let mut chmap = NAChannelMap::new();
19 match nch {
20 1 => chmap.add_channels(&CHMAP_MONO),
21 2 => chmap.add_channels(&CHMAP_STEREO),
22 _ => (),
23 }
24 chmap
25 }
26
27 fn get_duration(ainfo: &NAAudioInfo, duration: Option<u64>, data_size: usize) -> u64 {
28 if duration == None {
29 let size_bits = (data_size as u64) * 8;
30 let blk_size = (ainfo.get_channels() as u64) * (ainfo.get_format().get_bits() as u64);
31 size_bits / blk_size
32 } else {
33 duration.unwrap() as u64
34 }
35 }
36
37 impl NADecoder for PCMDecoder {
38 fn init(&mut self, info: Rc<NACodecInfo>) -> DecoderResult<()> {
39 if let NACodecTypeInfo::Audio(ainfo) = info.get_properties() {
40 self.chmap = get_default_chmap(ainfo.get_channels());
41 if self.chmap.num_channels() == 0 { return Err(DecoderError::InvalidData); }
42 Ok(())
43 } else {
44 Err(DecoderError::InvalidData)
45 }
46 }
47 fn decode(&mut self, pkt: &NAPacket) -> DecoderResult<NAFrameRef> {
48 let info = pkt.get_stream().get_info();
49 if let NACodecTypeInfo::Audio(ainfo) = info.get_properties() {
50 let duration = get_duration(&ainfo, pkt.get_duration(), pkt.get_buffer().len());
51 let pktbuf = pkt.get_buffer();
52 let abuf = NAAudioBuffer::new_from_buf(ainfo, pktbuf, self.chmap.clone());
53 let mut frm = NAFrame::new_from_pkt(pkt, info, NABufferType::AudioPacked(abuf));
54 frm.set_duration(Some(duration));
55 frm.set_keyframe(true);
56 Ok(Rc::new(RefCell::new(frm)))
57 } else {
58 Err(DecoderError::InvalidData)
59 }
60 }
61 }
62
63 pub fn get_decoder() -> Box<NADecoder> {
64 Box::new(PCMDecoder::new())
65 }