1 use nihav_core::formats::*;
2 use nihav_core::codecs::*;
3 use nihav_core::io::byteio::*;
5 #[derive(Clone,Copy,Debug,PartialEq)]
17 fn cvt_alaw(val: u8) -> i16 {
19 let sign = (val & 0x80) != 0;
20 let exp = ((val >> 4) & 7) + 4;
21 let mant = (val & 0xF) + if exp != 0 { 16 } else { 0 };
22 let aval = i16::from(mant) << exp;
23 if sign { aval } else { -aval }
26 fn cvt_mulaw(val: u8) -> i16 {
28 let sign = (val & 0x80) != 0;
29 let exp = ((val >> 4) & 7) + 3;
30 let mant = (val & 0xF) | 0x10;
31 let aval = (i16::from(mant) << exp) - 128 - 4;
32 if !sign { aval } else { -aval }
36 fn new(mode: PCMMode) -> Self {
37 PCMDecoder { chmap: NAChannelMap::new(), mode }
39 fn decode_xlaw(&self, pkt: &NAPacket, duration: u64, srate: u32) -> DecoderResult<NAFrameRef> {
40 let pktbuf = pkt.get_buffer();
41 let channels = self.chmap.num_channels();
42 let abuf = alloc_audio_buffer(NAAudioInfo::new(srate, channels as u8, SND_S16_FORMAT, 1), duration as usize, self.chmap.clone())?;
43 let mut buf = abuf.get_abuf_i16().unwrap();
44 let dst = buf.get_data_mut().unwrap();
45 for (src, dst) in pktbuf.chunks(channels).zip(dst.chunks_mut(channels)) {
46 for (isamp, dsamp) in src.iter().zip(dst.iter_mut()) {
47 *dsamp = if self.mode == PCMMode::ALaw { cvt_alaw(*isamp) } else { cvt_mulaw(*isamp) };
50 let info = pkt.get_stream().get_info();
51 let mut frm = NAFrame::new_from_pkt(pkt, info, abuf);
52 frm.set_duration(Some(duration));
53 frm.set_keyframe(true);
58 const CHMAP_MONO: [NAChannelType; 1] = [NAChannelType::C];
59 const CHMAP_STEREO: [NAChannelType; 2] = [NAChannelType::L, NAChannelType::R];
61 fn get_default_chmap(nch: u8) -> NAChannelMap {
62 let mut chmap = NAChannelMap::new();
64 1 => chmap.add_channels(&CHMAP_MONO),
65 2 => chmap.add_channels(&CHMAP_STEREO),
71 fn get_duration(ainfo: &NAAudioInfo, duration: Option<u64>, data_size: usize) -> u64 {
73 let size_bits = (data_size as u64) * 8;
74 let blk_size = u64::from(ainfo.get_channels()) * u64::from(ainfo.get_format().get_bits());
81 impl NADecoder for PCMDecoder {
82 fn init(&mut self, _supp: &mut NADecoderSupport, info: NACodecInfoRef) -> DecoderResult<()> {
83 if let NACodecTypeInfo::Audio(ainfo) = info.get_properties() {
84 self.chmap = get_default_chmap(ainfo.get_channels());
85 if self.chmap.num_channels() == 0 { return Err(DecoderError::InvalidData); }
88 Err(DecoderError::InvalidData)
91 fn decode(&mut self, _supp: &mut NADecoderSupport, pkt: &NAPacket) -> DecoderResult<NAFrameRef> {
92 let info = pkt.get_stream().get_info();
93 if let NACodecTypeInfo::Audio(ainfo) = info.get_properties() {
94 let duration = get_duration(&ainfo, pkt.get_duration(), pkt.get_buffer().len());
95 if self.mode != PCMMode::Infinity {
96 return self.decode_xlaw(pkt, duration, ainfo.sample_rate);
98 let pktbuf = pkt.get_buffer();
99 let abuf = NAAudioBuffer::new_from_buf(ainfo, pktbuf, self.chmap.clone());
100 let mut frm = NAFrame::new_from_pkt(pkt, info, NABufferType::AudioPacked(abuf));
101 frm.set_duration(Some(duration));
102 frm.set_keyframe(true);
105 Err(DecoderError::InvalidData)
108 fn flush(&mut self) {
112 impl NAOptionHandler for PCMDecoder {
113 fn get_supported_options(&self) -> &[NAOptionDefinition] { &[] }
114 fn set_options(&mut self, _options: &[NAOption]) { }
115 fn query_option_value(&self, _name: &str) -> Option<NAValue> { None }
118 pub fn get_decoder() -> Box<dyn NADecoder + Send> {
119 Box::new(PCMDecoder::new(PCMMode::Infinity))
122 pub fn get_a_law_decoder() -> Box<dyn NADecoder + Send> {
123 Box::new(PCMDecoder::new(PCMMode::ALaw))
126 pub fn get_mu_law_decoder() -> Box<dyn NADecoder + Send> {
127 Box::new(PCMDecoder::new(PCMMode::MuLaw))
131 stream: Option<NAStreamRef>,
132 pkt: Option<NAPacket>,
144 macro_rules! write_buffer {
145 ($abuf: expr, $dvec: expr, $write_be: ident, $write_le: ident, $dtype: tt) => {
146 let info = $abuf.get_info();
147 let len = $abuf.get_length();
148 let data = $abuf.get_data();
149 let channels = $abuf.get_chmap().num_channels();
150 let stride = $abuf.get_stride();
151 let step = $abuf.get_step();
152 let is_be = info.format.be;
154 $dvec = vec![0u8; len * channels * std::mem::size_of::<$dtype>()];
155 let mut mw = MemoryWriter::new_write($dvec.as_mut_slice());
156 let mut bw = ByteWriter::new(&mut mw);
158 for j in 0..channels {
160 bw.$write_be(data[off * step + j * stride] as $dtype).unwrap();
162 bw.$write_le(data[off * step + j * stride] as $dtype).unwrap();
169 impl NAEncoder for PCMEncoder {
170 fn negotiate_format(&self, encinfo: &EncodeParameters) -> EncoderResult<EncodeParameters> {
171 match encinfo.format {
172 NACodecTypeInfo::None => {
173 let mut ofmt = EncodeParameters::default();
174 ofmt.format = NACodecTypeInfo::Audio(NAAudioInfo::new(0, 0, SND_S16P_FORMAT, 0));
177 NACodecTypeInfo::Video(_) => Err(EncoderError::FormatError),
178 NACodecTypeInfo::Audio(_) => {
183 fn init(&mut self, stream_id: u32, encinfo: EncodeParameters) -> EncoderResult<NAStreamRef> {
184 match encinfo.format {
185 NACodecTypeInfo::None => Err(EncoderError::FormatError),
186 NACodecTypeInfo::Video(_) => Err(EncoderError::FormatError),
187 NACodecTypeInfo::Audio(_) => {
188 let info = NACodecInfo::new("pcm", encinfo.format, None);
189 let mut stream = NAStream::new(StreamType::Audio, stream_id, info, encinfo.tb_num, encinfo.tb_den);
190 stream.set_num(stream_id as usize);
191 let stream = stream.into_ref();
192 self.stream = Some(stream.clone());
197 fn encode(&mut self, frm: &NAFrame) -> EncoderResult<()> {
198 let buf = frm.get_buffer();
201 NABufferType::AudioU8(ref abuf) => {
202 let stride = abuf.get_stride();
203 if stride == 1 { // packed already
204 self.pkt = Some(NAPacket::new_from_refbuf(self.stream.clone().unwrap(), frm.ts, true, abuf.get_data_ref()));
207 let len = abuf.get_length();
208 let data = abuf.get_data();
209 let channels = abuf.get_chmap().num_channels();
210 dbuf = Vec::with_capacity(len * channels);
212 for j in 0..channels {
213 dbuf.push(data[off + j * stride]);
217 NABufferType::AudioI16(ref abuf) => {
218 write_buffer!(abuf, dbuf, write_u16be, write_u16le, u16);
220 NABufferType::AudioI32(ref abuf) => {
221 write_buffer!(abuf, dbuf, write_u32be, write_u32le, u32);
223 NABufferType::AudioF32(ref abuf) => {
224 write_buffer!(abuf, dbuf, write_f32be, write_f32le, f32);
226 NABufferType::AudioPacked(ref abuf) => {
227 self.pkt = Some(NAPacket::new_from_refbuf(self.stream.clone().unwrap(), frm.ts, true, abuf.get_data_ref()));
230 NABufferType::None => {
234 _ => return Err(EncoderError::FormatError),
236 self.pkt = Some(NAPacket::new(self.stream.clone().unwrap(), frm.ts, true, dbuf));
239 fn get_packet(&mut self) -> EncoderResult<Option<NAPacket>> {
241 std::mem::swap(&mut self.pkt, &mut npkt);
244 fn flush(&mut self) -> EncoderResult<()> {
249 impl NAOptionHandler for PCMEncoder {
250 fn get_supported_options(&self) -> &[NAOptionDefinition] { &[] }
251 fn set_options(&mut self, _options: &[NAOption]) { }
252 fn query_option_value(&self, _name: &str) -> Option<NAValue> { None }
255 pub fn get_encoder() -> Box<dyn NAEncoder + Send> {
256 Box::new(PCMEncoder::new())