Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion driver_android.go
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ func newContext(sampleRate int, channelCount int, format mux.Format, bufferSizeI
c.m.Lock()
defer c.m.Unlock()

if err := oboe.Play(sampleRate, channelCount, c.mux.ReadFloat32s, c.err.Join, bufferSizeInBytes); err != nil {
if err := oboe.Play(sampleRate, channelCount, c.mux.ReadFloat32s, c.mux.SetPlayed, c.mux.ClearPlayed, c.err.Join, bufferSizeInBytes); err != nil {
c.err.Join(err)
}
}()
Expand Down
2 changes: 2 additions & 0 deletions driver_console.go
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,8 @@ func newContext(sampleRate int, channelCount int, format mux.Format, bufferSizeI
c := &context{
mux: mux.New(sampleRate, channelCount, format),
}
// TODO: Report when the frames are played with c.mux.SetPlayed, where the
// console's audio API gives it.
theContext = c
C.oto_OpenAudioProxy(C.int(sampleRate), C.int(channelCount), C.int(bufferSizeInBytes))

Expand Down
4 changes: 4 additions & 0 deletions driver_darwin.go
Original file line number Diff line number Diff line change
Expand Up @@ -160,6 +160,10 @@ func newContext(sampleRate int, channelCount int, format mux.Format, bufferSizeI
channelCount: channelCount,
oneBufferSizeInBytes: oneBufferSizeInBytes,
}
// TODO: Report when the frames are played with c.mux.SetPlayed, from the delay:
// the frames enqueued less the queue's position from
// AudioQueueGetCurrentTime, plus the device's latency, which on iOS
// AVAudioSession's outputLatency gives.
theContext = c

if err := initializeAPI(); err != nil {
Expand Down
4 changes: 4 additions & 0 deletions driver_js.go
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,10 @@ func newContext(sampleRate int, channelCount int, format mux.Format, bufferSizeI
audioContext: class.New(options),
mux: mux.New(sampleRate, channelCount, format),
}
// TODO: Report when the frames are played with d.mux.SetPlayed: the
// AudioContext's getOutputTimestamp gives the context time of the frame
// played now, and the frames queued in the worklet or the script processor
// are played after it.

if bufferSizeInBytes == 0 {
// 4096 was not great at least on Safari 15.
Expand Down
3 changes: 3 additions & 0 deletions driver_unix.go
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,9 @@ func newContext(sampleRate int, channelCount int, format mux.Format, bufferSizeI
mux: mux.New(sampleRate, channelCount, format),
ready: make(chan struct{}),
}
// TODO: Report when the frames are played with ctx.mux.SetPlayed, from the
// delay: PulseAudio's latency query for its stream, and snd_pcm_delay on ALSA,
// plus what the driver has read and not yet written.

// Initializing a driver might take some time, so do it asynchronously.
// PulseAudio is the default; if no server is reachable, fall back to ALSA.
Expand Down
3 changes: 3 additions & 0 deletions driver_windows.go
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,9 @@ func newContext(sampleRate int, channelCount int, format mux.Format, bufferSizeI
mux: mux.New(sampleRate, channelCount, format),
ready: make(chan struct{}),
}
// TODO: Report when the frames are played with ctx.mux.SetPlayed, from the
// delay: on WASAPI, the frames written less the position IAudioClock reports;
// on WinMM, the frames written less the position waveOutGetPosition reports.

// Initializing drivers might take some time. Do this asynchronously.
go func() {
Expand Down
154 changes: 150 additions & 4 deletions internal/mux/mux.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ import (
"math"
"runtime"
"sync"
"sync/atomic"
"time"
)

Expand Down Expand Up @@ -61,8 +62,30 @@ type Mux struct {
// stopped says Stop was called, and the loop filling the players' buffers
// returns. It is guarded by cond.L.
stopped bool

// mixed counts the samples ReadFloat32s has mixed.
mixed atomic.Int64

// playedMu guards the driver's last report: frame playedFrame of the mix is
// played at playedAt, reported at reportedAt, while playedKnown is set.
playedMu sync.Mutex
playedKnown bool
playedFrame int64
playedAt time.Time
reportedAt time.Time
}

// maxSentSpans is the most spans of the mix a player remembers its data went
// into while they may be unplayed.
const maxSentSpans = 256

// reportLifetime is how long a report of when a frame is played holds.
const reportLifetime = time.Second

// maxReportedDelay is the furthest after a report that the frame it reports
// can be played.
const maxReportedDelay = 2 * time.Second

// New creates a new Mux.
func New(sampleRate int, channelCount int, format Format) *Mux {
m := &Mux{
Expand Down Expand Up @@ -155,6 +178,54 @@ func (m *Mux) removePlayer(player *playerImpl) {
delete(m.players, player)
}

// SetPlayed reports that frame of the mix is played at time at, where frame 0 is
// the first frame ReadFloat32s mixed. A driver that reports calls SetPlayed at
// least once every reportLifetime while playing. A report holds for
// reportLifetime, and one with at more than maxReportedDelay after the report,
// or more than reportLifetime before it, is taken as unknown.
func (m *Mux) SetPlayed(frame int64, at time.Time) {
now := time.Now()

m.playedMu.Lock()
defer m.playedMu.Unlock()

if at.Sub(now) > maxReportedDelay || now.Sub(at) > reportLifetime {
m.playedKnown = false
return
}
m.playedKnown = true
m.playedFrame = frame
m.playedAt = at
m.reportedAt = now
}

// ClearPlayed clears the driver's last report.
func (m *Mux) ClearPlayed() {
m.playedMu.Lock()
defer m.playedMu.Unlock()

m.playedKnown = false
}

// played returns how many of the samples mixed have been played, and whether the
// driver reports it.
func (m *Mux) played() (int64, bool) {
now := time.Now()

m.playedMu.Lock()
known, frame, at, reportedAt := m.playedKnown, m.playedFrame, m.playedAt, m.reportedAt
m.playedMu.Unlock()

if !known || now.Sub(reportedAt) > reportLifetime {
return 0, false
}
// The frames around the one reported are played at the sample rate.
frame += int64(now.Sub(at)) * int64(m.sampleRate) / int64(time.Second)
// No more than is mixed has been played, as when the device has run dry
// since the report.
return min(frame*int64(m.channelCount), m.mixed.Load()), true
}

// Stop stops the Mux from reading the players' sources.
func (m *Mux) Stop() {
m.cond.L.Lock()
Expand All @@ -180,9 +251,11 @@ func (m *Mux) ReadFloat32s(buf []float32) {
for i := range buf {
buf[i] = 0
}
start := m.mixed.Load()
for _, p := range players {
p.readBufferAndAdd(buf)
p.readBufferAndAdd(buf, start)
}
m.mixed.Add(int64(len(buf)))
m.signal()
}

Expand Down Expand Up @@ -225,7 +298,7 @@ type playerImpl struct {
err error

// srcErr is an error from the source that is not reported by err yet.
// It is moved to err after the data read before it is played or discarded.
// It is moved to err after the data read before it is mixed or discarded.
srcErr error

// reading reports whether a read from the source is in flight.
Expand All @@ -237,9 +310,20 @@ type playerImpl struct {
// The result of a read that started at an older generation is stale and must be discarded.
srcGen int

// sent holds the spans of the mix this player's data went into, oldest
// first, while they may be unplayed.
sent []sentSpan

m sync.Mutex
}

// A sentSpan is a span of the mix, from sample start to end, that a player's
// data went into, one sample of the data to each sample of the mix.
type sentSpan struct {
start int64
end int64
}

func (m *Mux) NewPlayer(src io.Reader) *Player {
p := &playerImpl{
mux: m,
Expand Down Expand Up @@ -406,6 +490,8 @@ func (p *playerImpl) Seek(offset int64, whence int) (int64, error) {
p.readPos = 0
p.eof = false
p.srcGen++
// The data sent before is from the old position.
p.sent = p.sent[:0]

// Wait until an ongoing read from the source finishes.
// Otherwise the source would be sought while it is being read.
Expand Down Expand Up @@ -433,6 +519,7 @@ func (p *playerImpl) Reset() {
p.buf = p.buf[:0]
p.readPos = 0
p.eof = false
p.sent = p.sent[:0]

// The buffered data is discarded, so a pending source error is reported now.
p.reportSourceErrorIfDrainedImpl()
Expand Down Expand Up @@ -489,6 +576,59 @@ func (p *playerImpl) BufferedSize() int {
return p.buffered()
}

func (p *Player) UnplayedSize() int {
return p.p.UnplayedSize()
}

func (p *playerImpl) UnplayedSize() int {
p.m.Lock()
defer p.m.Unlock()

n := p.buffered()
played, ok := p.mux.played()
if !ok {
// What is sent stays, as it may be played once the driver reports again,
// as after Resume.
return n
}
p.dropPlayed(played)
for _, s := range p.sent {
n += int(s.end-max(s.start, played)) * p.mux.format.ByteLength()
}
return n
}

// dropPlayed drops the spans sent that end by sample played of the mix.
//
// When dropPlayed is called, the mutex m must be locked.
func (p *playerImpl) dropPlayed(played int64) {
i := 0
for i < len(p.sent) && p.sent[i].end <= played {
i++
}
p.sent = append(p.sent[:0], p.sent[i:]...)
}

// recordSent records that the player's data went into samples start to end of
// the mix.
//
// When recordSent is called, the mutex m must be locked.
func (p *playerImpl) recordSent(start, end int64) {
// A span that follows on from the last merges with it, so a player that
// plays on keeps one.
if last := len(p.sent) - 1; last >= 0 && p.sent[last].end == start {
p.sent[last].end = end
return
}
if len(p.sent) == maxSentSpans {
p.sent = append(p.sent[:0], p.sent[1:]...)
}
p.sent = append(p.sent, sentSpan{
start: start,
end: end,
})
}

func (p *Player) Close() error {
p.cleanup.Stop()
return p.p.Close()
Expand Down Expand Up @@ -527,7 +667,9 @@ func (p *playerImpl) drained() bool {
return p.eof && p.buffered() < p.mux.format.ByteLength()
}

func (p *playerImpl) readBufferAndAdd(buf []float32) int {
// readBufferAndAdd adds the player's buffered data to buf, which goes into the
// mix from sample start.
func (p *playerImpl) readBufferAndAdd(buf []float32, start int64) int {
p.m.Lock()
defer p.m.Unlock()

Expand Down Expand Up @@ -587,6 +729,10 @@ func (p *playerImpl) readBufferAndAdd(buf []float32) int {

p.prevVolume = p.volume

if n > 0 {
p.recordSent(start, start+int64(n))
}

// The consumed region is compacted lazily when the buffer is refilled.
p.readPos += n * bitDepthInBytes
if p.readPos == len(p.buf) {
Expand Down Expand Up @@ -683,7 +829,7 @@ func (p *playerImpl) finishSourceRead(buf *[]byte, gen, n int, err error) int {
p.mux.removePlayer(p)
}
case err != nil:
// The data read before the error, including the data returned together with it, is played first.
// The data read before the error, including the data returned together with it, is mixed first.
p.srcErr = err
p.reportSourceErrorIfDrainedImpl()
}
Expand Down
Loading
Loading