//! RIFF WAVE format sounds.

use crate::durandal::{err::*, sound::*};
use std::io;

/// Writes a WAVE file from a sound.
///
/// # Errors
///
/// Errors if `out` cannot be written to.
pub fn write_wav(out: &mut impl io::Write, snd: &impl Sound) -> ResultS<()>
{
   let smp_rate = u32::from(snd.rate());
   let smp_size = smp_rate * 2;
   let dat_size = snd.len() as u32 * 2;

   out.write_all(b"RIFF")?;
   out.write_all(&u32::to_le_bytes(36 + dat_size))?;
   out.write_all(b"WAVE")?;

   out.write_all(b"fmt ")?;
   out.write_all(&u32::to_le_bytes(16))?;
   // PCM
   out.write_all(&u16::to_le_bytes(1))?;
   // mono
   out.write_all(&u16::to_le_bytes(1))?;
   out.write_all(&u32::to_le_bytes(smp_rate))?;
   out.write_all(&u32::to_le_bytes(smp_size))?;
   // block alignment
   out.write_all(&u16::to_le_bytes(2))?;
   // bits per sample
   out.write_all(&u16::to_le_bytes(16))?;

   out.write_all(b"data")?;
   out.write_all(&u32::to_le_bytes(dat_size))?;

   for p in 0..snd.len() {
      let sample = snd.index(p);
      out.write_all(&sample.to_le_bytes())?;
   }

   Ok(())
}

// EOF
