feat: port the client to MyGo native UI (0.3.0)
Switch from Asuka to MyGo, keeping the API client and the feature set: - servers: saved servers, passwordless and password login, proxy, self-signed certificates, per-server device tokens (Keystore), connect form, instance list sheet with switch/disconnect - sessions: virtualized list, search, new session, rename/archive/delete, running indicator, event stream keeps it live - chat: pushed window with system back bar, streaming Markdown via ui/markdown, reasoning and tool rows with image previews, footer menu (read aloud via a Kotlin TTS plugin, copy, fork), user message menu (copy, revert, fork), context usage ring and detail sheet, attachments (photos/files via the document picker), permissions - release builds allow plain http:// LAN servers (Go's net/http dials directly, no cleartext manifest needed) - a local fork of MyGo (third_party/mygo) lowers the Android host's minSdk to 24 (Android 7.0); Go 1.27.4 via mise Version 0.3.0.
This commit is contained in:
1 parent
2fb4a8ea79
commit
6c0ee61750
2538 files changed
+675779
-4792
No files matched your search
Vendored
+203
@@ -0,0 +1,203 @@
|
||||
// Package aac decodes AAC-LC for package audio, with
|
||||
// github.com/tphakala/go-aac: in MP4 (.m4a, and fragmented .m4s as DASH
|
||||
// streams it), through package audio/mp4, and in ADTS (.aac). Import it
|
||||
// for its side effect:
|
||||
//
|
||||
// import _ "github.com/egoist/mygo/audio/aac"
|
||||
//
|
||||
// HE-AAC (AAC+, with SBR) and HE-AAC v2 it does not decode: their files
|
||||
// fail to open, and mp4.Track's Decodable says so of them.
|
||||
//
|
||||
// go-aac is under the LGPL 2.1 or later, unlike MyGo, whose license is
|
||||
// MIT: an app that imports this package links it, and takes on the LGPL's
|
||||
// terms for it.
|
||||
package aac
|
||||
|
||||
import (
|
||||
"encoding/binary"
|
||||
"errors"
|
||||
"io"
|
||||
|
||||
"github.com/egoist/mygo/audio"
|
||||
"github.com/egoist/mygo/audio/mp4"
|
||||
aacpcm "github.com/tphakala/go-aac/pcm"
|
||||
)
|
||||
|
||||
func init() {
|
||||
mp4.RegisterCodec("mp4a", func(config []byte) (mp4.Codec, error) { return NewCodec(config) })
|
||||
open := func(r io.ReadSeeker) (audio.Decoder, error) { return NewADTSDecoder(r) }
|
||||
// The sync word of an ADTS header, of MPEG-4 or MPEG-2, with a CRC or
|
||||
// without; MP3's differ in their layer.
|
||||
for _, b := range []string{"\xff\xf1", "\xff\xf0", "\xff\xf9", "\xff\xf8"} {
|
||||
audio.RegisterFormat("aac", b, open)
|
||||
}
|
||||
}
|
||||
|
||||
// FrameLength is how many frames each AAC packet decodes to.
|
||||
const FrameLength = 1024
|
||||
|
||||
// codec decodes AAC packets, raw as in an MP4 or each with its ADTS header.
|
||||
type codec struct {
|
||||
fd *aacpcm.FrameDecoder
|
||||
pcm []byte
|
||||
}
|
||||
|
||||
// NewCodec returns a decoder of the raw AAC packets of a track configured
|
||||
// by asc, its AudioSpecificConfig: an MP4's, for package mp4.
|
||||
func NewCodec(asc []byte) (mp4.Codec, error) {
|
||||
fd, err := aacpcm.NewRawDecoder(asc)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &codec{fd: fd}, nil
|
||||
}
|
||||
|
||||
func (c *codec) SampleRate() int { return c.fd.SampleRate() }
|
||||
func (c *codec) Reset() { c.fd.Reset() }
|
||||
func (c *codec) Preroll() int { return 1 }
|
||||
func (c *codec) PacketFrames() int { return FrameLength }
|
||||
|
||||
func (c *codec) Decode(dst []float32, packet []byte) ([]float32, error) {
|
||||
pcm, n, err := c.fd.DecodeFrame(c.pcm[:0], packet)
|
||||
if err != nil {
|
||||
return dst, err
|
||||
}
|
||||
c.pcm = pcm
|
||||
ch := c.fd.Channels()
|
||||
right := 0
|
||||
if ch > 1 {
|
||||
right = 2
|
||||
}
|
||||
for i := range n {
|
||||
f := pcm[i*ch*2:]
|
||||
dst = append(dst,
|
||||
float32(int16(binary.LittleEndian.Uint16(f)))/(1<<15),
|
||||
float32(int16(binary.LittleEndian.Uint16(f[right:])))/(1<<15))
|
||||
}
|
||||
return dst, nil
|
||||
}
|
||||
|
||||
var adtsRates = [...]int{96000, 88200, 64000, 48000, 44100, 32000, 24000, 22050, 16000, 12000, 11025, 8000, 7350}
|
||||
|
||||
// adtsHeader reads an ADTS frame's header: its length in bytes, and its
|
||||
// sample rate.
|
||||
func adtsHeader(h []byte) (length, rate int, ok bool) {
|
||||
if len(h) < 7 || h[0] != 0xff || h[1]&0xf6 != 0xf0 {
|
||||
return 0, 0, false
|
||||
}
|
||||
i := int(h[2] >> 2 & 15)
|
||||
length = int(h[3]&3)<<11 | int(h[4])<<3 | int(h[5]>>5)
|
||||
if i >= len(adtsRates) || length < 7 {
|
||||
return 0, 0, false
|
||||
}
|
||||
return length, adtsRates[i], true
|
||||
}
|
||||
|
||||
// adts decodes AAC in ADTS frames, each with a header saying how long it
|
||||
// is, which it finds all of as it opens, for the length and to seek.
|
||||
type adts struct {
|
||||
r io.ReadSeeker
|
||||
c *codec
|
||||
rate int
|
||||
offs []int64
|
||||
sizes []int
|
||||
next int // the packet decoded next
|
||||
skip int64 // frames to drop before the frame Read returns next
|
||||
buf []byte
|
||||
out []float32
|
||||
pend []float32
|
||||
}
|
||||
|
||||
// NewADTSDecoder returns a decoder of the AAC in ADTS frames r holds, as
|
||||
// an .aac file, after an ID3 tag if one is first. It decodes to stereo.
|
||||
func NewADTSDecoder(r io.ReadSeeker) (audio.Decoder, error) {
|
||||
start, err := skipID3(r)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
d := &adts{r: r, c: &codec{fd: aacpcm.NewADTSDecoder()}}
|
||||
var h [7]byte
|
||||
for off := start; ; {
|
||||
if _, err := r.Seek(off, io.SeekStart); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if _, err := io.ReadFull(r, h[:]); err != nil {
|
||||
break
|
||||
}
|
||||
length, rate, ok := adtsHeader(h[:])
|
||||
if !ok {
|
||||
break
|
||||
}
|
||||
if d.rate == 0 {
|
||||
d.rate = rate
|
||||
}
|
||||
d.offs = append(d.offs, off)
|
||||
d.sizes = append(d.sizes, length)
|
||||
off += int64(length)
|
||||
}
|
||||
if len(d.offs) == 0 {
|
||||
return nil, errors.New("aac: not an ADTS stream")
|
||||
}
|
||||
return d, d.SetPosition(0)
|
||||
}
|
||||
|
||||
// skipID3 returns where r's audio starts: after an ID3 tag, if r starts
|
||||
// with one.
|
||||
func skipID3(r io.ReadSeeker) (int64, error) {
|
||||
var b [10]byte
|
||||
if _, err := r.Seek(0, io.SeekStart); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
if _, err := io.ReadFull(r, b[:]); err != nil || string(b[:3]) != "ID3" {
|
||||
return 0, nil
|
||||
}
|
||||
return 10 + int64(b[6]&0x7f)<<21 | int64(b[7]&0x7f)<<14 | int64(b[8]&0x7f)<<7 | int64(b[9]&0x7f), nil
|
||||
}
|
||||
|
||||
func (d *adts) SampleRate() int { return d.rate }
|
||||
func (d *adts) Channels() int { return 2 }
|
||||
func (d *adts) Len() int64 { return int64(len(d.offs)) * FrameLength }
|
||||
|
||||
func (d *adts) Read(dst []float32) (int, error) {
|
||||
for len(d.pend) == 0 {
|
||||
if d.next >= len(d.offs) {
|
||||
return 0, io.EOF
|
||||
}
|
||||
size := d.sizes[d.next]
|
||||
if cap(d.buf) < size {
|
||||
d.buf = make([]byte, size)
|
||||
}
|
||||
d.buf = d.buf[:size]
|
||||
if _, err := d.r.Seek(d.offs[d.next], io.SeekStart); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
if _, err := io.ReadFull(d.r, d.buf); err != nil {
|
||||
return 0, io.EOF
|
||||
}
|
||||
d.next++
|
||||
out, err := d.c.Decode(d.out[:0], d.buf)
|
||||
d.out = out
|
||||
if err != nil {
|
||||
continue // a packet gone bad: on to the next
|
||||
}
|
||||
drop := min(d.skip, int64(len(out)/2))
|
||||
d.skip -= drop
|
||||
d.pend = out[drop*2:]
|
||||
}
|
||||
n := copy(dst[:len(dst)/2*2], d.pend)
|
||||
d.pend = d.pend[n:]
|
||||
return n, nil
|
||||
}
|
||||
|
||||
// SetPosition goes to the packet holding frame, from the one before, whose
|
||||
// sound overlaps it, and drops what comes before frame.
|
||||
func (d *adts) SetPosition(frame int64) error {
|
||||
frame = min(max(frame, 0), d.Len())
|
||||
i := int(frame / FrameLength)
|
||||
start := max(0, i-1)
|
||||
d.c.Reset()
|
||||
d.next = start
|
||||
d.skip = frame - int64(start)*FrameLength
|
||||
d.pend = nil
|
||||
return nil
|
||||
}
|
||||
+156
@@ -0,0 +1,156 @@
|
||||
package aac_test
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/binary"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
_ "github.com/egoist/mygo/audio/aac"
|
||||
_ "github.com/egoist/mygo/audio/flac"
|
||||
"github.com/egoist/mygo/audio/internal/audiotest"
|
||||
"github.com/egoist/mygo/audio/mp4"
|
||||
)
|
||||
|
||||
// The source the files were encoded from.
|
||||
func source(t *testing.T) []float32 {
|
||||
return audiotest.ReadAll(t, audiotest.Open(t, audiotest.Read(t, "../flac/testdata/tone.flac"), "flac"))
|
||||
}
|
||||
|
||||
// AAC's encoder adds a packet of priming before the sound.
|
||||
const prime = 1024
|
||||
|
||||
// An AAC .m4a drops the encoder's priming, as its edit list says, so it
|
||||
// lines up with what it was encoded from and is as long. A seek decodes the
|
||||
// packet before, whose sound overlaps the one sought to.
|
||||
func TestMP4(t *testing.T) {
|
||||
b := audiotest.Read(t, "testdata/tone.m4a")
|
||||
tr, err := mp4.ReadTrack(bytes.NewReader(b), int64(len(b)))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if tr.Codec != "mp4a" || tr.Duration != 2*time.Second || !tr.Decodable() {
|
||||
t.Fatalf("%+v", tr)
|
||||
}
|
||||
d := audiotest.Open(t, b, "mp4")
|
||||
if d.SampleRate() != 44100 || d.Channels() != 2 || d.Len() != 88200 {
|
||||
t.Fatalf("%d Hz, %d channels, %d frames", d.SampleRate(), d.Channels(), d.Len())
|
||||
}
|
||||
got := audiotest.ReadAll(t, d)
|
||||
if len(got) != 88200*2 {
|
||||
t.Fatalf("decoded %d samples", len(got))
|
||||
}
|
||||
if db := audiotest.SNR(got, source(t)); db < 20 {
|
||||
t.Errorf("%.1f dB from the source", db)
|
||||
}
|
||||
// Noise the encoder substituted is random each time it's decoded.
|
||||
audiotest.SeekLands(t, d, got, 0.05, 0, 1, 4096, 50000, 77777)
|
||||
}
|
||||
|
||||
// An AAC .m4a cut into fragments, as a stream for DASH is, plays what it
|
||||
// was encoded from too, with its length from its segment index. Its movie
|
||||
// header has no edit list, so the encoder's priming plays; the padding of
|
||||
// its last packet doesn't, as its last packet's duration says.
|
||||
func TestFragmented(t *testing.T) {
|
||||
b := audiotest.Read(t, "testdata/fragmented.m4a")
|
||||
d := audiotest.Open(t, b, "mp4")
|
||||
length := d.Len()
|
||||
got := audiotest.ReadAll(t, d)
|
||||
src := source(t)
|
||||
if len(got) != len(src)+prime*2 {
|
||||
t.Fatalf("decoded %d samples, the source %d", len(got), len(src))
|
||||
}
|
||||
if length*2 != int64(len(got)) || d.Len() != length {
|
||||
t.Errorf("length %d, then %d, though %d frames decode", length, d.Len(), len(got)/2)
|
||||
}
|
||||
if db := audiotest.SNR(got[prime*2:], src); db < 20 {
|
||||
t.Errorf("%.1f dB from the source", db)
|
||||
}
|
||||
audiotest.SeekLands(t, d, got, 0.05, 0, 1, 4096, 50000, 77777)
|
||||
}
|
||||
|
||||
// AAC's packets each decode to 1024 frames, whatever the file says they
|
||||
// last: a seek lands where decoding straight through has the frame. Some
|
||||
// files have a packet near the start a few frames shorter, which would put
|
||||
// every seek past it that much off.
|
||||
func TestPacketsOfOtherDurations(t *testing.T) {
|
||||
b := bytes.Clone(audiotest.Read(t, "testdata/fragmented.m4a"))
|
||||
// The first fragment's packets last 1016 frames, its header says.
|
||||
at := bytes.Index(b, []byte("tfhd"))
|
||||
flags := binary.BigEndian.Uint32(b[at+4:]) & 0xffffff
|
||||
if flags&0x08 == 0 {
|
||||
t.Fatal("the fragment has no default duration")
|
||||
}
|
||||
at += 4 + 8
|
||||
if flags&0x01 != 0 {
|
||||
at += 8
|
||||
}
|
||||
if flags&0x02 != 0 {
|
||||
at += 4
|
||||
}
|
||||
if binary.BigEndian.Uint32(b[at:]) != 1024 {
|
||||
t.Fatal("no default duration of 1024 where expected")
|
||||
}
|
||||
binary.BigEndian.PutUint32(b[at:], 1016)
|
||||
d := audiotest.Open(t, b, "mp4")
|
||||
got := audiotest.ReadAll(t, d)
|
||||
for _, frame := range []int64{30000, 60000, 60001} {
|
||||
if err := d.SetPosition(frame); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var read []float32
|
||||
buf := make([]float32, 4096)
|
||||
for len(read) < 44100 {
|
||||
n, err := d.Read(buf)
|
||||
read = append(read, buf[:n]...)
|
||||
if err != nil || n == 0 {
|
||||
break
|
||||
}
|
||||
}
|
||||
if db := audiotest.SNR(read, got[frame*2:]); db < 20 {
|
||||
t.Errorf("seek to %d: %.1f dB from decoding straight through", frame, db)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// An .aac of ADTS frames plays what it was encoded from, after the
|
||||
// encoder's priming, which nothing says to drop.
|
||||
func TestADTS(t *testing.T) {
|
||||
b := audiotest.Read(t, "testdata/tone.aac")
|
||||
d := audiotest.Open(t, b, "aac")
|
||||
if d.SampleRate() != 44100 || d.Channels() != 2 {
|
||||
t.Fatalf("%d Hz, %d channels", d.SampleRate(), d.Channels())
|
||||
}
|
||||
got := audiotest.ReadAll(t, d)
|
||||
if int64(len(got)) != d.Len()*2 || len(got) < (88200+prime)*2 {
|
||||
t.Fatalf("decoded %d samples, length %d", len(got), d.Len())
|
||||
}
|
||||
if db := audiotest.SNR(got[prime*2:], source(t)); db < 20 {
|
||||
t.Errorf("%.1f dB from the source", db)
|
||||
}
|
||||
audiotest.SeekLands(t, d, got, 0.05, 0, 1, 4096, 50000, 77777)
|
||||
|
||||
// After an ID3 tag too.
|
||||
tag := append([]byte("ID3\x04\x00\x00\x00\x00\x00\x20"), make([]byte, 32)...)
|
||||
d = audiotest.Open(t, append(tag, b...), "aac")
|
||||
if again := audiotest.ReadAll(t, d); len(again) != len(got) {
|
||||
t.Errorf("decoded %d samples after an ID3 tag, %d without", len(again), len(got))
|
||||
}
|
||||
}
|
||||
|
||||
// HE-AAC, with SBR, isn't decoded: a track of it says so.
|
||||
func TestHEAAC(t *testing.T) {
|
||||
for _, tt := range []struct {
|
||||
name string
|
||||
config []byte
|
||||
want bool
|
||||
}{
|
||||
{"AAC-LC", []byte{0x12, 0x10}, true},
|
||||
{"HE-AAC", []byte{0x2b, 0x12, 0x08}, false},
|
||||
} {
|
||||
tr := mp4.Track{Codec: "mp4a", Config: tt.config}
|
||||
if got := tr.Decodable(); got != tt.want {
|
||||
t.Errorf("%s: decodable %v", tt.name, got)
|
||||
}
|
||||
}
|
||||
}
|
||||
Binary file not shown.
BIN
Binary file not shown.
BIN
Binary file not shown.
Vendored
+610
@@ -0,0 +1,610 @@
|
||||
// Package audio plays sound: effects decoded into memory, music streamed
|
||||
// as it plays, and sound an app makes itself, mixed in Go and sent to the
|
||||
// system's audio output:
|
||||
//
|
||||
// click, err := audio.DecodeSound(clickWAV) // decoded once
|
||||
// ...
|
||||
// click.Play() // as often as it sounds, over itself
|
||||
//
|
||||
// music, err := audio.OpenStream(f) // decoded as it plays
|
||||
// music.SetLoop(true).SetVolume(0.6).Play()
|
||||
//
|
||||
// WAV decodes out of the box; import audio/vorbis for Ogg Vorbis and
|
||||
// audio/mp3 for MP3, which register themselves as image's formats do.
|
||||
//
|
||||
// The output opens when something first plays and closes a few seconds
|
||||
// after everything stopped. Where no output can open, players still play
|
||||
// on time, unheard, and Err says why. Every function and method is safe
|
||||
// to call from any goroutine.
|
||||
package audio
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"bytes"
|
||||
"errors"
|
||||
"io"
|
||||
"math"
|
||||
"runtime"
|
||||
"slices"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
// The output's format: every player is resampled to it.
|
||||
const (
|
||||
sampleRate = 48000
|
||||
channels = 2
|
||||
)
|
||||
|
||||
// mu guards the voices playing and the state of every player.
|
||||
var mu sync.Mutex
|
||||
|
||||
// A Decoder decodes audio as interleaved float32 samples in [-1, 1], one
|
||||
// per channel for each frame. Formats registered with RegisterFormat
|
||||
// return one; implement one to play sound an app generates itself.
|
||||
type Decoder interface {
|
||||
// SampleRate returns the frames per second.
|
||||
SampleRate() int
|
||||
// Channels returns the samples per frame: 1 for mono, 2 for stereo
|
||||
// (left, right); later channels of more are not played.
|
||||
Channels() int
|
||||
// Read decodes the next samples into buf, a whole number of frames,
|
||||
// and returns how many it wrote, with io.EOF at the end.
|
||||
Read(buf []float32) (int, error)
|
||||
// SetPosition moves to frame, counted from the start.
|
||||
SetPosition(frame int64) error
|
||||
// Len returns the frames from the start to the end, or -1 if unknown.
|
||||
Len() int64
|
||||
}
|
||||
|
||||
type format struct {
|
||||
name, magic string
|
||||
open func(io.ReadSeeker) (Decoder, error)
|
||||
}
|
||||
|
||||
var (
|
||||
formatsMu sync.Mutex
|
||||
formats []format
|
||||
)
|
||||
|
||||
// RegisterFormat registers a format for DecodeSound, OpenStream and
|
||||
// NewDecoder: magic is the start of its files, where '?' matches any
|
||||
// byte, and open returns a decoder reading r from its start. A file that
|
||||
// starts with an ID3 tag is of the format its bytes after the tag match,
|
||||
// and its decoder reads it from the tag. A package for a format calls it
|
||||
// in its init function.
|
||||
func RegisterFormat(name, magic string, open func(r io.ReadSeeker) (Decoder, error)) {
|
||||
formatsMu.Lock()
|
||||
defer formatsMu.Unlock()
|
||||
formats = append(formats, format{name, magic, open})
|
||||
}
|
||||
|
||||
// ErrFormat reports data of no format registered.
|
||||
var ErrFormat = errors.New("audio: unknown format")
|
||||
|
||||
func match(magic string, b []byte) bool {
|
||||
if len(magic) > len(b) {
|
||||
return false
|
||||
}
|
||||
for i := 0; i < len(magic); i++ {
|
||||
if magic[i] != '?' && magic[i] != b[i] {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// NewDecoder returns a decoder of r's format, and the format's name.
|
||||
func NewDecoder(r io.ReadSeeker) (Decoder, string, error) {
|
||||
start, err := r.Seek(0, io.SeekCurrent)
|
||||
if err != nil {
|
||||
return nil, "", err
|
||||
}
|
||||
var head, after [16]byte
|
||||
n, err := io.ReadFull(r, head[:])
|
||||
if err != nil && err != io.ErrUnexpectedEOF {
|
||||
return nil, "", err
|
||||
}
|
||||
// An ID3 tag first, as MP3s have and some FLAC and AAC files too: the
|
||||
// format is what follows it.
|
||||
m := 0
|
||||
if n >= 10 && string(head[:3]) == "ID3" {
|
||||
size := int64(head[6]&0x7f)<<21 | int64(head[7]&0x7f)<<14 | int64(head[8]&0x7f)<<7 | int64(head[9]&0x7f)
|
||||
if _, err := r.Seek(start+10+size, io.SeekStart); err == nil {
|
||||
m, _ = io.ReadFull(r, after[:])
|
||||
}
|
||||
}
|
||||
if _, err := r.Seek(start, io.SeekStart); err != nil {
|
||||
return nil, "", err
|
||||
}
|
||||
formatsMu.Lock()
|
||||
fs := formats
|
||||
formatsMu.Unlock()
|
||||
for _, b := range [][]byte{after[:m], head[:n]} {
|
||||
for _, f := range fs {
|
||||
if len(b) > 0 && match(f.magic, b) {
|
||||
d, err := f.open(r)
|
||||
if err != nil {
|
||||
return nil, f.name, err
|
||||
}
|
||||
return d, f.name, nil
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil, "", ErrFormat
|
||||
}
|
||||
|
||||
// A Sound is audio decoded into memory, for effects that play often and
|
||||
// over themselves: each Play is a new Player.
|
||||
type Sound struct {
|
||||
samples []float32
|
||||
channels int
|
||||
rate int
|
||||
}
|
||||
|
||||
// DecodeSound decodes data of a registered format into memory.
|
||||
func DecodeSound(data []byte) (*Sound, error) {
|
||||
d, _, err := NewDecoder(bytes.NewReader(data))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return ReadSound(d)
|
||||
}
|
||||
|
||||
// reserveFrames is the most frames ReadSound reserves from a decoder's
|
||||
// Len, six minutes at 44.1 kHz: a header can say any length, and a longer
|
||||
// sound grows as it is decoded.
|
||||
const reserveFrames = 1 << 24
|
||||
|
||||
// ReadSound decodes everything d has into memory.
|
||||
func ReadSound(d Decoder) (*Sound, error) {
|
||||
ch := d.Channels()
|
||||
if ch < 1 || d.SampleRate() <= 0 {
|
||||
return nil, errors.New("audio: decoder of no channels or sample rate")
|
||||
}
|
||||
keep := min(ch, 2)
|
||||
var samples []float32
|
||||
if n := d.Len(); n > 0 {
|
||||
samples = make([]float32, 0, min(n, reserveFrames)*int64(keep))
|
||||
}
|
||||
buf := make([]float32, 4096/ch*ch)
|
||||
for {
|
||||
n, err := d.Read(buf)
|
||||
n -= n % ch
|
||||
for i := 0; i < n; i += ch {
|
||||
samples = append(samples, buf[i:i+keep]...)
|
||||
}
|
||||
if err == io.EOF {
|
||||
break
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if n == 0 {
|
||||
return nil, io.ErrNoProgress
|
||||
}
|
||||
}
|
||||
return &Sound{samples: samples, channels: keep, rate: d.SampleRate()}, nil
|
||||
}
|
||||
|
||||
// NewSound returns a sound of samples, interleaved frames of 1 (mono) or 2
|
||||
// (stereo) channels at sampleRate frames per second, as an app generates
|
||||
// them. The sound keeps samples: don't change them afterwards.
|
||||
func NewSound(sampleRate, channels int, samples []float32) *Sound {
|
||||
if channels != 1 && channels != 2 {
|
||||
panic("audio: NewSound takes 1 or 2 channels")
|
||||
}
|
||||
if sampleRate <= 0 {
|
||||
panic("audio: NewSound takes a positive sample rate")
|
||||
}
|
||||
return &Sound{samples: samples[:len(samples)/channels*channels], channels: channels, rate: sampleRate}
|
||||
}
|
||||
|
||||
// Duration returns how long the sound plays.
|
||||
func (s *Sound) Duration() time.Duration {
|
||||
return frames(int64(len(s.samples)/s.channels), s.rate)
|
||||
}
|
||||
|
||||
// NewPlayer returns a paused player of the sound.
|
||||
func (s *Sound) NewPlayer() *Player {
|
||||
src := &memSource{samples: s.samples, channels: s.channels}
|
||||
return newPlayer(src, s.rate, s.channels, int64(len(s.samples)/s.channels))
|
||||
}
|
||||
|
||||
// Play plays the sound from its start, over any other of its players, and
|
||||
// returns the player playing it.
|
||||
func (s *Sound) Play() *Player {
|
||||
p := s.NewPlayer()
|
||||
p.Play()
|
||||
return p
|
||||
}
|
||||
|
||||
// OpenStream returns a paused player decoding r as it plays, for music and
|
||||
// other long audio: it decodes about a second ahead. Closing the player
|
||||
// closes r if r is an io.Closer.
|
||||
func OpenStream(r io.ReadSeeker) (*Player, error) {
|
||||
d, _, err := NewDecoder(r)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if c, ok := r.(io.Closer); ok {
|
||||
d = closingDecoder{d, c}
|
||||
}
|
||||
return NewPlayer(d), nil
|
||||
}
|
||||
|
||||
type closingDecoder struct {
|
||||
Decoder
|
||||
io.Closer
|
||||
}
|
||||
|
||||
// NewPlayer returns a paused player decoding d as it plays, about a second
|
||||
// ahead. d is used by one goroutine at a time. Closing the player closes d
|
||||
// if d is an io.Closer.
|
||||
func NewPlayer(d Decoder) *Player {
|
||||
ch := min(d.Channels(), 2)
|
||||
s := newStream(d)
|
||||
p := newPlayer(s, d.SampleRate(), ch, d.Len())
|
||||
// A player dropped while paused would leave its decoder waiting; one
|
||||
// dropped while playing plays to its end, as a sound's do.
|
||||
runtime.AddCleanup(p, func(v *voice) {
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
if v.active {
|
||||
v.orphan = true
|
||||
} else {
|
||||
v.close()
|
||||
}
|
||||
}, p.v)
|
||||
return p
|
||||
}
|
||||
|
||||
// readerOf buffers r when it reads small amounts at a time, as a file.
|
||||
func readerOf(r io.Reader) io.Reader {
|
||||
if _, ok := r.(*bytes.Reader); ok {
|
||||
return r
|
||||
}
|
||||
return bufio.NewReader(r)
|
||||
}
|
||||
|
||||
// frames returns the duration of n frames at rate.
|
||||
func frames(n int64, rate int) time.Duration {
|
||||
return time.Duration(float64(n) * float64(time.Second) / float64(rate))
|
||||
}
|
||||
|
||||
// A Player plays a sound or a stream: its position, volume, pan, speed and
|
||||
// looping are its own.
|
||||
type Player struct {
|
||||
v *voice
|
||||
}
|
||||
|
||||
func newPlayer(src source, rate, ch int, length int64) *Player {
|
||||
v := &voice{src: src, rate: float64(rate), mono: ch == 1, length: length, volume: 1, speed: 1}
|
||||
v.reset(0)
|
||||
return &Player{v}
|
||||
}
|
||||
|
||||
// Play plays from where the player is, or from the start if it ended.
|
||||
func (p *Player) Play() {
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
v := p.v
|
||||
if v.closed || v.playing {
|
||||
return
|
||||
}
|
||||
if v.ended() {
|
||||
v.src.seek(0)
|
||||
v.reset(0)
|
||||
}
|
||||
v.playing = true
|
||||
if !v.active {
|
||||
// A sound starting at its start starts at once; one resuming in
|
||||
// the middle fades in, as one pausing fades out, without a click.
|
||||
// One still fading out ramps back from where it is.
|
||||
v.snap = v.head <= 0
|
||||
v.fadeIn = !v.snap
|
||||
v.active = true
|
||||
voices = append(voices, v)
|
||||
wakeOutput()
|
||||
}
|
||||
}
|
||||
|
||||
// Pause pauses the player where it is.
|
||||
func (p *Player) Pause() {
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
p.v.playing = false
|
||||
}
|
||||
|
||||
// Stop pauses the player and moves it to the start.
|
||||
func (p *Player) Stop() {
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
v := p.v
|
||||
if v.closed {
|
||||
return
|
||||
}
|
||||
v.playing = false
|
||||
v.src.seek(0)
|
||||
v.reset(0)
|
||||
}
|
||||
|
||||
// Playing reports whether the player plays: false once paused, stopped,
|
||||
// closed, or at its end.
|
||||
func (p *Player) Playing() bool {
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
return p.v.playing
|
||||
}
|
||||
|
||||
// endListener is a function OnEnd registered.
|
||||
type endListener struct {
|
||||
id uint64
|
||||
fn func()
|
||||
}
|
||||
|
||||
// OnEnd calls fn on a goroutine of its own each time the player plays to
|
||||
// its end, which a looping player never does, as a playlist plays the
|
||||
// next track then. off removes it.
|
||||
func (p *Player) OnEnd(fn func()) (off func()) {
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
v := p.v
|
||||
v.nextEnd++
|
||||
id := v.nextEnd
|
||||
v.onEnd = append(v.onEnd, endListener{id, fn})
|
||||
return func() {
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
v.onEnd = slices.DeleteFunc(slices.Clone(v.onEnd), func(l endListener) bool { return l.id == id })
|
||||
}
|
||||
}
|
||||
|
||||
// Seek moves the player to t from the start.
|
||||
func (p *Player) Seek(t time.Duration) {
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
v := p.v
|
||||
if v.closed {
|
||||
return
|
||||
}
|
||||
f := max(int64(math.Round(t.Seconds()*v.rate)), 0)
|
||||
if v.length >= 0 {
|
||||
f = min(f, v.length)
|
||||
}
|
||||
v.src.seek(f)
|
||||
v.reset(f)
|
||||
}
|
||||
|
||||
// Position returns how far the player is from the start, in what is heard:
|
||||
// the output mixes ahead of it (SetLatency), and the player goes on for
|
||||
// as long after a pause, but it is where Seek moved it at once.
|
||||
func (p *Player) Position() time.Duration {
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
return time.Duration(p.v.position(p.v.heardAt()) / p.v.rate * float64(time.Second))
|
||||
}
|
||||
|
||||
// Duration returns how long the player's audio is, or 0 if unknown.
|
||||
func (p *Player) Duration() time.Duration {
|
||||
if p.v.length < 0 {
|
||||
return 0
|
||||
}
|
||||
return frames(p.v.length, int(p.v.rate))
|
||||
}
|
||||
|
||||
// SetVolume sets the player's volume, a gain: 1 (the default) as decoded,
|
||||
// 0 silent. Changes ramp over a few milliseconds, without a click.
|
||||
func (p *Player) SetVolume(v float64) *Player {
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
p.v.volume = max(v, 0)
|
||||
return p
|
||||
}
|
||||
|
||||
// Volume returns the player's volume.
|
||||
func (p *Player) Volume() float64 {
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
return p.v.volume
|
||||
}
|
||||
|
||||
// SetPan places the player between the left speaker (-1) and the right
|
||||
// (1); 0, the default, is the middle. A mono sound pans keeping its
|
||||
// power; a stereo one keeps both channels, as Web Audio's StereoPannerNode
|
||||
// does.
|
||||
func (p *Player) SetPan(pan float64) *Player {
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
p.v.pan = min(max(pan, -1), 1)
|
||||
return p
|
||||
}
|
||||
|
||||
// Pan returns the player's pan.
|
||||
func (p *Player) Pan() float64 {
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
return p.v.pan
|
||||
}
|
||||
|
||||
// SetSpeed sets how fast the player plays, which changes its pitch with
|
||||
// it, as a record's speed does: 1 (the default) as decoded, 2 twice as
|
||||
// fast and an octave higher. Games vary it a little for effects that
|
||||
// play often. SetPreservesPitch keeps the pitch instead.
|
||||
func (p *Player) SetSpeed(s float64) *Player {
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
if s > 0 && !math.IsInf(s, 0) {
|
||||
p.v.speed = min(s, 16)
|
||||
}
|
||||
return p
|
||||
}
|
||||
|
||||
// Speed returns the player's speed.
|
||||
func (p *Player) Speed() float64 {
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
return p.v.speed
|
||||
}
|
||||
|
||||
// SetPreservesPitch sets whether the player keeps its pitch at a speed
|
||||
// other than 1, as HTML media's preservesPitch does: true time-stretches
|
||||
// it, as a podcast or a lecture plays at 1.5× in the voice it was
|
||||
// recorded in, while false, the default, changes the pitch with the
|
||||
// speed (SetSpeed). Time-stretching suits speech and other sound with a
|
||||
// pitch at speeds from about 0.5 to 4, and costs a little more to mix;
|
||||
// sharp attacks, as drums', come out a little smeared. A change applies
|
||||
// after what the player stretched ahead, about 16 ms, without a gap.
|
||||
func (p *Player) SetPreservesPitch(on bool) *Player {
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
v := p.v
|
||||
if v.closed {
|
||||
return p
|
||||
}
|
||||
v.pitch = on
|
||||
if on && v.st == nil {
|
||||
v.stretch()
|
||||
}
|
||||
return p
|
||||
}
|
||||
|
||||
// PreservesPitch reports whether the player keeps its pitch at its speed.
|
||||
func (p *Player) PreservesPitch() bool {
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
return p.v.pitch
|
||||
}
|
||||
|
||||
// SetLoop sets whether the player starts again from the start when it
|
||||
// ends, without a gap, or from its loop's start (SetLoopRange). A change
|
||||
// is heard after what the player decoded ahead: a few milliseconds of a
|
||||
// sound, up to a second of a stream.
|
||||
func (p *Player) SetLoop(loop bool) *Player {
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
if !p.v.closed {
|
||||
p.v.loop = loop
|
||||
p.v.src.setLoop(loop, p.v.loopStart, p.v.loopEnd)
|
||||
}
|
||||
return p
|
||||
}
|
||||
|
||||
// SetLoopRange loops the player between start and end, without a gap,
|
||||
// end 0 being the end of its audio: what is before start, as a tune's
|
||||
// intro, plays once, and playing past end goes on from start. It sets the
|
||||
// player looping; SetLoop(false) plays on past end, as far as the end.
|
||||
func (p *Player) SetLoopRange(start, end time.Duration) *Player {
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
v := p.v
|
||||
if v.closed {
|
||||
return p
|
||||
}
|
||||
s := max(int64(math.Round(start.Seconds()*v.rate)), 0)
|
||||
e := max(int64(math.Round(end.Seconds()*v.rate)), 0)
|
||||
if v.length >= 0 {
|
||||
s, e = min(s, v.length), min(e, v.length)
|
||||
}
|
||||
if e != 0 && e <= s {
|
||||
s, e = 0, 0 // nothing to loop: all of it
|
||||
}
|
||||
v.loopStart, v.loopEnd, v.loop = s, e, true
|
||||
v.src.setLoop(true, s, e)
|
||||
return p
|
||||
}
|
||||
|
||||
// Loop reports whether the player loops.
|
||||
func (p *Player) Loop() bool {
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
return p.v.loop
|
||||
}
|
||||
|
||||
// Close stops the player for good and frees what it decodes with. A
|
||||
// sound's players need no closing.
|
||||
func (p *Player) Close() {
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
p.v.playing = false
|
||||
p.v.close()
|
||||
}
|
||||
|
||||
var (
|
||||
volume = 1.0
|
||||
latency = LatencyInteractive
|
||||
outErr error
|
||||
errMu sync.Mutex
|
||||
)
|
||||
|
||||
// SetVolume sets the volume of everything played, a gain: 1 (the default)
|
||||
// as decoded, 0 silent.
|
||||
func SetVolume(v float64) {
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
volume = max(v, 0)
|
||||
}
|
||||
|
||||
// Volume returns the volume of everything played.
|
||||
func Volume() float64 {
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
return volume
|
||||
}
|
||||
|
||||
// Latency is how far ahead of what is heard the output mixes, as Web
|
||||
// Audio's latencyHint.
|
||||
type Latency int
|
||||
|
||||
const (
|
||||
// LatencyInteractive mixes about 40 ms ahead, so that sounds start,
|
||||
// stop and change as soon as they are asked to, as games and
|
||||
// interfaces want. It is the default.
|
||||
LatencyInteractive Latency = iota
|
||||
// LatencyPlayback mixes about 250 ms ahead, for apps that play music
|
||||
// and other long audio: it plays on through the moments the system
|
||||
// keeps an app waiting, as macOS does while its appearance changes,
|
||||
// where the interactive latency runs dry and is heard to stop. Plays,
|
||||
// pauses, seeks and volume changes are heard that much later.
|
||||
LatencyPlayback
|
||||
)
|
||||
|
||||
// ahead returns how much the output holds before it is heard.
|
||||
func (l Latency) ahead() time.Duration {
|
||||
if l == LatencyPlayback {
|
||||
return 250 * time.Millisecond
|
||||
}
|
||||
return 40 * time.Millisecond
|
||||
}
|
||||
|
||||
// SetLatency sets how far ahead the output mixes. An output already open
|
||||
// opens again, which drops what it held.
|
||||
func SetLatency(l Latency) {
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
if l != LatencyPlayback {
|
||||
l = LatencyInteractive
|
||||
}
|
||||
latency = l
|
||||
}
|
||||
|
||||
// outputLatency returns the latency set.
|
||||
func outputLatency() Latency {
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
return latency
|
||||
}
|
||||
|
||||
// Err returns why the last output to open is not the system's audio
|
||||
// output, as on a machine with none, or nil.
|
||||
func Err() error {
|
||||
errMu.Lock()
|
||||
defer errMu.Unlock()
|
||||
return outErr
|
||||
}
|
||||
|
||||
func setErr(err error) {
|
||||
errMu.Lock()
|
||||
defer errMu.Unlock()
|
||||
outErr = err
|
||||
}
|
||||
Vendored
+771
@@ -0,0 +1,771 @@
|
||||
package audio
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/binary"
|
||||
"errors"
|
||||
"io"
|
||||
"math"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/egoist/mygo/internal/wait"
|
||||
)
|
||||
|
||||
// setup mixes by hand, with nothing playing.
|
||||
func setup(t *testing.T) {
|
||||
t.Helper()
|
||||
mu.Lock()
|
||||
testMode = true
|
||||
for _, v := range voices {
|
||||
v.active = false
|
||||
}
|
||||
voices = nil
|
||||
volume = 1
|
||||
held, unheard = 0, 0
|
||||
mu.Unlock()
|
||||
}
|
||||
|
||||
// hold makes the output hold n frames ahead of what is heard, as a device
|
||||
// that just opened.
|
||||
func hold(n int64) {
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
held, unheard = n, 0
|
||||
}
|
||||
|
||||
// render mixes n frames.
|
||||
func render(n int) []float32 {
|
||||
out := make([]float32, n*channels)
|
||||
for i := 0; i < n; i += 256 {
|
||||
mix(out[i*channels : min(n, i+256)*channels])
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func near(a, b float32) bool { return math.Abs(float64(a-b)) < 1e-4 }
|
||||
|
||||
func ramp(n int) []float32 {
|
||||
s := make([]float32, n)
|
||||
for i := range s {
|
||||
s[i] = float32(i%100) / 200
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
func TestSoundPlaysAsDecoded(t *testing.T) {
|
||||
setup(t)
|
||||
samples := ramp(1000)
|
||||
p := NewSound(sampleRate, 1, samples).Play()
|
||||
out := render(1200)
|
||||
for i, s := range samples {
|
||||
if !near(out[2*i], s) || !near(out[2*i+1], s) {
|
||||
t.Fatalf("frame %d = %v %v, want %v", i, out[2*i], out[2*i+1], s)
|
||||
}
|
||||
}
|
||||
for i := 1000; i < 1200; i++ {
|
||||
if out[2*i] != 0 {
|
||||
t.Fatalf("frame %d after the end = %v", i, out[2*i])
|
||||
}
|
||||
}
|
||||
if p.Playing() {
|
||||
t.Error("still playing after its end")
|
||||
}
|
||||
if got := p.Position(); got != p.Duration() {
|
||||
t.Errorf("Position = %v at the end, want %v", got, p.Duration())
|
||||
}
|
||||
if len(voices) != 0 {
|
||||
t.Errorf("%d voices left", len(voices))
|
||||
}
|
||||
}
|
||||
|
||||
func TestStereoKeepsChannels(t *testing.T) {
|
||||
setup(t)
|
||||
NewSound(sampleRate, 2, []float32{0.1, 0.2, 0.3, 0.4}).Play()
|
||||
out := render(4)
|
||||
if !near(out[0], 0.1) || !near(out[1], 0.2) || !near(out[2], 0.3) || !near(out[3], 0.4) {
|
||||
t.Errorf("out = %v", out)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPlayAgainAfterEnd(t *testing.T) {
|
||||
setup(t)
|
||||
p := NewSound(sampleRate, 1, ramp(100)).Play()
|
||||
render(200)
|
||||
p.Play()
|
||||
if !p.Playing() {
|
||||
t.Fatal("Play at the end did not start again")
|
||||
}
|
||||
out := render(100)
|
||||
if !near(out[2*50], 0.25) {
|
||||
t.Errorf("frame 50 = %v, want 0.25", out[2*50])
|
||||
}
|
||||
}
|
||||
|
||||
func TestOnEnd(t *testing.T) {
|
||||
setup(t)
|
||||
p := NewSound(sampleRate, 1, ramp(100)).NewPlayer()
|
||||
ended := make(chan struct{}, 4)
|
||||
off := p.OnEnd(func() { ended <- struct{}{} })
|
||||
p.Play()
|
||||
render(200)
|
||||
wait.For(t, "the end", ended)
|
||||
render(200) // ended once
|
||||
p.Play()
|
||||
render(50)
|
||||
p.Pause()
|
||||
render(200) // paused, not at the end
|
||||
p.Seek(0)
|
||||
off()
|
||||
p.Play()
|
||||
render(200)
|
||||
if n := len(ended); n != 0 {
|
||||
t.Errorf("%d more ends, want 0", n)
|
||||
}
|
||||
|
||||
loop := NewSound(sampleRate, 1, ramp(100)).NewPlayer().SetLoop(true)
|
||||
loop.OnEnd(func() { ended <- struct{}{} })
|
||||
loop.Play()
|
||||
render(350)
|
||||
loop.Stop()
|
||||
render(200)
|
||||
if n := len(ended); n != 0 {
|
||||
t.Errorf("a loop or a stopped player ended %d times", n)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSoundsOverlap(t *testing.T) {
|
||||
setup(t)
|
||||
s := NewSound(sampleRate, 1, []float32{0.25, 0.25, 0.25, 0.25})
|
||||
s.Play()
|
||||
s.Play()
|
||||
out := render(2)
|
||||
if !near(out[0], 0.5) {
|
||||
t.Errorf("two players mix to %v, want 0.5", out[0])
|
||||
}
|
||||
}
|
||||
|
||||
func TestClipping(t *testing.T) {
|
||||
setup(t)
|
||||
s := NewSound(sampleRate, 1, []float32{0.8, 0.8})
|
||||
s.Play()
|
||||
s.Play()
|
||||
if out := render(1); out[0] != 1 {
|
||||
t.Errorf("out = %v, want clipped to 1", out[0])
|
||||
}
|
||||
}
|
||||
|
||||
func TestLoop(t *testing.T) {
|
||||
setup(t)
|
||||
samples := ramp(100)
|
||||
p := NewSound(sampleRate, 1, samples).NewPlayer().SetLoop(true)
|
||||
p.Play()
|
||||
out := render(350)
|
||||
for i := range 350 {
|
||||
if want := samples[i%100]; !near(out[2*i], want) {
|
||||
t.Fatalf("frame %d = %v, want %v", i, out[2*i], want)
|
||||
}
|
||||
}
|
||||
if !p.Playing() {
|
||||
t.Error("a loop stopped")
|
||||
}
|
||||
if got, want := p.Position(), frames(50, sampleRate); got != want {
|
||||
t.Errorf("Position = %v, want %v", got, want)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPauseFadesOutAndResumes(t *testing.T) {
|
||||
setup(t)
|
||||
samples := make([]float32, 10000)
|
||||
for i := range samples {
|
||||
samples[i] = 0.5
|
||||
}
|
||||
p := NewSound(sampleRate, 1, samples).Play()
|
||||
render(1000)
|
||||
p.Pause()
|
||||
if p.Playing() {
|
||||
t.Error("Playing after Pause")
|
||||
}
|
||||
out := render(rampFrames + 10)
|
||||
if !(out[0] > 0.45 && out[2*(rampFrames/2)] < 0.3 && out[2*(rampFrames/2)] > 0.2) {
|
||||
t.Errorf("fade out = %v, %v", out[0], out[2*(rampFrames/2)])
|
||||
}
|
||||
if out[2*(rampFrames+5)] != 0 || len(voices) != 0 {
|
||||
t.Errorf("after the fade: %v, %d voices", out[2*(rampFrames+5)], len(voices))
|
||||
}
|
||||
at := p.Position()
|
||||
render(500)
|
||||
if p.Position() != at {
|
||||
t.Error("a paused player moved")
|
||||
}
|
||||
p.Play()
|
||||
out = render(rampFrames + 10)
|
||||
if !(out[0] < 0.05 && near(out[2*(rampFrames+5)], 0.5)) {
|
||||
t.Errorf("fade in = %v … %v", out[0], out[2*(rampFrames+5)])
|
||||
}
|
||||
}
|
||||
|
||||
func TestVolumeRamps(t *testing.T) {
|
||||
setup(t)
|
||||
samples := make([]float32, 10000)
|
||||
for i := range samples {
|
||||
samples[i] = 0.5
|
||||
}
|
||||
p := NewSound(sampleRate, 1, samples).Play()
|
||||
render(10)
|
||||
p.SetVolume(0.5)
|
||||
out := render(rampFrames * 2)
|
||||
if !(out[0] > 0.45 && near(out[2*(rampFrames+10)], 0.25)) {
|
||||
t.Errorf("volume ramp = %v … %v", out[0], out[2*(rampFrames+10)])
|
||||
}
|
||||
SetVolume(0)
|
||||
out = render(rampFrames * 2)
|
||||
if out[2*(rampFrames+10)] != 0 {
|
||||
t.Errorf("master volume 0 = %v", out[2*(rampFrames+10)])
|
||||
}
|
||||
}
|
||||
|
||||
func TestPan(t *testing.T) {
|
||||
setup(t)
|
||||
mono := NewSound(sampleRate, 1, []float32{0.5, 0.5, 0.5})
|
||||
mono.NewPlayer().SetPan(-1).Play()
|
||||
out := render(2)
|
||||
if !near(out[0], 0.5*math.Sqrt2) || !near(out[1], 0) {
|
||||
t.Errorf("mono panned left = %v %v", out[0], out[1])
|
||||
}
|
||||
setup(t)
|
||||
stereo := NewSound(sampleRate, 2, []float32{0.2, 0.4, 0.2, 0.4})
|
||||
stereo.NewPlayer().SetPan(1).Play()
|
||||
out = render(1)
|
||||
if !near(out[0], 0) || !near(out[1], 0.6) {
|
||||
t.Errorf("stereo panned right = %v %v", out[0], out[1])
|
||||
}
|
||||
}
|
||||
|
||||
func TestSpeed(t *testing.T) {
|
||||
setup(t)
|
||||
p := NewSound(sampleRate, 1, ramp(1000)).NewPlayer().SetSpeed(2)
|
||||
p.Play()
|
||||
out := render(100)
|
||||
if !near(out[2*10], ramp(1000)[20]) {
|
||||
t.Errorf("frame 10 at speed 2 = %v, want %v", out[2*10], ramp(1000)[20])
|
||||
}
|
||||
if got, want := p.Position(), frames(200, sampleRate); got != want {
|
||||
t.Errorf("Position = %v, want %v", got, want)
|
||||
}
|
||||
}
|
||||
|
||||
func TestResamples(t *testing.T) {
|
||||
setup(t)
|
||||
// A 1 kHz sine at 24 kHz plays at 1 kHz.
|
||||
const rate = 24000
|
||||
samples := make([]float32, rate/10)
|
||||
for i := range samples {
|
||||
samples[i] = float32(math.Sin(2 * math.Pi * 1000 * float64(i) / rate))
|
||||
}
|
||||
p := NewSound(rate, 1, samples).Play()
|
||||
out := render(sampleRate / 20)
|
||||
for i := 100; i < sampleRate/20; i++ {
|
||||
want := math.Sin(2 * math.Pi * 1000 * float64(i) / sampleRate)
|
||||
if math.Abs(float64(out[2*i])-want) > 0.01 {
|
||||
t.Fatalf("frame %d = %v, want %v", i, out[2*i], want)
|
||||
}
|
||||
}
|
||||
if got, want := p.Position(), 50*time.Millisecond; got != want {
|
||||
t.Errorf("Position = %v, want %v", got, want)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSeek(t *testing.T) {
|
||||
setup(t)
|
||||
samples := ramp(48000)
|
||||
p := NewSound(sampleRate, 1, samples).NewPlayer()
|
||||
p.Seek(500 * time.Millisecond)
|
||||
if got := p.Position(); got != 500*time.Millisecond {
|
||||
t.Errorf("Position = %v after Seek", got)
|
||||
}
|
||||
p.Play()
|
||||
out := render(rampFrames + 20)
|
||||
if i := rampFrames + 10; !near(out[2*i], samples[24000+i]) {
|
||||
t.Errorf("frame %d after seeking = %v, want %v", i, out[2*i], samples[24000+i])
|
||||
}
|
||||
p.Stop()
|
||||
if p.Playing() || p.Position() != 0 {
|
||||
t.Errorf("after Stop: playing %v at %v", p.Playing(), p.Position())
|
||||
}
|
||||
}
|
||||
|
||||
func TestClose(t *testing.T) {
|
||||
setup(t)
|
||||
p := NewSound(sampleRate, 1, ramp(1000)).Play()
|
||||
p.Close()
|
||||
p.Play()
|
||||
if p.Playing() {
|
||||
t.Error("a closed player plays")
|
||||
}
|
||||
render(10)
|
||||
if len(voices) != 0 {
|
||||
t.Errorf("%d voices after Close", len(voices))
|
||||
}
|
||||
}
|
||||
|
||||
// genDecoder generates frames i/1000 of a channel each, with a length.
|
||||
type genDecoder struct {
|
||||
ch int
|
||||
pos int64
|
||||
length int64
|
||||
closed atomic.Bool
|
||||
}
|
||||
|
||||
func (d *genDecoder) SampleRate() int { return sampleRate }
|
||||
func (d *genDecoder) Channels() int { return d.ch }
|
||||
func (d *genDecoder) Len() int64 { return d.length }
|
||||
func (d *genDecoder) Close() error { d.closed.Store(true); return nil }
|
||||
|
||||
func (d *genDecoder) Read(buf []float32) (int, error) {
|
||||
n := 0
|
||||
for ; n+d.ch <= len(buf) && d.pos < d.length; n += d.ch {
|
||||
for c := range d.ch {
|
||||
buf[n+c] = float32(d.pos%1000)/1000 + float32(c)
|
||||
}
|
||||
d.pos++
|
||||
}
|
||||
if n == 0 {
|
||||
return 0, io.EOF
|
||||
}
|
||||
return n, nil
|
||||
}
|
||||
|
||||
func (d *genDecoder) SetPosition(f int64) error {
|
||||
if f > d.length {
|
||||
return errors.New("out of range")
|
||||
}
|
||||
d.pos = f
|
||||
return nil
|
||||
}
|
||||
|
||||
func waitDecoded(t *testing.T, p *Player) {
|
||||
t.Helper()
|
||||
s := p.v.src.(*stream)
|
||||
for range 1000 {
|
||||
s.mu.Lock()
|
||||
n := s.n
|
||||
s.mu.Unlock()
|
||||
if n > 0 {
|
||||
return
|
||||
}
|
||||
time.Sleep(time.Millisecond)
|
||||
}
|
||||
t.Fatal("the stream decoded nothing")
|
||||
}
|
||||
|
||||
func TestStream(t *testing.T) {
|
||||
setup(t)
|
||||
d := &genDecoder{ch: 3, length: 5000}
|
||||
p := NewPlayer(d)
|
||||
if p.Duration() != frames(5000, sampleRate) {
|
||||
t.Errorf("Duration = %v", p.Duration())
|
||||
}
|
||||
waitDecoded(t, p)
|
||||
p.Play()
|
||||
out := render(1000)
|
||||
for i := range 1000 {
|
||||
if l, r := out[2*i], out[2*i+1]; !near(l, float32(i)/1000) || !near(r, float32(i)/1000+1) && r != 1 {
|
||||
t.Fatalf("frame %d = %v %v", i, l, r)
|
||||
}
|
||||
}
|
||||
p.Close()
|
||||
for range 1000 {
|
||||
if d.closed.Load() {
|
||||
return
|
||||
}
|
||||
time.Sleep(time.Millisecond)
|
||||
}
|
||||
t.Error("Close did not close the decoder")
|
||||
}
|
||||
|
||||
func TestStreamLoopsWithoutGap(t *testing.T) {
|
||||
setup(t)
|
||||
d := &genDecoder{ch: 1, length: 300}
|
||||
p := NewPlayer(d).SetLoop(true)
|
||||
waitDecoded(t, p)
|
||||
p.Play()
|
||||
out := make([]float32, 0, 2000*channels)
|
||||
for len(out) < 2000*channels {
|
||||
chunk := make([]float32, 64*channels)
|
||||
// The decoder keeps a second ahead: wait for it, as the device
|
||||
// would not.
|
||||
for {
|
||||
s := p.v.src.(*stream)
|
||||
s.mu.Lock()
|
||||
n := s.n
|
||||
s.mu.Unlock()
|
||||
if n >= 64 {
|
||||
break
|
||||
}
|
||||
time.Sleep(time.Millisecond)
|
||||
}
|
||||
mix(chunk)
|
||||
out = append(out, chunk...)
|
||||
}
|
||||
for i := range 2000 {
|
||||
if want := float32(i%300) / 1000; !near(out[2*i], want) {
|
||||
t.Fatalf("frame %d = %v, want %v", i, out[2*i], want)
|
||||
}
|
||||
}
|
||||
p.Close()
|
||||
}
|
||||
|
||||
func TestStreamSeek(t *testing.T) {
|
||||
setup(t)
|
||||
d := &genDecoder{ch: 1, length: 48000}
|
||||
p := NewPlayer(d)
|
||||
p.Seek(frames(700, sampleRate))
|
||||
waitDecoded(t, p)
|
||||
p.Play()
|
||||
out := render(rampFrames + 20)
|
||||
if i := rampFrames + 10; !near(out[2*i], float32((700+i)%1000)/1000) {
|
||||
t.Errorf("frame %d = %v, want %v", i, out[2*i], float32((700+i)%1000)/1000)
|
||||
}
|
||||
p.Close()
|
||||
}
|
||||
|
||||
func TestOrphanedStreamPlaysToItsEnd(t *testing.T) {
|
||||
setup(t)
|
||||
d := &genDecoder{ch: 1, length: 500}
|
||||
v := NewPlayer(d).v
|
||||
for range 1000 {
|
||||
s := v.src.(*stream)
|
||||
s.mu.Lock()
|
||||
n := s.n
|
||||
s.mu.Unlock()
|
||||
if n > 0 {
|
||||
break
|
||||
}
|
||||
time.Sleep(time.Millisecond)
|
||||
}
|
||||
mu.Lock()
|
||||
v.playing, v.active, v.snap = true, true, true
|
||||
voices = append(voices, v)
|
||||
v.orphan = true
|
||||
mu.Unlock()
|
||||
render(600)
|
||||
if !v.closed {
|
||||
t.Error("an orphaned stream was not closed at its end")
|
||||
}
|
||||
}
|
||||
|
||||
func wav(tag, bits, ch int, data []byte) []byte {
|
||||
var b bytes.Buffer
|
||||
w := func(v any) { binary.Write(&b, binary.LittleEndian, v) }
|
||||
b.WriteString("RIFF")
|
||||
w(uint32(36 + len(data) + 10))
|
||||
b.WriteString("WAVE")
|
||||
b.WriteString("LIST")
|
||||
w(uint32(1)) // odd, padded
|
||||
b.Write([]byte{0, 0})
|
||||
b.WriteString("fmt ")
|
||||
w(uint32(16))
|
||||
w(uint16(tag))
|
||||
w(uint16(ch))
|
||||
w(uint32(22050))
|
||||
w(uint32(22050 * ch * bits / 8))
|
||||
w(uint16(ch * bits / 8))
|
||||
w(uint16(bits))
|
||||
b.WriteString("data")
|
||||
w(uint32(len(data)))
|
||||
b.Write(data)
|
||||
return b.Bytes()
|
||||
}
|
||||
|
||||
func TestWAV(t *testing.T) {
|
||||
le := binary.LittleEndian
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
tag, bits int
|
||||
data []byte
|
||||
}{
|
||||
{"u8", 1, 8, []byte{128, 192, 64, 0}},
|
||||
{"s16", 1, 16, le.AppendUint16(le.AppendUint16(le.AppendUint16(le.AppendUint16(nil, 0), 0x4000), 0xc000), 0x8000)},
|
||||
{"s24", 1, 24, []byte{0, 0, 0, 0, 0, 0x40, 0, 0, 0xc0, 0, 0, 0x80}},
|
||||
{"s32", 1, 32, le.AppendUint32(le.AppendUint32(le.AppendUint32(le.AppendUint32(nil, 0), 0x40000000), 0xc0000000), 0x80000000)},
|
||||
{"f32", 3, 32, le.AppendUint32(le.AppendUint32(le.AppendUint32(le.AppendUint32(nil, 0), math.Float32bits(0.5)), math.Float32bits(-0.5)), math.Float32bits(-1))},
|
||||
{"f64", 3, 64, le.AppendUint64(le.AppendUint64(le.AppendUint64(le.AppendUint64(nil, 0), math.Float64bits(0.5)), math.Float64bits(-0.5)), math.Float64bits(-1))},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
s, err := DecodeSound(wav(tc.tag, tc.bits, 2, tc.data))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
want := []float32{0, 0.5, -0.5, -1}
|
||||
if s.rate != 22050 || s.channels != 2 || len(s.samples) != 4 {
|
||||
t.Fatalf("decoded %d Hz, %d channels, %d samples", s.rate, s.channels, len(s.samples))
|
||||
}
|
||||
for i := range want {
|
||||
if s.samples[i] != want[i] {
|
||||
t.Errorf("sample %d = %v, want %v", i, s.samples[i], want[i])
|
||||
}
|
||||
}
|
||||
if s.Duration() != frames(2, 22050) {
|
||||
t.Errorf("Duration = %v", s.Duration())
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// A header can say any length: ReadSound reserves no more than a start
|
||||
// for it, and keeps what the decoder had.
|
||||
func TestSoundOfAWrongLength(t *testing.T) {
|
||||
t.Run("a WAV cut short", func(t *testing.T) {
|
||||
b := wav(1, 8, 1, []byte{128, 192, 64, 0})
|
||||
binary.LittleEndian.PutUint32(b[len(b)-8:], 0xfffffffe) // the data chunk's size
|
||||
s, err := DecodeSound(b)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(s.samples) != 4 {
|
||||
t.Errorf("decoded %d samples, want 4", len(s.samples))
|
||||
}
|
||||
if cap(s.samples) > reserveFrames {
|
||||
t.Errorf("reserved %d samples for 4", cap(s.samples))
|
||||
}
|
||||
})
|
||||
t.Run("a decoder of any length", func(t *testing.T) {
|
||||
s, err := ReadSound(wrongLength{&genDecoder{ch: 2, length: 8}})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(s.samples) != 16 {
|
||||
t.Errorf("decoded %d samples, want 16", len(s.samples))
|
||||
}
|
||||
if cap(s.samples) > 2*reserveFrames {
|
||||
t.Errorf("reserved %d samples for 16", cap(s.samples))
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// wrongLength says its decoder is longer than any sound.
|
||||
type wrongLength struct{ *genDecoder }
|
||||
|
||||
func (wrongLength) Len() int64 { return math.MaxInt64 }
|
||||
|
||||
func TestWAVSeek(t *testing.T) {
|
||||
data := make([]byte, 0, 200)
|
||||
for i := range 100 {
|
||||
data = binary.LittleEndian.AppendUint16(data, uint16(i*100))
|
||||
}
|
||||
d, name, err := NewDecoder(bytes.NewReader(wav(1, 16, 1, data)))
|
||||
if err != nil || name != "wav" {
|
||||
t.Fatal(name, err)
|
||||
}
|
||||
if d.Len() != 100 {
|
||||
t.Errorf("Len = %d", d.Len())
|
||||
}
|
||||
if err := d.SetPosition(40); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
buf := make([]float32, 4)
|
||||
if n, err := d.Read(buf); n != 4 || err != nil || buf[0] != float32(4000)/(1<<15) {
|
||||
t.Errorf("after SetPosition(40): %d %v %v", n, err, buf)
|
||||
}
|
||||
}
|
||||
|
||||
func TestUnknownFormat(t *testing.T) {
|
||||
if _, err := DecodeSound([]byte("not audio at all")); err != ErrFormat {
|
||||
t.Errorf("err = %v, want ErrFormat", err)
|
||||
}
|
||||
}
|
||||
|
||||
// The output plays on time where no device opens, and says why.
|
||||
func TestNullOutput(t *testing.T) {
|
||||
setup(t)
|
||||
mu.Lock()
|
||||
testMode = false
|
||||
mu.Unlock()
|
||||
defer func() {
|
||||
mu.Lock()
|
||||
testMode = true
|
||||
mu.Unlock()
|
||||
}()
|
||||
failure := errors.New("no device here")
|
||||
openOutput = func(time.Duration) (device, int, error) { return nil, 0, failure }
|
||||
defer func() { openOutput = openDevice }()
|
||||
p := NewSound(sampleRate, 1, make([]float32, sampleRate/10)).Play()
|
||||
// How long it takes is TestNullDeviceKeepsTime's: a minute only
|
||||
// guards against a hang.
|
||||
for start := time.Now(); p.Playing(); time.Sleep(5 * time.Millisecond) {
|
||||
if time.Since(start) > time.Minute {
|
||||
t.Fatal("100 ms still playing after a minute")
|
||||
}
|
||||
}
|
||||
if Err() != failure {
|
||||
t.Errorf("Err = %v", Err())
|
||||
}
|
||||
}
|
||||
|
||||
// Setting the latency opens the output again, to hold as far ahead as it
|
||||
// says.
|
||||
func TestSetLatencyReopens(t *testing.T) {
|
||||
setup(t)
|
||||
opened := make(chan time.Duration, 8)
|
||||
openOutput = func(ahead time.Duration) (device, int, error) {
|
||||
opened <- ahead
|
||||
return pacedDevice{}, nullFrames, nil
|
||||
}
|
||||
defer func() { openOutput = openDevice }()
|
||||
mu.Lock()
|
||||
testMode = false
|
||||
mu.Unlock()
|
||||
defer func() {
|
||||
mu.Lock()
|
||||
testMode = true
|
||||
latency = LatencyInteractive
|
||||
mu.Unlock()
|
||||
}()
|
||||
p := NewSound(sampleRate, 1, make([]float32, sampleRate)).NewPlayer().SetLoop(true)
|
||||
p.Play()
|
||||
defer p.Close()
|
||||
if got := wait.For(t, "the output to open", opened); got != 40*time.Millisecond {
|
||||
t.Errorf("opened %v ahead, want 40ms", got)
|
||||
}
|
||||
SetLatency(LatencyPlayback)
|
||||
if got := wait.For(t, "the output to open again", opened); got != 250*time.Millisecond {
|
||||
t.Errorf("opened again %v ahead, want 250ms", got)
|
||||
}
|
||||
}
|
||||
|
||||
// A pacedDevice takes what it is given a little at a time.
|
||||
type pacedDevice struct{}
|
||||
|
||||
func (pacedDevice) write([]float32) error { time.Sleep(time.Millisecond); return nil }
|
||||
func (pacedDevice) close() {}
|
||||
|
||||
// A null device takes as long as what it plays would, on a clock of its
|
||||
// own here, does not hurry to catch up once behind, and fails after a
|
||||
// while for the device to be tried again.
|
||||
func TestNullDeviceKeepsTime(t *testing.T) {
|
||||
start := time.Date(2026, 10, 16, 12, 0, 0, 0, time.UTC)
|
||||
clock := start
|
||||
d := newNullDevice(true)
|
||||
d.next, d.retry = start, start.Add(2*time.Second)
|
||||
d.now = func() time.Time { return clock }
|
||||
d.sleep = func(dt time.Duration) { clock = clock.Add(max(dt, 0)) }
|
||||
chunk := make([]float32, nullFrames*channels) // 10 ms
|
||||
for range 10 {
|
||||
if err := d.write(chunk); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
if got := clock.Sub(start); got != 100*time.Millisecond {
|
||||
t.Errorf("100 ms played in %v", got)
|
||||
}
|
||||
// Late by a second, as after the computer slept: the next chunk takes
|
||||
// its 10 ms from now.
|
||||
clock = clock.Add(time.Second)
|
||||
late := clock
|
||||
if err := d.write(chunk); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got := clock.Sub(late); got != 10*time.Millisecond {
|
||||
t.Errorf("10 ms played late in %v", got)
|
||||
}
|
||||
clock = start.Add(2*time.Second + time.Millisecond)
|
||||
if err := d.write(chunk); err != errRetry {
|
||||
t.Errorf("after 2 s: %v, want errRetry", err)
|
||||
}
|
||||
}
|
||||
|
||||
// A stream's decoder sleeps while the ring is mostly full, rather than
|
||||
// waking on every mix to find nothing to do.
|
||||
func TestStreamWakesItsDecoderRarely(t *testing.T) {
|
||||
setup(t)
|
||||
const total = 10 * sampleRate // 10 s
|
||||
d := &heldDecoder{
|
||||
genDecoder: genDecoder{ch: 2, length: total},
|
||||
held: make(chan struct{}),
|
||||
release: make(chan struct{}),
|
||||
}
|
||||
p := NewPlayer(d)
|
||||
defer p.Close()
|
||||
s := p.v.src.(*stream)
|
||||
// Count from its first read, while it can't be in the cond's Wait.
|
||||
wait.For(t, "the first read", d.held)
|
||||
s.mu.Lock()
|
||||
wakes := &wakeCounter{Locker: s.cond.L}
|
||||
s.cond.L = wakes
|
||||
s.mu.Unlock()
|
||||
close(d.release)
|
||||
decoded := func(n int) bool {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
return s.n >= n*s.keep || s.atEOF
|
||||
}
|
||||
wait.Until(t, "the ring to fill", func() bool {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
return len(s.ring)-s.n < decodeFrames*s.keep
|
||||
})
|
||||
p.Play()
|
||||
const chunk = 512 // as macOS mixes
|
||||
out := make([]float32, chunk*channels)
|
||||
for range total / chunk {
|
||||
// As fast as the decoder goes, never faster.
|
||||
wait.Until(t, "the stream to decode", func() bool { return decoded(chunk) })
|
||||
mix(out)
|
||||
}
|
||||
s.mu.Lock()
|
||||
n := wakes.n
|
||||
s.mu.Unlock()
|
||||
// Every wake but the last follows a quarter of the ring read, less
|
||||
// the chunk the decoder may have left free.
|
||||
if limit := total/(len(s.ring)/4/s.keep-decodeFrames) + 1; n > limit {
|
||||
t.Errorf("the decoder woke %d times in 10 s, want at most %d", n, limit)
|
||||
}
|
||||
}
|
||||
|
||||
// A heldDecoder holds its first Read until released.
|
||||
type heldDecoder struct {
|
||||
genDecoder
|
||||
held, release chan struct{}
|
||||
once sync.Once
|
||||
}
|
||||
|
||||
func (d *heldDecoder) Read(buf []float32) (int, error) {
|
||||
d.once.Do(func() { close(d.held); <-d.release })
|
||||
return d.genDecoder.Read(buf)
|
||||
}
|
||||
|
||||
// A wakeCounter counts the wakes of a cond whose L it is, as Wait locks
|
||||
// L again on each.
|
||||
type wakeCounter struct {
|
||||
sync.Locker
|
||||
n int
|
||||
}
|
||||
|
||||
func (l *wakeCounter) Lock() { l.Locker.Lock(); l.n++ }
|
||||
|
||||
// Mixing allocates nothing once playing, sounds and streams alike.
|
||||
func TestMixDoesNotAllocate(t *testing.T) {
|
||||
setup(t)
|
||||
p := NewPlayer(&genDecoder{ch: 2, length: 1 << 40})
|
||||
defer p.Close()
|
||||
s := p.v.src.(*stream)
|
||||
wait.Until(t, "the stream to decode", func() bool {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
return s.n > 0
|
||||
})
|
||||
p.Play()
|
||||
// 1.1 s, which ends within the 2.1 s mixed: ending allocates nothing
|
||||
// either.
|
||||
snd := NewSound(22050, 1, ramp(sampleRate/2)).Play()
|
||||
out := make([]float32, 512*channels)
|
||||
if n := testing.AllocsPerRun(200, func() { mix(out) }); n != 0 {
|
||||
t.Errorf("mix allocated %v times a call", n)
|
||||
}
|
||||
if snd.Playing() {
|
||||
t.Error("the sound still plays")
|
||||
}
|
||||
}
|
||||
Vendored
+30
@@ -0,0 +1,30 @@
|
||||
//go:build darwin || (linux && (amd64 || arm64))
|
||||
|
||||
package audio
|
||||
|
||||
import "github.com/ebitengine/purego"
|
||||
|
||||
// A cCaller calls C without allocating, for what a device calls on every
|
||||
// write: functions RegisterLibFunc made allocate, and SyscallN's own
|
||||
// arguments escape. Pointers among args must be to C memory, or to the
|
||||
// heap and kept alive by the caller.
|
||||
type cCaller struct{ args [6]uintptr }
|
||||
|
||||
// cFunc looks up C function name in lib, for a cCaller. As
|
||||
// RegisterLibFunc does, it panics when lib lacks it.
|
||||
func cFunc(lib uintptr, name string) uintptr {
|
||||
fn, err := purego.Dlsym(lib, name)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return fn
|
||||
}
|
||||
|
||||
func (c *cCaller) call(fn uintptr, args ...uintptr) uintptr {
|
||||
if len(args) > len(c.args) {
|
||||
panic("audio: too many arguments to cCaller.call")
|
||||
}
|
||||
n := copy(c.args[:], args)
|
||||
r, _, _ := purego.SyscallN(fn, c.args[:n]...)
|
||||
return r
|
||||
}
|
||||
Vendored
+33
@@ -0,0 +1,33 @@
|
||||
//go:build darwin || (linux && (amd64 || arm64))
|
||||
|
||||
package audio
|
||||
|
||||
import (
|
||||
"runtime"
|
||||
"testing"
|
||||
|
||||
"github.com/ebitengine/purego"
|
||||
)
|
||||
|
||||
func TestCCallDoesNotAllocate(t *testing.T) {
|
||||
name := "libc.so.6"
|
||||
if runtime.GOOS == "darwin" {
|
||||
name = "/usr/lib/libSystem.B.dylib"
|
||||
}
|
||||
lib, err := purego.Dlopen(name, purego.RTLD_NOW|purego.RTLD_GLOBAL)
|
||||
if err != nil {
|
||||
t.Skip(err)
|
||||
}
|
||||
labs, err := purego.Dlsym(lib, "labs")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var c cCaller
|
||||
minus5 := -5
|
||||
if got := int(c.call(labs, uintptr(minus5))); got != 5 {
|
||||
t.Fatalf("labs(-5) = %d", got)
|
||||
}
|
||||
if n := testing.AllocsPerRun(100, func() { c.call(labs, 7) }); n != 0 {
|
||||
t.Errorf("a call allocated %v times", n)
|
||||
}
|
||||
}
|
||||
Vendored
+300
@@ -0,0 +1,300 @@
|
||||
// Package flac decodes FLAC for package audio, with
|
||||
// github.com/mewkiz/flac: .flac files, and FLAC in MP4 through package
|
||||
// audio/mp4, as lossless DASH streams carry it. Import it for its side
|
||||
// effect:
|
||||
//
|
||||
// import _ "github.com/egoist/mygo/audio/flac"
|
||||
//
|
||||
// FLAC's frames stand alone, so a seek lands on the very frame of sound
|
||||
// asked for, without a seek table.
|
||||
package flac
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"bytes"
|
||||
"errors"
|
||||
"io"
|
||||
"math"
|
||||
|
||||
"github.com/egoist/mygo/audio"
|
||||
"github.com/egoist/mygo/audio/mp4"
|
||||
"github.com/mewkiz/flac"
|
||||
"github.com/mewkiz/flac/frame"
|
||||
"github.com/mewkiz/flac/meta"
|
||||
)
|
||||
|
||||
func init() {
|
||||
open := func(r io.ReadSeeker) (audio.Decoder, error) { return NewDecoder(r) }
|
||||
// After an ID3 tag too, which package audio looks past.
|
||||
audio.RegisterFormat("flac", "fLaC", open)
|
||||
mp4.RegisterCodec("fLaC", func(config []byte) (mp4.Codec, error) { return NewCodec(config) })
|
||||
}
|
||||
|
||||
// decoder decodes a FLAC file. A seek finds the frame of FLAC holding the
|
||||
// frame of sound asked for by its header, near where the bytes say it is,
|
||||
// and decodes from there.
|
||||
type decoder struct {
|
||||
r io.ReadSeeker
|
||||
info *meta.StreamInfo
|
||||
start int64 // the first frame's byte, after the metadata
|
||||
size int64
|
||||
br *bufio.Reader
|
||||
skip int64 // frames to drop, after a seek
|
||||
pend []float32 // decoded, and not yet read: stereo
|
||||
}
|
||||
|
||||
// NewDecoder returns a decoder of the FLAC file r holds, after an ID3 tag
|
||||
// if one is first. It decodes to stereo: a mono file in both, and the
|
||||
// front left and right of more channels.
|
||||
func NewDecoder(r io.ReadSeeker) (audio.Decoder, error) {
|
||||
size, err := r.Seek(0, io.SeekEnd)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
from, err := skipID3(r)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
start, err := dataStart(r, from)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
head := make([]byte, start-from)
|
||||
if _, err := r.Seek(from, io.SeekStart); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if _, err := io.ReadFull(r, head); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
st, err := flac.New(bytes.NewReader(head))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if st.Info == nil || st.Info.NChannels == 0 || st.Info.SampleRate == 0 {
|
||||
return nil, errors.New("flac: no stream info")
|
||||
}
|
||||
d := &decoder{r: r, info: st.Info, start: start, size: size}
|
||||
if err := d.at(start); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return d, nil
|
||||
}
|
||||
|
||||
// skipID3 returns where r's FLAC starts: after an ID3 tag, if r starts
|
||||
// with one.
|
||||
func skipID3(r io.ReadSeeker) (int64, error) {
|
||||
var b [10]byte
|
||||
if _, err := r.Seek(0, io.SeekStart); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
if _, err := io.ReadFull(r, b[:]); err != nil || string(b[:3]) != "ID3" {
|
||||
return 0, nil
|
||||
}
|
||||
return 10 + int64(b[6]&0x7f)<<21 | int64(b[7]&0x7f)<<14 | int64(b[8]&0x7f)<<7 | int64(b[9]&0x7f), nil
|
||||
}
|
||||
|
||||
// dataStart returns where the first frame starts, after the "fLaC" at off
|
||||
// and the metadata blocks.
|
||||
func dataStart(r io.ReadSeeker, off int64) (int64, error) {
|
||||
var h [4]byte
|
||||
if _, err := r.Seek(off, io.SeekStart); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
if _, err := io.ReadFull(r, h[:]); err != nil || string(h[:]) != "fLaC" {
|
||||
return 0, errors.New("flac: not a FLAC file")
|
||||
}
|
||||
off += 4
|
||||
for {
|
||||
if _, err := r.Seek(off, io.SeekStart); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
if _, err := io.ReadFull(r, h[:]); err != nil {
|
||||
return 0, io.ErrUnexpectedEOF
|
||||
}
|
||||
off += 4 + (int64(h[1])<<16 | int64(h[2])<<8 | int64(h[3]))
|
||||
if h[0]&0x80 != 0 { // the last
|
||||
return off, nil
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// at reads on from off.
|
||||
func (d *decoder) at(off int64) error {
|
||||
if _, err := d.r.Seek(off, io.SeekStart); err != nil {
|
||||
return err
|
||||
}
|
||||
if d.br == nil {
|
||||
d.br = bufio.NewReaderSize(d.r, 64<<10)
|
||||
} else {
|
||||
d.br.Reset(d.r)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (d *decoder) SampleRate() int { return int(d.info.SampleRate) }
|
||||
func (d *decoder) Channels() int { return 2 }
|
||||
|
||||
func (d *decoder) Len() int64 {
|
||||
if d.info.NSamples == 0 {
|
||||
return -1
|
||||
}
|
||||
return int64(d.info.NSamples)
|
||||
}
|
||||
|
||||
// parse parses the frame r is at: its header, then its samples, taking
|
||||
// what the header leaves to the stream info from there. The decoder may
|
||||
// panic on bytes that only look like a frame.
|
||||
func parse(r io.Reader, info *meta.StreamInfo) (f *frame.Frame, err error) {
|
||||
defer func() {
|
||||
if recover() != nil {
|
||||
f, err = nil, errors.New("flac: bad frame")
|
||||
}
|
||||
}()
|
||||
f, err = frame.New(r)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if f.BitsPerSample == 0 {
|
||||
f.BitsPerSample = info.BitsPerSample
|
||||
}
|
||||
if f.SampleRate == 0 {
|
||||
f.SampleRate = info.SampleRate
|
||||
}
|
||||
if err := f.Parse(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return f, nil
|
||||
}
|
||||
|
||||
func (d *decoder) Read(dst []float32) (int, error) {
|
||||
for len(d.pend) == 0 {
|
||||
f, err := parse(d.br, d.info)
|
||||
if err != nil {
|
||||
if err == io.ErrUnexpectedEOF {
|
||||
err = io.EOF
|
||||
}
|
||||
return 0, err
|
||||
}
|
||||
drop := min(d.skip, int64(f.BlockSize))
|
||||
d.skip -= drop
|
||||
d.pend = stereo(d.pend[:0], f, int(drop))
|
||||
}
|
||||
n := copy(dst[:len(dst)/2*2], d.pend)
|
||||
d.pend = d.pend[n:]
|
||||
return n, nil
|
||||
}
|
||||
|
||||
// stereo appends a frame's samples from the one at from to dst, as stereo.
|
||||
func stereo(dst []float32, f *frame.Frame, from int) []float32 {
|
||||
left, right := f.Subframes[0].Samples, f.Subframes[0].Samples
|
||||
if len(f.Subframes) > 1 {
|
||||
right = f.Subframes[1].Samples
|
||||
}
|
||||
scale := float32(1 / math.Exp2(float64(f.BitsPerSample-1)))
|
||||
for i := from; i < int(f.BlockSize); i++ {
|
||||
dst = append(dst, float32(left[i])*scale, float32(right[i])*scale)
|
||||
}
|
||||
return dst
|
||||
}
|
||||
|
||||
// SetPosition goes to target: to the frame of FLAC holding it, then drops
|
||||
// what comes before it there. It finds that frame by the secant method,
|
||||
// guessing where in the bytes it is from the frames found on either side,
|
||||
// until one is found less than a second before it.
|
||||
func (d *decoder) SetPosition(target int64) error {
|
||||
target = max(target, 0)
|
||||
total := int64(d.info.NSamples)
|
||||
if total > 0 {
|
||||
target = min(target, total)
|
||||
}
|
||||
loOff, lo := d.start, int64(0)
|
||||
hiOff, hi := d.size, total
|
||||
for tries := 0; tries < 8 && target-lo > int64(d.info.SampleRate) && hi > lo; tries++ {
|
||||
guess := loOff + int64(float64(hiOff-loOff)*float64(target-lo)/float64(hi-lo))
|
||||
off, at, ok := d.frameAfter(max(guess, loOff+1), hiOff)
|
||||
if !ok {
|
||||
break
|
||||
}
|
||||
if at > target {
|
||||
hiOff, hi = off, at
|
||||
} else {
|
||||
loOff, lo = off, at
|
||||
}
|
||||
}
|
||||
d.skip, d.pend = target-lo, d.pend[:0]
|
||||
return d.at(loOff)
|
||||
}
|
||||
|
||||
// frameAfter returns where the first whole frame at or after off and before
|
||||
// end starts, and the frame of sound it starts with. Bytes that only look
|
||||
// like a frame's header within the audio fail its checksums.
|
||||
func (d *decoder) frameAfter(off, end int64) (int64, int64, bool) {
|
||||
const window = 16 << 10
|
||||
buf := make([]byte, window)
|
||||
for off+2 < end {
|
||||
if _, err := d.r.Seek(off, io.SeekStart); err != nil {
|
||||
return 0, 0, false
|
||||
}
|
||||
n, _ := io.ReadFull(d.r, buf[:min(window, end-off)])
|
||||
if n < 2 {
|
||||
return 0, 0, false
|
||||
}
|
||||
for i := 0; i+1 < n; i++ {
|
||||
if buf[i] != 0xff || buf[i+1]&0xfe != 0xf8 {
|
||||
continue
|
||||
}
|
||||
if at, ok := d.frameAt(off + int64(i)); ok {
|
||||
return off + int64(i), at, true
|
||||
}
|
||||
}
|
||||
off += int64(n - 1)
|
||||
}
|
||||
return 0, 0, false
|
||||
}
|
||||
|
||||
// frameAt returns the frame of sound the frame of FLAC at off starts with,
|
||||
// if a whole one is there.
|
||||
func (d *decoder) frameAt(off int64) (int64, bool) {
|
||||
if _, err := d.r.Seek(off, io.SeekStart); err != nil {
|
||||
return 0, false
|
||||
}
|
||||
f, err := parse(bufio.NewReaderSize(d.r, 16<<10), d.info)
|
||||
if err != nil || f.Channels.Count() != int(d.info.NChannels) {
|
||||
return 0, false
|
||||
}
|
||||
return int64(f.SampleNumber()), true
|
||||
}
|
||||
|
||||
// codec decodes FLAC frames, each an MP4's packet.
|
||||
type codec struct {
|
||||
info *meta.StreamInfo
|
||||
r bytes.Reader
|
||||
}
|
||||
|
||||
// NewCodec returns a decoder of the FLAC frames of an MP4's track whose
|
||||
// configuration, its dfLa box's, is blocks: the metadata blocks, as a FLAC
|
||||
// file has them after "fLaC".
|
||||
func NewCodec(blocks []byte) (mp4.Codec, error) {
|
||||
st, err := flac.New(bytes.NewReader(append([]byte("fLaC"), blocks...)))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if st.Info == nil || st.Info.SampleRate == 0 || st.Info.NChannels == 0 {
|
||||
return nil, errors.New("flac: no stream info")
|
||||
}
|
||||
return &codec{info: st.Info}, nil
|
||||
}
|
||||
|
||||
func (c *codec) SampleRate() int { return int(c.info.SampleRate) }
|
||||
func (c *codec) Reset() {}
|
||||
func (c *codec) Preroll() int { return 0 }
|
||||
func (c *codec) PacketFrames() int { return 0 }
|
||||
|
||||
func (c *codec) Decode(dst []float32, packet []byte) ([]float32, error) {
|
||||
c.r.Reset(packet)
|
||||
f, err := parse(&c.r, c.info)
|
||||
if err != nil {
|
||||
return dst, err
|
||||
}
|
||||
return stereo(dst, f, 0), nil
|
||||
}
|
||||
+62
@@ -0,0 +1,62 @@
|
||||
package flac_test
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"testing"
|
||||
|
||||
"github.com/egoist/mygo/audio/flac"
|
||||
"github.com/egoist/mygo/audio/internal/audiotest"
|
||||
)
|
||||
|
||||
// tone.flac is 2 s of two chirps at 44.1 kHz, one in each channel, in
|
||||
// 16 bits: it decodes to exactly that, and a seek lands on the very frame
|
||||
// asked for, near or far, as far as its last.
|
||||
func TestDecode(t *testing.T) {
|
||||
b := audiotest.Read(t, "testdata/tone.flac")
|
||||
d := audiotest.Open(t, b, "flac")
|
||||
if d.SampleRate() != 44100 || d.Channels() != 2 || d.Len() != 88200 {
|
||||
t.Fatalf("%d Hz, %d channels, %d frames", d.SampleRate(), d.Channels(), d.Len())
|
||||
}
|
||||
got := audiotest.ReadAll(t, d)
|
||||
if len(got) != 88200*2 {
|
||||
t.Fatalf("decoded %d samples", len(got))
|
||||
}
|
||||
if got[2000] == got[2001] {
|
||||
t.Error("both channels alike")
|
||||
}
|
||||
audiotest.SeekLands(t, d, got, 0, 0, 1, 4095, 4096, 50000, 77777, 88199, 1000)
|
||||
}
|
||||
|
||||
// A FLAC file may start with an ID3 tag: it decodes as without one.
|
||||
func TestID3(t *testing.T) {
|
||||
b := audiotest.Read(t, "testdata/tone.flac")
|
||||
want := audiotest.ReadAll(t, audiotest.Open(t, b, "flac"))
|
||||
tag := append([]byte("ID3\x04\x00\x00\x00\x00\x01\x00"), make([]byte, 128)...)
|
||||
d := audiotest.Open(t, append(tag, b...), "flac")
|
||||
got := audiotest.ReadAll(t, d)
|
||||
if len(got) != len(want) || audiotest.MaxDiff(got, want) != 0 {
|
||||
t.Fatalf("decoded %d samples, off by up to %g", len(got), audiotest.MaxDiff(got, want))
|
||||
}
|
||||
audiotest.SeekLands(t, d, want, 0, 70000)
|
||||
}
|
||||
|
||||
// FLAC in a fragmented MP4, as a lossless DASH stream carries it, decodes
|
||||
// to what the .flac does.
|
||||
func TestFragmentedMP4(t *testing.T) {
|
||||
want := audiotest.ReadAll(t, audiotest.Open(t, audiotest.Read(t, "testdata/tone.flac"), "flac"))
|
||||
d := audiotest.Open(t, audiotest.Read(t, "testdata/fragmented.m4a"), "mp4")
|
||||
if d.SampleRate() != 44100 || d.Len() != 88200 {
|
||||
t.Fatalf("%d Hz, %d frames", d.SampleRate(), d.Len())
|
||||
}
|
||||
got := audiotest.ReadAll(t, d)
|
||||
if len(got) != len(want) || audiotest.MaxDiff(got, want) != 0 {
|
||||
t.Fatalf("decoded %d samples, off by up to %g", len(got), audiotest.MaxDiff(got, want))
|
||||
}
|
||||
audiotest.SeekLands(t, d, want, 0, 0, 1, 4096, 30000, 88199)
|
||||
}
|
||||
|
||||
func TestNotFLAC(t *testing.T) {
|
||||
if _, err := flac.NewDecoder(bytes.NewReader([]byte("OggS and more"))); err == nil {
|
||||
t.Fatal("decoded what isn't FLAC")
|
||||
}
|
||||
}
|
||||
Binary file not shown.
BIN
Binary file not shown.
@@ -0,0 +1,100 @@
|
||||
// Package audiotest has what the tests of package audio's formats share.
|
||||
package audiotest
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"math"
|
||||
"os"
|
||||
"testing"
|
||||
|
||||
"github.com/egoist/mygo/audio"
|
||||
)
|
||||
|
||||
// Read reads a file of testdata.
|
||||
func Read(t testing.TB, name string) []byte {
|
||||
t.Helper()
|
||||
b, err := os.ReadFile(name)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return b
|
||||
}
|
||||
|
||||
// Open opens b as package audio does, and checks the format's name.
|
||||
func Open(t testing.TB, b []byte, name string) audio.Decoder {
|
||||
t.Helper()
|
||||
d, got, err := audio.NewDecoder(bytes.NewReader(b))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got != name {
|
||||
t.Fatalf("format %q, not %q", got, name)
|
||||
}
|
||||
return d
|
||||
}
|
||||
|
||||
// ReadAll decodes what d has left.
|
||||
func ReadAll(t testing.TB, d audio.Decoder) []float32 {
|
||||
t.Helper()
|
||||
var out []float32
|
||||
buf := make([]float32, 4096)
|
||||
for {
|
||||
n, err := d.Read(buf)
|
||||
out = append(out, buf[:n]...)
|
||||
if err != nil || n == 0 {
|
||||
return out
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// SeekLands checks that a seek to each frame reads what decoding straight
|
||||
// through, ref, has there, to within tol, for a second or to the end.
|
||||
func SeekLands(t testing.TB, d audio.Decoder, ref []float32, tol float64, frames ...int64) {
|
||||
t.Helper()
|
||||
ch := int64(d.Channels())
|
||||
for _, frame := range frames {
|
||||
if err := d.SetPosition(frame); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
want := ref[frame*ch:]
|
||||
want = want[:min(len(want), d.SampleRate()*int(ch))]
|
||||
got := make([]float32, 0, len(want))
|
||||
buf := make([]float32, 4096)
|
||||
for len(got) < len(want) {
|
||||
n, err := d.Read(buf)
|
||||
got = append(got, buf[:n]...)
|
||||
if err != nil || n == 0 {
|
||||
break
|
||||
}
|
||||
}
|
||||
if len(got) < len(want) {
|
||||
t.Errorf("seek to %d: read %d samples of %d", frame, len(got), len(want))
|
||||
continue
|
||||
}
|
||||
if diff := MaxDiff(got, want); diff > tol {
|
||||
t.Errorf("seek to %d: off by up to %.4f", frame, diff)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MaxDiff returns how far apart a and b are at most, over the length of
|
||||
// the shorter.
|
||||
func MaxDiff(a, b []float32) float64 {
|
||||
d := 0.0
|
||||
for i := range min(len(a), len(b)) {
|
||||
d = math.Max(d, math.Abs(float64(a[i]-b[i])))
|
||||
}
|
||||
return d
|
||||
}
|
||||
|
||||
// SNR is how far below ref the difference between got and ref is, in dB,
|
||||
// over the length of the shorter.
|
||||
func SNR(got, ref []float32) float64 {
|
||||
var sig, noise float64
|
||||
for i := range min(len(got), len(ref)) {
|
||||
sig += float64(ref[i]) * float64(ref[i])
|
||||
d := float64(got[i] - ref[i])
|
||||
noise += d * d
|
||||
}
|
||||
return 10 * math.Log10(sig/noise)
|
||||
}
|
||||
Vendored
+94
@@ -0,0 +1,94 @@
|
||||
package audio
|
||||
|
||||
import (
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// A tune's intro plays once, then its loop again and again, without a gap.
|
||||
func TestLoopRange(t *testing.T) {
|
||||
setup(t)
|
||||
samples := ramp(100) // frame i is i/200
|
||||
p := NewSound(sampleRate, 1, samples).NewPlayer().
|
||||
SetLoopRange(frames(30, sampleRate), frames(60, sampleRate))
|
||||
p.Play()
|
||||
out := render(200)
|
||||
for i := range 200 {
|
||||
want := i
|
||||
if i >= 60 {
|
||||
want = 30 + (i-60)%30
|
||||
}
|
||||
if !near(out[2*i], samples[want]) {
|
||||
t.Fatalf("frame %d = %v, want frame %d's %v", i, out[2*i], want, samples[want])
|
||||
}
|
||||
}
|
||||
// 200 frames in: 60 + 140 = 4 loops of 30 and 20 more.
|
||||
if got, want := p.Position(), frames(50, sampleRate); got != want {
|
||||
t.Errorf("Position = %v, want %v", got, want)
|
||||
}
|
||||
// Looping no more, it plays on past the loop's end, to the end (after
|
||||
// what it read ahead, a few milliseconds).
|
||||
p.SetLoop(false)
|
||||
out = render(1000)
|
||||
last := -1
|
||||
for i := range 1000 {
|
||||
if out[2*i] != 0 {
|
||||
last = i
|
||||
}
|
||||
}
|
||||
if last < 0 || !near(out[2*last], samples[99]) || p.Playing() {
|
||||
t.Errorf("after SetLoop(false): last frame %d = %v, playing %v", last, out[2*max(last, 0)], p.Playing())
|
||||
}
|
||||
if !near(out[2*(last-39)], samples[60]) {
|
||||
t.Errorf("frames 60 to 99 do not end it: %v", out[2*(last-39)])
|
||||
}
|
||||
}
|
||||
|
||||
func TestStreamLoopRange(t *testing.T) {
|
||||
setup(t)
|
||||
d := &genDecoder{ch: 1, length: 5000} // frame i is (i%1000)/1000
|
||||
p := NewPlayer(d).SetLoopRange(frames(1000, sampleRate), frames(3000, sampleRate))
|
||||
waitDecoded(t, p)
|
||||
p.Play()
|
||||
out := make([]float32, 0, 9000*channels)
|
||||
for len(out) < 9000*channels {
|
||||
chunk := make([]float32, 64*channels)
|
||||
s := p.v.src.(*stream)
|
||||
for {
|
||||
s.mu.Lock()
|
||||
n := s.n
|
||||
s.mu.Unlock()
|
||||
if n >= 64 {
|
||||
break
|
||||
}
|
||||
time.Sleep(time.Millisecond)
|
||||
}
|
||||
mix(chunk)
|
||||
out = append(out, chunk...)
|
||||
}
|
||||
for i := range 9000 {
|
||||
f := i
|
||||
if i >= 3000 {
|
||||
f = 1000 + (i-3000)%2000
|
||||
}
|
||||
if want := float32(f%1000) / 1000; !near(out[2*i], want) {
|
||||
t.Fatalf("frame %d = %v, want frame %d's %v", i, out[2*i], f, want)
|
||||
}
|
||||
}
|
||||
p.Close()
|
||||
}
|
||||
|
||||
func TestLoopRangeOutOfRange(t *testing.T) {
|
||||
setup(t)
|
||||
p := NewSound(sampleRate, 1, ramp(100)).NewPlayer()
|
||||
// An end before the start loops it all.
|
||||
p.SetLoopRange(frames(60, sampleRate), frames(30, sampleRate))
|
||||
if p.v.loopStart != 0 || p.v.loopEnd != 0 || !p.Loop() {
|
||||
t.Errorf("loop %d to %d, looping %v", p.v.loopStart, p.v.loopEnd, p.Loop())
|
||||
}
|
||||
// Past the end, clamped to it.
|
||||
p.SetLoopRange(frames(10, sampleRate), time.Hour)
|
||||
if p.v.loopStart != 10 || p.v.loopEnd != 100 {
|
||||
t.Errorf("loop %d to %d", p.v.loopStart, p.v.loopEnd)
|
||||
}
|
||||
}
|
||||
Vendored
+445
@@ -0,0 +1,445 @@
|
||||
package audio
|
||||
|
||||
import (
|
||||
"math"
|
||||
"slices"
|
||||
)
|
||||
|
||||
// voices are the voices playing, or fading out, under mu.
|
||||
var voices []*voice
|
||||
|
||||
// The output's clock, under mu: the frames mixed so far, how many of the
|
||||
// latest the device holds, not heard yet, and how many it holds at most.
|
||||
var (
|
||||
mixed int64
|
||||
unheard int64
|
||||
held int64
|
||||
)
|
||||
|
||||
// setHeld tells the mixer that a device opened which holds n frames ahead
|
||||
// of what is heard, and none of what was mixed before.
|
||||
func setHeld(n int64) {
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
if !testMode {
|
||||
held, unheard = n, 0
|
||||
}
|
||||
}
|
||||
|
||||
// heard returns the output's frame heard now: the frames mixed before it
|
||||
// are.
|
||||
func heard() int64 { return mixed - unheard }
|
||||
|
||||
// rampFrames is how long volume changes, fades in and fades out take: 5 ms.
|
||||
const rampFrames = sampleRate / 200
|
||||
|
||||
// A source gives a voice its frames. Its methods run under mu and never
|
||||
// block.
|
||||
type source interface {
|
||||
// read reads frames into dst, interleaved, and returns how many it
|
||||
// read: fewer than fit only at the end, where ended is true, or while
|
||||
// a stream decodes, where it is false. It goes on from the start when
|
||||
// looping.
|
||||
read(dst []float32) (n int, ended bool)
|
||||
seek(frame int64)
|
||||
// setLoop sets whether the source loops, from frame start to end
|
||||
// (0 for its end).
|
||||
setLoop(loop bool, start, end int64)
|
||||
close()
|
||||
}
|
||||
|
||||
// A voice is a player's state: its source, where it is, and how it
|
||||
// resamples to the output.
|
||||
type voice struct {
|
||||
src source
|
||||
rate float64
|
||||
mono bool
|
||||
length int64 // frames, or -1
|
||||
|
||||
playing bool // as the API sees it
|
||||
active bool // in voices, which it stays in while fading out
|
||||
snap bool // starts at its start: no fade in
|
||||
fadeIn bool // resumes in the middle: fades in from silence
|
||||
closed bool
|
||||
orphan bool // its Player is gone: close at the end
|
||||
atEnd bool // played to its end, for mix to tell the OnEnd listeners
|
||||
|
||||
onEnd []endListener
|
||||
nextEnd uint64
|
||||
|
||||
volume, pan, speed float64
|
||||
pitch bool // preserves pitch at its speed: stretched by st
|
||||
loop bool
|
||||
loopStart, loopEnd int64 // frames, loopEnd 0 for the end
|
||||
|
||||
// The source frames around the output, stereo: frame f at f mod
|
||||
// ringFrames, and again ringFrames after, so that any ringFrames in a
|
||||
// row are in a row. The output is phase past frame idx, and head is
|
||||
// the frame that comes in next, as far ahead as the interpolation
|
||||
// reaches.
|
||||
ring [][2]float32
|
||||
idx int64
|
||||
phase float64
|
||||
head int64
|
||||
end int64 // the frame after the last, once the source ended, or -1
|
||||
|
||||
// The sinc's weights while the voice downsamples.
|
||||
bank sincBank
|
||||
|
||||
in []float32 // frames read from the source and not yet used
|
||||
inPos int
|
||||
inLen int
|
||||
|
||||
// Time-stretches the source once its player preserved pitch, which
|
||||
// counts where hist is in the source: nil for every other voice.
|
||||
st *stretcher
|
||||
|
||||
// The gains applied, a 2×2 matrix from the source's channels to the
|
||||
// output's (ll, rl, lr, rr), ramping to target.
|
||||
gain, target, step [4]float32
|
||||
rampLeft int
|
||||
|
||||
// Where the voice was in its source as the output mixed its frames,
|
||||
// oldest first, for Position to say where it is heard.
|
||||
marks []mark
|
||||
}
|
||||
|
||||
// A mark is the voice at output frame out: at frame pos of its source,
|
||||
// counted on past its loop's end. Between two marks the voice moved
|
||||
// evenly, or stood still where they are at the same pos.
|
||||
type mark struct {
|
||||
out int64
|
||||
pos float64
|
||||
}
|
||||
|
||||
// reset starts the voice over at frame f of its source, which the caller
|
||||
// has moved there.
|
||||
func (v *voice) reset(f int64) {
|
||||
// Silence before f.
|
||||
clear(v.ring)
|
||||
v.idx, v.phase, v.head = f, 0, f
|
||||
v.end = -1
|
||||
v.inPos, v.inLen = 0, 0
|
||||
if v.st != nil {
|
||||
v.st.reset(f, v.pitch)
|
||||
}
|
||||
// What it mixed before is not where it is any more, even while heard.
|
||||
v.marks = v.marks[:0]
|
||||
}
|
||||
|
||||
// ended reports whether the voice played to the end of its source.
|
||||
func (v *voice) ended() bool { return v.end >= 0 && v.idx >= v.end }
|
||||
|
||||
// at returns the source frame the voice mixes next, counted on past its
|
||||
// loop's end.
|
||||
func (v *voice) at() float64 {
|
||||
if st := v.st; st != nil {
|
||||
a := st.tags[v.idx&(ringFrames-1)]
|
||||
return a + v.phase*(st.tags[(v.idx+1)&(ringFrames-1)]-a)
|
||||
}
|
||||
return float64(v.idx) + v.phase
|
||||
}
|
||||
|
||||
// stretch gives the voice a stretcher, which goes on from the frames it
|
||||
// holds, as its player starts to preserve pitch.
|
||||
func (v *voice) stretch() {
|
||||
ch := 2
|
||||
if v.mono {
|
||||
ch = 1
|
||||
}
|
||||
st := newStretcher(int(v.rate), ch)
|
||||
// The frame coming in next is at head, and those in the ring at
|
||||
// themselves.
|
||||
st.reset(v.head, true)
|
||||
for f := v.idx; f < v.head; f++ {
|
||||
st.tags[f&(ringFrames-1)] = float64(f)
|
||||
}
|
||||
st.n = copy(st.buf, v.in[v.inPos:v.inLen]) / ch
|
||||
st.rd += int64(st.n)
|
||||
v.inPos = v.inLen
|
||||
v.st = st
|
||||
}
|
||||
|
||||
// mark notes that the output mixes frame out with the voice where it is,
|
||||
// and forgets the marks before the frame heard.
|
||||
func (v *voice) mark(out, heard int64) {
|
||||
m := mark{out, v.at()}
|
||||
if n := len(v.marks); n > 0 && v.marks[n-1] == m {
|
||||
return
|
||||
}
|
||||
k := 0
|
||||
for k+1 < len(v.marks) && v.marks[k+1].out <= heard {
|
||||
k++
|
||||
}
|
||||
v.marks = append(v.marks[:copy(v.marks, v.marks[k:])], m)
|
||||
}
|
||||
|
||||
// heardAt returns the source frame the voice was at when the output mixed
|
||||
// what is heard now, counted on past its loop's end. Until the output plays
|
||||
// what it mixed since a seek, that is where it seeked to.
|
||||
func (v *voice) heardAt() float64 {
|
||||
h := heard()
|
||||
k := slices.IndexFunc(v.marks, func(m mark) bool { return m.out > h })
|
||||
switch k {
|
||||
case -1:
|
||||
return v.at()
|
||||
case 0:
|
||||
return v.marks[0].pos
|
||||
}
|
||||
a, b := v.marks[k-1], v.marks[k]
|
||||
return a.pos + (b.pos-a.pos)*float64(h-a.out)/float64(b.out-a.out)
|
||||
}
|
||||
|
||||
// position returns source frame p, counted on past the loop's end, as a
|
||||
// frame of the source.
|
||||
func (v *voice) position(p float64) float64 {
|
||||
p = max(p, 0)
|
||||
if v.length == 0 {
|
||||
return 0
|
||||
}
|
||||
if v.loop {
|
||||
end := float64(v.loopEnd)
|
||||
if end <= 0 {
|
||||
end = float64(v.length)
|
||||
}
|
||||
if start := float64(v.loopStart); end > start && p >= end {
|
||||
p = start + math.Mod(p-start, end-start)
|
||||
}
|
||||
return p
|
||||
}
|
||||
if v.length > 0 {
|
||||
p = min(p, float64(v.length))
|
||||
}
|
||||
return p
|
||||
}
|
||||
|
||||
func (v *voice) close() {
|
||||
if v.closed {
|
||||
return
|
||||
}
|
||||
v.closed = true
|
||||
v.playing = false
|
||||
v.src.close()
|
||||
}
|
||||
|
||||
// next takes in the source's next frame, at head, and reports false while
|
||||
// a stream has none decoded yet.
|
||||
func (v *voice) next() bool {
|
||||
ch := 2
|
||||
if v.mono {
|
||||
ch = 1
|
||||
}
|
||||
if v.ring == nil {
|
||||
v.ring = make([][2]float32, 2*ringFrames)
|
||||
}
|
||||
if v.inPos >= v.inLen {
|
||||
if v.end >= 0 {
|
||||
// Past the end, silence.
|
||||
if v.st != nil {
|
||||
v.st.push(v.head, v.st.next)
|
||||
}
|
||||
v.push(0, 0)
|
||||
return true
|
||||
}
|
||||
var n int
|
||||
var ended bool
|
||||
if v.st != nil {
|
||||
n, ended = v.readStretched()
|
||||
} else {
|
||||
if v.in == nil {
|
||||
v.in = make([]float32, 256*ch)
|
||||
}
|
||||
n, ended = v.src.read(v.in)
|
||||
}
|
||||
v.inPos, v.inLen = 0, n*ch
|
||||
if n == 0 {
|
||||
if !ended {
|
||||
return false
|
||||
}
|
||||
v.end = v.head
|
||||
if v.st != nil {
|
||||
v.st.push(v.head, v.st.next)
|
||||
}
|
||||
v.push(0, 0)
|
||||
return true
|
||||
}
|
||||
}
|
||||
l := v.in[v.inPos]
|
||||
r := l
|
||||
if !v.mono {
|
||||
r = v.in[v.inPos+1]
|
||||
}
|
||||
if st := v.st; st != nil {
|
||||
st.push(v.head, st.tag0+float64(v.inPos/ch)*st.tagStep)
|
||||
}
|
||||
v.inPos += ch
|
||||
v.push(l, r)
|
||||
return true
|
||||
}
|
||||
|
||||
// push puts frame head into the ring.
|
||||
func (v *voice) push(l, r float32) {
|
||||
k := v.head & (ringFrames - 1)
|
||||
v.ring[k] = [2]float32{l, r}
|
||||
v.ring[k+ringFrames] = [2]float32{l, r}
|
||||
v.head++
|
||||
}
|
||||
|
||||
// gains returns the matrix of the voice's volume and pan, and the master
|
||||
// volume.
|
||||
func (v *voice) gains(master float64) [4]float32 {
|
||||
g := v.volume * master
|
||||
if !v.playing {
|
||||
g = 0
|
||||
}
|
||||
if v.mono {
|
||||
// Equal power, the middle as decoded.
|
||||
x := (v.pan + 1) / 2 * math.Pi / 2
|
||||
return [4]float32{float32(g * math.Sqrt2 * math.Cos(x)), 0, 0, float32(g * math.Sqrt2 * math.Sin(x))}
|
||||
}
|
||||
// Web Audio's StereoPannerNode for stereo input.
|
||||
if v.pan <= 0 {
|
||||
x := (v.pan + 1) * math.Pi / 2
|
||||
return [4]float32{float32(g), 0, float32(g * math.Cos(x)), float32(g * math.Sin(x))}
|
||||
}
|
||||
x := v.pan * math.Pi / 2
|
||||
return [4]float32{float32(g * math.Cos(x)), float32(g * math.Sin(x)), 0, float32(g)}
|
||||
}
|
||||
|
||||
// retarget ramps the gains to t from now.
|
||||
func (v *voice) retarget(t [4]float32) {
|
||||
switch {
|
||||
case v.snap:
|
||||
v.snap, v.fadeIn = false, false
|
||||
v.gain, v.target, v.rampLeft = t, t, 0
|
||||
return
|
||||
case v.fadeIn:
|
||||
v.fadeIn = false
|
||||
v.gain = [4]float32{}
|
||||
case t == v.target:
|
||||
return
|
||||
}
|
||||
v.target = t
|
||||
for i := range t {
|
||||
v.step[i] = (t[i] - v.gain[i]) / rampFrames
|
||||
}
|
||||
v.rampLeft = rampFrames
|
||||
}
|
||||
|
||||
// mix adds the voice's next frames to out, which the output mixes from
|
||||
// its frame at, and reports whether it is still active: false once at its
|
||||
// end, or faded out.
|
||||
func (v *voice) mix(out []float32, master float64, at, heard int64) bool {
|
||||
v.mark(at, heard)
|
||||
n, ok := v.play(out, master)
|
||||
v.mark(at+int64(n), heard)
|
||||
return ok
|
||||
}
|
||||
|
||||
// play adds the voice's next frames to out and returns how many it moved
|
||||
// through its source for, and whether it is still active.
|
||||
func (v *voice) play(out []float32, master float64) (int, bool) {
|
||||
v.retarget(v.gains(master))
|
||||
step := v.rate / sampleRate * v.speed
|
||||
if v.st != nil && v.st.on {
|
||||
// Stretched to the speed already.
|
||||
step = v.rate / sampleRate
|
||||
}
|
||||
// The spline reaches 2 frames ahead, the sinc further the faster.
|
||||
reach := 2
|
||||
if step > 1 {
|
||||
v.bank.set(step)
|
||||
reach = v.bank.reach
|
||||
}
|
||||
for i := 0; i < len(out); i += 2 {
|
||||
n := int64(v.phase)
|
||||
for v.head <= v.idx+n+int64(reach) {
|
||||
if !v.next() {
|
||||
// The stream is late: silence until it catches up.
|
||||
return i / 2, true
|
||||
}
|
||||
}
|
||||
v.idx += n
|
||||
v.phase -= float64(n)
|
||||
if v.ended() {
|
||||
v.atEnd = v.atEnd || v.playing
|
||||
v.playing = false
|
||||
return i / 2, false
|
||||
}
|
||||
if v.rampLeft > 0 {
|
||||
for k := range v.gain {
|
||||
v.gain[k] += v.step[k]
|
||||
}
|
||||
v.rampLeft--
|
||||
if v.rampLeft == 0 {
|
||||
v.gain = v.target
|
||||
}
|
||||
} else if !v.playing {
|
||||
// Faded out.
|
||||
return i / 2, false
|
||||
}
|
||||
var l, r float32
|
||||
if step > 1 {
|
||||
l, r = v.sinc()
|
||||
} else {
|
||||
l, r = v.sample()
|
||||
}
|
||||
out[i] += l*v.gain[0] + r*v.gain[2]
|
||||
out[i+1] += l*v.gain[1] + r*v.gain[3]
|
||||
v.phase += step
|
||||
}
|
||||
return len(out) / 2, true
|
||||
}
|
||||
|
||||
// sample interpolates between frames idx and idx+1 with a Catmull-Rom
|
||||
// spline through the frames either side.
|
||||
func (v *voice) sample() (l, r float32) {
|
||||
t := float32(v.phase)
|
||||
o := (v.idx - 1) & (ringFrames - 1)
|
||||
h := v.ring[o : o+4]
|
||||
cr := func(p0, p1, p2, p3 float32) float32 {
|
||||
return p1 + 0.5*t*(p2-p0+t*(2*p0-5*p1+4*p2-p3+t*(3*(p1-p2)+p3-p0)))
|
||||
}
|
||||
return cr(h[0][0], h[1][0], h[2][0], h[3][0]), cr(h[0][1], h[1][1], h[2][1], h[3][1])
|
||||
}
|
||||
|
||||
// mix fills out, interleaved stereo, with the voices playing, and reports
|
||||
// whether any is.
|
||||
func mix(out []float32) bool {
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
return mixLocked(out)
|
||||
}
|
||||
|
||||
// mixLocked is mix, under mu.
|
||||
func mixLocked(out []float32) bool {
|
||||
clear(out)
|
||||
at, h := mixed, heard()
|
||||
n := 0
|
||||
for _, v := range voices {
|
||||
if v.closed || !v.mix(out, volume, at, h) {
|
||||
if v.atEnd {
|
||||
v.atEnd = false
|
||||
for _, l := range v.onEnd {
|
||||
go l.fn()
|
||||
}
|
||||
}
|
||||
v.active = false
|
||||
if v.orphan {
|
||||
v.close()
|
||||
}
|
||||
continue
|
||||
}
|
||||
voices[n] = v
|
||||
n++
|
||||
}
|
||||
clear(voices[n:])
|
||||
voices = voices[:n]
|
||||
f := int64(len(out) / channels)
|
||||
mixed += f
|
||||
unheard = min(unheard+f, held)
|
||||
for i, s := range out {
|
||||
out[i] = min(max(s, -1), 1)
|
||||
}
|
||||
return n > 0
|
||||
}
|
||||
Vendored
+74
@@ -0,0 +1,74 @@
|
||||
// Package mp3 decodes MP3 files for package audio, with
|
||||
// github.com/hajimehoshi/go-mp3. Import it for its side effect:
|
||||
//
|
||||
// import _ "github.com/egoist/mygo/audio/mp3"
|
||||
package mp3
|
||||
|
||||
import (
|
||||
"encoding/binary"
|
||||
"io"
|
||||
|
||||
"github.com/egoist/mygo/audio"
|
||||
gomp3 "github.com/hajimehoshi/go-mp3"
|
||||
)
|
||||
|
||||
func init() {
|
||||
open := func(r io.ReadSeeker) (audio.Decoder, error) { return NewDecoder(r) }
|
||||
// An ID3 tag, or the sync word of a frame of MPEG-1 or 2 layer III.
|
||||
audio.RegisterFormat("mp3", "ID3", open)
|
||||
for _, b := range []string{"\xff\xfb", "\xff\xfa", "\xff\xf3", "\xff\xf2", "\xff\xe3", "\xff\xe2"} {
|
||||
audio.RegisterFormat("mp3", b, open)
|
||||
}
|
||||
}
|
||||
|
||||
// NewDecoder returns a decoder of the MP3 file r, which decodes to stereo.
|
||||
func NewDecoder(r io.ReadSeeker) (audio.Decoder, error) {
|
||||
d, err := gomp3.NewDecoder(r)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &decoder{d: d}, nil
|
||||
}
|
||||
|
||||
// go-mp3 decodes to 16-bit stereo: 4 bytes a frame.
|
||||
const frameBytes = 4
|
||||
|
||||
type decoder struct {
|
||||
d *gomp3.Decoder
|
||||
buf []byte
|
||||
}
|
||||
|
||||
func (d *decoder) SampleRate() int { return d.d.SampleRate() }
|
||||
func (d *decoder) Channels() int { return 2 }
|
||||
|
||||
func (d *decoder) Len() int64 {
|
||||
if n := d.d.Length(); n > 0 {
|
||||
return n / frameBytes
|
||||
}
|
||||
return -1
|
||||
}
|
||||
|
||||
func (d *decoder) Read(dst []float32) (int, error) {
|
||||
n := len(dst) / 2 * frameBytes
|
||||
if cap(d.buf) < n {
|
||||
d.buf = make([]byte, n)
|
||||
}
|
||||
b := d.buf[:n]
|
||||
got, err := io.ReadFull(d.d, b)
|
||||
got -= got % frameBytes
|
||||
for i := 0; i < got/2; i++ {
|
||||
dst[i] = float32(int16(binary.LittleEndian.Uint16(b[2*i:]))) / (1 << 15)
|
||||
}
|
||||
if got > 0 {
|
||||
return got / 2, nil
|
||||
}
|
||||
if err == io.ErrUnexpectedEOF {
|
||||
err = io.EOF
|
||||
}
|
||||
return 0, err
|
||||
}
|
||||
|
||||
func (d *decoder) SetPosition(frame int64) error {
|
||||
_, err := d.d.Seek(frame*frameBytes, io.SeekStart)
|
||||
return err
|
||||
}
|
||||
+59
@@ -0,0 +1,59 @@
|
||||
package mp3
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"math"
|
||||
"os"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/egoist/mygo/audio"
|
||||
)
|
||||
|
||||
// tone.mp3 is 0.5 s of a 440 Hz sine at 44.1 kHz, in mono, which decodes
|
||||
// to stereo with the encoder's padding.
|
||||
func TestDecode(t *testing.T) {
|
||||
data, err := os.ReadFile("testdata/tone.mp3")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
d, name, err := audio.NewDecoder(bytes.NewReader(data))
|
||||
if err != nil || name != "mp3" {
|
||||
t.Fatal(name, err)
|
||||
}
|
||||
if d.SampleRate() != 44100 || d.Channels() != 2 {
|
||||
t.Fatalf("%d Hz, %d channels", d.SampleRate(), d.Channels())
|
||||
}
|
||||
// go-mp3 keeps the encoder's delay and padding, a few frames of 1152.
|
||||
if n := d.Len(); n < 22050 || n > 22050+4*1152 {
|
||||
t.Errorf("Len = %d", n)
|
||||
}
|
||||
s, err := audio.DecodeSound(data)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got := s.Duration(); got < 500*time.Millisecond || got > 610*time.Millisecond {
|
||||
t.Errorf("Duration = %v", got)
|
||||
}
|
||||
if err := d.SetPosition(10000); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
buf := make([]float32, 2*8820)
|
||||
n := 0
|
||||
for n < len(buf) {
|
||||
m, err := d.Read(buf[n:])
|
||||
n += m
|
||||
if err != nil {
|
||||
break
|
||||
}
|
||||
}
|
||||
zc := 0
|
||||
for i := 2; i < n; i += 2 {
|
||||
if (buf[i-2] < 0) != (buf[i] < 0) {
|
||||
zc++
|
||||
}
|
||||
}
|
||||
if f := float64(zc) / 2 / (float64(n/2) / 44100); math.Abs(f-440) > 5 {
|
||||
t.Errorf("decoded %v Hz from frame 10000", f)
|
||||
}
|
||||
}
|
||||
BIN
Binary file not shown.
Vendored
+538
@@ -0,0 +1,538 @@
|
||||
package mp4
|
||||
|
||||
import (
|
||||
"encoding/binary"
|
||||
"errors"
|
||||
"math/bits"
|
||||
)
|
||||
|
||||
// An ALAC decoder decodes Apple Lossless packets, as an MP4 holds them, after
|
||||
// Apple's own decoder (https://github.com/macosforge/alac, under the Apache
|
||||
// License 2.0): each packet a frame of up to frameLength
|
||||
// samples a channel, adaptively Golomb coded, then predicted from the samples
|
||||
// before it. It gives stereo, of a mono file in both ears.
|
||||
type alacDecoder struct {
|
||||
frameLength uint32
|
||||
bitDepth uint8
|
||||
pb, mb, kb uint8
|
||||
channels uint8
|
||||
rate uint32
|
||||
predictor []int32
|
||||
u, v []int32 // a channel pair's, mixed
|
||||
shift []uint16
|
||||
left, right []int32 // the channels kept: the front pair
|
||||
leftCh, rightCh int
|
||||
bitsPerSample float32
|
||||
coefsU, coefsV [32]int16
|
||||
packet []byte // the last, with zeros after it
|
||||
}
|
||||
|
||||
// ALAC elements, as AAC's.
|
||||
const (
|
||||
alacSCE = 0 // a single channel
|
||||
alacCPE = 1 // a channel pair
|
||||
alacCCE = 2
|
||||
alacLFE = 3
|
||||
alacDSE = 4
|
||||
alacPCE = 5
|
||||
alacFIL = 6
|
||||
alacEND = 7
|
||||
)
|
||||
|
||||
// newALACDecoder reads the stream's magic cookie: its ALACSpecificConfig, in
|
||||
// an MP4 within an 'alac' atom of its own, and in QuickTime's after a 'frma'.
|
||||
func newALACDecoder(cookie []byte) (*alacDecoder, error) {
|
||||
for len(cookie) >= 12 {
|
||||
switch string(cookie[4:8]) {
|
||||
case "frma":
|
||||
cookie = cookie[12:]
|
||||
continue
|
||||
case "alac":
|
||||
cookie = cookie[12:]
|
||||
continue
|
||||
}
|
||||
break
|
||||
}
|
||||
if len(cookie) < 24 {
|
||||
return nil, errors.New("alac: short magic cookie")
|
||||
}
|
||||
d := &alacDecoder{
|
||||
frameLength: binary.BigEndian.Uint32(cookie),
|
||||
bitDepth: cookie[5],
|
||||
pb: cookie[6],
|
||||
mb: cookie[7],
|
||||
kb: cookie[8],
|
||||
channels: cookie[9],
|
||||
rate: binary.BigEndian.Uint32(cookie[20:]),
|
||||
}
|
||||
switch {
|
||||
case cookie[4] != 0:
|
||||
return nil, errors.New("alac: unknown version")
|
||||
case d.frameLength == 0 || d.frameLength > 1<<16:
|
||||
return nil, errors.New("alac: bad frame length")
|
||||
case d.bitDepth != 16 && d.bitDepth != 20 && d.bitDepth != 24 && d.bitDepth != 32:
|
||||
return nil, errors.New("alac: bad bit depth")
|
||||
case d.channels == 0 || d.channels > 8:
|
||||
return nil, errors.New("alac: bad channel count")
|
||||
case d.kb == 0 || d.kb > 30:
|
||||
return nil, errors.New("alac: bad parameters")
|
||||
}
|
||||
n := int(d.frameLength)
|
||||
d.predictor = make([]int32, n)
|
||||
d.u, d.v = make([]int32, n), make([]int32, n)
|
||||
d.shift = make([]uint16, 2*n)
|
||||
d.left, d.right = make([]int32, n), make([]int32, n)
|
||||
// The front left and right, of ALAC's channel layouts: C L R first from
|
||||
// three channels, and C Lc Rc L R from eight.
|
||||
switch d.channels {
|
||||
case 1:
|
||||
d.leftCh, d.rightCh = 0, 0
|
||||
case 2:
|
||||
d.leftCh, d.rightCh = 0, 1
|
||||
case 8:
|
||||
d.leftCh, d.rightCh = 3, 4
|
||||
default:
|
||||
d.leftCh, d.rightCh = 1, 2
|
||||
}
|
||||
d.bitsPerSample = 1 / float32(int64(1)<<(d.bitDepth-1))
|
||||
return d, nil
|
||||
}
|
||||
|
||||
// alacBits reads a packet's bits, most significant first. Reads past its end
|
||||
// read zeros, and mark it overrun.
|
||||
type alacBits struct {
|
||||
b []byte // with 8 bytes of zeros after it
|
||||
n uint // its bits, but the zeros
|
||||
pos uint
|
||||
}
|
||||
|
||||
func (r *alacBits) at(pos, n uint) uint32 {
|
||||
if n == 0 {
|
||||
return 0
|
||||
}
|
||||
i := pos >> 3
|
||||
if i+8 > uint(len(r.b)) {
|
||||
return 0
|
||||
}
|
||||
return uint32(binary.BigEndian.Uint64(r.b[i:]) << (pos & 7) >> (64 - n))
|
||||
}
|
||||
|
||||
func (r *alacBits) read(n uint) uint32 {
|
||||
v := r.at(r.pos, n)
|
||||
r.pos += n
|
||||
return v
|
||||
}
|
||||
|
||||
func (r *alacBits) over() bool { return r.pos > r.n }
|
||||
|
||||
var errALACData = errors.New("alac: bad packet")
|
||||
|
||||
// Decode decodes a packet into dst, as stereo, and returns it.
|
||||
func (d *alacDecoder) Decode(dst []float32, packet []byte) ([]float32, error) {
|
||||
// With zeros after it, for reads of 8 bytes at a time near its end.
|
||||
d.packet = append(append(d.packet[:0], packet...), make([]byte, 8)...)
|
||||
r := &alacBits{b: d.packet, n: uint(len(packet)) * 8}
|
||||
ch := 0
|
||||
samples := -1
|
||||
for {
|
||||
if r.over() {
|
||||
return dst, errALACData
|
||||
}
|
||||
tag := r.read(3)
|
||||
switch tag {
|
||||
case alacSCE, alacLFE, alacCPE:
|
||||
if ch >= int(d.channels) {
|
||||
return dst, errALACData
|
||||
}
|
||||
pair := tag == alacCPE
|
||||
n, err := d.element(r, pair, ch)
|
||||
if err != nil {
|
||||
return dst, err
|
||||
}
|
||||
if samples >= 0 && n != samples {
|
||||
return dst, errALACData
|
||||
}
|
||||
samples = n
|
||||
if pair {
|
||||
ch += 2
|
||||
} else {
|
||||
ch++
|
||||
}
|
||||
case alacDSE:
|
||||
r.read(4) // its instance
|
||||
align := r.read(1)
|
||||
count := r.read(8)
|
||||
if count == 255 {
|
||||
count += r.read(8)
|
||||
}
|
||||
if align != 0 {
|
||||
r.pos = (r.pos + 7) &^ 7
|
||||
}
|
||||
r.pos += uint(count) * 8
|
||||
case alacFIL:
|
||||
count := r.read(4)
|
||||
if count == 15 {
|
||||
count += r.read(8) - 1
|
||||
}
|
||||
r.pos += uint(count) * 8
|
||||
case alacEND:
|
||||
if samples < 0 {
|
||||
return dst, errALACData
|
||||
}
|
||||
for i := range samples {
|
||||
dst = append(dst, float32(d.left[i])*d.bitsPerSample, float32(d.right[i])*d.bitsPerSample)
|
||||
}
|
||||
return dst, nil
|
||||
default:
|
||||
return dst, errors.New("alac: unsupported element")
|
||||
}
|
||||
if ch >= int(d.channels) {
|
||||
// Done with the channels: an END element should follow, but
|
||||
// some encoders leave it out.
|
||||
if r.over() || samples < 0 {
|
||||
return dst, errALACData
|
||||
}
|
||||
for i := range samples {
|
||||
dst = append(dst, float32(d.left[i])*d.bitsPerSample, float32(d.right[i])*d.bitsPerSample)
|
||||
}
|
||||
return dst, nil
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// element decodes a single channel, or a pair, as channel ch on, and keeps
|
||||
// what of it plays. It returns its samples a channel.
|
||||
func (d *alacDecoder) element(r *alacBits, pair bool, ch int) (int, error) {
|
||||
r.read(4) // its instance
|
||||
if r.read(12) != 0 {
|
||||
return 0, errALACData
|
||||
}
|
||||
header := r.read(4)
|
||||
partial := header>>3 != 0
|
||||
shifted := uint(header >> 1 & 3)
|
||||
escape := header&1 != 0
|
||||
if shifted == 3 {
|
||||
return 0, errALACData
|
||||
}
|
||||
n := d.frameLength
|
||||
if partial {
|
||||
n = r.read(32)
|
||||
if n == 0 || n > d.frameLength {
|
||||
return 0, errALACData
|
||||
}
|
||||
}
|
||||
chanBits := uint(d.bitDepth) - shifted*8
|
||||
if pair {
|
||||
chanBits++
|
||||
}
|
||||
if chanBits > 32 {
|
||||
return 0, errALACData
|
||||
}
|
||||
u, v := d.u[:n], d.v[:n]
|
||||
var mixBits uint32
|
||||
var mixRes int32
|
||||
if !escape {
|
||||
mixBits = r.read(8)
|
||||
mixRes = int32(int8(r.read(8)))
|
||||
modeU, denU, pbU, coefsU := d.predictorHeader(r, &d.coefsU)
|
||||
var modeV, denV, pbV uint32
|
||||
var coefsV []int16
|
||||
if pair {
|
||||
modeV, denV, pbV, coefsV = d.predictorHeader(r, &d.coefsV)
|
||||
}
|
||||
var shiftBits alacBits
|
||||
if shifted != 0 {
|
||||
shiftBits = *r
|
||||
ways := uint(1)
|
||||
if pair {
|
||||
ways = 2
|
||||
}
|
||||
r.pos += shifted * 8 * ways * uint(n)
|
||||
}
|
||||
if err := d.channel(r, u, modeU, denU, pbU, coefsU, chanBits); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
if pair {
|
||||
if err := d.channel(r, v, modeV, denV, pbV, coefsV, chanBits); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
}
|
||||
if shifted != 0 {
|
||||
bits := shifted * 8
|
||||
if pair {
|
||||
for i := range n {
|
||||
d.shift[2*i] = uint16(shiftBits.read(bits))
|
||||
d.shift[2*i+1] = uint16(shiftBits.read(bits))
|
||||
}
|
||||
} else {
|
||||
for i := range n {
|
||||
d.shift[i] = uint16(shiftBits.read(bits))
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// Uncompressed, and never shifted.
|
||||
shifted = 0
|
||||
chanBits = uint(d.bitDepth)
|
||||
ext := 32 - chanBits
|
||||
for i := range n {
|
||||
u[i] = int32(r.read(chanBits)<<ext) >> ext
|
||||
if pair {
|
||||
v[i] = int32(r.read(chanBits)<<ext) >> ext
|
||||
}
|
||||
}
|
||||
}
|
||||
if r.over() {
|
||||
return 0, errALACData
|
||||
}
|
||||
keep := func(c int, out []int32) {
|
||||
switch c {
|
||||
case d.leftCh:
|
||||
copy(d.left, out)
|
||||
if d.rightCh == c {
|
||||
copy(d.right, out)
|
||||
}
|
||||
case d.rightCh:
|
||||
copy(d.right, out)
|
||||
}
|
||||
}
|
||||
bits := shifted * 8
|
||||
if !pair {
|
||||
if shifted != 0 {
|
||||
for i := range n {
|
||||
u[i] = u[i]<<bits | int32(d.shift[i])
|
||||
}
|
||||
}
|
||||
keep(ch, u)
|
||||
return int(n), nil
|
||||
}
|
||||
for i := range n {
|
||||
l, rr := u[i], v[i]
|
||||
if mixRes != 0 {
|
||||
l = u[i] + v[i] - (mixRes*v[i])>>mixBits
|
||||
rr = l - v[i]
|
||||
}
|
||||
if shifted != 0 {
|
||||
l = l<<bits | int32(d.shift[2*i])
|
||||
rr = rr<<bits | int32(d.shift[2*i+1])
|
||||
}
|
||||
u[i], v[i] = l, rr
|
||||
}
|
||||
keep(ch, u)
|
||||
keep(ch+1, v)
|
||||
return int(n), nil
|
||||
}
|
||||
|
||||
// predictorHeader reads a channel's predictor: its mode, its shift, its
|
||||
// rice parameter's factor and its coefficients.
|
||||
func (d *alacDecoder) predictorHeader(r *alacBits, coefs *[32]int16) (mode, den, pbFactor uint32, c []int16) {
|
||||
h := r.read(8)
|
||||
mode, den = h>>4, h&15
|
||||
h = r.read(8)
|
||||
pbFactor = h >> 5
|
||||
num := h & 31
|
||||
for i := range num {
|
||||
coefs[i] = int16(r.read(16))
|
||||
}
|
||||
return mode, den, pbFactor, coefs[:num]
|
||||
}
|
||||
|
||||
// channel entropy-decodes a channel's residues, and predicts its samples
|
||||
// from them, into out.
|
||||
func (d *alacDecoder) channel(r *alacBits, out []int32, mode, den, pbFactor uint32, coefs []int16, chanBits uint) error {
|
||||
pc := d.predictor[:len(out)]
|
||||
pb := uint32(d.pb) * pbFactor / 4
|
||||
if err := d.residues(r, pc, pb, chanBits); err != nil {
|
||||
return err
|
||||
}
|
||||
if mode != 0 {
|
||||
unpredict(pc, pc, nil, 31, uint32(chanBits), 0)
|
||||
}
|
||||
unpredict(pc, out, coefs, len(coefs), uint32(chanBits), den)
|
||||
return nil
|
||||
}
|
||||
|
||||
// The adaptive Golomb coder's constants.
|
||||
const (
|
||||
alacQBShift = 9
|
||||
alacQB = 1 << alacQBShift
|
||||
alacMMulShift = 2
|
||||
alacMDenShift = alacQBShift - alacMMulShift - 1
|
||||
alacMOff = 1 << (alacMDenShift - 2)
|
||||
alacBitOff = 24
|
||||
alacMaxPrefix = 9
|
||||
)
|
||||
|
||||
// residues decodes len(out) residues, adapting the code to their mean as it
|
||||
// goes, with runs of zeros coded apart where it's small.
|
||||
func (d *alacDecoder) residues(r *alacBits, out []int32, pb uint32, maxBits uint) error {
|
||||
mb := uint32(d.mb)
|
||||
kb := uint32(d.kb)
|
||||
wb := uint32(1)<<kb - 1
|
||||
zmode := uint32(0)
|
||||
for c := 0; c < len(out); {
|
||||
if r.pos >= r.n {
|
||||
return errALACData
|
||||
}
|
||||
m := mb >> alacQBShift
|
||||
k := min(uint32(31-bits.LeadingZeros32(m+3)), kb)
|
||||
m = 1<<k - 1
|
||||
n := r.golomb32(m, k, maxBits)
|
||||
nd := n + zmode
|
||||
del := int32((nd + 1) >> 1)
|
||||
if nd&1 != 0 {
|
||||
del = -del
|
||||
}
|
||||
out[c] = del
|
||||
c++
|
||||
mb = pb*(n+zmode) + mb - (pb*mb)>>alacQBShift
|
||||
if n > 0xffff {
|
||||
mb = 0xffff
|
||||
}
|
||||
zmode = 0
|
||||
if mb<<alacMMulShift < alacQB && c < len(out) {
|
||||
zmode = 1
|
||||
k := uint32(bits.LeadingZeros32(mb)) - alacBitOff + (mb+alacMOff)>>alacMDenShift
|
||||
mz := (uint32(1)<<k - 1) & wb
|
||||
run := r.golomb16(mz, k)
|
||||
if c+int(run) > len(out) {
|
||||
return errALACData
|
||||
}
|
||||
for range run {
|
||||
out[c] = 0
|
||||
c++
|
||||
}
|
||||
if run >= 0xffff {
|
||||
zmode = 0
|
||||
}
|
||||
mb = 0
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// golomb32 reads a residue: a unary prefix, then k bits, or else, after
|
||||
// alacMaxPrefix ones, the residue in maxBits.
|
||||
func (r *alacBits) golomb32(m, k uint32, maxBits uint) uint32 {
|
||||
word := r.at(r.pos, 32)
|
||||
pre := uint32(bits.LeadingZeros32(^word))
|
||||
if pre >= alacMaxPrefix {
|
||||
v := r.at(r.pos+alacMaxPrefix, maxBits)
|
||||
r.pos += alacMaxPrefix + maxBits
|
||||
return v
|
||||
}
|
||||
r.pos += uint(pre) + 1
|
||||
if k == 1 {
|
||||
return pre
|
||||
}
|
||||
v := word << (pre + 1) >> (32 - k)
|
||||
r.pos += uint(k) - 1
|
||||
res := pre * m
|
||||
if v >= 2 {
|
||||
res += v - 1
|
||||
r.pos++
|
||||
}
|
||||
return res
|
||||
}
|
||||
|
||||
// golomb16 reads the length of a run of zeros, as golomb32 does a residue
|
||||
// but escaping to 16 bits.
|
||||
func (r *alacBits) golomb16(m, k uint32) uint32 {
|
||||
word := r.at(r.pos, 32)
|
||||
pre := uint32(bits.LeadingZeros32(^word))
|
||||
if pre >= alacMaxPrefix {
|
||||
v := r.at(r.pos+alacMaxPrefix, 16)
|
||||
r.pos += alacMaxPrefix + 16
|
||||
return v
|
||||
}
|
||||
v := word << (pre + 1) >> (32 - k)
|
||||
r.pos += uint(pre) + 1 + uint(k)
|
||||
res := pre*m + v - 1
|
||||
if v < 2 {
|
||||
res = pre * m
|
||||
r.pos--
|
||||
}
|
||||
return res
|
||||
}
|
||||
|
||||
func signOf(i int32) int32 {
|
||||
switch {
|
||||
case i > 0:
|
||||
return 1
|
||||
case i < 0:
|
||||
return -1
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
// unpredict undoes the adaptive linear prediction of numActive coefficients
|
||||
// on pc into out, which may be the same. With 31 it's the first-order one.
|
||||
func unpredict(pc, out []int32, coefs []int16, numActive int, chanBits, denShift uint32) {
|
||||
num := len(out)
|
||||
if num == 0 {
|
||||
return
|
||||
}
|
||||
shift := 32 - chanBits
|
||||
out[0] = pc[0]
|
||||
if numActive == 0 {
|
||||
copy(out[1:], pc[1:num])
|
||||
return
|
||||
}
|
||||
if numActive == 31 {
|
||||
prev := out[0]
|
||||
for j := 1; j < num; j++ {
|
||||
del := pc[j] + prev
|
||||
prev = del << shift >> shift
|
||||
out[j] = prev
|
||||
}
|
||||
return
|
||||
}
|
||||
for j := 1; j <= numActive && j < num; j++ {
|
||||
del := pc[j] + out[j-1]
|
||||
out[j] = del << shift >> shift
|
||||
}
|
||||
var half int32
|
||||
if denShift > 0 {
|
||||
half = 1 << (denShift - 1)
|
||||
}
|
||||
lim := numActive + 1
|
||||
for j := lim; j < num; j++ {
|
||||
top := out[j-lim]
|
||||
var sum int32
|
||||
for k := range numActive {
|
||||
sum += int32(coefs[k]) * (out[j-1-k] - top)
|
||||
}
|
||||
del := pc[j]
|
||||
del0 := del
|
||||
sg := signOf(del)
|
||||
del += top + (sum+half)>>denShift
|
||||
out[j] = del << shift >> shift
|
||||
switch {
|
||||
case sg > 0:
|
||||
for k := numActive - 1; k >= 0; k-- {
|
||||
dd := top - out[j-1-k]
|
||||
sgn := signOf(dd)
|
||||
coefs[k] -= int16(sgn)
|
||||
del0 -= int32(numActive-k) * ((sgn * dd) >> denShift)
|
||||
if del0 <= 0 {
|
||||
break
|
||||
}
|
||||
}
|
||||
case sg < 0:
|
||||
for k := numActive - 1; k >= 0; k-- {
|
||||
dd := top - out[j-1-k]
|
||||
sgn := signOf(dd)
|
||||
coefs[k] += int16(sgn)
|
||||
del0 -= int32(numActive-k) * ((-sgn * dd) >> denShift)
|
||||
if del0 >= 0 {
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (d *alacDecoder) SampleRate() int { return int(d.rate) }
|
||||
func (d *alacDecoder) Reset() {}
|
||||
func (d *alacDecoder) Preroll() int { return 0 }
|
||||
func (d *alacDecoder) PacketFrames() int { return 0 }
|
||||
Vendored
+633
@@ -0,0 +1,633 @@
|
||||
package mp4
|
||||
|
||||
import (
|
||||
"encoding/binary"
|
||||
"errors"
|
||||
"io"
|
||||
"iter"
|
||||
)
|
||||
|
||||
// A track is an MP4's first sound track.
|
||||
type track struct {
|
||||
// Codec is the type of its sample entry: "mp4a", "alac", "fLaC", ...
|
||||
Codec string
|
||||
// Config is AAC's AudioSpecificConfig, ALAC's magic cookie, FLAC's
|
||||
// metadata blocks, or another codec's boxes within the sample entry.
|
||||
Config []byte
|
||||
Timescale int64 // the units of its times, a second's
|
||||
// Duration is how long it is, in the timescale, as its header says.
|
||||
Duration int64
|
||||
// Prime is where the edit list starts it: the encoder's priming, in
|
||||
// the timescale, to drop.
|
||||
Prime int64
|
||||
// Where each packet is, and where it ends, in the timescale. Only
|
||||
// read with the tables.
|
||||
Offsets []int64
|
||||
Sizes []uint32
|
||||
Ends []int64
|
||||
|
||||
// Fragmented says the packets aren't in the movie header's tables but
|
||||
// in fragments after it, as a stream cut up for DASH has them: the
|
||||
// tables fill in as fragment reads each. Next is where the boxes after
|
||||
// the movie header start.
|
||||
Fragmented bool
|
||||
Next int64
|
||||
id uint32 // the track's ID, which its fragments name
|
||||
defaults fragmentDefaults
|
||||
}
|
||||
|
||||
// fragmentDefaults are what a fragment's packets are unless it says.
|
||||
type fragmentDefaults struct {
|
||||
duration, size uint32
|
||||
}
|
||||
|
||||
// ErrNoMovie says an MP4 has no movie header: no tracks to play.
|
||||
var ErrNoMovie = errors.New("mp4: no movie header")
|
||||
|
||||
// readTrack reads the sound track of the MP4 r holds, of size bytes. With tables,
|
||||
// it reads where each packet is too. The movie header is often after the
|
||||
// media data: r may wait for the bytes asked of it, as a file coming in.
|
||||
func readTrack(r io.ReaderAt, size int64, tables bool) (*track, error) {
|
||||
var h [16]byte
|
||||
for off := int64(0); off+8 <= size; {
|
||||
if _, err := r.ReadAt(h[:8], off); err != nil {
|
||||
return nil, ErrNoMovie
|
||||
}
|
||||
n, head := int64(binary.BigEndian.Uint32(h[:])), int64(8)
|
||||
switch n {
|
||||
case 0: // to the end
|
||||
n = size - off
|
||||
case 1:
|
||||
if _, err := r.ReadAt(h[8:], off+8); err != nil {
|
||||
return nil, ErrNoMovie
|
||||
}
|
||||
n, head = int64(binary.BigEndian.Uint64(h[8:])), 16
|
||||
}
|
||||
if n < head || n > size-off {
|
||||
return nil, errors.New("mp4: bad box")
|
||||
}
|
||||
if string(h[4:8]) == "moov" {
|
||||
if n > 256<<20 {
|
||||
return nil, errors.New("mp4: movie header too big")
|
||||
}
|
||||
moov := make([]byte, n-head)
|
||||
if _, err := r.ReadAt(moov, off+head); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
a, err := parseMoov(moov, tables)
|
||||
if err != nil || !a.Fragmented {
|
||||
return a, err
|
||||
}
|
||||
a.Next = off + n
|
||||
a.readIndex(r, size)
|
||||
return a, nil
|
||||
}
|
||||
off += n
|
||||
}
|
||||
return nil, ErrNoMovie
|
||||
}
|
||||
|
||||
// boxes walks the boxes in b, giving each one's type and body.
|
||||
func boxes(b []byte) iter.Seq2[string, []byte] {
|
||||
return func(yield func(string, []byte) bool) {
|
||||
for len(b) >= 8 {
|
||||
size, head := uint64(binary.BigEndian.Uint32(b)), uint64(8)
|
||||
typ := string(b[4:8])
|
||||
switch size {
|
||||
case 0:
|
||||
size = uint64(len(b))
|
||||
case 1:
|
||||
if len(b) < 16 {
|
||||
return
|
||||
}
|
||||
size, head = binary.BigEndian.Uint64(b[8:]), 16
|
||||
}
|
||||
if size < head || size > uint64(len(b)) {
|
||||
return
|
||||
}
|
||||
if !yield(typ, b[head:size]) {
|
||||
return
|
||||
}
|
||||
b = b[size:]
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// child returns the body of the box of type typ in b, following the path of
|
||||
// types after it into the boxes within.
|
||||
func child(b []byte, path ...string) []byte {
|
||||
for _, typ := range path {
|
||||
var found []byte
|
||||
for t, body := range boxes(b) {
|
||||
if t == typ {
|
||||
found = body
|
||||
break
|
||||
}
|
||||
}
|
||||
if found == nil {
|
||||
return nil
|
||||
}
|
||||
b = found
|
||||
}
|
||||
return b
|
||||
}
|
||||
|
||||
// parseMoov finds the first sound track in a movie header.
|
||||
func parseMoov(moov []byte, tables bool) (*track, error) {
|
||||
mvex := child(moov, "mvex")
|
||||
for typ, trak := range boxes(moov) {
|
||||
if typ != "trak" {
|
||||
continue
|
||||
}
|
||||
mdia := child(trak, "mdia")
|
||||
if hdlr := child(mdia, "hdlr"); len(hdlr) < 12 || string(hdlr[8:12]) != "soun" {
|
||||
continue
|
||||
}
|
||||
a, err := parseTrack(trak, mdia, mvex, tables)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return a, nil
|
||||
}
|
||||
return nil, errors.New("mp4: no sound track")
|
||||
}
|
||||
|
||||
var errMP4Table = errors.New("mp4: bad sample table")
|
||||
|
||||
func parseTrack(trak, mdia, mvex []byte, tables bool) (*track, error) {
|
||||
a := &track{}
|
||||
mdhd := child(mdia, "mdhd")
|
||||
switch {
|
||||
case len(mdhd) >= 32 && mdhd[0] == 1:
|
||||
a.Timescale = int64(binary.BigEndian.Uint32(mdhd[20:]))
|
||||
a.Duration = int64(binary.BigEndian.Uint64(mdhd[24:]))
|
||||
case len(mdhd) >= 20:
|
||||
a.Timescale = int64(binary.BigEndian.Uint32(mdhd[12:]))
|
||||
a.Duration = int64(binary.BigEndian.Uint32(mdhd[16:]))
|
||||
}
|
||||
if a.Timescale <= 0 || a.Duration < 0 {
|
||||
return nil, errors.New("mp4: no timescale")
|
||||
}
|
||||
stbl := child(mdia, "minf", "stbl")
|
||||
if err := a.parseEntry(child(stbl, "stsd")); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if mvex != nil && !hasSamples(stbl) {
|
||||
a.Fragmented = true
|
||||
if tkhd := child(trak, "tkhd"); len(tkhd) >= 16 {
|
||||
at := 12
|
||||
if tkhd[0] == 1 {
|
||||
at = 20
|
||||
}
|
||||
a.id = binary.BigEndian.Uint32(tkhd[at:])
|
||||
}
|
||||
for typ, trex := range boxes(mvex) {
|
||||
if typ == "trex" && len(trex) >= 24 && binary.BigEndian.Uint32(trex[4:]) == a.id {
|
||||
a.defaults = fragmentDefaults{binary.BigEndian.Uint32(trex[12:]), binary.BigEndian.Uint32(trex[16:])}
|
||||
}
|
||||
}
|
||||
} else if tables {
|
||||
if err := a.parseTables(stbl); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
a.Duration = a.Ends[len(a.Ends)-1]
|
||||
}
|
||||
if elst := child(trak, "edts", "elst"); len(elst) >= 8 {
|
||||
n := binary.BigEndian.Uint32(elst[4:])
|
||||
b := elst[8:]
|
||||
for range n {
|
||||
var t int64
|
||||
if elst[0] == 1 {
|
||||
if len(b) < 20 {
|
||||
break
|
||||
}
|
||||
t, b = int64(binary.BigEndian.Uint64(b[8:])), b[20:]
|
||||
} else {
|
||||
if len(b) < 12 {
|
||||
break
|
||||
}
|
||||
t, b = int64(int32(binary.BigEndian.Uint32(b[4:]))), b[12:]
|
||||
}
|
||||
if t >= 0 { // past an empty edit, which plays nothing
|
||||
a.Prime = t
|
||||
if a.Duration > 0 {
|
||||
a.Prime = min(t, a.Duration)
|
||||
}
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
return a, nil
|
||||
}
|
||||
|
||||
// parseEntry reads the track's sample description: its codec and its
|
||||
// configuration, in a box within the entry, or within a 'wave' box there in
|
||||
// QuickTime's own kind.
|
||||
func (a *track) parseEntry(stsd []byte) error {
|
||||
if len(stsd) < 8+36 {
|
||||
return errors.New("mp4: no sample description")
|
||||
}
|
||||
entry := stsd[8:]
|
||||
size := int(binary.BigEndian.Uint32(entry))
|
||||
if size < 36 || size > len(entry) {
|
||||
return errors.New("mp4: bad sample description")
|
||||
}
|
||||
a.Codec = string(entry[4:8])
|
||||
inner := entry[36:size]
|
||||
switch binary.BigEndian.Uint16(entry[16:]) { // the version of the sound description
|
||||
case 1:
|
||||
inner = inner[min(16, len(inner)):]
|
||||
case 2:
|
||||
inner = inner[min(36, len(inner)):]
|
||||
}
|
||||
if wave := child(inner, "wave"); wave != nil {
|
||||
inner = wave
|
||||
}
|
||||
switch a.Codec {
|
||||
case "alac":
|
||||
cookie := child(inner, "alac")
|
||||
if len(cookie) < 4 {
|
||||
return errors.New("mp4: no ALAC configuration")
|
||||
}
|
||||
a.Config = cookie[4:]
|
||||
case "fLaC":
|
||||
dfla := child(inner, "dfLa")
|
||||
if len(dfla) < 4+4+34 {
|
||||
return errors.New("mp4: no FLAC configuration")
|
||||
}
|
||||
a.Config = dfla[4:]
|
||||
case "mp4a":
|
||||
esds := child(inner, "esds")
|
||||
if len(esds) < 4 {
|
||||
return errors.New("mp4: no AAC configuration")
|
||||
}
|
||||
asc, ok := decoderConfig(esds[4:])
|
||||
if !ok {
|
||||
return errors.New("mp4: not AAC")
|
||||
}
|
||||
a.Config = asc
|
||||
default:
|
||||
a.Config = inner
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// decoderConfig finds the DecoderSpecificInfo in an elementary stream's
|
||||
// descriptors: AAC's AudioSpecificConfig. A stream not of AAC has none it
|
||||
// takes, as an MP3's in an MP4.
|
||||
func decoderConfig(b []byte) ([]byte, bool) {
|
||||
descriptor := func(b []byte) (tag byte, body, rest []byte, ok bool) {
|
||||
if len(b) < 2 {
|
||||
return 0, nil, nil, false
|
||||
}
|
||||
tag, b = b[0], b[1:]
|
||||
n := 0
|
||||
for i := 0; i < 4 && len(b) > 0; i++ {
|
||||
c := b[0]
|
||||
b = b[1:]
|
||||
n = n<<7 | int(c&0x7f)
|
||||
if c&0x80 == 0 {
|
||||
break
|
||||
}
|
||||
}
|
||||
if n > len(b) {
|
||||
return 0, nil, nil, false
|
||||
}
|
||||
return tag, b[:n], b[n:], true
|
||||
}
|
||||
tag, es, _, ok := descriptor(b)
|
||||
if !ok || tag != 3 || len(es) < 3 {
|
||||
return nil, false
|
||||
}
|
||||
flags := es[2]
|
||||
es = es[3:]
|
||||
if flags&0x80 != 0 { // depends on a stream
|
||||
es = es[min(2, len(es)):]
|
||||
}
|
||||
if flags&0x40 != 0 && len(es) > 0 { // a URL
|
||||
es = es[min(1+int(es[0]), len(es)):]
|
||||
}
|
||||
if flags&0x20 != 0 { // an OCR stream
|
||||
es = es[min(2, len(es)):]
|
||||
}
|
||||
tag, dc, _, ok := descriptor(es)
|
||||
if !ok || tag != 4 || len(dc) < 13 {
|
||||
return nil, false
|
||||
}
|
||||
switch dc[0] { // MPEG-4 audio, or MPEG-2 AAC's profiles
|
||||
case 0x40, 0x66, 0x67, 0x68:
|
||||
default:
|
||||
return nil, false
|
||||
}
|
||||
tag, asc, _, ok := descriptor(dc[13:])
|
||||
if !ok || tag != 5 || len(asc) < 2 {
|
||||
return nil, false
|
||||
}
|
||||
return asc, true
|
||||
}
|
||||
|
||||
// maxSamples bounds the tables read, against a file that claims more than it
|
||||
// could hold: a day of AAC at 48 kHz.
|
||||
const maxSamples = 1 << 22
|
||||
|
||||
// parseTables reads the sample table: each packet's size, which chunk holds
|
||||
// it, where that chunk is, and how long each packet lasts.
|
||||
func (a *track) parseTables(stbl []byte) error {
|
||||
// Sizes.
|
||||
if stsz := child(stbl, "stsz"); len(stsz) >= 12 {
|
||||
fixed := binary.BigEndian.Uint32(stsz[4:])
|
||||
n := int(binary.BigEndian.Uint32(stsz[8:]))
|
||||
if n > maxSamples || fixed == 0 && len(stsz) < 12+4*n {
|
||||
return errMP4Table
|
||||
}
|
||||
a.Sizes = make([]uint32, n)
|
||||
for i := range a.Sizes {
|
||||
if fixed != 0 {
|
||||
a.Sizes[i] = fixed
|
||||
} else {
|
||||
a.Sizes[i] = binary.BigEndian.Uint32(stsz[12+4*i:])
|
||||
}
|
||||
}
|
||||
} else if stz2 := child(stbl, "stz2"); len(stz2) >= 12 {
|
||||
field := int(stz2[7])
|
||||
n := int(binary.BigEndian.Uint32(stz2[8:]))
|
||||
if n > maxSamples || field != 4 && field != 8 && field != 16 || len(stz2) < 12+(n*field+7)/8 {
|
||||
return errMP4Table
|
||||
}
|
||||
a.Sizes = make([]uint32, n)
|
||||
b := stz2[12:]
|
||||
for i := range a.Sizes {
|
||||
switch field {
|
||||
case 4:
|
||||
a.Sizes[i] = uint32(b[i/2]>>(4*(1-i%2))) & 15
|
||||
case 8:
|
||||
a.Sizes[i] = uint32(b[i])
|
||||
case 16:
|
||||
a.Sizes[i] = uint32(binary.BigEndian.Uint16(b[2*i:]))
|
||||
}
|
||||
}
|
||||
} else {
|
||||
return errMP4Table
|
||||
}
|
||||
if len(a.Sizes) == 0 {
|
||||
return errMP4Table
|
||||
}
|
||||
|
||||
// Where the chunks are.
|
||||
var chunks []int64
|
||||
if stco := child(stbl, "stco"); len(stco) >= 8 {
|
||||
n := int(binary.BigEndian.Uint32(stco[4:]))
|
||||
if n > maxSamples || len(stco) < 8+4*n {
|
||||
return errMP4Table
|
||||
}
|
||||
chunks = make([]int64, n)
|
||||
for i := range chunks {
|
||||
chunks[i] = int64(binary.BigEndian.Uint32(stco[8+4*i:]))
|
||||
}
|
||||
} else if co64 := child(stbl, "co64"); len(co64) >= 8 {
|
||||
n := int(binary.BigEndian.Uint32(co64[4:]))
|
||||
if n > maxSamples || len(co64) < 8+8*n {
|
||||
return errMP4Table
|
||||
}
|
||||
chunks = make([]int64, n)
|
||||
for i := range chunks {
|
||||
chunks[i] = int64(binary.BigEndian.Uint64(co64[8+8*i:]))
|
||||
}
|
||||
} else {
|
||||
return errMP4Table
|
||||
}
|
||||
|
||||
// Which packets each chunk holds, in runs of chunks alike.
|
||||
stsc := child(stbl, "stsc")
|
||||
if len(stsc) < 8 {
|
||||
return errMP4Table
|
||||
}
|
||||
runs := int(binary.BigEndian.Uint32(stsc[4:]))
|
||||
if runs > maxSamples || len(stsc) < 8+12*runs || runs == 0 {
|
||||
return errMP4Table
|
||||
}
|
||||
a.Offsets = make([]int64, len(a.Sizes))
|
||||
s := 0
|
||||
for r := 0; r < runs && s < len(a.Sizes); r++ {
|
||||
e := stsc[8+12*r:]
|
||||
first := int(binary.BigEndian.Uint32(e)) - 1
|
||||
per := int(binary.BigEndian.Uint32(e[4:]))
|
||||
last := len(chunks)
|
||||
if r+1 < runs {
|
||||
last = int(binary.BigEndian.Uint32(stsc[8+12*(r+1):])) - 1
|
||||
}
|
||||
if first < 0 || last > len(chunks) || per <= 0 {
|
||||
return errMP4Table
|
||||
}
|
||||
for c := first; c < last && s < len(a.Sizes); c++ {
|
||||
off := chunks[c]
|
||||
for range per {
|
||||
if s == len(a.Sizes) {
|
||||
break
|
||||
}
|
||||
a.Offsets[s] = off
|
||||
off += int64(a.Sizes[s])
|
||||
s++
|
||||
}
|
||||
}
|
||||
}
|
||||
if s < len(a.Sizes) {
|
||||
a.Sizes, a.Offsets = a.Sizes[:s], a.Offsets[:s]
|
||||
}
|
||||
|
||||
// How long each lasts.
|
||||
stts := child(stbl, "stts")
|
||||
if len(stts) < 8 {
|
||||
return errMP4Table
|
||||
}
|
||||
n := int(binary.BigEndian.Uint32(stts[4:]))
|
||||
if len(stts) < 8+8*n {
|
||||
return errMP4Table
|
||||
}
|
||||
a.Ends = make([]int64, 0, len(a.Sizes))
|
||||
var t int64
|
||||
for i := 0; i < n && len(a.Ends) < len(a.Sizes); i++ {
|
||||
count := int(binary.BigEndian.Uint32(stts[8+8*i:]))
|
||||
delta := int64(binary.BigEndian.Uint32(stts[12+8*i:]))
|
||||
for range min(count, len(a.Sizes)-len(a.Ends)) {
|
||||
t += delta
|
||||
a.Ends = append(a.Ends, t)
|
||||
}
|
||||
}
|
||||
if len(a.Ends) == 0 {
|
||||
return errMP4Table
|
||||
}
|
||||
a.Sizes, a.Offsets = a.Sizes[:len(a.Ends)], a.Offsets[:len(a.Ends)]
|
||||
return nil
|
||||
}
|
||||
|
||||
// hasSamples says whether a sample table lists any packets: a fragmented
|
||||
// file's lists none, its packets being in the fragments.
|
||||
func hasSamples(stbl []byte) bool {
|
||||
if stsz := child(stbl, "stsz"); len(stsz) >= 12 {
|
||||
return binary.BigEndian.Uint32(stsz[8:]) > 0
|
||||
}
|
||||
if stz2 := child(stbl, "stz2"); len(stz2) >= 12 {
|
||||
return binary.BigEndian.Uint32(stz2[8:]) > 0
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// readIndex reads how long a fragmented track is from the segment index
|
||||
// that comes before its first fragment, if there's one: the movie header
|
||||
// of such a file says nothing of it.
|
||||
func (a *track) readIndex(r io.ReaderAt, size int64) {
|
||||
var h [8]byte
|
||||
for off := a.Next; off+8 <= size; {
|
||||
if _, err := r.ReadAt(h[:], off); err != nil {
|
||||
return
|
||||
}
|
||||
n := int64(binary.BigEndian.Uint32(h[:]))
|
||||
switch string(h[4:]) {
|
||||
case "sidx":
|
||||
if n < 8+24 || n > 1<<20 || n > size-off {
|
||||
return
|
||||
}
|
||||
sidx := make([]byte, n-8)
|
||||
if _, err := r.ReadAt(sidx, off+8); err != nil {
|
||||
return
|
||||
}
|
||||
if d, ok := indexDuration(sidx); ok && a.Timescale > 0 {
|
||||
a.Duration = d * a.Timescale / int64(binary.BigEndian.Uint32(sidx[8:]))
|
||||
}
|
||||
return
|
||||
case "moof", "mdat":
|
||||
return
|
||||
}
|
||||
if n < 8 {
|
||||
return
|
||||
}
|
||||
off += n
|
||||
}
|
||||
}
|
||||
|
||||
// indexDuration adds up the durations of the segments a segment index lists.
|
||||
func indexDuration(sidx []byte) (int64, bool) {
|
||||
at := 20
|
||||
if len(sidx) > 0 && sidx[0] == 1 {
|
||||
at = 28
|
||||
}
|
||||
if len(sidx) < at+4 || binary.BigEndian.Uint32(sidx[8:]) == 0 {
|
||||
return 0, false
|
||||
}
|
||||
b := sidx[at:]
|
||||
n := int(binary.BigEndian.Uint16(b[2:]))
|
||||
b = b[4:]
|
||||
if len(b) < 12*n {
|
||||
return 0, false
|
||||
}
|
||||
var d int64
|
||||
for i := range n {
|
||||
d += int64(binary.BigEndian.Uint32(b[12*i+4:]))
|
||||
}
|
||||
return d, d > 0
|
||||
}
|
||||
|
||||
// fragment reads a fragment's movie header, the body of the moof box at off
|
||||
// in the file, adding where the track's packets are in it to the tables.
|
||||
func (a *track) fragment(moof []byte, off int64) error {
|
||||
for typ, traf := range boxes(moof) {
|
||||
if typ != "traf" {
|
||||
continue
|
||||
}
|
||||
tfhd := child(traf, "tfhd")
|
||||
if len(tfhd) < 8 || binary.BigEndian.Uint32(tfhd[4:]) != a.id {
|
||||
continue
|
||||
}
|
||||
flags := binary.BigEndian.Uint32(tfhd) & 0xffffff
|
||||
base := off // where the moof starts, unless it says
|
||||
d := a.defaults
|
||||
b := tfhd[8:]
|
||||
field := func(flag uint32, n int) ([]byte, bool) {
|
||||
if flags&flag == 0 {
|
||||
return nil, false
|
||||
}
|
||||
if len(b) < n {
|
||||
return nil, false
|
||||
}
|
||||
v := b[:n]
|
||||
b = b[n:]
|
||||
return v, true
|
||||
}
|
||||
if v, ok := field(0x01, 8); ok {
|
||||
base = int64(binary.BigEndian.Uint64(v))
|
||||
}
|
||||
field(0x02, 4) // the sample description: there's one
|
||||
if v, ok := field(0x08, 4); ok {
|
||||
d.duration = binary.BigEndian.Uint32(v)
|
||||
}
|
||||
if v, ok := field(0x10, 4); ok {
|
||||
d.size = binary.BigEndian.Uint32(v)
|
||||
}
|
||||
at := base
|
||||
for typ, trun := range boxes(traf) {
|
||||
if typ != "trun" {
|
||||
continue
|
||||
}
|
||||
var err error
|
||||
if at, err = a.run(trun, base, at, d); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// run reads a track run: packets one after another, from at unless it says
|
||||
// where from base. It returns where the next run starts, unless it says.
|
||||
func (a *track) run(trun []byte, base, at int64, d fragmentDefaults) (int64, error) {
|
||||
if len(trun) < 8 {
|
||||
return 0, errMP4Table
|
||||
}
|
||||
flags := binary.BigEndian.Uint32(trun) & 0xffffff
|
||||
n := int(binary.BigEndian.Uint32(trun[4:]))
|
||||
b := trun[8:]
|
||||
if flags&0x01 != 0 {
|
||||
if len(b) < 4 {
|
||||
return 0, errMP4Table
|
||||
}
|
||||
at = base + int64(int32(binary.BigEndian.Uint32(b)))
|
||||
b = b[4:]
|
||||
}
|
||||
if flags&0x04 != 0 { // the first packet's flags
|
||||
if len(b) < 4 {
|
||||
return 0, errMP4Table
|
||||
}
|
||||
b = b[4:]
|
||||
}
|
||||
per := 0
|
||||
for _, f := range []uint32{0x100, 0x200, 0x400, 0x800} {
|
||||
if flags&f != 0 {
|
||||
per += 4
|
||||
}
|
||||
}
|
||||
if n > maxSamples || len(b) < n*per || len(a.Sizes)+n > maxSamples {
|
||||
return 0, errMP4Table
|
||||
}
|
||||
var t int64
|
||||
if len(a.Ends) > 0 {
|
||||
t = a.Ends[len(a.Ends)-1]
|
||||
}
|
||||
for range n {
|
||||
duration, size := d.duration, d.size
|
||||
e := b
|
||||
if flags&0x100 != 0 {
|
||||
duration, e = binary.BigEndian.Uint32(e), e[4:]
|
||||
}
|
||||
if flags&0x200 != 0 {
|
||||
size = binary.BigEndian.Uint32(e)
|
||||
}
|
||||
b = b[per:]
|
||||
t += int64(duration)
|
||||
a.Offsets = append(a.Offsets, at)
|
||||
a.Sizes = append(a.Sizes, size)
|
||||
a.Ends = append(a.Ends, t)
|
||||
at += int64(size)
|
||||
}
|
||||
return at, nil
|
||||
}
|
||||
+247
@@ -0,0 +1,247 @@
|
||||
package mp4
|
||||
|
||||
import (
|
||||
"encoding/binary"
|
||||
"errors"
|
||||
"io"
|
||||
"sort"
|
||||
)
|
||||
|
||||
// A decoder decodes a track's packets, whose places it knows from the
|
||||
// movie header's sample table or, of a fragmented file, from each
|
||||
// fragment's header as it reaches it. A seek goes to the packet holding the
|
||||
// frame asked for.
|
||||
type decoder struct {
|
||||
r io.ReaderAt
|
||||
codec Codec
|
||||
rate int
|
||||
offs []int64
|
||||
sizes []int
|
||||
ends []int64 // where each packet ends, in frames
|
||||
// last is where the last packet found ends, in frames, as the file
|
||||
// says, when ends places packets by the codec's PacketFrames instead;
|
||||
// 0 when ends is as the file says.
|
||||
last int64
|
||||
// more finds the next fragment's packets, and says if there were
|
||||
// any. Nil once all are found.
|
||||
more func() bool
|
||||
prime int64 // the encoder's priming, in frames, to drop
|
||||
frames int64 // the length, or -1 if unknown
|
||||
exact bool // whether it is: then what's past it is padding, dropped
|
||||
next int // the packet decoded next
|
||||
pos int64 // the frame Read returns next
|
||||
skip int64 // frames to drop before it
|
||||
packet []byte
|
||||
out []float32
|
||||
pend []float32
|
||||
}
|
||||
|
||||
func newDecoder(r io.ReaderAt, size int64) (*decoder, error) {
|
||||
t, err := readTrack(r, size, true)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
c, err := openCodec(t)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
d := &decoder{r: r, codec: c, rate: c.SampleRate(), frames: -1}
|
||||
if d.rate <= 0 {
|
||||
return nil, errors.New("mp4: no sample rate")
|
||||
}
|
||||
// In frames, from the track's timescale: most often the same.
|
||||
frames := func(v int64) int64 { return v * int64(d.rate) / t.Timescale }
|
||||
d.prime = frames(t.Prime)
|
||||
d.skip = d.prime
|
||||
if !t.Fragmented {
|
||||
for i := range t.Sizes {
|
||||
d.add(t.Offsets[i], int(t.Sizes[i]), frames(t.Ends[i]))
|
||||
}
|
||||
if len(d.ends) == 0 {
|
||||
return nil, errors.New("mp4: no packets")
|
||||
}
|
||||
d.frames, d.exact = d.length()-d.prime, true
|
||||
return d, nil
|
||||
}
|
||||
d.fragments(t, size, frames)
|
||||
if t.Duration > 0 {
|
||||
// From the segment index: the fragments are found as they play.
|
||||
d.frames = frames(t.Duration) - d.prime
|
||||
} else {
|
||||
for d.findMore() {
|
||||
}
|
||||
}
|
||||
if !d.have(0) {
|
||||
return nil, errors.New("mp4: no fragments")
|
||||
}
|
||||
return d, nil
|
||||
}
|
||||
|
||||
func (d *decoder) SampleRate() int { return d.rate }
|
||||
func (d *decoder) Channels() int { return 2 }
|
||||
func (d *decoder) Len() int64 { return d.frames }
|
||||
|
||||
// add adds a packet of size bytes at off, ending at end frames as the file
|
||||
// says.
|
||||
func (d *decoder) add(off int64, size int, end int64) {
|
||||
d.offs = append(d.offs, off)
|
||||
d.sizes = append(d.sizes, size)
|
||||
if n := d.codec.PacketFrames(); n > 0 {
|
||||
d.last = end
|
||||
end = int64(len(d.ends)+1) * int64(n)
|
||||
}
|
||||
d.ends = append(d.ends, end)
|
||||
}
|
||||
|
||||
// length is where the packets found end, in frames, as the file says.
|
||||
func (d *decoder) length() int64 {
|
||||
if d.last > 0 {
|
||||
return d.last
|
||||
}
|
||||
return d.ends[len(d.ends)-1]
|
||||
}
|
||||
|
||||
// packetStart is the frame packet i starts at.
|
||||
func (d *decoder) packetStart(i int) int64 {
|
||||
if i == 0 {
|
||||
return 0
|
||||
}
|
||||
return d.ends[i-1]
|
||||
}
|
||||
|
||||
// have says whether packet i is known, finding more if need be.
|
||||
func (d *decoder) have(i int) bool {
|
||||
for i >= len(d.offs) {
|
||||
if !d.findMore() {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// findMore finds the next fragment's packets, if there are any left to
|
||||
// find. Once all are found, the length is known.
|
||||
func (d *decoder) findMore() bool {
|
||||
if d.more == nil {
|
||||
return false
|
||||
}
|
||||
if d.more() {
|
||||
return true
|
||||
}
|
||||
d.more = nil
|
||||
if len(d.ends) > 0 {
|
||||
d.frames, d.exact = d.length()-d.prime, true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func (d *decoder) Read(dst []float32) (int, error) {
|
||||
for len(d.pend) == 0 {
|
||||
if !d.have(d.next) {
|
||||
return 0, io.EOF
|
||||
}
|
||||
if !d.exact {
|
||||
// Whether this is the last packet, whose padding is dropped:
|
||||
// the next fragment's are found, if any.
|
||||
d.have(d.next + 1)
|
||||
}
|
||||
size := d.sizes[d.next]
|
||||
if cap(d.packet) < size {
|
||||
d.packet = make([]byte, size)
|
||||
}
|
||||
d.packet = d.packet[:size]
|
||||
if _, err := d.r.ReadAt(d.packet, d.offs[d.next]); err != nil {
|
||||
if err == io.ErrUnexpectedEOF {
|
||||
err = io.EOF // cut short
|
||||
}
|
||||
return 0, err
|
||||
}
|
||||
d.next++
|
||||
out, err := d.codec.Decode(d.out[:0], d.packet)
|
||||
d.out = out
|
||||
if err != nil {
|
||||
continue // a packet gone bad: on to the next
|
||||
}
|
||||
drop := min(d.skip, int64(len(out)/2))
|
||||
d.skip -= drop
|
||||
d.pend = out[drop*2:]
|
||||
}
|
||||
n := copy(dst[:len(dst)/2*2], d.pend)
|
||||
if d.exact {
|
||||
// What the encoder padded the last packet with.
|
||||
n = int(min(int64(n), (d.frames-d.pos)*2))
|
||||
if n <= 0 {
|
||||
d.pend = nil
|
||||
return 0, io.EOF
|
||||
}
|
||||
}
|
||||
d.pend = d.pend[n:]
|
||||
d.pos += int64(n / 2)
|
||||
return n, nil
|
||||
}
|
||||
|
||||
// SetPosition goes to the packet holding frame, from those before it its
|
||||
// sound overlaps, and drops what comes before frame.
|
||||
func (d *decoder) SetPosition(frame int64) error {
|
||||
frame = max(frame, 0)
|
||||
if d.frames >= 0 {
|
||||
frame = min(frame, d.frames)
|
||||
}
|
||||
at := frame + d.prime
|
||||
for (len(d.ends) == 0 || d.ends[len(d.ends)-1] <= at) && d.findMore() {
|
||||
}
|
||||
i := sort.Search(len(d.ends), func(i int) bool { return d.ends[i] > at })
|
||||
start := max(0, i-d.codec.Preroll())
|
||||
d.codec.Reset()
|
||||
d.next, d.pos = start, frame
|
||||
d.skip = at - d.packetStart(start)
|
||||
d.pend = nil
|
||||
return nil
|
||||
}
|
||||
|
||||
// fragments has the decoder find a fragmented file's packets as it needs
|
||||
// them, a fragment at a time, walking the boxes after the movie header.
|
||||
func (d *decoder) fragments(t *track, size int64, frames func(int64) int64) {
|
||||
off := t.Next
|
||||
var h [16]byte
|
||||
d.more = func() bool {
|
||||
for off+8 <= size {
|
||||
if _, err := d.r.ReadAt(h[:8], off); err != nil {
|
||||
return false
|
||||
}
|
||||
n, head := int64(binary.BigEndian.Uint32(h[:])), int64(8)
|
||||
if n == 1 {
|
||||
if _, err := d.r.ReadAt(h[8:], off+8); err != nil {
|
||||
return false
|
||||
}
|
||||
n, head = int64(binary.BigEndian.Uint64(h[8:])), 16
|
||||
}
|
||||
if n < head {
|
||||
return false // to the end, or broken: no more fragments
|
||||
}
|
||||
at := off
|
||||
off += n
|
||||
if string(h[4:8]) != "moof" {
|
||||
continue
|
||||
}
|
||||
if n > 16<<20 {
|
||||
return false
|
||||
}
|
||||
moof := make([]byte, n-head)
|
||||
if _, err := d.r.ReadAt(moof, at+head); err != nil {
|
||||
return false
|
||||
}
|
||||
found := len(t.Sizes)
|
||||
if err := t.fragment(moof, at); err != nil {
|
||||
return false
|
||||
}
|
||||
for i := found; i < len(t.Sizes); i++ {
|
||||
d.add(t.Offsets[i], int(t.Sizes[i]), frames(t.Ends[i]))
|
||||
}
|
||||
if len(t.Sizes) > found {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
}
|
||||
Vendored
+147
@@ -0,0 +1,147 @@
|
||||
// Package mp4 decodes the sound of MP4 files for package audio: .m4a and
|
||||
// .mp4, whole or cut into fragments as a stream for DASH is (.m4s). It
|
||||
// reads the container, and a codec registered with RegisterCodec decodes
|
||||
// its packets. Apple Lossless (ALAC) is built in; import package
|
||||
// audio/aac for AAC, and audio/flac for FLAC in MP4:
|
||||
//
|
||||
// import (
|
||||
// _ "github.com/egoist/mygo/audio/aac" // AAC, in MP4 too
|
||||
// _ "github.com/egoist/mygo/audio/flac" // FLAC, in MP4 too
|
||||
// )
|
||||
//
|
||||
// Each imports this package, which registers the format with package
|
||||
// audio.
|
||||
package mp4
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"io"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/egoist/mygo/audio"
|
||||
)
|
||||
|
||||
func init() {
|
||||
audio.RegisterFormat("mp4", "????ftyp", func(r io.ReadSeeker) (audio.Decoder, error) { return NewDecoder(r) })
|
||||
RegisterCodec("alac", func(config []byte) (Codec, error) { return newALACDecoder(config) })
|
||||
}
|
||||
|
||||
// A Codec decodes the packets of a track, one at a time, to stereo.
|
||||
type Codec interface {
|
||||
// SampleRate returns the frames per second it decodes to.
|
||||
SampleRate() int
|
||||
// Decode appends the sound of a packet to dst, as interleaved left
|
||||
// and right samples in [-1, 1], and returns it. A mono track plays in
|
||||
// both; of more channels, the front left and right play.
|
||||
Decode(dst []float32, packet []byte) ([]float32, error)
|
||||
// Reset forgets the packets decoded before, as after a seek.
|
||||
Reset()
|
||||
// Preroll returns how many packets before the one holding a frame
|
||||
// sought to are decoded first, for codecs whose packets overlap the
|
||||
// sound of the one before, as AAC's (1); 0 when packets stand alone.
|
||||
Preroll() int
|
||||
// PacketFrames returns how many frames every packet decodes to, when
|
||||
// all do, as AAC's 1024: packets are then placed in time by counting
|
||||
// them, whatever the file says they last. 0 places them as the file
|
||||
// says, for codecs whose packets differ.
|
||||
PacketFrames() int
|
||||
}
|
||||
|
||||
var (
|
||||
codecsMu sync.Mutex
|
||||
codecs = map[string]func([]byte) (Codec, error){}
|
||||
)
|
||||
|
||||
// RegisterCodec registers the codec of tracks whose sample entry is of
|
||||
// type fourcc, as "mp4a": open returns a decoder of its packets from the
|
||||
// track's configuration (see Track's Config). A package for a codec calls
|
||||
// it in its init function.
|
||||
func RegisterCodec(fourcc string, open func(config []byte) (Codec, error)) {
|
||||
codecsMu.Lock()
|
||||
defer codecsMu.Unlock()
|
||||
codecs[fourcc] = open
|
||||
}
|
||||
|
||||
func openCodec(t *track) (Codec, error) {
|
||||
codecsMu.Lock()
|
||||
open := codecs[t.Codec]
|
||||
codecsMu.Unlock()
|
||||
if open == nil {
|
||||
return nil, errors.New("mp4: no codec registered for " + t.Codec)
|
||||
}
|
||||
return open(t.Config)
|
||||
}
|
||||
|
||||
// Track describes an MP4's sound track, as its movie header says, for an
|
||||
// app to know of a file without decoding it, as a music library scanning
|
||||
// files does.
|
||||
type Track struct {
|
||||
// Codec is the type of the track's sample entry: "mp4a" (AAC),
|
||||
// "alac", "fLaC", "Opus", ...
|
||||
Codec string
|
||||
// Config configures the codec: AAC's AudioSpecificConfig, ALAC's
|
||||
// magic cookie, FLAC's metadata blocks, or another codec's boxes
|
||||
// within the sample entry.
|
||||
Config []byte
|
||||
// Duration is how long it plays, without the encoder's priming, or 0
|
||||
// for a fragmented file whose length its header doesn't say.
|
||||
Duration time.Duration
|
||||
// Fragmented says its packets are in fragments after the movie header.
|
||||
Fragmented bool
|
||||
}
|
||||
|
||||
// ReadTrack reads the first sound track of the MP4 file r holds, of size
|
||||
// bytes, from its movie header.
|
||||
func ReadTrack(r io.ReaderAt, size int64) (*Track, error) {
|
||||
t, err := readTrack(r, size, false)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &Track{
|
||||
Codec: t.Codec,
|
||||
Config: t.Config,
|
||||
Duration: time.Duration(max(t.Duration-t.Prime, 0) * int64(time.Second) / t.Timescale),
|
||||
Fragmented: t.Fragmented,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// Decodable says whether a codec registered decodes the track: HE-AAC, for
|
||||
// one, package aac does not.
|
||||
func (t *Track) Decodable() bool {
|
||||
_, err := openCodec(&track{Codec: t.Codec, Config: t.Config})
|
||||
return err == nil
|
||||
}
|
||||
|
||||
// NewDecoder returns a decoder of the first sound track of the MP4 file r
|
||||
// holds, which decodes to stereo. It reads the movie header, and the
|
||||
// packets as they are played, so a file still coming in plays as it comes
|
||||
// when r waits for the bytes asked of it: a fragmented one, a fragment at
|
||||
// a time, with its length from its segment index. One with no index is
|
||||
// read through for its length.
|
||||
func NewDecoder(r io.ReadSeeker) (audio.Decoder, error) {
|
||||
size, err := r.Seek(0, io.SeekEnd)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
ra, ok := r.(io.ReaderAt)
|
||||
if !ok {
|
||||
ra = &readerAt{r: r}
|
||||
}
|
||||
return newDecoder(ra, size)
|
||||
}
|
||||
|
||||
// readerAt reads at offsets of a ReadSeeker, seeking.
|
||||
type readerAt struct {
|
||||
mu sync.Mutex
|
||||
r io.ReadSeeker
|
||||
}
|
||||
|
||||
func (r *readerAt) ReadAt(b []byte, off int64) (int, error) {
|
||||
r.mu.Lock()
|
||||
defer r.mu.Unlock()
|
||||
if _, err := r.r.Seek(off, io.SeekStart); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return io.ReadFull(r.r, b)
|
||||
}
|
||||
+120
@@ -0,0 +1,120 @@
|
||||
package mp4_test
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"errors"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
_ "github.com/egoist/mygo/audio/flac"
|
||||
"github.com/egoist/mygo/audio/internal/audiotest"
|
||||
"github.com/egoist/mygo/audio/mp4"
|
||||
)
|
||||
|
||||
// alac.m4a is the first second of ../flac/testdata/tone.flac in Apple
|
||||
// Lossless: it decodes to exactly those samples, and a seek lands on the
|
||||
// very frame asked for.
|
||||
func TestALAC(t *testing.T) {
|
||||
b := audiotest.Read(t, "testdata/alac.m4a")
|
||||
tr, err := mp4.ReadTrack(bytes.NewReader(b), int64(len(b)))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if tr.Codec != "alac" || tr.Duration != time.Second || tr.Fragmented || !tr.Decodable() {
|
||||
t.Fatalf("%+v", tr)
|
||||
}
|
||||
d := audiotest.Open(t, b, "mp4")
|
||||
if d.SampleRate() != 44100 || d.Channels() != 2 || d.Len() != 44100 {
|
||||
t.Fatalf("%d Hz, %d channels, %d frames", d.SampleRate(), d.Channels(), d.Len())
|
||||
}
|
||||
got := audiotest.ReadAll(t, d)
|
||||
want := audiotest.ReadAll(t, audiotest.Open(t, audiotest.Read(t, "../flac/testdata/tone.flac"), "flac"))
|
||||
if len(got) != 44100*2 || audiotest.MaxDiff(got, want) != 0 {
|
||||
t.Fatalf("decoded %d samples, off from the FLAC by up to %g", len(got), audiotest.MaxDiff(got, want))
|
||||
}
|
||||
audiotest.SeekLands(t, d, got, 0, 0, 1, 4095, 4096, 30000, 44099)
|
||||
}
|
||||
|
||||
// A track of a codec none registered is described, and fails to decode:
|
||||
// this test doesn't import package aac.
|
||||
func TestNoCodec(t *testing.T) {
|
||||
b := audiotest.Read(t, "../aac/testdata/tone.m4a")
|
||||
tr, err := mp4.ReadTrack(bytes.NewReader(b), int64(len(b)))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if tr.Codec != "mp4a" || len(tr.Config) < 2 || tr.Duration != 2*time.Second || tr.Decodable() {
|
||||
t.Fatalf("%+v", tr)
|
||||
}
|
||||
if _, err := mp4.NewDecoder(bytes.NewReader(b)); err == nil {
|
||||
t.Fatal("decoded AAC with no codec for it")
|
||||
}
|
||||
}
|
||||
|
||||
// coming reads a file of which only the first n bytes are in, as one
|
||||
// still downloading, failing to read past them.
|
||||
type coming struct {
|
||||
*bytes.Reader
|
||||
n int64
|
||||
}
|
||||
|
||||
var errNotYet = errors.New("not in yet")
|
||||
|
||||
func (c *coming) ReadAt(b []byte, off int64) (int, error) {
|
||||
if off+int64(len(b)) > c.n {
|
||||
return 0, errNotYet
|
||||
}
|
||||
return c.Reader.ReadAt(b, off)
|
||||
}
|
||||
|
||||
// A fragmented MP4 plays with only its first fragment in, its length from
|
||||
// its segment index: the fragments after are read as it plays them.
|
||||
func TestFragmentedComingIn(t *testing.T) {
|
||||
b := audiotest.Read(t, "../flac/testdata/fragmented.m4a")
|
||||
r := &coming{bytes.NewReader(b), 16 << 10}
|
||||
tr, err := mp4.ReadTrack(r, int64(len(b)))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !tr.Fragmented || tr.Duration != 2*time.Second {
|
||||
t.Fatalf("%+v", tr)
|
||||
}
|
||||
d, err := mp4.NewDecoder(r)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if d.Len() != 88200 {
|
||||
t.Fatalf("length %d", d.Len())
|
||||
}
|
||||
buf := make([]float32, 2*4096)
|
||||
if n, err := d.Read(buf); n != len(buf) || err != nil {
|
||||
t.Fatalf("read %d samples: %v", n, err)
|
||||
}
|
||||
// Then the rest comes in.
|
||||
r.n = int64(len(b))
|
||||
got := append(buf, audiotest.ReadAll(t, d)...)
|
||||
if len(got) != 88200*2 {
|
||||
t.Fatalf("decoded %d samples", len(got))
|
||||
}
|
||||
}
|
||||
|
||||
// A fragmented MP4 with no segment index is read through for its length.
|
||||
func TestFragmentedNoIndex(t *testing.T) {
|
||||
b := bytes.Clone(audiotest.Read(t, "../flac/testdata/fragmented.m4a"))
|
||||
at := bytes.Index(b, []byte("sidx"))
|
||||
copy(b[at:], "free")
|
||||
d := audiotest.Open(t, b, "mp4")
|
||||
if d.Len() != 88200 {
|
||||
t.Fatalf("length %d", d.Len())
|
||||
}
|
||||
}
|
||||
|
||||
func TestNotMP4(t *testing.T) {
|
||||
_, err := mp4.NewDecoder(bytes.NewReader([]byte("\x00\x00\x00\x10ftypM4A \x00\x00\x00\x00")))
|
||||
if err == nil {
|
||||
t.Fatal("decoded an MP4 with no movie header")
|
||||
}
|
||||
if _, err := mp4.NewDecoder(bytes.NewReader(nil)); err == nil {
|
||||
t.Fatal("decoded nothing")
|
||||
}
|
||||
}
|
||||
BIN
Binary file not shown.
Vendored
+144
@@ -0,0 +1,144 @@
|
||||
package audio
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"runtime"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
// A device is the system's audio output, opened by openDevice to hold
|
||||
// about ahead of what is heard.
|
||||
type device interface {
|
||||
// write plays interleaved stereo frames after those written before,
|
||||
// waiting while the device holds enough already. An error closes the
|
||||
// device, and the output opens it again.
|
||||
write(samples []float32) error
|
||||
close()
|
||||
}
|
||||
|
||||
// idleClose is how long the output stays open with nothing playing.
|
||||
const idleClose = 5 * time.Second
|
||||
|
||||
var (
|
||||
openOutput = openDevice // tests replace it
|
||||
|
||||
wake = make(chan struct{}, 1)
|
||||
runOnce sync.Once
|
||||
testMode bool // tests mix by hand
|
||||
)
|
||||
|
||||
// wakeOutput starts the output, or tells it a voice started. The caller
|
||||
// holds mu.
|
||||
func wakeOutput() {
|
||||
if testMode {
|
||||
return
|
||||
}
|
||||
runOnce.Do(func() { go run() })
|
||||
select {
|
||||
case wake <- struct{}{}:
|
||||
default:
|
||||
}
|
||||
}
|
||||
|
||||
func active() bool {
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
return len(voices) > 0 && !testMode
|
||||
}
|
||||
|
||||
// mixFor mixes into buf for an output open at latency lat, and reports
|
||||
// whether anything plays; ok is false, and it mixes nothing, once tests
|
||||
// mix by hand or the latency changed.
|
||||
func mixFor(buf []float32, lat Latency) (busy, ok bool) {
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
if testMode || latency != lat {
|
||||
return false, false
|
||||
}
|
||||
return mixLocked(buf), true
|
||||
}
|
||||
|
||||
// run opens the device while anything plays, and mixes into it.
|
||||
func run() {
|
||||
for {
|
||||
for !active() {
|
||||
<-wake
|
||||
}
|
||||
lat := outputLatency()
|
||||
dev, n, err := openOutput(lat.ahead())
|
||||
if err != nil {
|
||||
setErr(err)
|
||||
dev, n = newNullDevice(err != errUnsupported), nullFrames
|
||||
// It holds nothing: what it takes is heard as it takes it.
|
||||
setHeld(0)
|
||||
} else {
|
||||
setErr(nil)
|
||||
setHeld(int64(lat.ahead() * sampleRate / time.Second))
|
||||
}
|
||||
buf := make([]float32, n*channels)
|
||||
idle := time.Duration(0)
|
||||
per := frames(int64(n), sampleRate)
|
||||
for {
|
||||
busy, ok := mixFor(buf, lat)
|
||||
if !ok {
|
||||
break
|
||||
}
|
||||
// write blocks in C, keeping the P, which the runtime would
|
||||
// take back every 10 ms, waking more often after.
|
||||
runtime.Gosched()
|
||||
if err := dev.write(buf); err != nil {
|
||||
// Lost, or a null device trying the real one again.
|
||||
break
|
||||
}
|
||||
if busy {
|
||||
idle = 0
|
||||
} else if idle += per; idle >= idleClose {
|
||||
break
|
||||
}
|
||||
}
|
||||
dev.close()
|
||||
}
|
||||
}
|
||||
|
||||
var errUnsupported = errors.New("audio: no audio output on this platform")
|
||||
|
||||
// nullFrames is how many frames a null device takes at a time: 10 ms.
|
||||
const nullFrames = sampleRate / 100
|
||||
|
||||
// A nullDevice plays nothing, on time: players still end when they would
|
||||
// have. One standing in for a device that failed to open fails after a
|
||||
// while, so that the output tries the device again.
|
||||
type nullDevice struct {
|
||||
next time.Time
|
||||
retry time.Time
|
||||
// now and sleep are its clock, which tests replace.
|
||||
now func() time.Time
|
||||
sleep func(time.Duration)
|
||||
}
|
||||
|
||||
func newNullDevice(retry bool) *nullDevice {
|
||||
d := &nullDevice{next: time.Now(), now: time.Now, sleep: time.Sleep}
|
||||
if retry {
|
||||
d.retry = d.next.Add(2 * time.Second)
|
||||
}
|
||||
return d
|
||||
}
|
||||
|
||||
var errRetry = errors.New("audio: try the device again")
|
||||
|
||||
func (d *nullDevice) write(samples []float32) error {
|
||||
now := d.now()
|
||||
if !d.retry.IsZero() && now.After(d.retry) {
|
||||
return errRetry
|
||||
}
|
||||
if now.Sub(d.next) > 100*time.Millisecond {
|
||||
// Behind, as after a sleep: don't hurry to catch up.
|
||||
d.next = now
|
||||
}
|
||||
d.next = d.next.Add(frames(int64(len(samples)/channels), sampleRate))
|
||||
d.sleep(d.next.Sub(d.now()))
|
||||
return nil
|
||||
}
|
||||
|
||||
func (d *nullDevice) close() {}
|
||||
+169
@@ -0,0 +1,169 @@
|
||||
//go:build !ios
|
||||
|
||||
package audio
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"sync"
|
||||
"time"
|
||||
"unsafe"
|
||||
|
||||
"github.com/ebitengine/purego"
|
||||
)
|
||||
|
||||
// macOS plays through an Audio Queue on the default output, which follows
|
||||
// it when it changes.
|
||||
|
||||
type audioStreamBasicDescription struct {
|
||||
sampleRate float64
|
||||
formatID uint32
|
||||
formatFlags uint32
|
||||
bytesPerPacket uint32
|
||||
framesPerPacket uint32
|
||||
bytesPerFrame uint32
|
||||
channelsPerFrame uint32
|
||||
bitsPerChannel uint32
|
||||
reserved uint32
|
||||
}
|
||||
|
||||
type audioQueueBuffer struct {
|
||||
audioDataBytesCapacity uint32
|
||||
audioData unsafe.Pointer
|
||||
audioDataByteSize uint32
|
||||
userData uintptr
|
||||
packetDescCapacity uint32
|
||||
packetDescs uintptr
|
||||
packetDescCount uint32
|
||||
}
|
||||
|
||||
const (
|
||||
kAudioFormatLinearPCM = 0x6C70636D // 'lpcm'
|
||||
kAudioFormatFlagIsFloat = 1
|
||||
aqFrames = 512 // per buffer: 10.7 ms, as many as hold ahead
|
||||
dispatchTimeNow = 0
|
||||
)
|
||||
|
||||
var (
|
||||
aqLoad sync.Once
|
||||
aqErr error
|
||||
|
||||
audioQueueNewOutput func(format *audioStreamBasicDescription, callback uintptr, user uintptr, runLoop, runLoopMode uintptr, flags uint32, out *uintptr) int32
|
||||
audioQueueAllocateBuffer func(q uintptr, size uint32, out **audioQueueBuffer) int32
|
||||
audioQueueStart func(q uintptr, at uintptr) int32
|
||||
audioQueueStop func(q uintptr, immediate bool) int32
|
||||
audioQueueDispose func(q uintptr, immediate bool) int32
|
||||
dispatchSemaphoreCreate func(value int) uintptr
|
||||
dispatchRelease func(obj uintptr)
|
||||
|
||||
// Called on every buffer, through a cCaller.
|
||||
audioQueueEnqueueBuffer uintptr
|
||||
dispatchSemaphoreWait uintptr
|
||||
dispatchTime uintptr
|
||||
|
||||
dispatchSemaphoreSignal uintptr // every queue's callback
|
||||
)
|
||||
|
||||
func loadAudioToolbox() error {
|
||||
aqLoad.Do(func() {
|
||||
lib, err := purego.Dlopen("/System/Library/Frameworks/AudioToolbox.framework/AudioToolbox", purego.RTLD_LAZY|purego.RTLD_GLOBAL)
|
||||
if err != nil {
|
||||
aqErr = err
|
||||
return
|
||||
}
|
||||
purego.RegisterLibFunc(&audioQueueNewOutput, lib, "AudioQueueNewOutput")
|
||||
purego.RegisterLibFunc(&audioQueueAllocateBuffer, lib, "AudioQueueAllocateBuffer")
|
||||
purego.RegisterLibFunc(&audioQueueStart, lib, "AudioQueueStart")
|
||||
purego.RegisterLibFunc(&audioQueueStop, lib, "AudioQueueStop")
|
||||
purego.RegisterLibFunc(&audioQueueDispose, lib, "AudioQueueDispose")
|
||||
purego.RegisterLibFunc(&dispatchSemaphoreCreate, purego.RTLD_DEFAULT, "dispatch_semaphore_create")
|
||||
purego.RegisterLibFunc(&dispatchRelease, purego.RTLD_DEFAULT, "dispatch_release")
|
||||
audioQueueEnqueueBuffer = cFunc(lib, "AudioQueueEnqueueBuffer")
|
||||
dispatchSemaphoreWait = cFunc(purego.RTLD_DEFAULT, "dispatch_semaphore_wait")
|
||||
dispatchSemaphoreSignal = cFunc(purego.RTLD_DEFAULT, "dispatch_semaphore_signal")
|
||||
dispatchTime = cFunc(purego.RTLD_DEFAULT, "dispatch_time")
|
||||
})
|
||||
return aqErr
|
||||
}
|
||||
|
||||
// An aqDevice is an Audio Queue whose callback is
|
||||
// dispatch_semaphore_signal, its semaphore the user data (C on arm64 and
|
||||
// x86-64 ignores the queue and buffer passed after it), so no Go runs on
|
||||
// the queue's thread. The queue plays buffers in order: each signal frees
|
||||
// the oldest.
|
||||
type aqDevice struct {
|
||||
q uintptr
|
||||
sema uintptr
|
||||
bufs []*audioQueueBuffer
|
||||
next int // the buffer written next, the oldest enqueued once all are
|
||||
queued int // buffers enqueued before the queue started
|
||||
started bool
|
||||
c cCaller
|
||||
}
|
||||
|
||||
func openDevice(ahead time.Duration) (device, int, error) {
|
||||
if err := loadAudioToolbox(); err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
desc := audioStreamBasicDescription{
|
||||
sampleRate: sampleRate,
|
||||
formatID: kAudioFormatLinearPCM,
|
||||
formatFlags: kAudioFormatFlagIsFloat,
|
||||
bytesPerPacket: channels * 4,
|
||||
framesPerPacket: 1,
|
||||
bytesPerFrame: channels * 4,
|
||||
channelsPerFrame: channels,
|
||||
bitsPerChannel: 32,
|
||||
}
|
||||
n := max(2, int((int64(ahead)*sampleRate/int64(time.Second)+aqFrames-1)/aqFrames))
|
||||
// Fails only for a negative value.
|
||||
d := &aqDevice{sema: dispatchSemaphoreCreate(0), bufs: make([]*audioQueueBuffer, n)}
|
||||
if st := audioQueueNewOutput(&desc, dispatchSemaphoreSignal, d.sema, 0, 0, 0, &d.q); st != 0 {
|
||||
dispatchRelease(d.sema)
|
||||
return nil, 0, fmt.Errorf("audio: AudioQueueNewOutput failed (OSStatus %d)", st)
|
||||
}
|
||||
for i := range d.bufs {
|
||||
if st := audioQueueAllocateBuffer(d.q, aqFrames*channels*4, &d.bufs[i]); st != 0 {
|
||||
d.close()
|
||||
return nil, 0, fmt.Errorf("audio: AudioQueueAllocateBuffer failed (OSStatus %d)", st)
|
||||
}
|
||||
}
|
||||
return d, aqFrames, nil
|
||||
}
|
||||
|
||||
func (d *aqDevice) write(samples []float32) error {
|
||||
if d.started {
|
||||
// Wait for the oldest buffer to play.
|
||||
deadline := d.c.call(dispatchTime, dispatchTimeNow, uintptr(time.Second))
|
||||
if d.c.call(dispatchSemaphoreWait, d.sema, deadline) != 0 {
|
||||
// The queue stopped taking buffers, as when its device went.
|
||||
return fmt.Errorf("audio: the audio queue stopped")
|
||||
}
|
||||
}
|
||||
b := d.bufs[d.next]
|
||||
d.next = (d.next + 1) % len(d.bufs)
|
||||
copy(unsafe.Slice((*float32)(b.audioData), len(samples)), samples)
|
||||
b.audioDataByteSize = uint32(len(samples) * 4)
|
||||
// b is C memory, as a cCaller needs.
|
||||
if st := int32(d.c.call(audioQueueEnqueueBuffer, d.q, uintptr(unsafe.Pointer(b)), 0, 0)); st != 0 {
|
||||
return fmt.Errorf("audio: AudioQueueEnqueueBuffer failed (OSStatus %d)", st)
|
||||
}
|
||||
if !d.started {
|
||||
// Start once every buffer holds something, not to begin with an
|
||||
// underrun.
|
||||
if d.queued++; d.queued == len(d.bufs) {
|
||||
if st := audioQueueStart(d.q, 0); st != 0 {
|
||||
return fmt.Errorf("audio: AudioQueueStart failed (OSStatus %d)", st)
|
||||
}
|
||||
d.started = true
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (d *aqDevice) close() {
|
||||
// Synchronous: no callback runs once it returns.
|
||||
audioQueueStop(d.q, true)
|
||||
audioQueueDispose(d.q, true)
|
||||
// Never below its initial value, which dispatch_release requires.
|
||||
dispatchRelease(d.sema)
|
||||
}
|
||||
Vendored
+183
@@ -0,0 +1,183 @@
|
||||
package audio
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"syscall/js"
|
||||
"time"
|
||||
"unsafe"
|
||||
)
|
||||
|
||||
// Browsers play through an AudioWorklet, which asks the page for a chunk
|
||||
// whenever it used one up. One AudioContext serves the page for its life:
|
||||
// closing the output suspends it. Pages may start audio only after the
|
||||
// user interacted with them, so it resumes on the first input too.
|
||||
|
||||
const (
|
||||
jsFrames = 1024 // per chunk: 21 ms
|
||||
jsChunks = 3 // queued in the worklet to begin with, and at least
|
||||
)
|
||||
|
||||
const worklet = `
|
||||
class MyGoOutput extends AudioWorkletProcessor {
|
||||
constructor() {
|
||||
super();
|
||||
this.queue = [];
|
||||
this.offset = 0;
|
||||
this.port.onmessage = (e) => this.queue.push(e.data);
|
||||
for (let i = 0; i < %d; i++) this.port.postMessage(0);
|
||||
}
|
||||
process(inputs, outputs) {
|
||||
const left = outputs[0][0], right = outputs[0][1];
|
||||
let i = 0;
|
||||
while (i < left.length) {
|
||||
const chunk = this.queue[0];
|
||||
if (!chunk) {
|
||||
left.fill(0, i);
|
||||
right.fill(0, i);
|
||||
break;
|
||||
}
|
||||
const n = Math.min(left.length - i, chunk.length / 2 - this.offset);
|
||||
for (let j = 0; j < n; j++) {
|
||||
left[i + j] = chunk[2 * (this.offset + j)];
|
||||
right[i + j] = chunk[2 * (this.offset + j) + 1];
|
||||
}
|
||||
i += n;
|
||||
this.offset += n;
|
||||
if (this.offset * 2 >= chunk.length) {
|
||||
this.queue.shift();
|
||||
this.offset = 0;
|
||||
this.port.postMessage(0);
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
}
|
||||
registerProcessor("mygo-output", MyGoOutput);
|
||||
`
|
||||
|
||||
var (
|
||||
jsContext js.Value
|
||||
jsPort js.Value
|
||||
jsCredits = make(chan struct{}, 32)
|
||||
jsErr error
|
||||
|
||||
// jsAhead is how many chunks are queued in the worklet or asked for,
|
||||
// and jsOwed how many it asks for that are to go unanswered, as the
|
||||
// output holds less than it did.
|
||||
jsAhead = jsChunks
|
||||
jsOwed int
|
||||
)
|
||||
|
||||
// jsSetup creates the page's AudioContext and its worklet, once: the
|
||||
// context keeps the latency it began with, the worklet's queue follows
|
||||
// the latency set since.
|
||||
func jsSetup(ahead time.Duration) error {
|
||||
if !jsContext.IsUndefined() || jsErr != nil {
|
||||
return jsErr
|
||||
}
|
||||
class := js.Global().Get("AudioContext")
|
||||
if !class.Truthy() {
|
||||
jsErr = errors.New("audio: this browser has no AudioContext")
|
||||
return jsErr
|
||||
}
|
||||
hint := "interactive"
|
||||
if ahead >= LatencyPlayback.ahead() {
|
||||
hint = "playback"
|
||||
}
|
||||
ctx := class.New(map[string]any{"sampleRate": sampleRate, "latencyHint": hint})
|
||||
if !ctx.Get("audioWorklet").Truthy() {
|
||||
jsErr = errors.New("audio: this browser has no AudioWorklet")
|
||||
return jsErr
|
||||
}
|
||||
blob := js.Global().Get("Blob").New([]any{fmt.Sprintf(worklet, jsChunks)}, map[string]any{"type": "text/javascript"})
|
||||
url := js.Global().Get("URL").Call("createObjectURL", blob)
|
||||
done := make(chan error, 1)
|
||||
var ok, fail js.Func
|
||||
ok = js.FuncOf(func(this js.Value, args []js.Value) any {
|
||||
done <- nil
|
||||
return nil
|
||||
})
|
||||
fail = js.FuncOf(func(this js.Value, args []js.Value) any {
|
||||
done <- fmt.Errorf("audio: loading the AudioWorklet failed: %s", js.Global().Get("String").Invoke(args[0]).String())
|
||||
return nil
|
||||
})
|
||||
ctx.Get("audioWorklet").Call("addModule", url).Call("then", ok, fail)
|
||||
err := <-done
|
||||
ok.Release()
|
||||
fail.Release()
|
||||
js.Global().Get("URL").Call("revokeObjectURL", url)
|
||||
if err != nil {
|
||||
jsErr = err
|
||||
return err
|
||||
}
|
||||
node := js.Global().Get("AudioWorkletNode").New(ctx, "mygo-output", map[string]any{
|
||||
"numberOfInputs": 0,
|
||||
"outputChannelCount": []any{channels},
|
||||
})
|
||||
node.Call("connect", ctx.Get("destination"))
|
||||
jsPort = node.Get("port")
|
||||
jsPort.Set("onmessage", js.FuncOf(func(this js.Value, args []js.Value) any {
|
||||
select {
|
||||
case jsCredits <- struct{}{}:
|
||||
default:
|
||||
}
|
||||
return nil
|
||||
}))
|
||||
// The first input lets a page start audio.
|
||||
resume := js.FuncOf(func(this js.Value, args []js.Value) any {
|
||||
if jsContext.Get("state").String() == "suspended" && jsOpen {
|
||||
jsContext.Call("resume")
|
||||
}
|
||||
return nil
|
||||
})
|
||||
for _, ev := range []string{"pointerdown", "keydown", "touchend"} {
|
||||
js.Global().Call("addEventListener", ev, resume, map[string]any{"capture": true})
|
||||
}
|
||||
jsContext = ctx
|
||||
return nil
|
||||
}
|
||||
|
||||
// jsOpen is whether the output is open, which keeps the context running.
|
||||
var jsOpen bool
|
||||
|
||||
type jsDevice struct{}
|
||||
|
||||
func openDevice(ahead time.Duration) (device, int, error) {
|
||||
if err := jsSetup(ahead); err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
want := max(jsChunks, int((int64(ahead)*sampleRate/int64(time.Second)+jsFrames-1)/jsFrames))
|
||||
if more := want - jsAhead; more > 0 {
|
||||
// Asks the owed ones answer first.
|
||||
cancel := min(jsOwed, more)
|
||||
jsOwed -= cancel
|
||||
for range more - cancel {
|
||||
jsCredits <- struct{}{}
|
||||
}
|
||||
} else {
|
||||
jsOwed -= more
|
||||
}
|
||||
jsAhead = want
|
||||
jsOpen = true
|
||||
jsContext.Call("resume")
|
||||
return jsDevice{}, jsFrames, nil
|
||||
}
|
||||
|
||||
func (jsDevice) write(samples []float32) error {
|
||||
// A suspended context, until an input lets the page play, asks for
|
||||
// nothing: the output waits without mixing ahead.
|
||||
for ; jsOwed > 0; jsOwed-- {
|
||||
<-jsCredits
|
||||
}
|
||||
<-jsCredits
|
||||
a := js.Global().Get("Float32Array").New(len(samples))
|
||||
js.CopyBytesToJS(js.Global().Get("Uint8Array").New(a.Get("buffer")), unsafe.Slice((*byte)(unsafe.Pointer(&samples[0])), len(samples)*4))
|
||||
jsPort.Call("postMessage", a, []any{a.Get("buffer")})
|
||||
return nil
|
||||
}
|
||||
|
||||
func (jsDevice) close() {
|
||||
jsOpen = false
|
||||
jsContext.Call("suspend")
|
||||
}
|
||||
+190
@@ -0,0 +1,190 @@
|
||||
//go:build linux && !android && (amd64 || arm64) && !android
|
||||
|
||||
package audio
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"sync"
|
||||
"time"
|
||||
"unsafe"
|
||||
|
||||
"github.com/ebitengine/purego"
|
||||
)
|
||||
|
||||
// Linux plays through PulseAudio's simple API, which PipeWire serves as
|
||||
// well, or else ALSA's default device. Both block while the device holds
|
||||
// enough, from the output's goroutine.
|
||||
|
||||
const linuxFrames = sampleRate / 100 // per write: 10 ms
|
||||
|
||||
var (
|
||||
pulseLoad sync.Once
|
||||
pulseErr error
|
||||
|
||||
paSimpleNew func(server, name *byte, dir int32, dev, stream *byte, spec *paSampleSpec, chmap, attr unsafe.Pointer, err *int32) uintptr
|
||||
paSimpleWrite uintptr // through a cCaller, on every write
|
||||
paSimpleFree func(s uintptr)
|
||||
paStrerror func(err int32) string
|
||||
|
||||
alsaLoad sync.Once
|
||||
alsaErr error
|
||||
|
||||
sndPcmOpen func(pcm *uintptr, name *byte, stream int32, mode int32) int32
|
||||
sndPcmSetParams func(pcm uintptr, format, access int32, channels, rate uint32, softResample int32, latency uint32) int32
|
||||
sndPcmWritei uintptr // through a cCaller, on every write
|
||||
sndPcmRecover func(pcm uintptr, err int32, silent int32) int32
|
||||
sndPcmClose func(pcm uintptr) int32
|
||||
sndStrerror func(err int32) string
|
||||
)
|
||||
|
||||
type paSampleSpec struct {
|
||||
format int32
|
||||
rate uint32
|
||||
channels uint8
|
||||
}
|
||||
|
||||
type paBufferAttr struct {
|
||||
maxLength, tLength, preBuf, minReq, fragSize uint32
|
||||
}
|
||||
|
||||
const (
|
||||
paStreamPlayback = 1
|
||||
paSampleFloat32LE = 5
|
||||
|
||||
sndPcmStreamPlayback = 0
|
||||
sndPcmFormatFloatLE = 14
|
||||
sndPcmAccessRWInterleaved = 3
|
||||
)
|
||||
|
||||
func cstr(s string) *byte {
|
||||
b := append([]byte(s), 0)
|
||||
return &b[0]
|
||||
}
|
||||
|
||||
func appName() string {
|
||||
if exe, err := os.Executable(); err == nil {
|
||||
return filepath.Base(exe)
|
||||
}
|
||||
return "mygo"
|
||||
}
|
||||
|
||||
func openDevice(ahead time.Duration) (device, int, error) {
|
||||
d, perr := openPulse(ahead)
|
||||
if perr == nil {
|
||||
return d, linuxFrames, nil
|
||||
}
|
||||
d, aerr := openALSA(ahead)
|
||||
if aerr == nil {
|
||||
return d, linuxFrames, nil
|
||||
}
|
||||
return nil, 0, errors.Join(perr, aerr)
|
||||
}
|
||||
|
||||
type pulseDevice struct {
|
||||
s uintptr
|
||||
code int32 // pa_simple_write's error
|
||||
c cCaller
|
||||
}
|
||||
|
||||
func openPulse(ahead time.Duration) (device, error) {
|
||||
pulseLoad.Do(func() {
|
||||
lib, err := purego.Dlopen("libpulse-simple.so.0", purego.RTLD_NOW|purego.RTLD_GLOBAL)
|
||||
if err != nil {
|
||||
pulseErr = err
|
||||
return
|
||||
}
|
||||
purego.RegisterLibFunc(&paSimpleNew, lib, "pa_simple_new")
|
||||
paSimpleWrite = cFunc(lib, "pa_simple_write")
|
||||
purego.RegisterLibFunc(&paSimpleFree, lib, "pa_simple_free")
|
||||
purego.RegisterLibFunc(&paStrerror, lib, "pa_strerror")
|
||||
})
|
||||
if pulseErr != nil {
|
||||
return nil, pulseErr
|
||||
}
|
||||
spec := paSampleSpec{format: paSampleFloat32LE, rate: sampleRate, channels: channels}
|
||||
// ahead, asking for more every 10 ms.
|
||||
const frame = channels * 4
|
||||
attr := paBufferAttr{
|
||||
maxLength: ^uint32(0),
|
||||
tLength: uint32(int64(ahead) * sampleRate / int64(time.Second) * frame),
|
||||
preBuf: ^uint32(0),
|
||||
minReq: linuxFrames * frame,
|
||||
fragSize: ^uint32(0),
|
||||
}
|
||||
var code int32
|
||||
name := appName()
|
||||
s := paSimpleNew(nil, cstr(name), paStreamPlayback, nil, cstr(name), &spec, nil, unsafe.Pointer(&attr), &code)
|
||||
if s == 0 {
|
||||
return nil, fmt.Errorf("audio: PulseAudio: %s", paStrerror(code))
|
||||
}
|
||||
return &pulseDevice{s: s}, nil
|
||||
}
|
||||
|
||||
func (d *pulseDevice) write(samples []float32) error {
|
||||
// samples and d.code are on the heap, as a cCaller needs.
|
||||
r := int32(d.c.call(paSimpleWrite, d.s, uintptr(unsafe.Pointer(&samples[0])), uintptr(len(samples)*4), uintptr(unsafe.Pointer(&d.code))))
|
||||
runtime.KeepAlive(samples)
|
||||
if r < 0 {
|
||||
return fmt.Errorf("audio: PulseAudio: %s", paStrerror(d.code))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (d *pulseDevice) close() { paSimpleFree(d.s) }
|
||||
|
||||
type alsaDevice struct {
|
||||
pcm uintptr
|
||||
c cCaller
|
||||
}
|
||||
|
||||
func openALSA(ahead time.Duration) (device, error) {
|
||||
alsaLoad.Do(func() {
|
||||
lib, err := purego.Dlopen("libasound.so.2", purego.RTLD_NOW|purego.RTLD_GLOBAL)
|
||||
if err != nil {
|
||||
alsaErr = err
|
||||
return
|
||||
}
|
||||
purego.RegisterLibFunc(&sndPcmOpen, lib, "snd_pcm_open")
|
||||
purego.RegisterLibFunc(&sndPcmSetParams, lib, "snd_pcm_set_params")
|
||||
sndPcmWritei = cFunc(lib, "snd_pcm_writei")
|
||||
purego.RegisterLibFunc(&sndPcmRecover, lib, "snd_pcm_recover")
|
||||
purego.RegisterLibFunc(&sndPcmClose, lib, "snd_pcm_close")
|
||||
purego.RegisterLibFunc(&sndStrerror, lib, "snd_strerror")
|
||||
})
|
||||
if alsaErr != nil {
|
||||
return nil, alsaErr
|
||||
}
|
||||
var pcm uintptr
|
||||
if e := sndPcmOpen(&pcm, cstr("default"), sndPcmStreamPlayback, 0); e < 0 {
|
||||
return nil, fmt.Errorf("audio: ALSA: %s", sndStrerror(e))
|
||||
}
|
||||
if e := sndPcmSetParams(pcm, sndPcmFormatFloatLE, sndPcmAccessRWInterleaved, channels, sampleRate, 1, uint32(ahead.Microseconds())); e < 0 {
|
||||
sndPcmClose(pcm)
|
||||
return nil, fmt.Errorf("audio: ALSA: %s", sndStrerror(e))
|
||||
}
|
||||
return &alsaDevice{pcm: pcm}, nil
|
||||
}
|
||||
|
||||
func (d *alsaDevice) write(samples []float32) error {
|
||||
for len(samples) > 0 {
|
||||
// samples is on the heap, as a cCaller needs.
|
||||
n := int(d.c.call(sndPcmWritei, d.pcm, uintptr(unsafe.Pointer(&samples[0])), uintptr(len(samples)/channels)))
|
||||
runtime.KeepAlive(samples)
|
||||
if n < 0 {
|
||||
// An underrun or a suspend, recovered from by preparing the
|
||||
// device again.
|
||||
if e := sndPcmRecover(d.pcm, int32(n), 1); e < 0 {
|
||||
return fmt.Errorf("audio: ALSA: %s", sndStrerror(e))
|
||||
}
|
||||
continue
|
||||
}
|
||||
samples = samples[n*channels:]
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (d *alsaDevice) close() { sndPcmClose(d.pcm) }
|
||||
+35
@@ -0,0 +1,35 @@
|
||||
//go:build ios || android
|
||||
|
||||
package audio
|
||||
|
||||
import (
|
||||
"time"
|
||||
"unsafe"
|
||||
|
||||
"github.com/egoist/mygo/internal/mobile"
|
||||
)
|
||||
|
||||
// Phones play through their hosts: AVAudioEngine on iOS, AudioTrack on Android.
|
||||
// Writes block on this goroutine's thread, in the host, as the output fills.
|
||||
|
||||
type mobileDevice struct{}
|
||||
|
||||
// mobileFrames is how many frames go in a write: 10 ms.
|
||||
const mobileFrames = sampleRate / 100
|
||||
|
||||
func openDevice(ahead time.Duration) (device, int, error) {
|
||||
if err := mobile.AudioOpen(sampleRate, int(ahead/time.Millisecond)); err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
return mobileDevice{}, mobileFrames, nil
|
||||
}
|
||||
|
||||
func (mobileDevice) write(samples []float32) error {
|
||||
if len(samples) == 0 {
|
||||
return nil
|
||||
}
|
||||
b := unsafe.Slice((*byte)(unsafe.Pointer(&samples[0])), len(samples)*4)
|
||||
return mobile.AudioWrite(b)
|
||||
}
|
||||
|
||||
func (mobileDevice) close() { mobile.AudioClose() }
|
||||
+7
@@ -0,0 +1,7 @@
|
||||
//go:build !(darwin && !ios) && !(linux && !android && (amd64 || arm64)) && !(windows && (amd64 || arm64)) && !js && !ios && !android
|
||||
|
||||
package audio
|
||||
|
||||
import "time"
|
||||
|
||||
func openDevice(ahead time.Duration) (device, int, error) { return nil, 0, errUnsupported }
|
||||
+269
@@ -0,0 +1,269 @@
|
||||
//go:build windows && (amd64 || arm64)
|
||||
|
||||
package audio
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"runtime"
|
||||
"syscall"
|
||||
"time"
|
||||
"unsafe"
|
||||
)
|
||||
|
||||
// Windows plays through WASAPI in shared mode on the default output,
|
||||
// opened again when the default changes or the device goes. Every call
|
||||
// runs on the output's thread, locked, in COM's multithreaded apartment.
|
||||
|
||||
type guid struct {
|
||||
data1 uint32
|
||||
data2 uint16
|
||||
data3 uint16
|
||||
data4 [8]byte
|
||||
}
|
||||
|
||||
var (
|
||||
clsidMMDeviceEnumerator = guid{0xbcde0395, 0xe52f, 0x467c, [8]byte{0x8e, 0x3d, 0xc4, 0x57, 0x92, 0x91, 0x69, 0x2e}}
|
||||
iidIMMDeviceEnumerator = guid{0xa95664d2, 0x9614, 0x4f35, [8]byte{0xa7, 0x46, 0xde, 0x8d, 0xb6, 0x36, 0x17, 0xe6}}
|
||||
iidIAudioClient = guid{0x1cb9ad4c, 0xdbfa, 0x4c32, [8]byte{0xb1, 0x78, 0xc2, 0xf5, 0x68, 0xa7, 0x03, 0xb2}}
|
||||
iidIAudioRenderClient = guid{0xf294acfc, 0x3146, 0x4483, [8]byte{0xa7, 0xbf, 0xad, 0xdc, 0xa7, 0xc2, 0x60, 0xe2}}
|
||||
ksDataFormatSubtypeFloat = guid{0x00000003, 0x0000, 0x0010, [8]byte{0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71}}
|
||||
ole32 = syscall.NewLazyDLL("ole32.dll")
|
||||
kernel32 = syscall.NewLazyDLL("kernel32.dll")
|
||||
procCoInitializeEx = ole32.NewProc("CoInitializeEx")
|
||||
procCoCreateInstance = ole32.NewProc("CoCreateInstance")
|
||||
procCoTaskMemFree = ole32.NewProc("CoTaskMemFree")
|
||||
procCreateEventW = kernel32.NewProc("CreateEventW")
|
||||
procCloseHandle = kernel32.NewProc("CloseHandle")
|
||||
comInitialized bool
|
||||
errDefaultDeviceChanged = errors.New("audio: the default output changed")
|
||||
errAudioClientUnresponded = errors.New("audio: the audio client stopped asking for frames")
|
||||
)
|
||||
|
||||
type waveFormatExtensible struct {
|
||||
formatTag uint16
|
||||
channels uint16
|
||||
samplesPerSec uint32
|
||||
avgBytesPerSec uint32
|
||||
blockAlign uint16
|
||||
bitsPerSample uint16
|
||||
size uint16
|
||||
validBits uint16
|
||||
channelMask uint32
|
||||
subFormat guid
|
||||
}
|
||||
|
||||
const (
|
||||
clsctxAll = 0x17
|
||||
coinitMultithreaded = 0
|
||||
eRender = 0
|
||||
eConsole = 0
|
||||
waveFormatExtensibleTag = 0xfffe
|
||||
speakerFrontLeft = 0x1
|
||||
speakerFrontRight = 0x2
|
||||
audclntShareModeShared = 0
|
||||
audclntStreamFlagsEventCB = 0x00040000
|
||||
audclntStreamFlagsNoPersist = 0x00080000
|
||||
audclntStreamFlagsAutoConvert = 0x80000000
|
||||
audclntStreamFlagsSRCQuality = 0x08000000
|
||||
waitObject0 = 0
|
||||
windowsFrames = sampleRate / 100 // per write: 10 ms
|
||||
)
|
||||
|
||||
// comCall calls method i of the COM interface obj. Pointers converted to
|
||||
// uintptr in the call stay valid until it returns (go:uintptrescapes),
|
||||
// which moves what they point to, and args, to the heap: write calls
|
||||
// syscall.SyscallN and method instead.
|
||||
//
|
||||
//go:uintptrescapes
|
||||
func comCall(obj uintptr, i int, args ...uintptr) uintptr {
|
||||
var a [16]uintptr
|
||||
a[0] = obj
|
||||
n := copy(a[1:], args)
|
||||
r, _, _ := syscall.SyscallN(method(obj, i), a[:n+1]...)
|
||||
return r
|
||||
}
|
||||
|
||||
// method returns the address of method i of the COM interface obj, to
|
||||
// call with syscall.SyscallN, obj first. SyscallN keeps pointers
|
||||
// converted to uintptr in its call valid without moving them to the heap
|
||||
// (go:uintptrkeepalive), so such a call allocates nothing.
|
||||
func method(obj uintptr, i int) uintptr {
|
||||
vtbl := *(*uintptr)(native(obj))
|
||||
return *(*uintptr)(unsafe.Add(native(vtbl), i*int(unsafe.Sizeof(uintptr(0)))))
|
||||
}
|
||||
|
||||
// native converts a native address to a pointer.
|
||||
func native(addr uintptr) unsafe.Pointer { return *(*unsafe.Pointer)(unsafe.Pointer(&addr)) }
|
||||
|
||||
func failed(hr uintptr) bool { return int32(uint32(hr)) < 0 }
|
||||
|
||||
func hresult(what string, hr uintptr) error {
|
||||
return fmt.Errorf("audio: %s failed (HRESULT %#08x)", what, uint32(hr))
|
||||
}
|
||||
|
||||
func release(obj uintptr) {
|
||||
if obj != 0 {
|
||||
comCall(obj, 2)
|
||||
}
|
||||
}
|
||||
|
||||
type wasapiDevice struct {
|
||||
enumerator, client, render uintptr
|
||||
event uintptr
|
||||
frames uint32 // the client's buffer
|
||||
id string // the device's endpoint ID
|
||||
checked time.Time
|
||||
}
|
||||
|
||||
// defaultID returns the endpoint ID of the default output.
|
||||
func defaultID(enumerator uintptr) (string, error) {
|
||||
var dev uintptr
|
||||
if hr := comCall(enumerator, 4, eRender, eConsole, uintptr(unsafe.Pointer(&dev))); failed(hr) {
|
||||
if uint32(hr) == 0x80070490 { // E_NOTFOUND
|
||||
return "", errors.New("audio: no audio output")
|
||||
}
|
||||
return "", hresult("GetDefaultAudioEndpoint", hr)
|
||||
}
|
||||
defer release(dev)
|
||||
var p *uint16
|
||||
if hr := comCall(dev, 5, uintptr(unsafe.Pointer(&p))); failed(hr) {
|
||||
return "", hresult("IMMDevice.GetId", hr)
|
||||
}
|
||||
defer procCoTaskMemFree.Call(uintptr(unsafe.Pointer(p)))
|
||||
n := 0
|
||||
for *(*uint16)(unsafe.Add(unsafe.Pointer(p), n*2)) != 0 {
|
||||
n++
|
||||
}
|
||||
return syscall.UTF16ToString(unsafe.Slice(p, n)), nil
|
||||
}
|
||||
|
||||
func openDevice(ahead time.Duration) (device, int, error) {
|
||||
if !comInitialized {
|
||||
// COM is initialized per thread: run's goroutine keeps this one.
|
||||
runtime.LockOSThread()
|
||||
// S_FALSE, already initialized, succeeds as well.
|
||||
if hr, _, _ := procCoInitializeEx.Call(0, coinitMultithreaded); failed(hr) {
|
||||
runtime.UnlockOSThread()
|
||||
return nil, 0, hresult("CoInitializeEx", hr)
|
||||
}
|
||||
comInitialized = true
|
||||
}
|
||||
d := &wasapiDevice{}
|
||||
if err := d.open(ahead); err != nil {
|
||||
d.close()
|
||||
return nil, 0, err
|
||||
}
|
||||
return d, windowsFrames, nil
|
||||
}
|
||||
|
||||
func (d *wasapiDevice) open(ahead time.Duration) error {
|
||||
if hr, _, _ := procCoCreateInstance.Call(uintptr(unsafe.Pointer(&clsidMMDeviceEnumerator)), 0, clsctxAll,
|
||||
uintptr(unsafe.Pointer(&iidIMMDeviceEnumerator)), uintptr(unsafe.Pointer(&d.enumerator))); failed(hr) {
|
||||
return hresult("CoCreateInstance(MMDeviceEnumerator)", hr)
|
||||
}
|
||||
var dev uintptr
|
||||
if hr := comCall(d.enumerator, 4, eRender, eConsole, uintptr(unsafe.Pointer(&dev))); failed(hr) {
|
||||
if uint32(hr) == 0x80070490 { // E_NOTFOUND
|
||||
return errors.New("audio: no audio output")
|
||||
}
|
||||
return hresult("GetDefaultAudioEndpoint", hr)
|
||||
}
|
||||
defer release(dev)
|
||||
id, err := defaultID(d.enumerator)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
d.id = id
|
||||
if hr := comCall(dev, 3, uintptr(unsafe.Pointer(&iidIAudioClient)), clsctxAll, 0, uintptr(unsafe.Pointer(&d.client))); failed(hr) {
|
||||
return hresult("IMMDevice.Activate", hr)
|
||||
}
|
||||
f := waveFormatExtensible{
|
||||
formatTag: waveFormatExtensibleTag,
|
||||
channels: channels,
|
||||
samplesPerSec: sampleRate,
|
||||
avgBytesPerSec: sampleRate * channels * 4,
|
||||
blockAlign: channels * 4,
|
||||
bitsPerSample: 32,
|
||||
size: 22,
|
||||
validBits: 32,
|
||||
channelMask: speakerFrontLeft | speakerFrontRight,
|
||||
subFormat: ksDataFormatSubtypeFloat,
|
||||
}
|
||||
// ahead, converted to the device's format by WASAPI's resampler.
|
||||
duration := uintptr(ahead / 100) // in 100 ns
|
||||
flags := uintptr(audclntStreamFlagsEventCB | audclntStreamFlagsNoPersist | audclntStreamFlagsAutoConvert | audclntStreamFlagsSRCQuality)
|
||||
if hr := comCall(d.client, 3, audclntShareModeShared, flags, duration, 0, uintptr(unsafe.Pointer(&f)), 0); failed(hr) {
|
||||
return hresult("IAudioClient.Initialize", hr)
|
||||
}
|
||||
if hr := comCall(d.client, 4, uintptr(unsafe.Pointer(&d.frames))); failed(hr) {
|
||||
return hresult("IAudioClient.GetBufferSize", hr)
|
||||
}
|
||||
if hr := comCall(d.client, 14, uintptr(unsafe.Pointer(&iidIAudioRenderClient)), uintptr(unsafe.Pointer(&d.render))); failed(hr) {
|
||||
return hresult("IAudioClient.GetService", hr)
|
||||
}
|
||||
ev, _, err := procCreateEventW.Call(0, 0, 0, 0)
|
||||
if ev == 0 {
|
||||
return fmt.Errorf("audio: CreateEvent failed: %v", err)
|
||||
}
|
||||
d.event = ev
|
||||
if hr := comCall(d.client, 13, d.event); failed(hr) {
|
||||
return hresult("IAudioClient.SetEventHandle", hr)
|
||||
}
|
||||
if hr := comCall(d.client, 10); failed(hr) {
|
||||
return hresult("IAudioClient.Start", hr)
|
||||
}
|
||||
d.checked = time.Now()
|
||||
return nil
|
||||
}
|
||||
|
||||
func (d *wasapiDevice) write(samples []float32) error {
|
||||
n := uint32(len(samples) / channels)
|
||||
deadline := time.Now().Add(time.Second)
|
||||
// Called on every write: through syscall.SyscallN, not comCall, so
|
||||
// padding and data stay on the stack.
|
||||
for {
|
||||
var padding uint32
|
||||
if hr, _, _ := syscall.SyscallN(method(d.client, 6), d.client, uintptr(unsafe.Pointer(&padding))); failed(hr) {
|
||||
return hresult("IAudioClient.GetCurrentPadding", hr)
|
||||
}
|
||||
if padding <= d.frames && d.frames-padding >= n {
|
||||
break
|
||||
}
|
||||
if time.Now().After(deadline) {
|
||||
return errAudioClientUnresponded
|
||||
}
|
||||
syscall.WaitForSingleObject(syscall.Handle(d.event), 100)
|
||||
}
|
||||
var data unsafe.Pointer
|
||||
if hr, _, _ := syscall.SyscallN(method(d.render, 3), d.render, uintptr(n), uintptr(unsafe.Pointer(&data))); failed(hr) {
|
||||
return hresult("IAudioRenderClient.GetBuffer", hr)
|
||||
}
|
||||
copy(unsafe.Slice((*float32)(data), len(samples)), samples)
|
||||
if hr, _, _ := syscall.SyscallN(method(d.render, 4), d.render, uintptr(n), 0); failed(hr) {
|
||||
return hresult("IAudioRenderClient.ReleaseBuffer", hr)
|
||||
}
|
||||
// The default output changing (headphones plugged in, a choice in
|
||||
// Settings) moves a shared stream nowhere: open the new one.
|
||||
if time.Since(d.checked) > 500*time.Millisecond {
|
||||
d.checked = time.Now()
|
||||
if id, err := defaultID(d.enumerator); err != nil || id != d.id {
|
||||
return errDefaultDeviceChanged
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (d *wasapiDevice) close() {
|
||||
if d.client != 0 {
|
||||
comCall(d.client, 11)
|
||||
}
|
||||
release(d.render)
|
||||
release(d.client)
|
||||
release(d.enumerator)
|
||||
d.render, d.client, d.enumerator = 0, 0, 0
|
||||
if d.event != 0 {
|
||||
procCloseHandle.Call(d.event)
|
||||
d.event = 0
|
||||
}
|
||||
}
|
||||
+138
@@ -0,0 +1,138 @@
|
||||
package audio
|
||||
|
||||
import (
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// heldFrames is what the output holds ahead in these tests: 100 ms.
|
||||
const heldFrames = sampleRate / 10
|
||||
|
||||
// atFrame checks that p's position is source frame f.
|
||||
func atFrame(t *testing.T, p *Player, f int64, when string) {
|
||||
t.Helper()
|
||||
got, want := p.Position(), frames(f, sampleRate)
|
||||
if d := got - want; d < -time.Microsecond || d > time.Microsecond {
|
||||
t.Errorf("%s: Position = %v, want %v (frame %d)", when, got, want, f)
|
||||
}
|
||||
}
|
||||
|
||||
func longSound() *Sound { return NewSound(sampleRate, 1, make([]float32, 10*sampleRate)) }
|
||||
|
||||
// Position is what is heard: it stands still while the device fills, and
|
||||
// then lags what was mixed by what the device holds.
|
||||
func TestPositionIsHeard(t *testing.T) {
|
||||
setup(t)
|
||||
hold(heldFrames)
|
||||
p := longSound().Play()
|
||||
render(heldFrames / 2)
|
||||
atFrame(t, p, 0, "half the device filled")
|
||||
render(heldFrames / 2)
|
||||
atFrame(t, p, 0, "the device filled")
|
||||
render(3000)
|
||||
atFrame(t, p, 3000, "3000 frames on")
|
||||
// A device opening again holds nothing of what was mixed before,
|
||||
// which it dropped: the position goes on from what was mixed.
|
||||
hold(heldFrames)
|
||||
atFrame(t, p, heldFrames+3000, "a device opened again")
|
||||
}
|
||||
|
||||
// Right after a seek, Position is where it seeked to, and goes on from
|
||||
// there once the device plays what was mixed since.
|
||||
func TestPositionHoldsAtSeek(t *testing.T) {
|
||||
setup(t)
|
||||
hold(heldFrames)
|
||||
p := longSound().Play()
|
||||
render(2 * heldFrames)
|
||||
p.Seek(2 * time.Second)
|
||||
atFrame(t, p, 2*sampleRate, "right after Seek")
|
||||
render(heldFrames - 100)
|
||||
atFrame(t, p, 2*sampleRate, "before the seek is heard")
|
||||
render(600)
|
||||
atFrame(t, p, 2*sampleRate+500, "500 frames into the seek heard")
|
||||
p.Stop()
|
||||
atFrame(t, p, 0, "after Stop")
|
||||
}
|
||||
|
||||
// Paused, a player goes on for as long as the device plays what it holds,
|
||||
// then stands still; playing again, it stands still until that is heard.
|
||||
func TestPositionPlaysOutPause(t *testing.T) {
|
||||
setup(t)
|
||||
hold(heldFrames)
|
||||
p := longSound().Play()
|
||||
render(10000)
|
||||
p.Pause()
|
||||
atFrame(t, p, 10000-heldFrames, "at Pause")
|
||||
render(2000)
|
||||
atFrame(t, p, 12000-heldFrames, "2000 frames after Pause")
|
||||
// It faded out over rampFrames after the pause.
|
||||
render(2 * heldFrames)
|
||||
atFrame(t, p, 10000+rampFrames, "played out")
|
||||
render(1000)
|
||||
atFrame(t, p, 10000+rampFrames, "paused, played out")
|
||||
p.Play()
|
||||
render(heldFrames - 100)
|
||||
atFrame(t, p, 10000+rampFrames, "before playing again is heard")
|
||||
render(600)
|
||||
atFrame(t, p, 10000+rampFrames+500, "500 frames into playing again")
|
||||
}
|
||||
|
||||
// With a speed, what the device holds is that many more frames of the
|
||||
// source.
|
||||
func TestPositionAtSpeed(t *testing.T) {
|
||||
setup(t)
|
||||
hold(heldFrames)
|
||||
p := longSound().NewPlayer().SetSpeed(2)
|
||||
p.Play()
|
||||
render(3 * heldFrames)
|
||||
atFrame(t, p, 4*heldFrames, "200 ms heard at speed 2")
|
||||
p.SetSpeed(0.5)
|
||||
render(heldFrames * 3 / 2)
|
||||
// Of the 150 ms heard since, 100 ms were mixed at 2, 50 ms at 0.5.
|
||||
atFrame(t, p, 4*heldFrames+2*heldFrames+heldFrames/4, "after slowing down")
|
||||
}
|
||||
|
||||
// A looping player's position heard comes back to the loop's start.
|
||||
func TestPositionWrapsLoops(t *testing.T) {
|
||||
setup(t)
|
||||
hold(50)
|
||||
p := NewSound(sampleRate, 1, ramp(100)).NewPlayer().
|
||||
SetLoopRange(frames(30, sampleRate), frames(60, sampleRate))
|
||||
p.Play()
|
||||
render(160)
|
||||
atFrame(t, p, 50, "110 frames heard")
|
||||
render(10)
|
||||
// 120 heard: 60, then two loops of 30.
|
||||
atFrame(t, p, 30, "120 frames heard")
|
||||
}
|
||||
|
||||
// A stream that is late stands still while it is, as heard.
|
||||
func TestLateStreamPositionIsHeard(t *testing.T) {
|
||||
setup(t)
|
||||
hold(heldFrames)
|
||||
src := &lateSource{ready: 1000}
|
||||
p := newPlayer(src, sampleRate, 1, -1)
|
||||
p.Play()
|
||||
// It plays 998 frames of the 1000, reading two ahead to interpolate,
|
||||
// then waits for 1002.
|
||||
render(heldFrames + 2000)
|
||||
src.ready = 1 << 30
|
||||
render(500)
|
||||
atFrame(t, p, 998, "the device playing the wait")
|
||||
render(heldFrames)
|
||||
atFrame(t, p, 998+500, "the wait heard")
|
||||
}
|
||||
|
||||
// A lateSource has ready frames decoded, and then waits for more.
|
||||
type lateSource struct{ ready int }
|
||||
|
||||
func (s *lateSource) read(dst []float32) (int, bool) {
|
||||
n := min(len(dst), s.ready)
|
||||
clear(dst[:n])
|
||||
s.ready -= n
|
||||
return n, false
|
||||
}
|
||||
|
||||
func (*lateSource) seek(int64) {}
|
||||
func (*lateSource) setLoop(bool, int64, int64) {}
|
||||
func (*lateSource) close() {}
|
||||
Vendored
+210
@@ -0,0 +1,210 @@
|
||||
package audio
|
||||
|
||||
import (
|
||||
"math"
|
||||
"sync"
|
||||
)
|
||||
|
||||
// A voice that plays more than one source frame an output frame, a sound
|
||||
// of more than 48 kHz or one sped up, would fold what it has above the
|
||||
// output's Nyquist frequency, 24 kHz, back below it: a spline does not
|
||||
// remove it. Such a voice interpolates with a windowed sinc instead, a
|
||||
// low-pass at the output's rate: a Kaiser window over sincReach output
|
||||
// frames either side, flat to 20 kHz, -6 dB at 22 kHz and at least 80 dB
|
||||
// down from 24 kHz. In source frames, the kernel is as much wider as the
|
||||
// source is faster, and its cutoff as much lower.
|
||||
const (
|
||||
sincReach = 32 // output frames either side
|
||||
sincCutoff = 22000.0 / sampleRate // of the output's rate
|
||||
sincBeta = 7.857 // the Kaiser window's: 80 dB
|
||||
sincRes = 256 // entries of sincTable an output frame
|
||||
// The kernels a voice keeps for the phases between two source frames
|
||||
// (as many an output frame, so fewer the faster), and interpolates
|
||||
// between.
|
||||
sincPhases = 128
|
||||
|
||||
// The most source frames the kernel reaches either side: the whole
|
||||
// kernel up to 8 source frames an output frame. Faster, the window
|
||||
// narrows to these, which widens the band from what it passes to what
|
||||
// it stops as much, and the cutoff comes down for that band to end at
|
||||
// 24 kHz still, as far as half of it.
|
||||
maxReach = 256
|
||||
// The frames a voice keeps around where it is: enough for the kernel
|
||||
// to grow to maxReach while it holds frames as far ahead.
|
||||
ringFrames = 2 * maxReach
|
||||
|
||||
// The most weights a sincBank holds at any step: (rows+1)×2×reach.
|
||||
maxWeights = 2*sincPhases*sincReach + 2*sincPhases + 4*maxReach + 4
|
||||
)
|
||||
|
||||
// A sincBank is the kernel at a step, in source frames an output frame:
|
||||
// the weights of the 2×reach frames from reach-1 before the output's to
|
||||
// reach after it, for each of rows+1 phases from 0 to 1, each with the
|
||||
// difference to the next phase's.
|
||||
type sincBank struct {
|
||||
step float64
|
||||
reach int
|
||||
rows int
|
||||
cutoff float64 // of the output's rate
|
||||
w [][2]float32
|
||||
}
|
||||
|
||||
// set makes the bank's kernels those at step, unless they are.
|
||||
func (b *sincBank) set(step float64) {
|
||||
if b.step == step {
|
||||
return
|
||||
}
|
||||
if b.w == nil {
|
||||
b.w = make([][2]float32, 0, maxWeights)
|
||||
}
|
||||
b.step = step
|
||||
b.reach = min(int(math.Ceil(sincReach*step)), maxReach)
|
||||
b.rows = int(math.Ceil(sincPhases / step))
|
||||
b.cutoff = sincCutoff
|
||||
if sincReach*step > maxReach {
|
||||
// Half the band from what it passes to what it stops, as many
|
||||
// times wider as the window is narrower.
|
||||
half := (0.5 - sincCutoff) * sincReach * step / maxReach
|
||||
b.cutoff = max(0.5-half, half)
|
||||
}
|
||||
n := 2 * b.reach
|
||||
b.w = b.w[:(b.rows+1)*n]
|
||||
for p := range b.rows + 1 {
|
||||
b.kernel(b.w[p*n:(p+1)*n], float64(p)/float64(b.rows))
|
||||
}
|
||||
for p := range b.rows {
|
||||
w, next := b.w[p*n:(p+1)*n], b.w[(p+1)*n:(p+2)*n]
|
||||
for j := range w {
|
||||
w[j][1] = next[j][0] - w[j][0]
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// kernel sets the weights in w for an output phase past the frame reach-1
|
||||
// after w's first, summing to 1 so that what is constant stays as it is.
|
||||
func (b *sincBank) kernel(w [][2]float32, phase float64) {
|
||||
d0 := float64(1-b.reach) - phase // source frames from the output to w's first
|
||||
var sum float64
|
||||
if sincReach*b.step <= maxReach {
|
||||
t := sincTable()
|
||||
dx := sincRes / b.step
|
||||
for j := range w {
|
||||
x := math.Abs(d0+float64(j)) * dx
|
||||
i := int(x)
|
||||
h := float64(t[i][0]) + (x-float64(i))*float64(t[i][1])
|
||||
w[j][0] = float32(h)
|
||||
sum += h
|
||||
}
|
||||
} else {
|
||||
// The ring cannot hold the whole kernel: the sinc at the cutoff,
|
||||
// by rotation from one frame to the next, in a window as wide as
|
||||
// the frames reached.
|
||||
k := kaiserTable()
|
||||
end := len(k) - 1
|
||||
dk := float64(end) / float64(b.reach)
|
||||
a := math.Pi * 2 * b.cutoff / b.step // radians a source frame
|
||||
s, c := math.Sincos(a * d0)
|
||||
sa, ca := math.Sincos(a)
|
||||
for j := range w {
|
||||
d := d0 + float64(j)
|
||||
h := 0.0
|
||||
if u := math.Abs(d) * dk; int(u) < end {
|
||||
i := int(u)
|
||||
h = k[i] + (u-float64(i))*(k[i+1]-k[i])
|
||||
if th := a * d; math.Abs(th) > 1e-9 {
|
||||
h *= s / th
|
||||
}
|
||||
}
|
||||
w[j][0] = float32(h)
|
||||
sum += h
|
||||
s, c = s*ca+c*sa, c*ca-s*sa
|
||||
}
|
||||
}
|
||||
for j := range w {
|
||||
w[j][0] = float32(float64(w[j][0]) / sum)
|
||||
}
|
||||
}
|
||||
|
||||
// sinc interpolates the voice's frames where the output is with its bank's
|
||||
// kernel, between those of the phases either side.
|
||||
func (v *voice) sinc() (l, r float32) {
|
||||
b := &v.bank
|
||||
n := 2 * b.reach
|
||||
u := v.phase * float64(b.rows)
|
||||
p := int(u)
|
||||
f := float32(u - float64(p))
|
||||
w := b.w[p*n : (p+1)*n]
|
||||
x := v.ring[(v.idx-int64(b.reach)+1)&(ringFrames-1):]
|
||||
x = x[:len(w)]
|
||||
switch {
|
||||
case v.mono:
|
||||
for j, e := range w {
|
||||
l += (e[0] + f*e[1]) * x[j][0]
|
||||
}
|
||||
return l, l
|
||||
case f == 0:
|
||||
// On a phase of the bank, as every frame at a whole number of
|
||||
// source frames an output frame.
|
||||
for j, e := range w {
|
||||
l += e[0] * x[j][0]
|
||||
r += e[0] * x[j][1]
|
||||
}
|
||||
default:
|
||||
for j, e := range w {
|
||||
h, s := e[0]+f*e[1], x[j]
|
||||
l += h * s[0]
|
||||
r += h * s[1]
|
||||
}
|
||||
}
|
||||
return l, r
|
||||
}
|
||||
|
||||
// sincTable is the kernel from 0 to sincReach output frames, sincRes
|
||||
// entries a frame, each with the difference to the next for interpolating
|
||||
// between them, and zeros as far after as a kernel's last frame reaches.
|
||||
var sincTable = sync.OnceValue(func() [][2]float32 {
|
||||
n := sincReach * sincRes
|
||||
t := make([][2]float32, n+2*sincRes)
|
||||
next := 0.0
|
||||
for i := n; i >= 0; i-- {
|
||||
x := float64(i) / sincRes
|
||||
h := sinc(2*sincCutoff*x) * kaiser(x/sincReach)
|
||||
t[i] = [2]float32{float32(h), float32(next - h)}
|
||||
next = h
|
||||
}
|
||||
return t
|
||||
})
|
||||
|
||||
// kaiserTable is the window from its middle to its edge, for kernels the
|
||||
// ring cannot hold whole.
|
||||
var kaiserTable = sync.OnceValue(func() []float64 {
|
||||
t := make([]float64, 1025)
|
||||
for i := range t {
|
||||
t[i] = kaiser(float64(i) / float64(len(t)-1))
|
||||
}
|
||||
return t
|
||||
})
|
||||
|
||||
func sinc(x float64) float64 {
|
||||
if x == 0 {
|
||||
return 1
|
||||
}
|
||||
return math.Sin(math.Pi*x) / (math.Pi * x)
|
||||
}
|
||||
|
||||
// kaiser returns the Kaiser window at u, from -1 to 1.
|
||||
func kaiser(u float64) float64 {
|
||||
return bessel0(sincBeta*math.Sqrt(max(1-u*u, 0))) / bessel0(sincBeta)
|
||||
}
|
||||
|
||||
// bessel0 returns the modified Bessel function of the first kind, of order
|
||||
// zero.
|
||||
func bessel0(x float64) float64 {
|
||||
sum, term := 1.0, 1.0
|
||||
for k := 1; term > 1e-12*sum; k++ {
|
||||
h := x / 2 / float64(k)
|
||||
term *= h * h
|
||||
sum += term
|
||||
}
|
||||
return sum
|
||||
}
|
||||
+212
@@ -0,0 +1,212 @@
|
||||
package audio
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"math"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Mixing one looping stereo voice, a buffer of 10 ms at a time, at the
|
||||
// rates sounds come in.
|
||||
func BenchmarkMix(b *testing.B) {
|
||||
for _, rate := range []int{44100, 48000, 88200, 96000, 192000} {
|
||||
b.Run(fmt.Sprint(rate), func(b *testing.B) {
|
||||
mu.Lock()
|
||||
testMode = true
|
||||
voices = nil
|
||||
volume = 1
|
||||
mu.Unlock()
|
||||
NewSound(rate, 2, sine(rate, 1, 440, 660)).NewPlayer().SetLoop(true).Play()
|
||||
buf := make([]float32, sampleRate/100*channels)
|
||||
// The first allocates the voice's ring, and its kernels.
|
||||
mix(buf)
|
||||
b.ReportAllocs()
|
||||
for b.Loop() {
|
||||
mix(buf)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestDownsampleAlias(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
rate, tone, alias int // Hz
|
||||
}{
|
||||
{"88k2", 88200, 30000, 18000},
|
||||
{"96k", 96000, 30000, 18000},
|
||||
{"192k", 192000, 90000, 6000},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
setup(t)
|
||||
input := make([]float32, 2*tc.rate)
|
||||
for i := range tc.rate {
|
||||
phase := 2 * math.Pi * float64(i) / float64(tc.rate)
|
||||
input[2*i] = float32(0.1 * math.Sin(6000*phase))
|
||||
input[2*i+1] = float32(0.1 * math.Sin(float64(tc.tone)*phase))
|
||||
}
|
||||
NewSound(tc.rate, 2, input).Play()
|
||||
out := render(9600)[2*4800:] // Analyze 100 ms after startup.
|
||||
pass := measuredAmplitude(out, 0, 6000)
|
||||
alias := measuredAmplitude(out, 1, tc.alias)
|
||||
t.Logf("control %.6f, alias %.6f", pass, alias)
|
||||
if math.Abs(pass-0.1) > 0.005 {
|
||||
t.Fatalf("invalid passband control: %g", pass)
|
||||
}
|
||||
if alias > 0.1*0.001 {
|
||||
t.Errorf("alias at %d Hz exceeds -60 dB relative to input", tc.alias)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// measuredAmplitude returns the peak amplitude of channel ch of out at hz.
|
||||
func measuredAmplitude(out []float32, ch, hz int) float64 {
|
||||
var re, im float64
|
||||
n := len(out) / 2
|
||||
for i := range n {
|
||||
phase := 2 * math.Pi * float64(hz*i) / 48000
|
||||
x := float64(out[2*i+ch])
|
||||
re += x * math.Cos(phase)
|
||||
im += x * math.Sin(phase)
|
||||
}
|
||||
return 2 * math.Hypot(re, im) / float64(n)
|
||||
}
|
||||
|
||||
// fold returns the frequency that hz plays at at the output's rate.
|
||||
func fold(hz int) int {
|
||||
hz %= sampleRate
|
||||
return min(hz, sampleRate-hz)
|
||||
}
|
||||
|
||||
// Downsampled, what is below 20 kHz plays as it is, within 0.1 dB, and
|
||||
// where the source is.
|
||||
func TestDownsamplePassband(t *testing.T) {
|
||||
for _, rate := range []int{88200, 96000, 192000} {
|
||||
for _, hz := range [][2]float64{{1000, 15000}, {6000, 20000}} {
|
||||
setup(t)
|
||||
p := NewSound(rate, 2, sine(rate, 0.5, hz[0], hz[1])).Play()
|
||||
out := render(9600)
|
||||
for c, f := range hz {
|
||||
got := measuredAmplitude(out[2*4800:], c, int(f))
|
||||
if db := 20 * math.Log10(got/0.5); math.Abs(db) > 0.1 {
|
||||
t.Errorf("%d Hz at %d Hz plays at %+.3f dB", int(f), rate, db)
|
||||
}
|
||||
}
|
||||
if got, want := p.Position(), 200*time.Millisecond; got-want > time.Microsecond || want-got > time.Microsecond {
|
||||
t.Errorf("at %d Hz: Position = %v, want %v", rate, got, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Downsampled, at the sound's rate or its speed, what is above 24 kHz
|
||||
// does not fold back below it: 80 dB down from 24.5 kHz.
|
||||
func TestDownsampleStopband(t *testing.T) {
|
||||
// A sound at rate played at speed: a tone of pass Hz on the left, one
|
||||
// of stop Hz on the right.
|
||||
type tones struct {
|
||||
rate int
|
||||
speed float64
|
||||
pass, stop int
|
||||
}
|
||||
var cases []tones
|
||||
for _, rate := range []int{88200, 96000, 192000} {
|
||||
for hz := 24500; hz < rate/2; hz += 3000 + hz/4 {
|
||||
cases = append(cases, tones{rate, 1, 1000, hz})
|
||||
}
|
||||
}
|
||||
cases = append(cases,
|
||||
tones{48000, 1.25, 1000, 20000}, // 25 kHz
|
||||
tones{44100, 2, 1000, 15000}, // 30 kHz
|
||||
tones{96000, 3, 1000, 9000}, // 27 kHz
|
||||
// Wider kernels than the ring holds.
|
||||
tones{48000, 12, 1000, 2500}, // 30 kHz
|
||||
tones{96000, 16, 500, 2000}, // 32 kHz
|
||||
tones{192000, 16, 250, 4000}, // 64 kHz
|
||||
tones{96000, 16, 500, 1580}, // 25.3 kHz
|
||||
)
|
||||
for _, tc := range cases {
|
||||
setup(t)
|
||||
p := NewSound(tc.rate, 2, sine(tc.rate, 0.25*tc.speed, float64(tc.pass), float64(tc.stop))).NewPlayer()
|
||||
p.SetSpeed(tc.speed).Play()
|
||||
out := render(9600)[2*4800:]
|
||||
heard := int(float64(tc.stop) * tc.speed)
|
||||
pass := measuredAmplitude(out, 0, int(float64(tc.pass)*tc.speed))
|
||||
alias := measuredAmplitude(out, 1, fold(heard))
|
||||
if db := 20 * math.Log10(pass/0.5); math.Abs(db) > 0.1 {
|
||||
t.Errorf("%d Hz at %v×: %v Hz plays at %+.3f dB", tc.rate, tc.speed, float64(tc.pass)*tc.speed, db)
|
||||
}
|
||||
if db := 20 * math.Log10(alias/0.5); db > -80 {
|
||||
t.Errorf("%d Hz at %v×: %d Hz folds to %d Hz at %.1f dB", tc.rate, tc.speed, heard, fold(heard), db)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Downsampling goes on from one buffer to the next as if it mixed them
|
||||
// all at once.
|
||||
func TestDownsampleAcrossBuffers(t *testing.T) {
|
||||
const n = 9600
|
||||
samples := sine(88200, 0.2, 1000, 17000)
|
||||
for i := 1000; i < 1100; i++ {
|
||||
// A step, which rings.
|
||||
samples[2*i] += 0.3
|
||||
}
|
||||
setup(t)
|
||||
NewSound(88200, 2, samples).Play()
|
||||
whole := make([]float32, n*channels)
|
||||
mix(whole)
|
||||
setup(t)
|
||||
NewSound(88200, 2, samples).Play()
|
||||
parts := make([]float32, n*channels)
|
||||
sizes := []int{1, 7, 64, 333, 2, 480, 129}
|
||||
for i, k := 0, 0; i < n; k++ {
|
||||
m := min(sizes[k%len(sizes)], n-i)
|
||||
mix(parts[i*channels : (i+m)*channels])
|
||||
i += m
|
||||
}
|
||||
for i := range whole {
|
||||
if whole[i] != parts[i] {
|
||||
t.Fatalf("frame %d channel %d = %v in parts, %v at once", i/2, i%2, parts[i], whole[i])
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Changing speed, a voice goes from the spline to the sinc and back, and
|
||||
// from one kernel to another, without a click.
|
||||
func TestDownsampleSpeedChanges(t *testing.T) {
|
||||
setup(t)
|
||||
p := NewSound(sampleRate, 1, sine(sampleRate, 2, 1000)).NewPlayer()
|
||||
p.Play()
|
||||
var out []float32
|
||||
for _, s := range []float64{1, 1.5, 3, 0.8, 2, 9, 1} {
|
||||
p.SetSpeed(s)
|
||||
out = append(out, render(480)...)
|
||||
}
|
||||
// The steepest a sine of 0.5 at 9 kHz is.
|
||||
steep := 2 * math.Pi * 9000 / sampleRate * 0.5
|
||||
for i := 1; i < len(out)/2; i++ {
|
||||
if d := math.Abs(float64(out[2*i] - out[2*(i-1)])); d > 1.05*steep {
|
||||
t.Fatalf("a click at frame %d: %v to %v", i, out[2*(i-1)], out[2*i])
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Downsampling allocates nothing as it mixes, as its speed changes.
|
||||
func TestDownsampleAllocatesNothing(t *testing.T) {
|
||||
setup(t)
|
||||
p := NewSound(96000, 2, sine(96000, 0.5, 200, 300)).NewPlayer().SetLoop(true)
|
||||
p.Play()
|
||||
buf := make([]float32, 480*channels)
|
||||
speeds := []float64{1, 1.3, 0.7, 3.7, 12, 1.001}
|
||||
i := 0
|
||||
if n := testing.AllocsPerRun(600, func() {
|
||||
mix(buf)
|
||||
if i++; i%50 == 0 {
|
||||
p.SetSpeed(speeds[i/50%len(speeds)])
|
||||
}
|
||||
}); n != 0 {
|
||||
t.Errorf("%v allocations a buffer", n)
|
||||
}
|
||||
}
|
||||
Vendored
+220
@@ -0,0 +1,220 @@
|
||||
package audio
|
||||
|
||||
import (
|
||||
"io"
|
||||
"sync"
|
||||
)
|
||||
|
||||
// A memSource reads a sound's samples.
|
||||
type memSource struct {
|
||||
samples []float32
|
||||
channels int
|
||||
pos int // sample
|
||||
loop bool
|
||||
start, end int64 // the frames looped, end 0 for all
|
||||
}
|
||||
|
||||
func (s *memSource) read(dst []float32) (int, bool) {
|
||||
n := 0
|
||||
for n < len(dst) {
|
||||
limit := len(s.samples)
|
||||
if s.loop && s.end > 0 {
|
||||
limit = min(limit, int(s.end)*s.channels)
|
||||
}
|
||||
if s.pos >= limit {
|
||||
if !s.loop || limit == 0 {
|
||||
return n / s.channels, true
|
||||
}
|
||||
s.pos = int(s.start) * s.channels
|
||||
if s.pos >= limit {
|
||||
s.pos = 0
|
||||
}
|
||||
}
|
||||
c := copy(dst[n:], s.samples[s.pos:limit])
|
||||
c -= c % s.channels
|
||||
if c == 0 {
|
||||
break
|
||||
}
|
||||
n += c
|
||||
s.pos += c
|
||||
}
|
||||
return n / s.channels, false
|
||||
}
|
||||
|
||||
func (s *memSource) seek(frame int64) {
|
||||
s.pos = int(min(frame*int64(s.channels), int64(len(s.samples))))
|
||||
}
|
||||
|
||||
func (s *memSource) setLoop(loop bool, start, end int64) {
|
||||
s.loop, s.start, s.end = loop, start, end
|
||||
}
|
||||
func (s *memSource) close() {}
|
||||
|
||||
// decodeFrames is how many frames a stream's decoder decodes at a time.
|
||||
const decodeFrames = 2048
|
||||
|
||||
// A stream decodes ahead of a voice on a goroutine of its own, into a ring
|
||||
// the voice reads without waiting. The decoder fills the ring and sleeps
|
||||
// until a quarter of it is free, waking a few times a second.
|
||||
type stream struct {
|
||||
d Decoder
|
||||
channels int // of d
|
||||
keep int // channels kept: 1 or 2
|
||||
|
||||
mu sync.Mutex
|
||||
cond sync.Cond
|
||||
ring []float32 // frames of keep channels
|
||||
r, n int // where the next sample is read, and how many there are
|
||||
loop bool
|
||||
start int64 // the frames looped, end 0 for all
|
||||
end int64
|
||||
pos int64 // the frame d decodes next
|
||||
wrap bool // d decoded to the loop's end: it goes on from its start
|
||||
atEOF bool // d reached its end
|
||||
seekTo int64 // where to seek d next, or -1
|
||||
gen int // counts seeks, to drop what was decoded before one
|
||||
closed bool
|
||||
full bool // the decoder sleeps until a quarter of the ring is free
|
||||
}
|
||||
|
||||
func newStream(d Decoder) *stream {
|
||||
ch := max(d.Channels(), 1)
|
||||
s := &stream{d: d, channels: ch, keep: min(ch, 2), seekTo: -1}
|
||||
s.cond.L = &s.mu
|
||||
// About a second ahead, and a quarter holds what the decoder decodes.
|
||||
frames := max(d.SampleRate(), 4*decodeFrames)
|
||||
s.ring = make([]float32, frames*s.keep)
|
||||
go s.decode()
|
||||
return s
|
||||
}
|
||||
|
||||
func (s *stream) decode() {
|
||||
buf := make([]float32, decodeFrames*s.channels)
|
||||
var kept []float32
|
||||
if s.keep != s.channels {
|
||||
kept = make([]float32, decodeFrames*s.keep)
|
||||
}
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
for {
|
||||
for !s.closed && s.seekTo < 0 && !s.wrap && (s.atEOF && !s.loop || s.full) {
|
||||
s.cond.Wait()
|
||||
}
|
||||
if s.closed {
|
||||
if c, ok := s.d.(io.Closer); ok {
|
||||
c.Close()
|
||||
}
|
||||
return
|
||||
}
|
||||
if s.seekTo >= 0 || s.wrap || s.atEOF {
|
||||
// A seek, or a loop back to its start.
|
||||
to := s.seekTo
|
||||
if to < 0 {
|
||||
to = s.start
|
||||
}
|
||||
s.seekTo, s.wrap = -1, false
|
||||
gen := s.gen
|
||||
s.mu.Unlock()
|
||||
err := s.d.SetPosition(to)
|
||||
s.mu.Lock()
|
||||
if gen == s.gen {
|
||||
// Where it cannot go, the stream ends.
|
||||
s.atEOF = err != nil
|
||||
s.loop = s.loop && err == nil
|
||||
s.pos = to
|
||||
}
|
||||
continue
|
||||
}
|
||||
if len(s.ring)-s.n < decodeFrames*s.keep {
|
||||
s.full = true
|
||||
continue
|
||||
}
|
||||
gen := s.gen
|
||||
s.mu.Unlock()
|
||||
n, err := s.d.Read(buf)
|
||||
n -= n % s.channels
|
||||
samples := buf[:n]
|
||||
if kept != nil {
|
||||
k := 0
|
||||
for i := 0; i < n; i += s.channels {
|
||||
k += copy(kept[k:], buf[i:i+s.keep])
|
||||
}
|
||||
samples = kept[:k]
|
||||
}
|
||||
s.mu.Lock()
|
||||
if gen != s.gen {
|
||||
// Seeked meanwhile.
|
||||
continue
|
||||
}
|
||||
frames := int64(n / s.channels)
|
||||
if s.loop && s.end > 0 && s.pos+frames >= s.end {
|
||||
// Past the loop's end: what is before it, then its start.
|
||||
samples = samples[:max(s.end-s.pos, 0)*int64(s.keep)]
|
||||
s.wrap = true
|
||||
}
|
||||
s.pos += frames
|
||||
for len(samples) > 0 {
|
||||
w := (s.r + s.n) % len(s.ring)
|
||||
c := copy(s.ring[w:min(len(s.ring), w+len(s.ring)-s.n)], samples)
|
||||
s.n += c
|
||||
samples = samples[c:]
|
||||
}
|
||||
if err != nil || n == 0 {
|
||||
// The end, or an error, which ends the stream as well.
|
||||
s.atEOF = true
|
||||
if err != io.EOF && err != nil || n == 0 && err == nil {
|
||||
// A decoder that fails or makes no progress loops no more.
|
||||
s.loop = false
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (s *stream) read(dst []float32) (int, bool) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
want := min(len(dst), s.n)
|
||||
want -= want % s.keep
|
||||
got := 0
|
||||
for got < want {
|
||||
c := copy(dst[got:want], s.ring[s.r:])
|
||||
got += c
|
||||
s.r = (s.r + c) % len(s.ring)
|
||||
s.n -= c
|
||||
}
|
||||
if s.full && len(s.ring)-s.n >= len(s.ring)/4 {
|
||||
s.full = false
|
||||
s.cond.Signal()
|
||||
}
|
||||
ended := got < len(dst)/s.keep*s.keep && s.n == 0 && s.atEOF && !s.loop && s.seekTo < 0
|
||||
return got / s.keep, ended
|
||||
}
|
||||
|
||||
func (s *stream) seek(frame int64) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
s.seekTo = frame
|
||||
s.atEOF, s.wrap = false, false
|
||||
s.r, s.n = 0, 0
|
||||
s.gen++
|
||||
s.full = false
|
||||
s.cond.Signal()
|
||||
}
|
||||
|
||||
func (s *stream) setLoop(loop bool, start, end int64) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
if s.wrap && !loop {
|
||||
// Looping no more at its end: from there, where it decoded past.
|
||||
s.wrap, s.seekTo = false, s.end
|
||||
}
|
||||
s.loop, s.start, s.end = loop, start, end
|
||||
s.cond.Signal()
|
||||
}
|
||||
|
||||
func (s *stream) close() {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
s.closed = true
|
||||
s.cond.Signal()
|
||||
}
|
||||
Vendored
+297
@@ -0,0 +1,297 @@
|
||||
package audio
|
||||
|
||||
import "math"
|
||||
|
||||
// A stretcher time-stretches a voice's source for SetPreservesPitch, by
|
||||
// WSOLA (waveform similarity overlap-add): it plays segments of the
|
||||
// source, two hops long, half overlapping, crossfaded with a Hann window,
|
||||
// one hop of the output each. Where the speed puts the next segment, it
|
||||
// looks within tolerance for the start most like the natural continuation
|
||||
// of the last, so that the waveform goes on without a seam, skipping or
|
||||
// repeating whole periods of it; the pitch stays. The voice then
|
||||
// resamples what it gives at its rate alone, without its speed.
|
||||
//
|
||||
// A voice gets one the first time its player preserves pitch and keeps
|
||||
// it: with it off, it passes the source through as it is, which a voice
|
||||
// without one reads itself.
|
||||
type stretcher struct {
|
||||
ch int // channels of the source: 1 or 2
|
||||
hs int // a hop: half a segment, about 16 ms
|
||||
delta int64 // how far a segment may move to match, about 10 ms
|
||||
dec int // the stride of the coarse search: about 16 kHz
|
||||
win []float32
|
||||
|
||||
// Frames of the source from frame base, n of them. rd is the frame
|
||||
// read next: base+n, or before base while skipping up to it.
|
||||
buf []float32
|
||||
base int64
|
||||
n int
|
||||
rd int64
|
||||
end int64 // the frame after the source's last, once it ended, or -1
|
||||
held int // frames of buf a pass-through read gave, dropped at the next
|
||||
|
||||
mono []float32 // the frames searched, mixed to mono
|
||||
tm []float32 // tail, mixed to mono
|
||||
tail []float32 // a hop of the natural continuation of the last segment
|
||||
nat int64 // the frame tail starts at
|
||||
out []float32 // a hop: what a step gives
|
||||
own []float32 // the source's frames, passed through
|
||||
|
||||
on bool // stretching, rather than passing the source through
|
||||
first bool // no segment yet since it started stretching
|
||||
done bool // nothing more to give
|
||||
ana float64 // the frame the speed puts the next segment at
|
||||
|
||||
// The source frames, counted on past its loop's end, that the frames
|
||||
// of the voice's ring are at, as it holds them; those of what it read
|
||||
// last, from tag0 by tagStep; and where the frames after them are.
|
||||
tags []float64
|
||||
tag0, tagStep float64
|
||||
next float64
|
||||
}
|
||||
|
||||
func newStretcher(rate, ch int) *stretcher {
|
||||
hs := max(rate/64, 16)
|
||||
delta := max(rate/96, 8)
|
||||
// The frames a step reads at most, and what a voice hands over.
|
||||
size := max(2*delta+2*hs+1, 256)
|
||||
st := &stretcher{
|
||||
ch: ch, hs: hs, delta: int64(delta), dec: max(rate/16000, 1),
|
||||
win: make([]float32, hs),
|
||||
buf: make([]float32, size*ch),
|
||||
mono: make([]float32, 2*delta+hs+1),
|
||||
tm: make([]float32, hs),
|
||||
tail: make([]float32, hs*ch),
|
||||
out: make([]float32, hs*ch),
|
||||
own: make([]float32, 256*ch),
|
||||
tags: make([]float64, ringFrames),
|
||||
}
|
||||
for j := range st.win {
|
||||
s := math.Sin(math.Pi / 2 * (float64(j) + 0.5) / float64(hs))
|
||||
st.win[j] = float32(s * s)
|
||||
}
|
||||
return st
|
||||
}
|
||||
|
||||
// reset starts over at frame f, from which the source reads next, and
|
||||
// sets the voice's frames before it, which it has not read yet, at the
|
||||
// frames before f.
|
||||
func (st *stretcher) reset(f int64, on bool) {
|
||||
st.base, st.rd, st.n, st.held = f, f, 0, 0
|
||||
st.end = -1
|
||||
st.on, st.first, st.done = on, true, false
|
||||
st.ana, st.next = float64(f), float64(f)
|
||||
// The voice is at f, until frames come in.
|
||||
st.tags[f&(ringFrames-1)] = float64(f)
|
||||
st.tags[(f+1)&(ringFrames-1)] = float64(f + 1)
|
||||
}
|
||||
|
||||
// push notes that frame f, coming into the voice's ring, is at tag.
|
||||
func (st *stretcher) push(f int64, tag float64) {
|
||||
st.tags[f&(ringFrames-1)] = tag
|
||||
}
|
||||
|
||||
// drop forgets the frames before to; those not read yet are skipped.
|
||||
func (st *stretcher) drop(to int64) {
|
||||
if to <= st.base {
|
||||
return
|
||||
}
|
||||
if k := to - st.base; k < int64(st.n) {
|
||||
st.n -= int(k)
|
||||
copy(st.buf, st.buf[int(k)*st.ch:(int(k)+st.n)*st.ch])
|
||||
} else {
|
||||
st.n = 0
|
||||
}
|
||||
st.base = to
|
||||
}
|
||||
|
||||
// fill reads the source up to frame upto, or its end, and reports false
|
||||
// while a stream has not decoded that far.
|
||||
func (st *stretcher) fill(src source, upto int64) bool {
|
||||
ch := st.ch
|
||||
for st.end < 0 && st.rd < upto {
|
||||
skip := st.rd < st.base
|
||||
var dst []float32
|
||||
if skip {
|
||||
dst = st.buf[:min(st.base-st.rd, int64(len(st.buf)/ch))*int64(ch)]
|
||||
} else {
|
||||
dst = st.buf[st.n*ch : (st.n+int(min(upto-st.rd, int64(len(st.buf)/ch-st.n))))*ch]
|
||||
}
|
||||
got, ended := src.read(dst)
|
||||
if !skip {
|
||||
st.n += got
|
||||
}
|
||||
st.rd += int64(got)
|
||||
if ended {
|
||||
st.end = st.rd
|
||||
} else if got == 0 {
|
||||
return false
|
||||
}
|
||||
}
|
||||
if st.end >= 0 && st.base+int64(st.n) < upto {
|
||||
// Silence after the end.
|
||||
k := int(upto - st.base)
|
||||
clear(st.buf[st.n*ch : k*ch])
|
||||
st.n = k
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// readStretched gives the voice its next frames, in v.in, as a source does:
|
||||
// time-stretched while it preserves pitch, else as the source has them.
|
||||
func (v *voice) readStretched() (int, bool) {
|
||||
st := v.st
|
||||
if st.held > 0 {
|
||||
st.drop(st.base + int64(st.held))
|
||||
st.held = 0
|
||||
}
|
||||
if st.done {
|
||||
return 0, true
|
||||
}
|
||||
if v.pitch != st.on {
|
||||
// From what is held, which goes on from the last segment.
|
||||
if v.pitch {
|
||||
st.first, st.ana = true, float64(st.base)
|
||||
} else if !st.first && st.nat >= st.base {
|
||||
st.drop(st.nat)
|
||||
}
|
||||
if st.end >= 0 {
|
||||
// Not the silence after the end.
|
||||
st.n = int(max(min(int64(st.n), st.end-st.base), 0))
|
||||
}
|
||||
st.on = v.pitch
|
||||
}
|
||||
if st.on {
|
||||
n, ended := st.stretch(v.src, v.speed)
|
||||
v.in = st.out
|
||||
return n, ended
|
||||
}
|
||||
st.tagStep = 1
|
||||
if st.n > 0 {
|
||||
st.tag0, st.held = float64(st.base), st.n
|
||||
st.next = float64(st.base + int64(st.n))
|
||||
v.in = st.buf
|
||||
return st.n, false
|
||||
}
|
||||
n, ended := v.src.read(st.own)
|
||||
st.tag0 = float64(st.rd)
|
||||
st.rd += int64(n)
|
||||
st.base = st.rd
|
||||
st.next = float64(st.rd)
|
||||
v.in = st.own
|
||||
return n, ended
|
||||
}
|
||||
|
||||
// stretch puts the next frames into st.out and returns how many, with
|
||||
// ended true once there are none, and none while a stream is late.
|
||||
func (st *stretcher) stretch(src source, speed float64) (int, bool) {
|
||||
hs, ch := st.hs, st.ch
|
||||
a := int64(math.Round(st.ana))
|
||||
lo, hi := a, a
|
||||
if !st.first {
|
||||
lo = max(a-st.delta, st.base)
|
||||
hi = max(a+st.delta, lo)
|
||||
}
|
||||
st.drop(lo)
|
||||
if !st.fill(src, hi+int64(2*hs)) {
|
||||
return 0, false
|
||||
}
|
||||
if e := st.end; e >= 0 && a >= e {
|
||||
// The speed is past the end: what was playing fades out.
|
||||
st.done, st.next = true, float64(e)
|
||||
if st.first {
|
||||
return 0, true
|
||||
}
|
||||
for j := range hs {
|
||||
w := 1 - st.win[j]
|
||||
for k := j * ch; k < (j+1)*ch; k++ {
|
||||
st.out[k] = st.tail[k] * w
|
||||
}
|
||||
}
|
||||
st.tag0, st.tagStep = float64(e), 0
|
||||
return hs, false
|
||||
}
|
||||
s := lo
|
||||
if !st.first {
|
||||
s = st.best(lo, hi)
|
||||
}
|
||||
in := st.buf[int(s-st.base)*ch:]
|
||||
o := st.out[:hs*ch]
|
||||
if st.first || s == st.nat {
|
||||
// No seam: the source as it is.
|
||||
copy(o, in)
|
||||
} else {
|
||||
for j := range hs {
|
||||
w := st.win[j]
|
||||
for k := j * ch; k < (j+1)*ch; k++ {
|
||||
o[k] = st.tail[k] + (in[k]-st.tail[k])*w
|
||||
}
|
||||
}
|
||||
}
|
||||
copy(st.tail, in[hs*ch:2*hs*ch])
|
||||
st.first = false
|
||||
st.nat = s + int64(hs)
|
||||
st.tag0, st.tagStep = st.ana, speed
|
||||
st.ana += float64(hs) * speed
|
||||
st.next = st.ana
|
||||
if e := st.end; e >= 0 && st.next > float64(e) {
|
||||
// Where the source ends, the frames after are at its end.
|
||||
st.tagStep = max(float64(e)-st.tag0, 0) / float64(hs)
|
||||
st.next = float64(e)
|
||||
}
|
||||
return hs, false
|
||||
}
|
||||
|
||||
// best returns the start between lo and hi of the segment whose first hop
|
||||
// is most like tail, by normalized cross-correlation in mono: every dec
|
||||
// frames, then each frame around the best.
|
||||
func (st *stretcher) best(lo, hi int64) int64 {
|
||||
if st.nat >= lo && st.nat <= hi {
|
||||
// The natural continuation itself: a perfect match.
|
||||
return st.nat
|
||||
}
|
||||
hs, ch := st.hs, st.ch
|
||||
span := int(hi - lo)
|
||||
off := int(lo - st.base)
|
||||
m, t := st.mono[:span+hs], st.tm
|
||||
if ch == 1 {
|
||||
copy(m, st.buf[off:])
|
||||
copy(t, st.tail)
|
||||
} else {
|
||||
for i := range m {
|
||||
m[i] = st.buf[2*(off+i)] + st.buf[2*(off+i)+1]
|
||||
}
|
||||
for i := range t {
|
||||
t[i] = st.tail[2*i] + st.tail[2*i+1]
|
||||
}
|
||||
}
|
||||
score := func(s, stride int) float32 {
|
||||
var xy, yy float32
|
||||
y := m[s : s+hs]
|
||||
for j := 0; j < hs; j += stride {
|
||||
xy += t[j] * y[j]
|
||||
yy += y[j] * y[j]
|
||||
}
|
||||
if yy == 0 {
|
||||
return 0
|
||||
}
|
||||
return xy / float32(math.Sqrt(float64(yy)))
|
||||
}
|
||||
dec := st.dec
|
||||
b, bs := 0, float32(math.Inf(-1))
|
||||
for s := 0; s <= span; s += dec {
|
||||
if x := score(s, dec); x > bs {
|
||||
b, bs = s, x
|
||||
}
|
||||
}
|
||||
if dec > 1 {
|
||||
c := b
|
||||
bs = float32(math.Inf(-1))
|
||||
for s := max(c-dec+1, 0); s <= min(c+dec-1, span); s++ {
|
||||
if x := score(s, 1); x > bs {
|
||||
b, bs = s, x
|
||||
}
|
||||
}
|
||||
}
|
||||
return lo + int64(b)
|
||||
}
|
||||
+337
@@ -0,0 +1,337 @@
|
||||
package audio
|
||||
|
||||
import (
|
||||
"io"
|
||||
"math"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// sine returns secs of sines of amplitude 0.5 at rate, one frequency for
|
||||
// each channel.
|
||||
func sine(rate int, secs float64, freqs ...float64) []float32 {
|
||||
ch := len(freqs)
|
||||
n := int(secs * float64(rate))
|
||||
s := make([]float32, n*ch)
|
||||
for i := range n {
|
||||
for c, f := range freqs {
|
||||
s[i*ch+c] = float32(0.5 * math.Sin(2*math.Pi*f*float64(i)/float64(rate)))
|
||||
}
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
// channel returns channel c of out, interleaved stereo, from frame from
|
||||
// to frame to.
|
||||
func channel(out []float32, c, from, to int) []float32 {
|
||||
x := make([]float32, to-from)
|
||||
for i := range x {
|
||||
x[i] = out[2*(from+i)+c]
|
||||
}
|
||||
return x
|
||||
}
|
||||
|
||||
// dominant returns the frequency, to the hertz, of x's strongest
|
||||
// component between 50 Hz and 2 kHz, by the Goertzel algorithm.
|
||||
func dominant(x []float32) float64 {
|
||||
best, at := 0.0, 0.0
|
||||
for f := 50.0; f <= 2000; f++ {
|
||||
w := 2 * math.Pi * f / sampleRate
|
||||
c := 2 * math.Cos(w)
|
||||
var s1, s2 float64
|
||||
for _, v := range x {
|
||||
s1, s2 = float64(v)+c*s1-s2, s1
|
||||
}
|
||||
if p := s1*s1 + s2*s2 - c*s1*s2; p > best {
|
||||
best, at = p, f
|
||||
}
|
||||
}
|
||||
return at
|
||||
}
|
||||
|
||||
// smooth checks that channel c of out, a sine of amplitude 0.5 at up to
|
||||
// maxHz, has no click and no gap from frame from to frame to: no step
|
||||
// between frames much larger than the sine's steepest, and no period
|
||||
// without its peaks.
|
||||
func smooth(t *testing.T, out []float32, c, from, to int, maxHz float64, what string) {
|
||||
t.Helper()
|
||||
steep := 2 * math.Pi * maxHz * 0.5 / sampleRate
|
||||
for i := from + 1; i < to; i++ {
|
||||
if d := math.Abs(float64(out[2*i+c] - out[2*(i-1)+c])); d > 1.6*steep {
|
||||
t.Fatalf("%s: a click at frame %d: %v to %v", what, i, out[2*(i-1)+c], out[2*i+c])
|
||||
}
|
||||
}
|
||||
period := int(sampleRate/maxHz*2) + 1
|
||||
for i := from; i+period <= to; i += period / 2 {
|
||||
peak := float32(0)
|
||||
for _, v := range channel(out, c, i, i+period) {
|
||||
peak = max(peak, v, -v)
|
||||
}
|
||||
if peak < 0.35 {
|
||||
t.Fatalf("%s: a gap at frame %d: peak %v", what, i, peak)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// renderToEnd mixes p until it ends, and returns what it mixed.
|
||||
func renderToEnd(t *testing.T, p *Player) []float32 {
|
||||
t.Helper()
|
||||
var out []float32
|
||||
for p.Playing() {
|
||||
out = append(out, render(256)...)
|
||||
if len(out) > 60*sampleRate*channels {
|
||||
t.Fatal("a minute and not at its end")
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// framesPlayed returns the frames of out up to its last that is not silent.
|
||||
func framesPlayed(out []float32) int {
|
||||
for i := len(out)/2 - 1; i >= 0; i-- {
|
||||
if out[2*i] != 0 || out[2*i+1] != 0 {
|
||||
return i + 1
|
||||
}
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
// At 1.5×, a sine stretched keeps its frequency, and one resampled, the
|
||||
// default, rises a fifth.
|
||||
func TestPreservesPitch(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
rate int
|
||||
freqs []float64
|
||||
}{
|
||||
{"mono", sampleRate, []float64{220}},
|
||||
{"stereo", sampleRate, []float64{200, 300}},
|
||||
{"mono at 24 kHz", 24000, []float64{220}},
|
||||
{"stereo at 96 kHz", 96000, []float64{200, 300}},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
s := NewSound(tc.rate, len(tc.freqs), sine(tc.rate, 2, tc.freqs...))
|
||||
for _, keep := range []bool{true, false} {
|
||||
setup(t)
|
||||
p := s.NewPlayer().SetSpeed(1.5)
|
||||
if keep {
|
||||
p.SetPreservesPitch(true)
|
||||
}
|
||||
p.Play()
|
||||
out := render(sampleRate)
|
||||
for c := range 2 {
|
||||
f := tc.freqs[min(c, len(tc.freqs)-1)]
|
||||
want := f
|
||||
if !keep {
|
||||
want = f * 1.5
|
||||
}
|
||||
if got := dominant(channel(out, c, sampleRate/4, sampleRate*3/4)); math.Abs(got-want) > want*0.01 {
|
||||
t.Errorf("preserving pitch %v: channel %d of %v Hz plays at %v Hz, want %v", keep, c, f, got, want)
|
||||
}
|
||||
if keep {
|
||||
smooth(t, out, c, 0, sampleRate, f, "stretched")
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// Stretched, a sound plays for its duration over the speed, and ends
|
||||
// where it ends.
|
||||
func TestPreservesPitchDuration(t *testing.T) {
|
||||
for _, ch := range []int{1, 2} {
|
||||
freqs := []float64{220, 330}[:ch]
|
||||
s := NewSound(sampleRate, ch, sine(sampleRate, 1, freqs...))
|
||||
for _, speed := range []float64{0.25, 0.5, 1, 1.25, 1.5, 2, 4, 16} {
|
||||
setup(t)
|
||||
p := s.NewPlayer().SetSpeed(speed).SetPreservesPitch(true)
|
||||
ended := make(chan struct{}, 1)
|
||||
p.OnEnd(func() { ended <- struct{}{} })
|
||||
p.Play()
|
||||
out := renderToEnd(t, p)
|
||||
got := frames(int64(framesPlayed(out)), sampleRate)
|
||||
want := time.Duration(float64(time.Second) / speed)
|
||||
// Within a hop.
|
||||
if d := got - want; d < -25*time.Millisecond || d > 25*time.Millisecond {
|
||||
t.Errorf("%d channels at %v×: played %v, want %v", ch, speed, got, want)
|
||||
}
|
||||
if p.Position() != p.Duration() {
|
||||
t.Errorf("%d channels at %v×: Position = %v at the end, want %v", ch, speed, p.Position(), p.Duration())
|
||||
}
|
||||
select {
|
||||
case <-ended:
|
||||
case <-time.After(time.Minute):
|
||||
t.Fatalf("%d channels at %v×: no OnEnd", ch, speed)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Resampling stays the default: a player gets no stretcher until it
|
||||
// preserves pitch, and at speed 1 a stretched one plays as decoded.
|
||||
func TestPreservesPitchIsOptIn(t *testing.T) {
|
||||
setup(t)
|
||||
samples := sine(sampleRate, 0.5, 220)
|
||||
p := NewSound(sampleRate, 1, samples).NewPlayer().SetSpeed(1.5).SetPreservesPitch(false)
|
||||
if p.PreservesPitch() || p.v.st != nil {
|
||||
t.Fatalf("PreservesPitch = %v, stretcher %v, by default", p.PreservesPitch(), p.v.st)
|
||||
}
|
||||
p.SetSpeed(1).SetPreservesPitch(true).Play()
|
||||
if !p.PreservesPitch() {
|
||||
t.Error("PreservesPitch = false after SetPreservesPitch(true)")
|
||||
}
|
||||
out := render(sampleRate / 4)
|
||||
for i := range sampleRate / 4 {
|
||||
if !near(out[2*i], samples[i]) {
|
||||
t.Fatalf("frame %d at 1× = %v, want %v as decoded", i, out[2*i], samples[i])
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Position follows the source at the speed while stretched, as resampled.
|
||||
func TestPreservesPitchPosition(t *testing.T) {
|
||||
setup(t)
|
||||
hold(heldFrames)
|
||||
p := NewSound(sampleRate, 1, sine(sampleRate, 4, 220)).NewPlayer().SetSpeed(1.5).SetPreservesPitch(true)
|
||||
p.Play()
|
||||
render(3 * heldFrames)
|
||||
atFrame(t, p, 3*heldFrames, "200 ms heard at 1.5×")
|
||||
p.SetSpeed(2)
|
||||
render(heldFrames)
|
||||
// Of the 100 ms heard since, all were mixed at 1.5: what changed is
|
||||
// a hop or so behind.
|
||||
atFrame(t, p, 3*heldFrames+heldFrames*3/2, "100 ms more at 1.5×")
|
||||
p.Seek(time.Second)
|
||||
atFrame(t, p, sampleRate, "right after Seek")
|
||||
render(heldFrames + 1000)
|
||||
atFrame(t, p, sampleRate+2000, "1000 frames into the seek at 2×")
|
||||
}
|
||||
|
||||
// The stretch goes on without a click or a gap as the speed changes, over
|
||||
// a loop's seam, and as it turns on and off; a seek starts it over at the
|
||||
// frame seeked to.
|
||||
func TestStretchIsContinuous(t *testing.T) {
|
||||
setup(t)
|
||||
// 100 periods of 200 Hz: a seamless loop.
|
||||
samples := sine(sampleRate, 0.5, 200)
|
||||
p := NewSound(sampleRate, 1, samples).NewPlayer().SetLoop(true).SetPreservesPitch(true)
|
||||
p.Play()
|
||||
var out []float32
|
||||
for _, speed := range []float64{1, 1.25, 1.5, 2, 3, 0.75, 0.5, 4} {
|
||||
p.SetSpeed(speed)
|
||||
out = append(out, render(sampleRate/5)...)
|
||||
}
|
||||
// 8 × 200 ms at 1.95× on average: 6 loops.
|
||||
smooth(t, out, 0, 0, len(out)/2, 200, "changing speed and looping")
|
||||
if got := dominant(channel(out, 0, 0, len(out)/2)); got != 200 {
|
||||
t.Errorf("plays at %v Hz, want 200", got)
|
||||
}
|
||||
|
||||
p.SetSpeed(1.5)
|
||||
out = render(sampleRate / 5)
|
||||
p.SetPreservesPitch(false)
|
||||
out = append(out, render(sampleRate/5)...)
|
||||
p.SetPreservesPitch(true)
|
||||
out = append(out, render(sampleRate/5)...)
|
||||
smooth(t, out, 0, 0, len(out)/2, 300, "turning on and off")
|
||||
if got := dominant(channel(out, 0, sampleRate/5+2000, 2*sampleRate/5)); got != 300 {
|
||||
t.Errorf("resampled at 1.5× again: %v Hz, want 300", got)
|
||||
}
|
||||
if got := dominant(channel(out, 0, 2*sampleRate/5+2000, 3*sampleRate/5)); got != 200 {
|
||||
t.Errorf("stretched again: %v Hz, want 200", got)
|
||||
}
|
||||
|
||||
setup(t)
|
||||
ramped := ramp(sampleRate)
|
||||
q := NewSound(sampleRate, 1, ramped).NewPlayer().SetSpeed(2).SetPreservesPitch(true)
|
||||
q.Play()
|
||||
render(5000)
|
||||
q.Seek(500 * time.Millisecond)
|
||||
out = render(rampFrames + 20)
|
||||
// What a stretch begins with plays as it is.
|
||||
if i := rampFrames + 10; !near(out[2*i], ramped[24000+i]) {
|
||||
t.Errorf("frame %d after seeking = %v, want %v", i, out[2*i], ramped[24000+i])
|
||||
}
|
||||
}
|
||||
|
||||
// sineDecoder decodes a sine of amplitude 0.5 in each of ch channels.
|
||||
type sineDecoder struct {
|
||||
ch int
|
||||
hz float64
|
||||
pos, length int64
|
||||
}
|
||||
|
||||
func (d *sineDecoder) SampleRate() int { return sampleRate }
|
||||
func (d *sineDecoder) Channels() int { return d.ch }
|
||||
func (d *sineDecoder) Len() int64 { return d.length }
|
||||
|
||||
func (d *sineDecoder) Read(buf []float32) (int, error) {
|
||||
n := 0
|
||||
for ; n+d.ch <= len(buf) && d.pos < d.length; n += d.ch {
|
||||
for c := range d.ch {
|
||||
buf[n+c] = float32(0.5 * math.Sin(2*math.Pi*d.hz*float64(d.pos)/sampleRate))
|
||||
}
|
||||
d.pos++
|
||||
}
|
||||
if n == 0 {
|
||||
return 0, io.EOF
|
||||
}
|
||||
return n, nil
|
||||
}
|
||||
|
||||
func (d *sineDecoder) SetPosition(f int64) error { d.pos = f; return nil }
|
||||
|
||||
// A stream stretches as a sound does, to its end.
|
||||
func TestStreamStretches(t *testing.T) {
|
||||
setup(t)
|
||||
p := NewPlayer(&sineDecoder{ch: 2, hz: 250, length: sampleRate}).SetSpeed(1.5).SetPreservesPitch(true)
|
||||
defer p.Close()
|
||||
p.Play()
|
||||
s := p.v.src.(*stream)
|
||||
var out []float32
|
||||
for p.Playing() {
|
||||
// The decoder keeps a second ahead: wait for it, as the device
|
||||
// would not.
|
||||
for {
|
||||
s.mu.Lock()
|
||||
ok := s.n >= 8192 || s.atEOF
|
||||
s.mu.Unlock()
|
||||
if ok {
|
||||
break
|
||||
}
|
||||
time.Sleep(time.Millisecond)
|
||||
}
|
||||
out = append(out, render(256)...)
|
||||
if len(out) > 10*sampleRate*channels {
|
||||
t.Fatal("10 s and not at its end")
|
||||
}
|
||||
}
|
||||
n := framesPlayed(out)
|
||||
if got, want := frames(int64(n), sampleRate), time.Second*2/3; got < want-25*time.Millisecond || got > want+25*time.Millisecond {
|
||||
t.Errorf("played %v, want %v", got, want)
|
||||
}
|
||||
smooth(t, out, 1, 0, n-2*sampleRate/250, 250, "a stream")
|
||||
if got := dominant(channel(out, 0, 0, n)); got != 250 {
|
||||
t.Errorf("plays at %v Hz, want 250", got)
|
||||
}
|
||||
}
|
||||
|
||||
// Stretching allocates nothing as it mixes.
|
||||
func TestStretchAllocatesNothing(t *testing.T) {
|
||||
setup(t)
|
||||
p := NewSound(sampleRate, 2, sine(sampleRate, 0.5, 200, 300)).NewPlayer().
|
||||
SetLoop(true).SetSpeed(1.5).SetPreservesPitch(true)
|
||||
p.Play()
|
||||
buf := make([]float32, 480*channels)
|
||||
speeds := []float64{1.5, 2, 0.75}
|
||||
i := 0
|
||||
if n := testing.AllocsPerRun(500, func() {
|
||||
mix(buf)
|
||||
if i++; i%50 == 0 {
|
||||
p.SetSpeed(speeds[i/50%len(speeds)])
|
||||
}
|
||||
}); n != 0 {
|
||||
t.Errorf("%v allocations a buffer", n)
|
||||
}
|
||||
}
|
||||
BIN
Binary file not shown.
+34
@@ -0,0 +1,34 @@
|
||||
// Package vorbis decodes Ogg Vorbis files for package audio, with
|
||||
// github.com/jfreymuth/oggvorbis. Import it for its side effect:
|
||||
//
|
||||
// import _ "github.com/egoist/mygo/audio/vorbis"
|
||||
package vorbis
|
||||
|
||||
import (
|
||||
"io"
|
||||
|
||||
"github.com/egoist/mygo/audio"
|
||||
"github.com/jfreymuth/oggvorbis"
|
||||
)
|
||||
|
||||
func init() {
|
||||
audio.RegisterFormat("vorbis", "OggS", func(r io.ReadSeeker) (audio.Decoder, error) { return NewDecoder(r) })
|
||||
}
|
||||
|
||||
// NewDecoder returns a decoder of the Ogg Vorbis file r.
|
||||
func NewDecoder(r io.ReadSeeker) (audio.Decoder, error) {
|
||||
v, err := oggvorbis.NewReader(r)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return decoder{v}, nil
|
||||
}
|
||||
|
||||
type decoder struct{ *oggvorbis.Reader }
|
||||
|
||||
func (d decoder) Len() int64 {
|
||||
if n := d.Length(); n > 0 {
|
||||
return n
|
||||
}
|
||||
return -1
|
||||
}
|
||||
+58
@@ -0,0 +1,58 @@
|
||||
package vorbis
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"math"
|
||||
"os"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/egoist/mygo/audio"
|
||||
)
|
||||
|
||||
// tone.ogg is 0.5 s of a 440 Hz sine at 22.05 kHz, in stereo.
|
||||
func TestDecode(t *testing.T) {
|
||||
data, err := os.ReadFile("testdata/tone.ogg")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
d, name, err := audio.NewDecoder(bytes.NewReader(data))
|
||||
if err != nil || name != "vorbis" {
|
||||
t.Fatal(name, err)
|
||||
}
|
||||
if d.SampleRate() != 22050 || d.Channels() != 2 || d.Len() < 11025 || d.Len() > 11025+128 {
|
||||
t.Fatalf("%d Hz, %d channels, %d frames", d.SampleRate(), d.Channels(), d.Len())
|
||||
}
|
||||
buf := make([]float32, 2*d.Len())
|
||||
n := 0
|
||||
for n < len(buf) {
|
||||
m, err := d.Read(buf[n:])
|
||||
n += m
|
||||
if err != nil {
|
||||
break
|
||||
}
|
||||
}
|
||||
if n != len(buf) {
|
||||
t.Fatalf("decoded %d samples", n)
|
||||
}
|
||||
// Zero crossings of the left channel, 2 a period.
|
||||
zc := 0
|
||||
for i := 2; i < n; i += 2 {
|
||||
if (buf[i-2] < 0) != (buf[i] < 0) {
|
||||
zc++
|
||||
}
|
||||
}
|
||||
if f := float64(zc) / 2 / (float64(n/2) / 22050); math.Abs(f-440) > 5 {
|
||||
t.Errorf("decoded %v Hz", f)
|
||||
}
|
||||
s, err := audio.DecodeSound(data)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got := s.Duration(); got < 500*time.Millisecond || got > 510*time.Millisecond {
|
||||
t.Errorf("Duration = %v", got)
|
||||
}
|
||||
if err := d.SetPosition(5000); err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
}
|
||||
Vendored
+160
@@ -0,0 +1,160 @@
|
||||
package audio
|
||||
|
||||
import (
|
||||
"encoding/binary"
|
||||
"errors"
|
||||
"io"
|
||||
"math"
|
||||
)
|
||||
|
||||
func init() {
|
||||
RegisterFormat("wav", "RIFF????WAVE", func(r io.ReadSeeker) (Decoder, error) { return newWAV(r) })
|
||||
}
|
||||
|
||||
// A wavDecoder decodes WAV files of integer PCM of 8 to 32 bits, or of
|
||||
// 32 or 64 bit floats.
|
||||
type wavDecoder struct {
|
||||
r io.ReadSeeker
|
||||
br io.Reader
|
||||
rate int
|
||||
channels int
|
||||
bits int
|
||||
float bool
|
||||
start int64 // the data's offset
|
||||
length int64 // frames, or -1
|
||||
pos int64 // frame
|
||||
buf []byte
|
||||
}
|
||||
|
||||
var errWAV = errors.New("audio: invalid WAV")
|
||||
|
||||
func newWAV(r io.ReadSeeker) (*wavDecoder, error) {
|
||||
start, err := r.Seek(0, io.SeekCurrent)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var riff [12]byte
|
||||
if _, err := io.ReadFull(r, riff[:]); err != nil {
|
||||
return nil, errWAV
|
||||
}
|
||||
d := &wavDecoder{r: r}
|
||||
off := start + 12
|
||||
haveFmt := false
|
||||
for {
|
||||
var h [8]byte
|
||||
if _, err := io.ReadFull(r, h[:]); err != nil {
|
||||
return nil, errWAV
|
||||
}
|
||||
size := int64(binary.LittleEndian.Uint32(h[4:]))
|
||||
off += 8
|
||||
switch string(h[:4]) {
|
||||
case "fmt ":
|
||||
if size < 16 || size > 1<<16 {
|
||||
return nil, errWAV
|
||||
}
|
||||
b := make([]byte, size)
|
||||
if _, err := io.ReadFull(r, b); err != nil {
|
||||
return nil, errWAV
|
||||
}
|
||||
tag := binary.LittleEndian.Uint16(b)
|
||||
d.channels = int(binary.LittleEndian.Uint16(b[2:]))
|
||||
d.rate = int(binary.LittleEndian.Uint32(b[4:]))
|
||||
d.bits = int(binary.LittleEndian.Uint16(b[14:]))
|
||||
if tag == 0xfffe && size >= 40 {
|
||||
// WAVE_FORMAT_EXTENSIBLE: the tag starts the sub-format.
|
||||
tag = binary.LittleEndian.Uint16(b[24:])
|
||||
}
|
||||
switch {
|
||||
case tag == 1 && d.bits >= 8 && d.bits <= 32 && d.bits%8 == 0:
|
||||
case tag == 3 && (d.bits == 32 || d.bits == 64):
|
||||
d.float = true
|
||||
default:
|
||||
return nil, errors.New("audio: WAV of an encoding other than PCM or float")
|
||||
}
|
||||
if d.channels < 1 || d.rate < 1 {
|
||||
return nil, errWAV
|
||||
}
|
||||
haveFmt = true
|
||||
case "data":
|
||||
if !haveFmt {
|
||||
return nil, errWAV
|
||||
}
|
||||
d.start = off
|
||||
d.length = -1
|
||||
if size != 0 && size != 0xffffffff {
|
||||
// Not one written as it streamed.
|
||||
d.length = size / int64(d.frameBytes())
|
||||
}
|
||||
d.br = readerOf(r)
|
||||
return d, nil
|
||||
}
|
||||
// Chunks are padded to even sizes.
|
||||
size += size & 1
|
||||
if _, err := r.Seek(off+size, io.SeekStart); err != nil {
|
||||
return nil, errWAV
|
||||
}
|
||||
off += size
|
||||
}
|
||||
}
|
||||
|
||||
func (d *wavDecoder) frameBytes() int { return d.channels * d.bits / 8 }
|
||||
func (d *wavDecoder) SampleRate() int { return d.rate }
|
||||
func (d *wavDecoder) Channels() int { return d.channels }
|
||||
func (d *wavDecoder) Len() int64 { return d.length }
|
||||
|
||||
func (d *wavDecoder) Read(dst []float32) (int, error) {
|
||||
fb := d.frameBytes()
|
||||
n := len(dst) / d.channels
|
||||
if d.length >= 0 {
|
||||
n = int(min(int64(n), d.length-d.pos))
|
||||
}
|
||||
if n <= 0 {
|
||||
return 0, io.EOF
|
||||
}
|
||||
if cap(d.buf) < n*fb {
|
||||
d.buf = make([]byte, n*fb)
|
||||
}
|
||||
b := d.buf[:n*fb]
|
||||
got, err := io.ReadFull(d.br, b)
|
||||
n = got / fb
|
||||
if n == 0 {
|
||||
if err == nil || err == io.ErrUnexpectedEOF {
|
||||
err = io.EOF
|
||||
}
|
||||
return 0, err
|
||||
}
|
||||
bs := d.bits / 8
|
||||
for i := range n * d.channels {
|
||||
s := b[i*bs:]
|
||||
var v float32
|
||||
switch {
|
||||
case d.float && bs == 4:
|
||||
v = math.Float32frombits(binary.LittleEndian.Uint32(s))
|
||||
case d.float:
|
||||
v = float32(math.Float64frombits(binary.LittleEndian.Uint64(s)))
|
||||
case bs == 1:
|
||||
v = (float32(s[0]) - 128) / 128
|
||||
case bs == 2:
|
||||
v = float32(int16(binary.LittleEndian.Uint16(s))) / (1 << 15)
|
||||
case bs == 3:
|
||||
v = float32(int32(uint32(s[0])<<8|uint32(s[1])<<16|uint32(s[2])<<24)>>8) / (1 << 23)
|
||||
default:
|
||||
v = float32(int32(binary.LittleEndian.Uint32(s))) / (1 << 31)
|
||||
}
|
||||
dst[i] = v
|
||||
}
|
||||
d.pos += int64(n)
|
||||
return n * d.channels, nil
|
||||
}
|
||||
|
||||
func (d *wavDecoder) SetPosition(frame int64) error {
|
||||
if frame < 0 || d.length >= 0 && frame > d.length {
|
||||
return errors.New("audio: seek out of range")
|
||||
}
|
||||
if _, err := d.r.Seek(d.start+frame*int64(d.frameBytes()), io.SeekStart); err != nil {
|
||||
return err
|
||||
}
|
||||
d.br = readerOf(d.r)
|
||||
d.pos = frame
|
||||
return nil
|
||||
}
|
||||
Reference in new issue
Block a user