perf: allow request bursts, reuse album track metadata; feat: qobuz lyrics

Two related changes: a 68-track Qobuz album was gated by the API throttle
rather than the network, and Qobuz lyrics are now supported, which is what the
faster album path had to be designed around.

--- perf ---

ratelimit: token bucket instead of fixed spacing
  The limiter spaced every request exactly interval apart with no burst, so at
  the default 60 requests/minute it allowed exactly one request per second no
  matter how many workers ran. Measured: 8 requests took 7s with 1 worker and
  7s with 6, i.e. max_connections had no effect on anything touching the API.
  Since a track needs its metadata and stream URL before downloading, workers
  could only start a track every two seconds, which is why an album looked
  serial even at 57 MiB/s per track.

  New() now takes a burst (providers pass max_connections), idle time accrues
  budget up to that burst, and burst is clamped to one minute's worth of
  requests so a large max_connections cannot bypass a small configured rate.

app: reuse the track objects already in the album payload
  ripAlbum fetched the album, kept only the track ids, then asked the provider
  for every track again, doubling the request count. Providers opt in via
  AlbumTracksAreComplete(); only Qobuz does, because it is only verified there
  and because Tidal does extra work in its track lookup.

  Verified against the live Qobuz API on a 68-track release: the embedded track
  objects already carry title, version, track_number, media_number,
  parental_warning, isrc, copyright, performer, performers, composer, duration,
  audio_info, maximum_bit_depth, maximum_sampling_rate and
  release_date_original. The only field a per-track lookup adds that this app
  reads is the nested album object, so albumTrackMetadata attaches the parent
  album with its own track list stripped, or a 68-track album would hold 68
  copies of itself. trackMetaUsable refetches anyway when title or track number
  is missing, so a thin payload cannot produce a wrongly named file.

  Measured end-to-end through the real app and limiter at the shipped defaults,
  68 tracks: 137 API calls / 2m11s before, 69 calls / 1m3s after.

--- qobuz lyrics ---

Qobuz's main API does not serve lyrics: has_lyrics is only a flag, extra=lyrics
adds nothing, and track/getLyrics does not exist. Its apps use a two-step flow
instead, confirmed live:

  GET track/lyricsUrl?track_id=&app_id=&request_ts=&request_sig=
    -> {"track_id","album_id","lyrics_url"}      (signed CloudFront URL)
  GET <lyrics_url>
    -> {"original":{"type","lang","lines":[{"line","start","end"}]},
        "translation_langs":[...],"writers","publishers":[...]}

type is plain, lsync or wsync; start/end are milliseconds; the line text is
under "line". Passing a language returns a translation instead of the original,
and only for languages that exist for the track (en 403s on an English song),
so the language parameter is deliberately omitted. A 403 on the signed URL is
how Qobuz represents "no lyrics", so it is not treated as an error.

Lyrics are exposed through a TrackLyrics method rather than inside GetMetadata,
because album rips skip the per-track metadata call. That keeps the fast path:
with lyrics on, an album costs the same two provider calls per track it always
did, and the lyrics document itself comes from a CDN that does not consume the
provider's request budget. With metadata.exclude = ["lyrics"] it drops to one
call per track and the full speedup applies.

Existing behaviour is preserved: Tidal and Deezer already attach lyrics in
their metadata, so attachLyrics leaves them alone, and a lyrics failure is
logged and ignored rather than failing a download.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
JorenandClaude Opus 5 committed 2026-10-03 21:55:48 +02:00
1 parent 26fb466afc
commit da4add57fe
13 files changed
+1029 -31

No files matched your search

+162 -1
View File
@@ -97,7 +97,7 @@ func New(cfg *config.Config) *Client {
// read, so the 30s API client aborted any track that took longer than
// 30s to stream. internal/download does the same for this reason.
streamHTTP: netutil.NewHTTPClient(0, cfg.Session.Downloads.VerifySSL, cfg.Session.Downloads.MaxConnections),
limiter: ratelimit.New(cfg.Session.Downloads.RequestsPerMinute),
limiter: ratelimit.New(cfg.Session.Downloads.RequestsPerMinute, cfg.Session.Downloads.MaxConnections),
baseURL: baseURL,
fetchCfg: nil,
}
@@ -1507,3 +1507,164 @@ func (c *Client) mobileAppSecret() string {
}
return config.DefaultQobuzMobileAppSecret
}
// AlbumTracksAreComplete reports that Qobuz's album/get response embeds track
// objects complete enough to tag from, so internal/app can skip the per-track
// track/get call.
//
// Checked against the live API for a 68-track release: the embedded items
// carry title, version, track_number, media_number, parental_warning, isrc,
// copyright, performer, performers, composer, duration, audio_info,
// maximum_bit_depth, maximum_sampling_rate and release_date_original. The only
// field track/get adds that this app reads is the nested album object, and the
// caller attaches the parent album itself. Everything else track/get returns
// (articles, created_at, has_lyrics, indexed_at) is unused.
func (c *Client) AlbumTracksAreComplete() bool { return true }
// Qobuz serves lyrics in two steps, mirroring its Android app: track/lyricsUrl
// returns a short-lived signed CloudFront URL, and that URL serves the lyrics
// document itself.
//
// Verified against the live API:
//
// GET track/lyricsUrl?track_id=&app_id=&request_ts=&request_sig=
// -> {"track_id","album_id","lyrics_url"}
// GET <lyrics_url>
// -> {"original":{"type","lang","lines":[{"line","start","end"}]},
// "translation_langs":[...],"writers","publishers":[...]}
//
// "type" is plain, lsync (line-synced) or wsync (word-synced); start and end
// are milliseconds. Passing a language parameter returns a translation
// document instead of the original, and only for languages that exist for the
// track, so this deliberately omits it and always takes the original.
const lyricsURLEndpoint = "track/lyricsUrl"
// lyricsExcluded reports whether the user opted out via
// metadata.exclude = ["lyrics"].
func (c *Client) lyricsExcluded() bool {
for _, k := range c.cfg.Session.Metadata.Exclude {
if strings.EqualFold(strings.TrimSpace(k), "lyrics") {
return true
}
}
return false
}
// TrackLyrics returns the plain and synced (LRC) lyrics for a track, or empty
// strings when Qobuz has none. It is exposed separately from GetMetadata so
// that album rips, which reuse the track objects embedded in the album
// payload, can still fetch lyrics without a full per-track metadata call.
func (c *Client) TrackLyrics(ctx context.Context, trackID string) (string, string, error) {
trackID = strings.TrimSpace(trackID)
if trackID == "" || c.lyricsExcluded() {
return "", "", nil
}
if !c.LoggedIn() {
return "", "", errNotLoggedIn
}
requestTS := strconv.FormatInt(time.Now().Unix(), 10)
sigRaw := "tracklyricsUrltrack_id" + trackID + requestTS + c.secret
sum := md5.Sum([]byte(sigRaw))
params := url.Values{}
params.Set("app_id", c.cfg.Session.Qobuz.AppID)
params.Set("track_id", trackID)
params.Set("request_ts", requestTS)
params.Set("request_sig", hex.EncodeToString(sum[:]))
resp, status, err := c.apiRequest(ctx, lyricsURLEndpoint, params, c.authHeaders())
if err != nil {
return "", "", err
}
if status != http.StatusOK {
// A track without lyrics is not an error worth failing a rip over.
verbose.Printf(verbose.V, "qobuz: no lyrics for track %s (status=%d)\n", trackID, status)
return "", "", nil
}
docURL := strings.TrimSpace(jsonutil.StringFromAny(resp["lyrics_url"]))
if docURL == "" {
return "", "", nil
}
return c.fetchLyricsDocument(ctx, trackID, docURL)
}
// fetchLyricsDocument retrieves the signed lyrics document. The URL points at
// a CDN rather than the Qobuz API, so it deliberately bypasses the API rate
// limiter: it is a different host and does not count against the provider's
// request budget.
func (c *Client) fetchLyricsDocument(ctx context.Context, trackID, docURL string) (string, string, error) {
req, err := http.NewRequestWithContext(ctx, http.MethodGet, docURL, nil)
if err != nil {
return "", "", err
}
resp, err := c.http.Do(req)
if err != nil {
return "", "", err
}
defer func() { _ = resp.Body.Close() }()
if resp.StatusCode != http.StatusOK {
// The signed URL 403s when the document does not exist, which is how
// Qobuz represents "no lyrics in this language".
verbose.Printf(verbose.V, "qobuz: lyrics document for track %s unavailable (status=%d)\n", trackID, resp.StatusCode)
return "", "", nil
}
body, err := io.ReadAll(resp.Body)
if err != nil {
return "", "", err
}
var doc map[string]any
if err = json.Unmarshal(body, &doc); err != nil {
return "", "", fmt.Errorf("qobuz lyrics document: %w", err)
}
plain, synced := parseQobuzLyrics(jsonutil.NestedMap(doc, "original"))
return plain, synced, nil
}
// parseQobuzLyrics turns a lyrics object into plain text and, when the lines
// carry timings, an LRC transcript.
func parseQobuzLyrics(obj map[string]any) (string, string) {
lines, ok := obj["lines"].([]any)
if !ok || len(lines) == 0 {
return "", ""
}
// wsync documents are line objects that additionally carry per-word
// timings; the line text and start are in the same place, so both synced
// variants are handled identically.
synced := strings.EqualFold(jsonutil.StringFromAny(obj["type"]), "lsync") ||
strings.EqualFold(jsonutil.StringFromAny(obj["type"]), "wsync")
plainParts := make([]string, 0, len(lines))
lrcParts := make([]string, 0, len(lines))
timed := false
for _, raw := range lines {
m, ok := raw.(map[string]any)
if !ok {
continue
}
text := strings.TrimSpace(jsonutil.StringFromAny(m["line"]))
if text == "" {
continue
}
plainParts = append(plainParts, text)
if synced {
if start, has := m["start"]; has {
ms := jsonutil.IntFromAny(start)
lrcParts = append(lrcParts, fmt.Sprintf("[%02d:%05.2f]%s", ms/60000, float64(ms%60000)/1000.0, text))
timed = true
}
}
}
if len(plainParts) == 0 {
return "", ""
}
lrc := ""
if timed {
lrc = strings.Join(lrcParts, "\n")
}
return strings.Join(plainParts, "\n"), lrc
}
+162
View File
@@ -416,3 +416,165 @@ func testConfigData() config.ConfigData {
d.Downloads.RequestsPerMinute = -1
return d
}
// newLyricsServer serves the two-step Qobuz lyrics flow: track/lyricsUrl
// returns a URL on this same server, which then serves the document.
func newLyricsServer(t *testing.T, doc any, docStatus int) *httptest.Server {
t.Helper()
var srv *httptest.Server
srv = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch r.URL.Path {
case "/track/lyricsUrl":
if r.URL.Query().Get("request_sig") == "" {
t.Error("track/lyricsUrl called without a request signature")
}
if r.URL.Query().Get("language") != "" {
t.Error("language must be omitted so the original lyrics are returned, not a translation")
}
_ = json.NewEncoder(w).Encode(map[string]any{
"track_id": r.URL.Query().Get("track_id"),
"album_id": "a1",
"lyrics_url": srv.URL + "/doc.json?Signature=x",
})
case "/doc.json":
if docStatus != http.StatusOK {
w.WriteHeader(docStatus)
_, _ = w.Write([]byte(`<?xml version="1.0"?><Error><Code>AccessDenied</Code></Error>`))
return
}
_ = json.NewEncoder(w).Encode(doc)
default:
w.WriteHeader(http.StatusNotFound)
}
}))
t.Cleanup(srv.Close)
return srv
}
func lyricsClient(t *testing.T, srv *httptest.Server, exclude ...string) *Client {
t.Helper()
d := testConfigData()
d.Metadata.Exclude = exclude
c := New(&config.Config{File: d, Session: d})
c.baseURL = srv.URL
c.loggedIn = true
c.secret = "secret"
return c
}
func TestTrackLyricsLineSynced(t *testing.T) {
srv := newLyricsServer(t, map[string]any{
"track_id": "42",
"translation_langs": []any{"fr", "de"},
"original": map[string]any{
"type": "lsync",
"lang": "en",
"lines": []any{
map[string]any{"line": "First line", "start": 5780, "end": 8710},
map[string]any{"line": "", "start": 9000, "end": 9100},
map[string]any{"line": "Second line", "start": 65250, "end": 68000},
},
},
}, http.StatusOK)
plain, lrc, err := lyricsClient(t, srv).TrackLyrics(context.Background(), "42")
if err != nil {
t.Fatalf("TrackLyrics() error = %v", err)
}
if plain != "First line\nSecond line" {
t.Errorf("plain = %q", plain)
}
want := "[00:05.78]First line\n[01:05.25]Second line"
if lrc != want {
t.Errorf("lrc = %q, want %q", lrc, want)
}
}
func TestTrackLyricsPlainHasNoTimestamps(t *testing.T) {
srv := newLyricsServer(t, map[string]any{
"original": map[string]any{
"type": "plain",
"lines": []any{
map[string]any{"line": "Just text"},
map[string]any{"line": "More text"},
},
},
}, http.StatusOK)
plain, lrc, err := lyricsClient(t, srv).TrackLyrics(context.Background(), "42")
if err != nil {
t.Fatal(err)
}
if plain != "Just text\nMore text" {
t.Errorf("plain = %q", plain)
}
if lrc != "" {
t.Errorf("plain lyrics must not produce an LRC transcript, got %q", lrc)
}
}
func TestTrackLyricsWordSyncedUsesLineTimings(t *testing.T) {
srv := newLyricsServer(t, map[string]any{
"original": map[string]any{
"type": "wsync",
"lines": []any{
map[string]any{
"line": "Hello world",
"start": 1500,
"words": []any{
map[string]any{"text": "Hello", "start": 1500, "end": 1800},
map[string]any{"text": "world", "start": 1800, "end": 2100},
},
},
},
},
}, http.StatusOK)
plain, lrc, err := lyricsClient(t, srv).TrackLyrics(context.Background(), "42")
if err != nil {
t.Fatal(err)
}
if plain != "Hello world" {
t.Errorf("plain = %q", plain)
}
if lrc != "[00:01.50]Hello world" {
t.Errorf("lrc = %q", lrc)
}
}
// A missing document 403s on the signed URL; that is how Qobuz says "no
// lyrics", so it must not fail the rip.
func TestTrackLyricsMissingDocumentIsNotAnError(t *testing.T) {
srv := newLyricsServer(t, nil, http.StatusForbidden)
plain, lrc, err := lyricsClient(t, srv).TrackLyrics(context.Background(), "42")
if err != nil {
t.Fatalf("a missing lyrics document must not be an error, got %v", err)
}
if plain != "" || lrc != "" {
t.Errorf("expected no lyrics, got plain=%q lrc=%q", plain, lrc)
}
}
func TestTrackLyricsRespectsMetadataExclude(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
t.Errorf("no request should be made when lyrics are excluded, got %s", r.URL.Path)
}))
defer srv.Close()
plain, lrc, err := lyricsClient(t, srv, "lyrics").TrackLyrics(context.Background(), "42")
if err != nil || plain != "" || lrc != "" {
t.Fatalf("exclude should short-circuit; got plain=%q lrc=%q err=%v", plain, lrc, err)
}
}
func TestTrackLyricsEmptyIDIsNoOp(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
t.Errorf("no request expected for an empty track id, got %s", r.URL.Path)
}))
defer srv.Close()
if plain, lrc, err := lyricsClient(t, srv).TrackLyrics(context.Background(), " "); err != nil || plain != "" || lrc != "" {
t.Fatalf("got plain=%q lrc=%q err=%v", plain, lrc, err)
}
}