use nom::Parser;
use nom::bytes::complete::tag;
use crate::audio::{CodecState, decompress};
use crate::error::Error;
use crate::parser::{
FrameInfo, RawChunk, VQAHeader, VQAVersion, form_chunk, frame_info, raw_chunk, vqa_header,
};
use crate::video::{Frame, FrameDecoder};
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct VQA<'a> {
pub form_size: u32,
pub header: VQAHeader,
pub frame_index: Option<Vec<FrameInfo>>,
body: &'a [u8],
}
impl<'a> VQA<'a> {
pub fn parse(buffer: &'a [u8]) -> Result<VQA<'a>, Error> {
let (rest, form) = form_chunk(buffer).map_err(|_| Error::Parse)?;
let (rest, _) = tag::<_, _, nom::error::Error<&[u8]>>("WVQA")
.parse(rest)
.map_err(|_| Error::Parse)?;
let (body, header) = vqa_header(rest).map_err(|_| Error::Parse)?;
let frame_index = Chunks { input: body }
.take_while(Result::is_ok)
.flatten()
.find(|chunk| &chunk.id == b"FINF")
.map(|chunk| {
nom::multi::count(frame_info, chunk.data.len() / 4)
.parse(chunk.data)
.map(|(_, frames)| frames)
.map_err(|_| Error::Parse)
})
.transpose()?;
Ok(VQA {
form_size: form.size,
header,
frame_index,
body,
})
}
pub fn chunks(&self) -> Chunks<'a> {
Chunks { input: self.body }
}
pub fn frames(&self) -> Result<Frames<'a>, Error> {
Ok(Frames {
chunks: self.chunks(),
decoder: FrameDecoder::new(&self.header)?,
done: false,
})
}
pub fn decode_audio(&self) -> Result<Vec<i16>, Error> {
let stereo = self.header.num_channels() >= 2;
let mut left = CodecState::new();
let mut right = CodecState::new();
let mut samples = Vec::new();
for chunk in self.chunks() {
let chunk = chunk?;
match &chunk.id {
b"SND2" => {
if !stereo {
samples.extend(decompress(&mut left, chunk.data));
} else if self.header.version == VQAVersion::Three {
let half = chunk.data.len() / 2;
let l = decompress(&mut left, &chunk.data[..half]);
let r = decompress(&mut right, &chunk.data[half..]);
interleave(&mut samples, &l, &r);
} else {
let lb: Vec<u8> = chunk.data.iter().step_by(2).copied().collect();
let rb: Vec<u8> = chunk.data.iter().skip(1).step_by(2).copied().collect();
let l = decompress(&mut left, &lb);
let r = decompress(&mut right, &rb);
interleave(&mut samples, &l, &r);
}
}
b"SND0" => {
if self.header.bit_depth() == 16 {
samples.extend(
chunk
.data
.chunks_exact(2)
.map(|b| i16::from_le_bytes([b[0], b[1]])),
);
} else {
samples.extend(chunk.data.iter().map(|&b| (i16::from(b) - 128) << 8));
}
}
b"SND1" => return Err(Error::UnsupportedSound("SND1 (Westwood ADPCM)")),
_ => {}
}
}
Ok(samples)
}
}
fn interleave(samples: &mut Vec<i16>, left: &[i16], right: &[i16]) {
for (&l, &r) in left.iter().zip(right) {
samples.push(l);
samples.push(r);
}
}
#[derive(Debug, Clone)]
pub struct Chunks<'a> {
input: &'a [u8],
}
impl<'a> Iterator for Chunks<'a> {
type Item = Result<RawChunk<'a>, Error>;
fn next(&mut self) -> Option<Self::Item> {
if self.input.is_empty() {
return None;
}
match raw_chunk(self.input) {
Ok((rest, chunk)) => {
self.input = rest;
Some(Ok(chunk))
}
Err(_) => {
self.input = &[];
Some(Err(Error::Parse))
}
}
}
}
pub struct Frames<'a> {
chunks: Chunks<'a>,
decoder: FrameDecoder,
done: bool,
}
impl Iterator for Frames<'_> {
type Item = Result<Frame, Error>;
fn next(&mut self) -> Option<Self::Item> {
if self.done {
return None;
}
loop {
match self.chunks.next()? {
Ok(chunk) => match &chunk.id {
b"VQFL" => {
if let Err(e) = self.decoder.process_vqfl(chunk.data) {
self.done = true;
return Some(Err(e));
}
}
b"VQFR" => {
let result = self.decoder.decode_frame(chunk.data);
self.done = result.is_err();
return Some(result);
}
_ => {}
},
Err(e) => {
self.done = true;
return Some(Err(e));
}
}
}
}
}