split remaining decoders and demuxer from core
[nihav.git] / nihav-commonfmt / src / codecs / pcm.rs
CommitLineData
38953fb5
KS
1use std::rc::Rc;
2use std::cell::RefCell;
3use nihav_core::formats::*;
4use nihav_core::codecs::*;
5use nihav_core::frame::*;
3234da61
KS
6
7struct PCMDecoder { chmap: NAChannelMap }
8
9impl PCMDecoder {
10 fn new() -> Self {
11 PCMDecoder { chmap: NAChannelMap::new() }
12 }
13}
14
15const CHMAP_MONO: [NAChannelType; 1] = [NAChannelType::C];
16const CHMAP_STEREO: [NAChannelType; 2] = [NAChannelType::L, NAChannelType::R];
17
18fn 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
12ccce74 28fn get_duration(ainfo: &NAAudioInfo, duration: Option<u64>, data_size: usize) -> u64 {
3234da61 29 if duration == None {
12ccce74
KS
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);
3234da61
KS
32 size_bits / blk_size
33 } else {
12ccce74 34 duration.unwrap() as u64
3234da61
KS
35 }
36}
37
38impl NADecoder for PCMDecoder {
39 fn init(&mut self, info: Rc<NACodecInfo>) -> DecoderResult<()> {
40 if let NACodecTypeInfo::Audio(ainfo) = info.get_properties() {
3234da61
KS
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());
3234da61
KS
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));
12ccce74 57 frm.set_duration(Some(duration));
3234da61
KS
58 frm.set_keyframe(true);
59 Ok(Rc::new(RefCell::new(frm)))
60 } else {
61 Err(DecoderError::InvalidData)
62 }
63 }
64}
65
66pub fn get_decoder() -> Box<NADecoder> {
67 Box::new(PCMDecoder::new())
68}