Skip to content

Commit

Permalink
Improved track format selection
Browse files Browse the repository at this point in the history
  • Loading branch information
devgianlu committed Sep 22, 2023
1 parent b5cb80f commit 75da255
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 9 deletions.
24 changes: 24 additions & 0 deletions player/format.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,3 +16,27 @@ func formatBitrate(format metadatapb.AudioFile_Format) int {
return 0
}
}

func selectBestFormat(files []*metadatapb.AudioFile, preferredBitrate int) *metadatapb.AudioFile {
absDist := func(a, b int) int {
if a > b {
return a - b
} else {
return b - a
}
}

// pick the best format by selecting which has the smallest distance from the preferred bitrate
var best *metadatapb.AudioFile
var bestDist int
for _, ff := range files {
bitrate := formatBitrate(*ff.Format)
dist := absDist(bitrate, preferredBitrate)
if best == nil || dist < bestDist {
best = ff
bestDist = dist
}
}

return best
}
11 changes: 2 additions & 9 deletions player/player.go
Original file line number Diff line number Diff line change
Expand Up @@ -222,16 +222,9 @@ func (p *Player) NewStream(tid librespot.TrackId, bitrate int, trackPosition int
}
}

var file *metadatapb.AudioFile
for _, ff := range trackMeta.File {
if formatBitrate(*ff.Format) == bitrate {
file = ff
break
}
}

file := selectBestFormat(trackMeta.File, bitrate)
if file == nil {
return nil, fmt.Errorf("failed fetching requested bitrate: %d", bitrate)
return nil, fmt.Errorf("no playable formats for %s", tid.Uri())
}

log.Debugf("selected format %s for %s", file.Format.String(), tid.Uri())
Expand Down

0 comments on commit 75da255

Please sign in to comment.