#[cfg(feature = "kira")]
pub mod kira;
#[cfg(feature = "mixer")]
pub mod mixer;
pub mod voice;
pub mod watch;
use std::sync::Arc;
use crate::compiler::song::{EventKind, Song, DEFAULT_TEMPO_MILLI};
use crate::player::voice::Voice;
use crate::synth::{self, Synth, SynthSpec, VoiceBank};
use crate::{msg, Diagnostic, Span};
use pikopiko_runtime::binary::Sequencer;
use pikopiko_runtime::duty::DutyChannel;
use pikopiko_runtime::envelope::EnvChannel;
use pikopiko_runtime::interrupt::{self, Interrupt, MAX_SFX, MAX_SFX_TRACKS};
use pikopiko_runtime::pitch::PitchChannel;
pub use activity::TrackActivity;
pub use pikopiko_runtime::interrupt::SfxChannels;
mod activity;
mod render;
mod sfx;
mod shots;
mod transport;
use render::*;
use sfx::*;
use shots::*;
use transport::*;
pub const MAX_REGISTERED_SFX: usize = 32;
pub const NOTICE_CAPACITY: usize = 64;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct SfxId(pub u8);
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SfxError {
SynthMismatch,
Encode,
BadTracks,
Full,
Unknown,
BadChannels,
Busy,
}
impl crate::text::Localized for SfxError {
fn text_key(&self) -> &'static str {
match self {
SfxError::SynthMismatch => "err-player-sfx-synth-mismatch",
SfxError::Encode => "err-player-sfx-encode",
SfxError::BadTracks => "err-player-sfx-bad-tracks",
SfxError::Full => "err-player-sfx-full",
SfxError::Unknown => "err-player-sfx-unknown",
SfxError::BadChannels => "err-player-sfx-bad-channels",
SfxError::Busy => "err-player-sfx-busy",
}
}
fn catalogs(&self) -> &'static [crate::text::Catalog] {
crate::text_table::CATALOGS
}
}
impl std::fmt::Display for SfxError {
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 SfxError {}
pub use pikopiko_runtime::notice::{JumpAt, NoticeMask};
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Notice {
Marker { index: u8 },
Bar(u32),
Beat { bar: u32, beat: u8 },
Looped(u32),
Jumped { marker: u8 },
Finished,
Transposed { track: u8 },
SfxFinished(SfxId),
SfxRejected(SfxId),
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum Command {
Play,
Pause,
Stop,
SetVolume(f32),
SetTempoScale(f32),
SetLooping(bool),
SetLoopLimit(Option<u32>),
Seek(u64),
SetMute { track: u8, muted: bool },
SetSolo(Option<u8>),
SetRange { start: u64, end: Option<u64> },
SetTranspose(i8),
PlaySfx {
sfx: SfxId,
channels: SfxChannels,
priority: u8,
looping: bool,
},
StopSfx(SfxId),
StopAllSfx,
SetNotify(NoticeMask),
JumpToMarker { marker: u8, at: JumpAt },
CancelJump,
}
const SCALE_ONE: u64 = 1000;
pub const MAX_SHOT_VOICES: usize = 8;
pub struct Player {
song: Arc<Song>,
sample_rate: u32,
synth: Routed,
param_info: Vec<(u8, u32, bool)>,
sfx: Vec<SfxEntry>,
sfx_seqs: Vec<Option<SfxSeq<'static>>>,
sfx_playing: [Option<u8>; MAX_SFX],
notices: Notices,
next_marker: usize,
next_beat: u64,
pending_jump: Option<(u8, JumpAt, u64)>,
next_event: usize,
tick: u64,
acc: u64,
tempo: u32,
tempo_scale: u64,
tempo_sent: Option<u32>,
tail_left: u32,
preroll: u32,
state: State,
volume: f32,
looping: bool,
loop_limit: Option<u32>,
loops_done: u32,
muted: Vec<bool>,
solo: Option<u8>,
range_start: u64,
range_end: Option<u64>,
transpose: i8,
fold_reported: bool,
sounding: Vec<Option<Span>>,
sounding_list: Vec<Span>,
track_key: Vec<u8>,
track_ons: Vec<u32>,
track_chord_len: Vec<u8>,
track_chord_pcs: Vec<u16>,
track_offs: Vec<u32>,
env: Vec<EnvChannel>,
env_selected: Vec<Option<u8>>,
env_current: Vec<Option<u8>>,
pitch: Vec<PitchChannel>,
vib_selected: Vec<Option<u8>>,
detune_selected: Vec<Option<u8>>,
arp_selected: Vec<Option<u8>>,
vib_current: Vec<Option<u8>>,
detune_current: Vec<Option<u8>>,
arp_current: Vec<Option<u8>>,
duty: Vec<DutyChannel>,
duty_selected: Vec<Option<u8>>,
duty_current: Vec<Option<u8>>,
tone_set: Vec<u8>,
shot_pcm: Vec<Arc<[[f32; 2]]>>,
shot_voices: [ShotVoice; SHOT_SLOTS],
shot_order: u32,
shot_fade: u32,
}
pub(crate) fn announce_tones(synth: &mut dyn Synth, song: &Song) {
let mut seen = [false; 256];
let mut tell = |t: u8| {
if !core::mem::replace(&mut seen[usize::from(t)], true) {
synth.prepare_tone(t);
}
};
tell(song.default_tone);
for e in &song.events {
if let EventKind::Tone(t) = e.kind {
tell(t);
}
}
}
impl Player {
pub fn new(song: Arc<Song>, sample_rate: u32) -> Self {
let synth = synth::create_builtin(&song.synth, sample_rate, song.tracks.len());
let spec = synth::find(synth::BUILTIN, &song.synth.name);
let mut p = Self::with_synth(song, sample_rate, synth);
if let Some(spec) = spec {
p.set_spec_info(spec);
}
p
}
pub fn with_spec(song: Arc<Song>, sample_rate: u32, spec: &SynthSpec) -> Self {
let synth = (spec.create)(&song.synth, sample_rate, song.tracks.len());
let mut p = Self::with_synth(song, sample_rate, synth);
p.set_spec_info(spec);
p
}
fn set_spec_info(&mut self, spec: &SynthSpec) {
self.param_info = spec
.params
.iter()
.enumerate()
.take(256)
.map(|(i, p)| (i as u8, p.default, p.scope == synth::Scope::Synth))
.collect();
}
pub fn with_voices(
song: Arc<Song>,
sample_rate: u32,
mut make_voice: impl FnMut(u8) -> Box<dyn Voice>,
) -> (Self, Vec<Diagnostic>) {
let n = song.tracks.len();
let voices: Vec<Box<dyn Voice>> = (0..n).map(|i| make_voice(i as u8)).collect();
let pitch: Vec<bool> = voices.iter().map(|v| v.supports_pitch()).collect();
let warnings = voice_warnings(&song, &pitch);
let bank = VoiceBank::new(voices, song.default_tone);
(
Self::with_synth(song, sample_rate, Box::new(bank)),
warnings,
)
}
pub fn with_synth(song: Arc<Song>, sample_rate: u32, mut synth: Box<dyn Synth>) -> Self {
let n = song.tracks.len();
let frame_hz = song.frame_hz;
let default_tone = song.default_tone;
synth.reset();
announce_tones(synth.as_mut(), &song);
let state = if song.length_ticks == 0 {
State::Finished
} else {
State::Playing
};
let mut p = Player {
song,
sample_rate: sample_rate.max(1),
synth: Routed {
inner: synth,
ints: None,
},
param_info: Vec::new(),
sfx: Vec::new(),
sfx_seqs: Vec::new(),
sfx_playing: [None; MAX_SFX],
notices: Notices::new(),
next_marker: 0,
next_beat: 0,
pending_jump: None,
next_event: 0,
tick: 0,
acc: 0,
tempo: DEFAULT_TEMPO_MILLI,
tempo_scale: SCALE_ONE,
tempo_sent: None,
tail_left: 0,
preroll: 0,
state,
volume: 1.0,
looping: false,
loop_limit: None,
loops_done: 0,
muted: vec![false; n],
solo: None,
range_start: 0,
range_end: None,
transpose: 0,
fold_reported: false,
sounding: vec![None; n],
sounding_list: Vec::with_capacity(n),
track_key: vec![0; n],
track_ons: vec![0; n],
track_chord_len: vec![0; n],
track_chord_pcs: vec![0; n],
track_offs: vec![0; n],
env: vec![EnvChannel::with_frame_hz(frame_hz); n],
env_selected: vec![None; n],
env_current: vec![None; n],
pitch: vec![PitchChannel::with_frame_hz(frame_hz); n],
vib_selected: vec![None; n],
detune_selected: vec![None; n],
arp_selected: vec![None; n],
vib_current: vec![None; n],
detune_current: vec![None; n],
arp_current: vec![None; n],
duty: vec![DutyChannel::with_frame_hz(frame_hz); n],
duty_selected: vec![None; n],
duty_current: vec![None; n],
tone_set: vec![default_tone; n],
shot_pcm: Vec::new(),
shot_voices: [ShotVoice::EMPTY; SHOT_SLOTS],
shot_order: 0,
shot_fade: (sample_rate / 500).max(1),
};
p.shot_pcm = render_shots(&p.song, p.sample_rate);
p.send_tempo();
p.preroll = p.synth.latency_frames();
p
}
fn send_tempo(&mut self) {
let bpm_milli =
(self.tempo as u64 * self.tempo_scale / SCALE_ONE).min(u32::MAX as u64) as u32;
if self.tempo_sent != Some(bpm_milli) {
self.tempo_sent = Some(bpm_milli);
self.synth.set_tempo(bpm_milli);
}
}
pub fn song(&self) -> &Arc<Song> {
&self.song
}
pub fn sample_rate(&self) -> u32 {
self.sample_rate
}
pub fn position(&self) -> u64 {
self.tick
}
pub fn is_finished(&self) -> bool {
self.state == State::Finished && !self.sfx_active() && !self.shots_active()
}
pub fn sounding_spans(&self) -> &[Span] {
&self.sounding_list
}
}
pub fn render_to_vec(song: &Song, sample_rate: u32) -> Vec<[f32; 2]> {
let synth = synth::create_builtin(&song.synth, sample_rate, song.tracks.len());
render_to_vec_with(song, sample_rate, synth)
}
pub fn render_to_vec_looped(song: &Song, sample_rate: u32, loops: u32) -> Vec<[f32; 2]> {
let synth = synth::create_builtin(&song.synth, sample_rate, song.tracks.len());
render_inner(song, sample_rate, synth, loops)
}
pub fn render_to_vec_with(song: &Song, sample_rate: u32, synth: Box<dyn Synth>) -> Vec<[f32; 2]> {
render_inner(song, sample_rate, synth, 0)
}
pub fn render_to_vec_looped_with(
song: &Song,
sample_rate: u32,
synth: Box<dyn Synth>,
loops: u32,
) -> Vec<[f32; 2]> {
render_inner(song, sample_rate, synth, loops)
}
fn voice_warnings(song: &Song, pitch: &[bool]) -> Vec<Diagnostic> {
use crate::compiler::diagnostic::codes;
let n = song.tracks.len();
let mut pitch_warned = vec![false; n];
let mut chord_warned = vec![false; n];
let mut out = Vec::new();
for e in &song.events {
let t = e.track as usize;
if t >= n {
continue;
}
let name = song.tracks[t].as_str();
match e.kind {
EventKind::Vibrato(Some(_))
| EventKind::Detune(Some(_))
| EventKind::Arp(Some(_))
| EventKind::Portamento { .. }
if !pitch.get(t).copied().unwrap_or(false) && !pitch_warned[t] =>
{
pitch_warned[t] = true;
out.push(Diagnostic::warning(
codes::VOICE_WITHOUT_PITCH,
e.span,
msg!("W0109-voice", track = name),
));
}
EventKind::Chord { .. } if !chord_warned[t] => {
chord_warned[t] = true;
out.push(Diagnostic::warning(
codes::VOICE_CHORD,
e.span,
msg!("W0110-voice", track = name),
));
}
_ => {}
}
}
out.sort_by_key(|d| (d.span.source, d.span.line, d.span.col));
out
}