From 75da255c28e82abc2bbbd06eebb74d693826b233 Mon Sep 17 00:00:00 2001 From: devgianlu Date: Fri, 22 Sep 2023 19:09:23 +0200 Subject: [PATCH] Improved track format selection --- player/format.go | 24 ++++++++++++++++++++++++ player/player.go | 11 ++--------- 2 files changed, 26 insertions(+), 9 deletions(-) diff --git a/player/format.go b/player/format.go index bfbad24..6767f8c 100644 --- a/player/format.go +++ b/player/format.go @@ -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 +} diff --git a/player/player.go b/player/player.go index 3fbe3ec..8fa6d2f 100644 --- a/player/player.go +++ b/player/player.go @@ -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())