use pikopiko_runtime::binary::Sequencer;
use pikopiko_runtime::synth::ay::{AySynth, AyVariant};
use crate::export::binary::{encode, EncodeError};
use crate::synth::ay_config;
use crate::Song;
pub const SAMPLE_RATE: u32 = 44_100;
const VERSION: u32 = 0x0000_0161;
const HEADER_LEN: usize = 0x80;
const REGISTERS: u8 = 14;
const MAX_SAMPLES: u64 = SAMPLE_RATE as u64 * 3600;
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum VgmError {
UnsupportedSynth(String),
Encode(EncodeError),
TooLong,
}
impl crate::text::Localized for VgmError {
fn text_key(&self) -> &'static str {
match self {
VgmError::UnsupportedSynth(_) => "err-vgm-synth",
VgmError::Encode(e) => crate::text::Localized::text_key(e),
VgmError::TooLong => "err-vgm-too-long",
}
}
fn text_args(&self, f: &mut dyn FnMut(&'static str, crate::text::TextArg<'_>)) {
match self {
VgmError::UnsupportedSynth(name) => f("synth", crate::text::TextArg::Str(name)),
VgmError::Encode(e) => crate::text::Localized::text_args(e, f),
VgmError::TooLong => {}
}
}
fn catalogs(&self) -> &'static [crate::text::Catalog] {
crate::text_table::CATALOGS
}
}
impl std::fmt::Display for VgmError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
crate::text::write_localized(f, self, crate::text::DEFAULT_LANG)
}
}
impl std::error::Error for VgmError {}
fn put_u32(out: &mut [u8], at: usize, v: u32) {
out[at..at + 4].copy_from_slice(&v.to_le_bytes());
}
fn wait(out: &mut Vec<u8>, mut n: u64) {
while n > 0 {
let k = n.min(0xffff);
out.push(0x61);
out.extend_from_slice(&(k as u16).to_le_bytes());
n -= k;
}
}
fn gd3_str(out: &mut Vec<u8>, s: &str) {
for u in s.encode_utf16() {
out.extend_from_slice(&u.to_le_bytes());
}
out.extend_from_slice(&[0, 0]);
}
fn gd3(song: &Song, system: &str) -> Vec<u8> {
let m = &song.meta;
let title = m.title.as_deref().unwrap_or("");
let author = m.composer.as_deref().or(m.artist.as_deref()).unwrap_or("");
let mut notes = m.comment.clone().unwrap_or_default();
if let Some(c) = &m.copyright {
if !notes.is_empty() {
notes.push('\n');
}
notes.push_str(c);
}
let mut body = Vec::new();
for s in [
title, title, "", "", system, system, author, author, "", "pikopiko",
notes.as_str(),
] {
gd3_str(&mut body, s);
}
let mut out = Vec::with_capacity(12 + body.len());
out.extend_from_slice(b"Gd3 ");
out.extend_from_slice(&0x0000_0100u32.to_le_bytes());
out.extend_from_slice(&(body.len() as u32).to_le_bytes());
out.extend_from_slice(&body);
out
}
pub fn encode_vgm(song: &Song) -> Result<Vec<u8>, VgmError> {
let (variant, system, chip_type) = match song.synth.name.as_str() {
"ay-3-8912" => (AyVariant::Ay, "AY-3-8912", 0x01u8),
"ym2149" => (AyVariant::Ym, "YM2149", 0x10u8),
other => return Err(VgmError::UnsupportedSynth(other.to_string())),
};
let bin = encode(song).map_err(VgmError::Encode)?;
let mut synth = AySynth::new(
ay_config(variant, &song.synth),
SAMPLE_RATE,
song.tracks.len(),
);
let mut seq = Sequencer::<3>::new(&bin, SAMPLE_RATE).expect("encode が作ったバイナリは読める");
seq.set_looping(false);
let header = *seq.header();
let loop_at_tick = header.loop_at.map(|u| u as u64 * header.unit as u64);
let mut data: Vec<u8> = Vec::new();
let mut last = [0u8; REGISTERS as usize];
let mut restarts = synth.envelope_restarts();
let mut written: u64 = 0; let mut loop_sample: Option<u64> = None;
let mut loop_pos: usize = 0;
let mut i: u64 = 0;
while {
let before = seq.position();
let more = seq.step(&mut synth);
if more {
if i >= MAX_SAMPLES {
return Err(VgmError::TooLong);
}
let is_loop = loop_sample.is_none() && loop_at_tick.is_some_and(|t| before >= t);
let first = i == 0;
let started = synth.envelope_restarts() != restarts;
restarts = synth.envelope_restarts();
if is_loop || first {
wait(&mut data, i - written);
written = i;
if is_loop {
loop_sample = Some(i);
loop_pos = data.len();
}
for r in 0..REGISTERS {
let v = synth.read_register(r);
data.extend_from_slice(&[0xa0, r, v]);
last[r as usize] = v;
}
} else {
let mut changes: Vec<(u8, u8)> = Vec::new();
for r in 0..REGISTERS {
let v = synth.read_register(r);
if v != last[r as usize] || (r == 13 && started) {
changes.push((r, v));
last[r as usize] = v;
}
}
if !changes.is_empty() {
wait(&mut data, i - written);
written = i;
for (r, v) in changes {
data.extend_from_slice(&[0xa0, r, v]);
}
}
}
i += 1;
}
more
} {}
let total = i;
wait(&mut data, total - written);
data.push(0x66);
let gd3 = gd3(song, system);
let mut out = vec![0u8; HEADER_LEN];
out[0..4].copy_from_slice(b"Vgm ");
put_u32(&mut out, 0x08, VERSION);
put_u32(&mut out, 0x18, total.min(u32::MAX as u64) as u32);
if let Some(ls) = loop_sample {
put_u32(&mut out, 0x1c, (HEADER_LEN + loop_pos - 0x1c) as u32);
put_u32(&mut out, 0x20, (total - ls).min(u32::MAX as u64) as u32);
}
put_u32(&mut out, 0x24, song.frame_hz as u32); put_u32(&mut out, 0x34, (HEADER_LEN - 0x34) as u32);
put_u32(&mut out, 0x74, synth.clock_hz());
out[0x78] = chip_type;
out.extend_from_slice(&data);
let gd3_at = (out.len() - 0x14) as u32;
put_u32(&mut out, 0x14, gd3_at);
out.extend_from_slice(&gd3);
let eof = (out.len() - 4) as u32;
put_u32(&mut out, 0x04, eof);
Ok(out)
}