use super::*;
pub(super) fn vibrato_of(song: &Song, idx: Option<u8>) -> Option<pikopiko_runtime::pitch::Vibrato> {
idx.and_then(|i| song.vibratos.get(i as usize))
.map(|v| v.view())
}
pub(super) fn detune_of(
song: &Song,
idx: Option<u8>,
) -> Option<pikopiko_runtime::pitch::Detune<'_>> {
idx.and_then(|i| song.detunes.get(i as usize))
.map(|d| d.view())
}
pub(super) fn envelope_of(
song: &Song,
idx: Option<u8>,
) -> Option<pikopiko_runtime::envelope::Envelope<'_>> {
idx.and_then(|i| song.envelopes.get(i as usize))
.map(|e| e.view())
}
pub(super) fn duty_of(
song: &Song,
idx: Option<u8>,
) -> Option<pikopiko_runtime::envelope::Envelope<'_>> {
idx.and_then(|i| song.duties.get(i as usize))
.map(|e| e.view())
}
pub(super) fn arp_of(song: &Song, idx: Option<u8>) -> Option<pikopiko_runtime::pitch::Detune<'_>> {
idx.and_then(|i| song.arps.get(i as usize))
.map(|d| d.view())
}
pub(super) fn pitch_fx_of(
song: &Song,
vib: Option<u8>,
detune: Option<u8>,
arp: Option<u8>,
) -> pikopiko_runtime::pitch::PitchFx<'_> {
pikopiko_runtime::pitch::PitchFx {
vib: vibrato_of(song, vib),
detune: detune_of(song, detune),
arp: arp_of(song, arp),
}
}
pub(super) fn render_inner(
song: &Song,
sample_rate: u32,
synth: Box<dyn Synth>,
loops: u32,
) -> Vec<[f32; 2]> {
let mut p = Player::with_synth(Arc::new(song.clone()), sample_rate, synth);
if loops > 0 {
p.handle(Command::SetLooping(true));
p.handle(Command::SetLoopLimit(Some(loops)));
}
let mut out = Vec::new();
let mut buf = [[0.0f32; 2]; 1024];
while !p.is_finished() {
let n = p.render_counted(&mut buf);
out.extend_from_slice(&buf[..n]);
}
out
}
impl Player {
pub fn render(&mut self, out: &mut [[f32; 2]]) {
self.render_counted(out);
}
pub fn render_counted(&mut self, out: &mut [[f32; 2]]) -> usize {
if self.sfx.is_empty() {
let mut none: [Option<(usize, SfxSeq<'_>)>; MAX_SFX] = [None, None, None, None];
return self.render_frames(out, &mut none);
}
let sfx = std::mem::take(&mut self.sfx);
let mut seqs = std::mem::take(&mut self.sfx_seqs);
let mut bound: [Option<(usize, SfxSeq<'_>)>; MAX_SFX] = [None, None, None, None];
for (slot, playing) in self.sfx_playing.iter().enumerate() {
if let Some(e) = *playing {
let e = e as usize;
bound[slot] = seqs[e]
.take()
.and_then(|s| s.bind(&sfx[e].data))
.map(|s| (e, s));
}
}
let produced = self.render_frames(out, &mut bound);
for (e, seq) in bound.into_iter().flatten() {
seqs[e] = Some(seq.unbind());
}
self.sfx = sfx;
self.sfx_seqs = seqs;
produced
}
pub(super) fn render_frames(
&mut self,
out: &mut [[f32; 2]],
sfx: &mut [Option<(usize, SfxSeq<'_>)>; MAX_SFX],
) -> usize {
if self.preroll > 0 && matches!(self.state, State::Playing) {
let mut scratch = [[0.0f32; 2]; 256];
while self.preroll > 0 {
let n = (self.preroll as usize).min(scratch.len());
self.render_frames_inner(&mut scratch[..n], sfx);
self.preroll -= n as u32;
}
}
self.render_frames_inner(out, sfx)
}
fn render_frames_inner(
&mut self,
out: &mut [[f32; 2]],
sfx: &mut [Option<(usize, SfxSeq<'_>)>; MAX_SFX],
) -> usize {
let mut produced = 0;
let denom = 60 * self.sample_rate as u64 * SCALE_ONE * 1000;
for frame in out.iter_mut() {
match self.state {
State::Paused => {
*frame = [0.0, 0.0];
continue;
}
State::Finished => {
if self.sfx_active() || self.shots_active() {
self.step_sfx(sfx);
*frame = self.mix();
produced += 1;
} else {
*frame = [0.0, 0.0];
}
continue;
}
State::Tail => {
self.step_sfx(sfx);
*frame = self.mix();
produced += 1;
self.tail_left = self.tail_left.saturating_sub(1);
if self.tail_left == 0 {
self.state = State::Finished;
}
continue;
}
State::Playing => {}
}
if let Some((m, JumpAt::Beat | JumpAt::Bar, due)) = self.pending_jump {
if self.tick >= due {
self.jump(m);
}
}
self.process_events();
self.pass_points();
if self.tick >= self.end_tick() {
let may_loop = self.looping && self.loop_limit.is_none_or(|n| self.loops_done < n);
if let Some((m, _, _)) = self.pending_jump {
self.jump(m);
self.state = State::Playing;
self.process_events();
self.pass_points();
} else if may_loop {
self.loops_done = self.loops_done.saturating_add(1);
let to = self.song.loop_tick.unwrap_or(self.range_start);
self.seek(to);
self.state = State::Playing;
self.notices.push(Notice::Looped(self.loops_done));
self.process_events();
self.pass_points();
} else {
for ch in 0..self.synth.channels() {
self.synth.note_off(ch);
}
self.env.fill(EnvChannel::with_frame_hz(self.song.frame_hz));
self.duty
.fill(DutyChannel::with_frame_hz(self.song.frame_hz));
self.pitch
.fill(PitchChannel::with_frame_hz(self.song.frame_hz));
self.sounding.fill(None);
self.rebuild_sounding();
self.notices.push(Notice::Finished);
self.tail_left = self.synth.tail_frames();
if self.tail_left == 0 {
self.state = State::Finished;
if self.sfx_active() || self.shots_active() {
self.step_sfx(sfx);
*frame = self.mix();
produced += 1;
} else {
*frame = [0.0, 0.0];
}
continue;
}
self.state = State::Tail;
self.step_sfx(sfx);
*frame = self.mix();
produced += 1;
self.tail_left -= 1;
if self.tail_left == 0 {
self.state = State::Finished;
}
continue;
}
}
self.tick_envelopes();
self.tick_duty();
self.tick_pitch();
self.step_sfx(sfx);
*frame = self.mix();
produced += 1;
self.acc += self.tempo as u64 * self.song.ppq as u64 * self.tempo_scale;
if self.acc >= denom {
self.tick += self.acc / denom;
self.acc %= denom;
}
}
produced
}
pub(super) fn mix(&mut self) -> [f32; 2] {
let audible = self.audible_mask();
let mut shots = None;
if !self.shot_pcm.is_empty() {
let frame = self.mix_shots(audible);
if !self.synth.mix_input(frame) {
shots = Some(frame);
}
}
let [mut l, mut r] = self.synth.next(audible);
if let Some([sl, sr]) = shots {
l += sl;
r += sr;
}
[
(l * self.volume).clamp(-1.0, 1.0),
(r * self.volume).clamp(-1.0, 1.0),
]
}
pub(super) fn tick_envelopes(&mut self) {
let sr = self.sample_rate;
let song = &self.song;
let synth = &mut self.synth;
for (ti, ec) in self.env.iter_mut().enumerate() {
if ec.is_running() {
let env = envelope_of(song, self.env_current[ti]);
ec.tick(synth, ti, env, sr);
}
}
}
pub(super) fn tick_duty(&mut self) {
let sr = self.sample_rate;
let song = &self.song;
let synth = &mut self.synth;
for (ti, dc) in self.duty.iter_mut().enumerate() {
if dc.is_running() {
dc.tick(synth, ti, duty_of(song, self.duty_current[ti]), sr);
}
}
}
pub(super) fn tick_pitch(&mut self) {
let sr = self.sample_rate;
let song = &self.song;
let synth = &mut self.synth;
for (ti, pc) in self.pitch.iter_mut().enumerate() {
if self.vib_current[ti].is_none() && !pc.is_running() {
continue;
}
let sounding = self.env[ti].is_held() || self.env[ti].is_releasing();
let fx = pitch_fx_of(
song,
self.vib_current[ti],
self.detune_current[ti],
self.arp_current[ti],
);
if fx.vib.is_some() || pc.is_running() {
pc.tick(synth, ti, sounding, fx, sr);
}
}
}
fn shift_key(&mut self, ti: usize, key: u8) -> u8 {
let (k, wrapped) = pikopiko_runtime::transpose_key(&self.synth, ti, key, self.transpose);
if wrapped && !self.fold_reported {
self.fold_reported = true;
self.notices.push(Notice::Transposed { track: ti as u8 });
}
k
}
pub(super) fn process_events(&mut self) {
let mut changed = false;
while let Some(e) = self.song.events.get(self.next_event) {
if e.tick > self.tick {
break;
}
let e = *e;
self.next_event += 1;
let ti = e.track as usize;
match e.kind {
EventKind::NoteOn { key, vel } => {
let key = self.shift_key(ti, key);
if let Some(ec) = self.env.get_mut(ti) {
let retrigger = !ec.is_held();
if retrigger {
self.env_current[ti] = self.env_selected[ti];
self.vib_current[ti] = self.vib_selected[ti];
self.detune_current[ti] = self.detune_selected[ti];
self.arp_current[ti] = self.arp_selected[ti];
self.duty_current[ti] = self.duty_selected[ti];
}
if retrigger {
let d = duty_of(&self.song, self.duty_current[ti]);
self.duty[ti].note_on(&mut self.synth, ti, d);
}
self.pitch[ti].note_on(
&mut self.synth,
ti,
retrigger,
pitch_fx_of(
&self.song,
self.vib_current[ti],
self.detune_current[ti],
self.arp_current[ti],
),
);
let env = envelope_of(&self.song, self.env_current[ti]);
ec.note_on(&mut self.synth, ti, key, vel, env);
}
self.record_note_on(ti, &[key]);
if let Some(s) = self.sounding.get_mut(ti) {
*s = Some(e.span);
changed = true;
}
}
EventKind::Chord { keys, vel, legato } => {
let mut shifted = [0u8; crate::compiler::song::MAX_CHORD_NOTES];
let src = keys.as_slice();
let count = src.len();
for (d, &k) in shifted.iter_mut().zip(src) {
*d = self.shift_key(ti, k);
}
if let Some(ec) = self.env.get_mut(ti) {
self.env_current[ti] = self.env_selected[ti];
self.vib_current[ti] = self.vib_selected[ti];
self.detune_current[ti] = self.detune_selected[ti];
self.arp_current[ti] = self.arp_selected[ti];
self.duty_current[ti] = self.duty_selected[ti];
let d = duty_of(&self.song, self.duty_current[ti]);
self.duty[ti].note_on(&mut self.synth, ti, d);
self.pitch[ti].note_on(
&mut self.synth,
ti,
true,
pitch_fx_of(
&self.song,
self.vib_current[ti],
self.detune_current[ti],
self.arp_current[ti],
),
);
let env = envelope_of(&self.song, self.env_current[ti]);
ec.chord_on(&mut self.synth, ti, &shifted[..count], vel, legato, env);
}
self.record_note_on(ti, &shifted[..count]);
if let Some(s) = self.sounding.get_mut(ti) {
*s = Some(e.span);
changed = true;
}
}
EventKind::NoteOff => {
self.record_note_off(ti);
if let Some(ec) = self.env.get_mut(ti) {
self.pitch[ti].note_off(pitch_fx_of(
&self.song,
self.vib_current[ti],
self.detune_current[ti],
self.arp_current[ti],
));
let env = envelope_of(&self.song, self.env_current[ti]);
ec.note_off(&mut self.synth, ti, env);
let d = duty_of(&self.song, self.duty_current[ti]);
self.duty[ti].note_off(&mut self.synth, ti, d);
}
if let Some(s) = self.sounding.get_mut(ti) {
*s = None;
changed = true;
}
}
EventKind::Tempo(t) => {
self.tempo = t;
self.send_tempo();
}
EventKind::Tone(t) => {
self.synth.set_tone(ti, t);
if let Some(s) = self.tone_set.get_mut(ti) {
*s = t;
}
}
EventKind::Wave(i) => {
if let Some(w) = self.song.waves.get(i as usize) {
self.synth.set_wave(ti, w);
}
}
EventKind::Param { id, value } => {
pikopiko_runtime::set_param_id(&mut self.synth, ti, id, value)
}
EventKind::Envelope(i) => {
if let Some(s) = self.env_selected.get_mut(ti) {
*s = Some(i);
}
}
EventKind::Vibrato(i) => {
if let Some(s) = self.vib_selected.get_mut(ti) {
*s = i;
}
}
EventKind::Detune(i) => {
if let Some(s) = self.detune_selected.get_mut(ti) {
*s = i;
}
}
EventKind::Arp(i) => {
if let Some(s) = self.arp_selected.get_mut(ti) {
*s = i;
}
}
EventKind::Duty(i) => {
if let Some(s) = self.duty_selected.get_mut(ti) {
*s = i;
}
if i.is_none() {
self.duty_current[ti] = None;
self.duty[ti].reset();
let t = self.tone_set[ti];
self.synth.set_tone(ti, t);
}
}
EventKind::Portamento { cents, frames } => {
if let Some(pc) = self.pitch.get_mut(ti) {
let vib = vibrato_of(&self.song, self.vib_current[ti]);
pc.glide(&mut self.synth, ti, cents, frames, vib);
}
}
EventKind::Shot { id, vel } => self.start_shot(id, vel, e.track),
}
}
if changed {
self.rebuild_sounding();
}
}
}