Skip to content

Commit

Permalink
audio: remove locks from (*Player).Position
Browse files Browse the repository at this point in the history
  • Loading branch information
hajimehoshi committed Nov 6, 2024
1 parent 1014e45 commit 0981355
Showing 1 changed file with 9 additions and 10 deletions.
19 changes: 9 additions & 10 deletions audio/player.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ import (
"io"
"runtime"
"sync"
"sync/atomic"
"time"
)

Expand Down Expand Up @@ -73,10 +74,10 @@ type playerImpl struct {
initBufferSize int
bytesPerSample int

// adjustedPosition is the player's more accurate position.
// adjustedPosition is the player's more accurate position as time.Duration.
// The underlying buffer might not be changed even if the player is playing.
// adjustedPosition is adjusted by the time duration during the player position doesn't change while its playing.
adjustedPosition time.Duration
adjustedPosition atomic.Int64

// lastSamples is the last value of the number of samples.
// When lastSamples is a negative number, this value is not initialized yet.
Expand Down Expand Up @@ -269,9 +270,7 @@ func (p *playerImpl) Close() error {
}

func (p *playerImpl) Position() time.Duration {
p.m.Lock()
defer p.m.Unlock()
return p.adjustedPosition
return time.Duration(p.adjustedPosition.Load())
}

func (p *playerImpl) Rewind() error {
Expand All @@ -283,7 +282,7 @@ func (p *playerImpl) SetPosition(offset time.Duration) error {
defer p.m.Unlock()

if offset == 0 && p.player == nil {
p.adjustedPosition = 0
p.adjustedPosition.Store(0)
return nil
}

Expand All @@ -297,7 +296,7 @@ func (p *playerImpl) SetPosition(offset time.Duration) error {
}
p.lastSamples = -1
// Just after setting a position, the buffer size should be 0 as no data is sent.
p.adjustedPosition = p.stream.positionInTimeDuration()
p.adjustedPosition.Store(int64(p.stream.positionInTimeDuration()))
p.stopwatch.reset()
if p.isPlaying() {
p.stopwatch.start()
Expand Down Expand Up @@ -359,11 +358,11 @@ func (p *playerImpl) updatePosition() {
defer p.m.Unlock()

if p.player == nil {
p.adjustedPosition = 0
p.adjustedPosition.Store(0)
return
}
if !p.context.IsReady() {
p.adjustedPosition = 0
p.adjustedPosition.Store(0)
return
}

Expand All @@ -383,7 +382,7 @@ func (p *playerImpl) updatePosition() {
}

// Update the adjusted position every tick. This is necessary to keep the position accurate.
p.adjustedPosition = time.Duration(samples)*time.Second/time.Duration(p.factory.sampleRate) + adjustingTime
p.adjustedPosition.Store(int64(time.Duration(samples)*time.Second/time.Duration(p.factory.sampleRate) + adjustingTime))
}

type timeStream struct {
Expand Down

0 comments on commit 0981355

Please sign in to comment.