Documentation
¶
Overview ¶
Package tracker renders tick-based replays using synth voices.
Index ¶
- func FormatNoteName(key uint8) (string, error)
- func KeyToFrequency(key uint8) (float64, error)
- func ParseNoteName(name string) (uint8, error)
- func RegisterFormat[M any, R Replay](name string, size int, probe func([]byte) bool, ...)
- type Cell
- type ChannelID
- type Effect
- type EffectSpec
- type InstrumentID
- type NoteAction
- type NoteDelay
- type PatternID
- type PitchSlide
- type Player
- func (p *Player[T]) PCMFormat() audio.Format
- func (p *Player[T]) Position() Position
- func (p *Player[T]) PreferredBlockFrames() int
- func (p *Player[T]) ReadFrames(dst audio.Buffer[T]) (int, error)
- func (p *Player[T]) Restart() error
- func (p *Player[T]) SeekFrame(frame int64) error
- func (p *Player[T]) SeekTime(at time.Duration) (time.Duration, error)
- type Position
- type PriorVoice
- type Replay
- type ReplayConfig
- type Retrigger
- type Song
- func (s *Song[T]) AddInstrument(instrument synth.Instrument[T]) (InstrumentID, error)
- func (s *Song[T]) AddPattern(rows int) (PatternID, error)
- func (s *Song[T]) Cell(id PatternID, row, channel int) (Cell, error)
- func (s *Song[T]) PreviewInstrument(id InstrumentID, format audio.Format) (synth.Voice[T], error)
- func (s *Song[T]) SetCell(id PatternID, row, channel int, cell Cell) error
- func (s *Song[T]) SetOrder(order []PatternID) error
- func (s *Song[T]) SetRowTiming(id PatternID, row int, timing Timing) error
- type TickContext
- func (ctx *TickContext) BreakPattern(row int) error
- func (ctx *TickContext) Channel() (ChannelID, bool)
- func (ctx *TickContext) Emit(voice VoiceID, event synth.VoiceEvent) error
- func (ctx *TickContext) EndSong()
- func (ctx *TickContext) ExtendRow(extraTicks int) error
- func (ctx *TickContext) ForegroundVoice(channel ChannelID) (VoiceID, bool)
- func (ctx *TickContext) Frame() int64
- func (ctx *TickContext) JumpOrder(order int) error
- func (ctx *TickContext) LoopRow(row int) error
- func (ctx *TickContext) Position() Position
- func (ctx *TickContext) RateHz() int
- func (ctx *TickContext) RepeatRow(count int) error
- func (ctx *TickContext) RowRepeat() int
- func (ctx *TickContext) SetSpeed(ticksPerRow int) error
- func (ctx *TickContext) SetTickDuration(seconds float64) error
- func (ctx *TickContext) SetTickFrames(frames int64) error
- func (ctx *TickContext) StartVoice(channel ChannelID, instrument InstrumentID, trigger synth.Trigger, ...) (VoiceID, error)
- func (ctx *TickContext) Tick() int
- func (ctx *TickContext) VoicePresent(voice VoiceID) bool
- func (ctx *TickContext) VoiceRunningBackward(voice VoiceID) bool
- func (ctx *TickContext) WithChannel(channel ChannelID) (TickContext, error)
- type TickTiming
- type Timing
- type VoiceID
- type Volume
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func FormatNoteName ¶
FormatNoteName writes a MIDI key in scientific pitch notation using sharps.
func KeyToFrequency ¶
KeyToFrequency converts a MIDI key to equal-tempered Hertz at A4 = 440 Hz.
func ParseNoteName ¶
ParseNoteName parses a scientific pitch name such as C4, F#3, or Bb5. It accepts ASCII sharps and flats and returns a MIDI key from 0 to 127.
func RegisterFormat ¶
func RegisterFormat[M any, R Replay]( name string, size int, probe func([]byte) bool, load func(io.Reader) (*M, error), newReplay func(*M) (R, ReplayConfig[int32], error), metadata func(*M) tag.Metadata, )
RegisterFormat enables a native module format in audio.NewDecoder. probe inspects up to size bytes. load reads the module from its beginning, newReplay supplies its player configuration, and metadata reads tags from the loaded module. Pass nil for metadata if the format supplies no tags. The decoder renders signed 16-bit stereo at the requested rate or at 48 kHz by default. Loading observes the decoder context between reads. The caller must interrupt any underlying read that remains blocked after cancellation.
Types ¶
type Cell ¶
type Cell struct {
Action NoteAction
Key uint8 // MIDI key for NoteTrigger.
Instrument InstrumentID // Zero keeps the current instrument.
Gain *float64 // Nil keeps the current channel gain.
Effects []EffectSpec
}
Cell holds one channel's settings and note action on a pattern row. An empty cell holds the current state.
type ChannelID ¶
type ChannelID uint32
ChannelID is a zero-based channel index. A VoiceID identifies one playback instance. InstrumentID indexes a replay's instrument bank.
type Effect ¶
type Effect interface {
// Apply schedules an effect during the current logical tick.
Apply(ctx *TickContext) error
}
Effect applies a replay operation to a tick, optionally scoped to a channel.
Example ¶
package main
import (
"fmt"
"github.com/BeatGlow/audio"
"github.com/BeatGlow/audio/tracker"
)
// tickLength is both an immutable effect specification and its runtime effect.
type tickLength int64
func (length tickLength) NewEffect() (tracker.Effect, error) { return length, nil }
func (length tickLength) Apply(tick *tracker.TickContext) error {
return tick.SetTickFrames(int64(length))
}
// effectReplay applies an effect during the player's tick callback.
type effectReplay struct{ effect tracker.Effect }
func (effectReplay) Reset() error { return nil }
func (r effectReplay) StepTick(tick *tracker.TickContext) error {
return r.effect.Apply(tick)
}
func main() {
format := audio.Format{
RateHz: 8000,
Layout: audio.MonoLayout,
Encoding: audio.Encoding{
Kind: audio.FloatPCM,
Bits: 64,
},
}
player, err := tracker.NewReplayPlayer(
format,
effectReplay{effect: tickLength(2)},
tracker.ReplayConfig[float64]{
Channels: 1,
VoiceLimit: 1,
OrderRows: []int{1},
InitialTiming: tracker.TickTiming{
SecondsPerTick: 0.01,
TicksPerRow: 1,
},
},
)
if err != nil {
panic(err)
}
// The effect makes this one-tick replay finish after two frames.
n, err := player.ReadFrames(audio.Buffer[float64]{{0, 0, 0}})
fmt.Println(n, err)
}
Output: 2 EOF
type EffectSpec ¶
EffectSpec creates an effect for a single authored cell slot. Specs are immutable and NewEffect must be safe to call concurrently. Return fresh state per call or a shared immutable effect safe for concurrent use.
Example ¶
package main
import (
"fmt"
"github.com/BeatGlow/audio"
"github.com/BeatGlow/audio/tracker"
)
// tickLength is both an immutable effect specification and its runtime effect.
type tickLength int64
func (length tickLength) NewEffect() (tracker.Effect, error) { return length, nil }
func (length tickLength) Apply(tick *tracker.TickContext) error {
return tick.SetTickFrames(int64(length))
}
func main() {
song, err := tracker.NewSong[float64](1, tracker.Timing{
BPM: 120,
RowsPerBeat: 4,
TicksPerRow: 1,
})
if err != nil {
panic(err)
}
pattern, err := song.AddPattern(1)
if err != nil {
panic(err)
}
if err := song.SetOrder([]tracker.PatternID{pattern}); err != nil {
panic(err)
}
// The player builds a runtime effect from the cell's specification.
if err := song.SetCell(pattern, 0, 0, tracker.Cell{
Effects: []tracker.EffectSpec{tickLength(2)},
}); err != nil {
panic(err)
}
format := audio.Format{
RateHz: 8000,
Layout: audio.MonoLayout,
Encoding: audio.Encoding{
Kind: audio.FloatPCM,
Bits: 64,
},
}
player, err := tracker.NewSongPlayer(song, format)
if err != nil {
panic(err)
}
n, err := player.ReadFrames(audio.Buffer[float64]{{0, 0, 0}})
fmt.Println(n, err)
}
Output: 2 EOF
type InstrumentID ¶
type InstrumentID uint32
ChannelID is a zero-based channel index. A VoiceID identifies one playback instance. InstrumentID indexes a replay's instrument bank.
type NoteAction ¶
type NoteAction uint8
NoteAction determines what a cell does to its channel's foreground note.
const ( NoteUnchanged NoteAction = iota // Keep the current note. NoteTrigger // Start a new note. NoteRelease // Release the current note. NoteCut // Stop the current note immediately. )
type NoteDelay ¶
type NoteDelay struct{ Ticks int }
NoteDelay shifts this cell's trigger to a later tick of the current row. The last delay in the cell wins. A delay beyond the row suppresses its note.
type PatternID ¶
type PatternID uint32
PatternID identifies a pattern in an authored song. IDs start at one.
type PitchSlide ¶
type PitchSlide struct{ SemitonesPerTick float64 }
PitchSlide changes the foreground pitch by the given semitones per nonzero tick. A new trigger uses its own key as the starting pitch.
func (PitchSlide) NewEffect ¶
func (s PitchSlide) NewEffect() (Effect, error)
type Player ¶
Player renders a replay in its negotiated PCM format. Its caller serializes reads, seeks, and restarts.
func NewReplayPlayer ¶
func NewReplayPlayer[T audio.Sample]( format audio.Format, replay Replay, config ReplayConfig[T], ) (*Player[T], error)
NewReplayPlayer validates and snapshots the replay configuration and resets the replay. An empty order list plays no frames. The replay instance is mutable and belongs exclusively to the returned player.
func NewSongPlayer ¶
NewSongPlayer snapshots an authored song and prepares an independent replay. An empty order list produces no PCM. Edits apply to subsequently opened players.
Example ¶
package main
import (
"fmt"
"time"
"github.com/BeatGlow/audio"
"github.com/BeatGlow/audio/synth"
"github.com/BeatGlow/audio/tracker"
)
func main() {
check := func(err error) {
if err != nil {
panic(err)
}
}
song, err := tracker.NewSong[float64](1, tracker.Timing{
BPM: 120,
RowsPerBeat: 4,
TicksPerRow: 4,
})
check(err)
instrument, err := song.AddInstrument(synth.Sine[float64]{})
check(err)
pattern, err := song.AddPattern(2)
check(err)
check(song.SetOrder([]tracker.PatternID{pattern}))
check(song.SetCell(
pattern,
0,
0,
tracker.Cell{
Action: tracker.NoteTrigger,
Instrument: instrument,
Key: 69,
Gain: new(.2),
},
))
check(song.SetRowTiming(pattern, 1, tracker.Timing{
BPM: 150,
RowsPerBeat: 4,
TicksPerRow: 4,
}))
check(song.SetCell(pattern, 1, 0, tracker.Cell{
Effects: []tracker.EffectSpec{
tracker.PitchSlide{SemitonesPerTick: .5},
},
}))
format := audio.Format{
RateHz: 48000,
Layout: audio.MonoLayout,
Encoding: audio.Encoding{
Kind: audio.FloatPCM,
Bits: 64,
},
}
preview, err := song.PreviewInstrument(instrument, format)
check(err)
check(preview.Schedule(synth.TriggerAt(0, synth.Pitch{
Kind: synth.PitchHz,
Value: 440,
}, .2, 0)))
_, err = preview.ReadFrames(audio.Buffer[float64]{make([]float64, 240)})
check(err)
player, err := tracker.NewSongPlayer(song, format)
check(err)
var source audio.Source[float64] = player
actual, err := player.SeekTime(150 * time.Millisecond)
check(err)
buffer := audio.Buffer[float64]{make([]float64, player.PreferredBlockFrames())}
n, err := source.ReadFrames(buffer)
check(err)
fmt.Printf("%s, %d frames, row %d\n", actual, n, player.Position().Row)
check(player.Restart())
fmt.Printf("restart row %d\n", player.Position().Row)
}
Output: 150ms, 256 frames, row 1 restart row 0
func (*Player[T]) Position ¶
Position returns the tick containing the next frame to render. At EOF it retains the final rendered tick.
func (*Player[T]) PreferredBlockFrames ¶
PreferredBlockFrames reports the number of frames in the internal mix block.
func (*Player[T]) ReadFrames ¶
ReadFrames renders whole or partial ticks. The final call can return PCM together with io.EOF. Restart is required to render again after a replay or voice error. SeekTime can also reset and replay after an error.
func (*Player[T]) Restart ¶
Restart starts a new pass at frame zero with the configured repeat count.
func (*Player[T]) SeekFrame ¶
SeekFrame positions the player on its zero-based output timeline. A request beyond the rendered pass reaches its end and returns io.EOF.
type PriorVoice ¶
type PriorVoice uint8
PriorVoice selects what happens to the previous foreground voice.
const ( CutPrior PriorVoice = iota // Stop the previous voice immediately. ReleasePrior // Let the previous voice complete its release. KeepPrior // Leave the previous voice playing. )
type Replay ¶
type Replay interface {
// Reset restores the playback state at the start of the module or song.
Reset() error
// StepTick schedules the next logical tick. The context is valid until the call returns.
StepTick(ctx *TickContext) error
}
Replay supplies the notes and effects for each logical tick. The player owns the replay instance and calls Reset before each pass and restart.
Example ¶
package main
import (
"fmt"
"github.com/BeatGlow/audio"
"github.com/BeatGlow/audio/synth"
"github.com/BeatGlow/audio/tracker"
)
// noteReplay triggers one instrument when the player first enters the pattern.
type noteReplay struct{}
func (noteReplay) Reset() error { return nil }
func (noteReplay) StepTick(tick *tracker.TickContext) error {
if tick.Position() != (tracker.Position{}) {
return nil
}
_, err := tick.StartVoice(
0,
1,
synth.Trigger{
Pitch: synth.Pitch{
Kind: synth.PitchHz,
Value: 2000,
},
Gain: 0.5,
},
tracker.CutPrior,
)
return err
}
func main() {
format := audio.Format{
RateHz: 8000,
Layout: audio.MonoLayout,
Encoding: audio.Encoding{
Kind: audio.FloatPCM,
Bits: 64,
},
}
player, err := tracker.NewReplayPlayer(format, noteReplay{}, tracker.ReplayConfig[float64]{
Channels: 1,
VoiceLimit: 1,
OrderRows: []int{1},
InitialTiming: tracker.TickTiming{
SecondsPerTick: 0.01,
TicksPerRow: 1,
},
Instruments: map[tracker.InstrumentID]synth.Instrument[float64]{
1: synth.Sine[float64]{},
},
})
if err != nil {
panic(err)
}
dst := audio.Buffer[float64]{{0, 0}}
n, err := player.ReadFrames(dst)
fmt.Println(n, dst[0][1] > 0, err)
}
Output: 2 true <nil>
type ReplayConfig ¶
type ReplayConfig[T audio.Sample] struct { Channels int OrderRows []int // Row count for each playable order. Instruments map[InstrumentID]synth.Instrument[T] InitialTiming TickTiming VoiceLimit int RepeatCount int // Additional passes after the first. MixGain float64 // Gain before clipping, or zero for unity gain. // StopAtOrderLoop ends a pass when an order jump returns to an already // visited row. Pattern loops requested through LoopRow still play out. StopAtOrderLoop bool // WrapWAVMixAccumulator reproduces the Impulse Tracker WAV mixer's // signed 32-bit overflow before applying MixGain and clipping. WrapWAVMixAccumulator bool }
ReplayConfig describes the shared topology and timing of a replay. Native pattern and cell data belong to the replay.
type Retrigger ¶
Retrigger restarts the foreground sound on each positive multiple of Every ticks within the row. It skips the tick of a new note trigger.
type Song ¶
Song is an editable pattern grid and order list. Serialize its edits with other operations on the song. Existing players own independent snapshots.
func (*Song[T]) AddInstrument ¶
func (s *Song[T]) AddInstrument(instrument synth.Instrument[T]) (InstrumentID, error)
AddInstrument adds a reusable instrument and returns its nonzero ID.
func (*Song[T]) AddPattern ¶
AddPattern creates a blank pattern with the song's channel count.
func (*Song[T]) Cell ¶
Cell returns a copy of the selected cell. Editing the returned value is independent of the song until a call to SetCell.
func (*Song[T]) PreviewInstrument ¶
PreviewInstrument opens an independent voice in the host's PCM format. Schedule a trigger and release or cut on the returned voice to play it.
type TickContext ¶
type TickContext struct {
// contains filtered or unexported fields
}
TickContext exposes one tick's position and accepts playback requests. The context and channel-scoped copies are valid only during StepTick.
func (*TickContext) BreakPattern ¶
func (ctx *TickContext) BreakPattern(row int) error
BreakPattern sets the entry row of the next or explicitly selected order.
func (*TickContext) Channel ¶
func (ctx *TickContext) Channel() (ChannelID, bool)
Channel returns the context's channel scope, if any.
func (*TickContext) Emit ¶
func (ctx *TickContext) Emit(voice VoiceID, event synth.VoiceEvent) error
Emit schedules a control whose song-frame timestamp equals Frame.
func (*TickContext) EndSong ¶
func (ctx *TickContext) EndSong()
EndSong requests the end of this pass after the current row finishes.
func (*TickContext) ExtendRow ¶
func (ctx *TickContext) ExtendRow(extraTicks int) error
ExtendRow sets the number of extra ticks for this row. The next row starts at the normal speed.
func (*TickContext) ForegroundVoice ¶
func (ctx *TickContext) ForegroundVoice(channel ChannelID) (VoiceID, bool)
ForegroundVoice returns the currently assigned voice for a channel.
func (*TickContext) Frame ¶
func (ctx *TickContext) Frame() int64
Frame returns the current tick boundary in song frames.
func (*TickContext) JumpOrder ¶
func (ctx *TickContext) JumpOrder(order int) error
JumpOrder requests an order change after the current row finishes.
func (*TickContext) LoopRow ¶
func (ctx *TickContext) LoopRow(row int) error
LoopRow requests a return to a row of the current order.
func (*TickContext) Position ¶
func (ctx *TickContext) Position() Position
Position returns the order, row, and tick being processed.
func (*TickContext) RateHz ¶
func (ctx *TickContext) RateHz() int
RateHz returns the output sample rate.
func (*TickContext) RepeatRow ¶
func (ctx *TickContext) RepeatRow(count int) error
RepeatRow extends the current row by count additional cycles of ticks. The replay receives tick zero again for each cycle before row flow applies.
func (*TickContext) RowRepeat ¶
func (ctx *TickContext) RowRepeat() int
RowRepeat returns the number of elapsed extra cycles of the current row. The first cycle returns zero.
func (*TickContext) SetSpeed ¶
func (ctx *TickContext) SetSpeed(ticksPerRow int) error
SetSpeed changes the tick limit of this row and subsequent rows.
func (*TickContext) SetTickDuration ¶
func (ctx *TickContext) SetTickDuration(seconds float64) error
SetTickDuration changes this tick and future ticks until the next change.
func (*TickContext) SetTickFrames ¶
func (ctx *TickContext) SetTickFrames(frames int64) error
SetTickFrames sets this tick's duration to an exact number of output frames. The duration carries forward until another timing change.
func (*TickContext) StartVoice ¶
func (ctx *TickContext) StartVoice( channel ChannelID, instrument InstrumentID, trigger synth.Trigger, prior PriorVoice, ) (VoiceID, error)
StartVoice installs a new foreground voice at this tick's first frame.
func (*TickContext) Tick ¶
func (ctx *TickContext) Tick() int
Tick returns the current row-relative tick.
func (*TickContext) VoicePresent ¶
func (ctx *TickContext) VoicePresent(voice VoiceID) bool
VoicePresent reports whether a foreground or detached voice is still playing.
func (*TickContext) VoiceRunningBackward ¶
func (ctx *TickContext) VoiceRunningBackward(voice VoiceID) bool
VoiceRunningBackward reports the cursor direction of a PCM voice.
func (*TickContext) WithChannel ¶
func (ctx *TickContext) WithChannel(channel ChannelID) (TickContext, error)
WithChannel returns a copy that shares the current tick's requests.
type TickTiming ¶
type TickTiming struct {
SecondsPerTick float64
TicksPerRow int
TruncateFrames bool // Floor accumulated tick boundaries instead of rounding to nearest.
}
TickTiming specifies the duration of a tick and the tick limit of a row.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
Package all registers all built-in tracker formats with audio.
|
Package all registers all built-in tracker formats with audio. |
|
internal
|
|
|
module
Package module provides byte and PCM helpers for native tracker formats.
|
Package module provides byte and PCM helpers for native tracker formats. |
|
Package it loads and replays Impulse Tracker modules.
|
Package it loads and replays Impulse Tracker modules. |
|
Package mod loads four-channel M.K. modules and replays their PCM samples.
|
Package mod loads four-channel M.K. modules and replays their PCM samples. |
|
Package mtm loads MultiTracker modules with reusable tracks and PCM samples.
|
Package mtm loads MultiTracker modules with reusable tracks and PCM samples. |
|
Package s3m loads and replays Scream Tracker 3 modules.
|
Package s3m loads and replays Scream Tracker 3 modules. |
|
Package stm loads Scream Tracker 2 embedded-sample modules.
|
Package stm loads Scream Tracker 2 embedded-sample modules. |
|
Package xm loads FastTracker 2 XM 1.04 modules and replays pitched PCM.
|
Package xm loads FastTracker 2 XM 1.04 modules and replays pitched PCM. |