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