Documentation
¶
Overview ¶
Package waveform generates stereo peak envelopes for files, CUE tracks, and live PCM. File decoding uses the formats registered with the audio package.
Index ¶
- Constants
- Variables
- func WaveForm(ctx context.Context, stream io.ReaderAt, size int64, options Options) ([][Channels]float32, error)
- func WaveFormCUE(ctx context.Context, library fs.FS, sheetPath string, trackNumber int, ...) ([][Channels]float32, error)
- func WaveFormWithMatroskaPacketLimit(ctx context.Context, stream io.ReaderAt, size int64, options Options, ...) ([][Channels]float32, error)
- func WaveFormsCUE(ctx context.Context, library fs.FS, sheetPath string, options Options) (map[int][][Channels]float32, error)
- type Options
- type StreamBatch
- type StreamWaveForm
Examples ¶
Constants ¶
const ( Channels = 2 // Values per stereo peak. DefaultPoints = 2048 // Peaks in a file or CUE waveform. DefaultFileSampleRate = 0 // Keep the native sample rate. DefaultLiveSampleRate = 48000 // Live PCM rate in Hz. DefaultLivePointsPerSecond = 40 // One live peak per 25 ms. DefaultLiveFramesPerPoint = DefaultLiveSampleRate / DefaultLivePointsPerSecond // Frames per peak. DefaultLiveWindowPoints = 8 * DefaultLivePointsPerSecond // Eight seconds of live peaks. )
Variables ¶
var ErrCUETrack = errors.New("waveform: invalid CUE audio track")
ErrCUETrack indicates a missing or invalid audio track in a CUE sheet.
var ErrOptions = errors.New("waveform: invalid options")
ErrOptions indicates an invalid waveform size or rate.
var ErrWaveformFormat = errors.New("waveform: unsupported audio format")
ErrWaveformFormat indicates that the file has no supported PCM decoder.
Functions ¶
func WaveForm ¶
func WaveForm(ctx context.Context, stream io.ReaderAt, size int64, options Options) ([][Channels]float32, error)
WaveForm returns chronological left/right peak pairs in the range zero to one. Zero options produce DefaultPoints pairs at the native sample rate. Mono contributes equally to both sides. Multichannel PCM is downmixed by speaker position and the LFE channel contributes nothing to the mix.
WaveForm reads from offset zero without moving or closing stream. It returns ErrWaveformFormat when no registered decoder recognizes the input. If a ReadAt is blocked, the caller must unblock or cancel the transport. A nil context returns audio.ErrNilContext.
Example ¶
package main
import (
"context"
"fmt"
"os"
"github.com/BeatGlow/audio/codec"
_ "github.com/BeatGlow/audio/codec/all"
"github.com/BeatGlow/audio/waveform"
)
func main() {
ctx := context.Background()
input, err := os.Open("../testdata/aac-lc-stereo-44100.m4a")
if err != nil {
panic(err)
}
defer func() { _ = input.Close() }()
info, err := input.Stat()
if err != nil {
panic(err)
}
peaks, err := waveform.WaveForm(ctx, input, info.Size(), waveform.Options{})
if err != nil {
panic(err)
}
format := codec.ReadSourceFormat(input)
fmt.Printf("%s at %d Hz, %d stereo peaks\n", format.Codec, format.SampleRateHz, len(peaks))
}
Output: AAC at 44100 Hz, 2048 stereo peaks
func WaveFormCUE ¶
func WaveFormCUE(ctx context.Context, library fs.FS, sheetPath string, trackNumber int, options Options) ([][Channels]float32, error)
WaveFormCUE measures an AUDIO track from the FLAC file named by its FILE directive. Paths are relative to the sheet in library. INDEX 01 starts the range and the next track's INDEX 01 in the same FILE ends it. The last track in each FILE ends at EOF. CUE positions use 75 sectors per second. WaveFormCUE opens and closes both the sheet and its referenced file. A nil context returns audio.ErrNilContext.
func WaveFormWithMatroskaPacketLimit ¶ added in v1.0.1
func WaveFormWithMatroskaPacketLimit( ctx context.Context, stream io.ReaderAt, size int64, options Options, limit int, ) ([][Channels]float32, error)
WaveFormWithMatroskaPacketLimit behaves like WaveForm with a cumulative packet limit for built-in Matroska and WebM decoding. A zero limit leaves the cumulative limit unset. A negative limit returns ErrOptions.
The limit includes packets read during audio track selection and each frame in a lace. Unrelated tracks do not count. If another selected packet would exceed the limit, the function returns audio.ErrMatroskaPacketLimit and no peaks. Other formats ignore the limit.
Example ¶
package main
import (
"context"
"fmt"
"os"
_ "github.com/BeatGlow/audio/codec/all"
"github.com/BeatGlow/audio/waveform"
)
func main() {
ctx := context.Background()
input, err := os.Open("../testdata/matroska-pcm-back-right.mka")
if err != nil {
panic(err)
}
defer func() { _ = input.Close() }()
info, err := input.Stat()
if err != nil {
panic(err)
}
// Allow this fixture's single audio packet.
peaks, err := waveform.WaveFormWithMatroskaPacketLimit(
ctx,
input,
info.Size(),
waveform.Options{},
1,
)
if err != nil {
panic(err)
}
fmt.Printf("%d stereo peaks\n", len(peaks))
}
Output: 2048 stereo peaks
func WaveFormsCUE ¶
func WaveFormsCUE(ctx context.Context, library fs.FS, sheetPath string, options Options) (map[int][][Channels]float32, error)
WaveFormsCUE returns the waveforms of all AUDIO tracks, keyed by CUE track number. It uses the same INDEX 01 ranges as WaveFormCUE and decodes each FILE group in one forward pass. It opens and closes the sheet and each FLAC used by an AUDIO track. A sheet without AUDIO tracks returns ErrCUETrack. A nil context returns audio.ErrNilContext.
Types ¶
type Options ¶
type Options struct {
Points int // Peaks returned for a file or CUE track.
// SampleRate requests decoder output in Hz for files and CUE tracks.
// For live waveforms it describes the supplied PCM, which must already
// be at that rate.
SampleRate int
LivePointsPerSecond int // Peaks emitted per second of live PCM.
LiveWindowPoints int // Completed live peaks to retain.
}
Options configures file, CUE, and live waveforms. Zero fields use the corresponding package defaults.
type StreamBatch ¶
type StreamBatch struct {
PCM audio.Buffer[float32] // Equal-length normalized left and right planes.
Epoch uint64 // Increases when the stream restarts.
FirstFrame uint64 // Frame offset within the epoch.
}
StreamBatch describes a run of consecutive stereo PCM frames. Count dropped frames in the next FirstFrame. On restart, increase Epoch and start FirstFrame at zero.
Example ¶
package main
import (
"fmt"
"github.com/BeatGlow/audio"
"github.com/BeatGlow/audio/waveform"
)
func main() {
// Each captured batch contains 25 ms of normalized 48 kHz stereo PCM.
const framesPerBatch = waveform.DefaultLiveFramesPerPoint
history, err := audio.NewHistory[float32](audio.Format{
RateHz: waveform.DefaultLiveSampleRate,
Layout: audio.StereoLayout,
Encoding: audio.Encoding{
Kind: audio.FloatPCM,
Bits: 32,
},
}, 3*framesPerBatch)
if err != nil {
panic(err)
}
var live waveform.StreamWaveForm
epoch, firstFrame := uint64(1), uint64(0)
planes := audio.Buffer[float32]{
make([]float32, framesPerBatch),
make([]float32, framesPerBatch),
}
deliver := func(left, right float32) {
for i := range framesPerBatch {
planes[0][i], planes[1][i] = left, right
}
batch := waveform.StreamBatch{
PCM: planes,
Epoch: epoch,
FirstFrame: firstFrame,
}
if err := history.AddBlock(planes, epoch, firstFrame); err != nil {
panic(err)
}
firstFrame += uint64(planes.Frames())
live.AddBatch(batch)
}
deliver(0.5, -0.25)
// Capture advanced by another batch, but those samples were dropped.
firstFrame += framesPerBatch
deliver(0.25, -0.75)
var peaks [3][2]float32
n := live.ReadLatest(peaks[:])
fmt.Println("Web waveform:", peaks[:n])
screen := audio.Buffer[float32]{
make([]float32, 2*framesPerBatch),
make([]float32, 2*framesPerBatch),
}
_, ready := history.SnapshotConsecutive(screen)
fmt.Println("Consecutive screen samples after the gap:", ready)
// A restarted capture has a new epoch and starts counting from zero.
epoch++
firstFrame = 0
deliver(0.125, 0.5)
n = live.ReadLatest(peaks[:])
fmt.Println("Web waveform after restart:", peaks[:n])
_, ready = history.SnapshotConsecutive(audio.Buffer[float32]{
screen[0][:framesPerBatch],
screen[1][:framesPerBatch],
})
fmt.Println("Consecutive screen samples after restart:", ready)
}
Output: Web waveform: [[0.5 0.25] [0 0] [0.25 0.75]] Consecutive screen samples after the gap: false Web waveform after restart: [[0.125 0.5]] Consecutive screen samples after restart: true
type StreamWaveForm ¶
type StreamWaveForm struct {
// contains filtered or unexported fields
}
StreamWaveForm retains the latest stereo PCM peaks. Its zero value uses the default live options. One consumer owns it and must serialize its methods. It must not be copied after first use.
func NewStreamWaveForm ¶
func NewStreamWaveForm(options Options) (*StreamWaveForm, error)
NewStreamWaveForm configures a live waveform for the supplied PCM rate.
func (*StreamWaveForm) AddBatch ¶
func (w *StreamWaveForm) AddBatch(batch StreamBatch)
AddBatch consumes consecutive stereo samples without retaining the PCM. It ignores batches without two equal-length planes. A new epoch clears the old waveform. Missing frames advance it through silence.
func (*StreamWaveForm) ReadLatest ¶
func (w *StreamWaveForm) ReadLatest(dst [][Channels]float32) int
ReadLatest copies the newest complete stereo points into dst as left and right peak pairs. It returns the number of points written.