Skip to content

Commit f392d6e

Browse files
committed
feat: perform prefetch synchronously with main loop
Fixes #79
1 parent d59f40b commit f392d6e

3 files changed

Lines changed: 11 additions & 8 deletions

File tree

cmd/daemon/controls.go

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -20,8 +20,10 @@ import (
2020
"google.golang.org/protobuf/proto"
2121
)
2222

23-
func (p *AppPlayer) prefetchNext() {
24-
ctx := context.TODO()
23+
func (p *AppPlayer) prefetchNext(ctx context.Context) {
24+
// Limit ourselves to 30 seconds for prefetching
25+
ctx, cancel := context.WithTimeout(ctx, 30*time.Second)
26+
defer cancel()
2527

2628
next := p.state.tracks.PeekNext(ctx)
2729
if next == nil {
@@ -61,16 +63,15 @@ func (p *AppPlayer) prefetchNext() {
6163

6264
func (p *AppPlayer) schedulePrefetchNext() {
6365
if p.state.player.IsPaused || p.primaryStream == nil {
64-
p.prefetchTimer.Reset(time.Duration(math.MaxInt64))
66+
p.prefetchTimer.Stop()
6567
return
6668
}
6769

6870
untilTrackEnd := time.Duration(p.primaryStream.Media.Duration()-int32(p.player.PositionMs())) * time.Millisecond
6971
untilTrackEnd -= 30 * time.Second
7072
if untilTrackEnd < 10*time.Second {
71-
p.prefetchTimer.Reset(time.Duration(math.MaxInt64))
72-
73-
go p.prefetchNext()
73+
p.prefetchTimer.Reset(0)
74+
p.app.log.Tracef("prefetch as soon as possible")
7475
} else {
7576
p.prefetchTimer.Reset(untilTrackEnd)
7677
p.app.log.Tracef("scheduling prefetch in %.0fs", untilTrackEnd.Seconds())

cmd/daemon/main.go

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -122,8 +122,8 @@ func (app *App) newAppPlayer(ctx context.Context, creds any) (_ *AppPlayer, err
122122
volumeUpdate: make(chan float32, 1),
123123
}
124124

125-
// start a dummy timer for prefetching next media
126-
appPlayer.prefetchTimer = time.AfterFunc(time.Duration(math.MaxInt64), appPlayer.prefetchNext)
125+
appPlayer.prefetchTimer = time.NewTimer(math.MaxInt64)
126+
appPlayer.prefetchTimer.Stop()
127127

128128
if appPlayer.sess, err = session.NewSessionFromOptions(ctx, &session.Options{
129129
Log: app.log,

cmd/daemon/player.go

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -718,6 +718,8 @@ func (p *AppPlayer) Run(ctx context.Context, apiRecv <-chan ApiRequest, mprisRec
718718
}
719719

720720
p.handlePlayerEvent(ctx, &ev)
721+
case <-p.prefetchTimer.C:
722+
p.prefetchNext(ctx)
721723
case volume := <-p.volumeUpdate:
722724
// Received a new volume: from Spotify Connect, from the REST API,
723725
// or from the system volume mixer.

0 commit comments

Comments
 (0)