The first public release of Fabled Minstrel #158

Merged
bvandeusen merged 256 commits from dev into main 2026-12-03 21:41:58 -05:00
22 changed files with 555 additions and 108 deletions
Showing only changes of commit 6351b4651a - Show all commits
+4 -2
View File
@@ -8,6 +8,7 @@ import (
"github.com/jackc/pgx/v5/pgtype" "github.com/jackc/pgx/v5/pgtype"
"git.fabledsword.com/bvandeusen/minstrel/internal/db"
"git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq" "git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq"
) )
@@ -128,7 +129,8 @@ func albumRefFrom(a dbq.Album, artistName string, trackCount, durationSec int) A
} }
// trackRefFrom projects a dbq.Track into a TrackRef. Parent names must be // trackRefFrom projects a dbq.Track into a TrackRef. Parent names must be
// pre-resolved because Track only carries album_id and artist_id. // pre-resolved because Track only carries album_id and artist_id; the track's
// own credit, when its tags name a guest, replaces artistName.
func trackRefFrom(t dbq.Track, albumTitle, artistName string) TrackRef { func trackRefFrom(t dbq.Track, albumTitle, artistName string) TrackRef {
ref := TrackRef{ ref := TrackRef{
ID: uuidToString(t.ID), ID: uuidToString(t.ID),
@@ -136,7 +138,7 @@ func trackRefFrom(t dbq.Track, albumTitle, artistName string) TrackRef {
AlbumID: uuidToString(t.AlbumID), AlbumID: uuidToString(t.AlbumID),
AlbumTitle: albumTitle, AlbumTitle: albumTitle,
ArtistID: uuidToString(t.ArtistID), ArtistID: uuidToString(t.ArtistID),
ArtistName: artistName, ArtistName: db.TrackCredit(t, artistName),
DurationSec: durationMsToSec(t.DurationMs), DurationSec: durationMsToSec(t.DurationMs),
StreamURL: streamURL(t.ID), StreamURL: streamURL(t.ID),
Unavailable: t.MissingSince.Valid, Unavailable: t.MissingSince.Valid,
+13 -3
View File
@@ -9,9 +9,8 @@ import (
) )
// ArtistNames names the artists credited on an album's tracks. A track's own // ArtistNames names the artists credited on an album's tracks. A track's own
// artist differs from its album's on a compilation (Various Artists) and on a // artist differs from its album's on a compilation (Various Artists), so an
// track with a featured guest, so an album's track list names each track by // album's track list names each track by its own artist.
// its own artist.
type ArtistNames map[pgtype.UUID]string type ArtistNames map[pgtype.UUID]string
// TrackArtistNames reads the artists credited on the album's tracks. // TrackArtistNames reads the artists credited on the album's tracks.
@@ -35,3 +34,14 @@ func (n ArtistNames) For(id pgtype.UUID, fallback string) string {
} }
return fallback return fallback
} }
// TrackCredit is the artist credit to show beside track t, whose filing
// artist is named artistName: the track's full credit when its tags name a
// guest or several artists ("Low Tide Choir feat. Ruby Calloway"), else
// artistName.
func TrackCredit(t dbq.Track, artistName string) string {
if t.ArtistCredit != nil && *t.ArtistCredit != "" {
return *t.ArtistCredit
}
return artistName
}
+2 -1
View File
@@ -261,7 +261,7 @@ func (q *Queries) InsertSkipEvent(ctx context.Context, arg InsertSkipEventParams
} }
const listRecentSessionTracks = `-- name: ListRecentSessionTracks :many const listRecentSessionTracks = `-- name: ListRecentSessionTracks :many
SELECT t.id, t.title, t.album_id, t.artist_id, t.track_number, t.disc_number, t.duration_ms, t.file_path, t.file_size, t.file_format, t.bitrate, t.mbid, t.genre, t.added_at, t.updated_at, t.tag_source, t.tag_sources_version, t.tag_read_version, t.missing_since, t.mbid_source, t.song_id, t.song_key, t.source_verdict, t.source_verdict_at, t.emptied_at, t.removed_reason, t.removed_by FROM tracks t SELECT t.id, t.title, t.album_id, t.artist_id, t.track_number, t.disc_number, t.duration_ms, t.file_path, t.file_size, t.file_format, t.bitrate, t.mbid, t.genre, t.added_at, t.updated_at, t.tag_source, t.tag_sources_version, t.tag_read_version, t.missing_since, t.mbid_source, t.song_id, t.song_key, t.source_verdict, t.source_verdict_at, t.emptied_at, t.removed_reason, t.removed_by, t.artist_credit FROM tracks t
JOIN play_events pe ON pe.track_id = t.id JOIN play_events pe ON pe.track_id = t.id
WHERE pe.session_id = $1 WHERE pe.session_id = $1
AND pe.started_at < $2 AND pe.started_at < $2
@@ -315,6 +315,7 @@ func (q *Queries) ListRecentSessionTracks(ctx context.Context, arg ListRecentSes
&i.EmptiedAt, &i.EmptiedAt,
&i.RemovedReason, &i.RemovedReason,
&i.RemovedBy, &i.RemovedBy,
&i.ArtistCredit,
); err != nil { ); err != nil {
return nil, err return nil, err
} }
+2 -1
View File
@@ -14,7 +14,7 @@ import (
const listUserHistory = `-- name: ListUserHistory :many const listUserHistory = `-- name: ListUserHistory :many
SELECT pe.id AS event_id, SELECT pe.id AS event_id,
pe.started_at, pe.started_at,
t.id, t.title, t.album_id, t.artist_id, t.track_number, t.disc_number, t.duration_ms, t.file_path, t.file_size, t.file_format, t.bitrate, t.mbid, t.genre, t.added_at, t.updated_at, t.tag_source, t.tag_sources_version, t.tag_read_version, t.missing_since, t.mbid_source, t.song_id, t.song_key, t.source_verdict, t.source_verdict_at, t.emptied_at, t.removed_reason, t.removed_by, t.id, t.title, t.album_id, t.artist_id, t.track_number, t.disc_number, t.duration_ms, t.file_path, t.file_size, t.file_format, t.bitrate, t.mbid, t.genre, t.added_at, t.updated_at, t.tag_source, t.tag_sources_version, t.tag_read_version, t.missing_since, t.mbid_source, t.song_id, t.song_key, t.source_verdict, t.source_verdict_at, t.emptied_at, t.removed_reason, t.removed_by, t.artist_credit,
albums.title AS album_title, albums.title AS album_title,
artists.name AS artist_name artists.name AS artist_name
FROM play_events pe FROM play_events pe
@@ -89,6 +89,7 @@ func (q *Queries) ListUserHistory(ctx context.Context, arg ListUserHistoryParams
&i.Track.EmptiedAt, &i.Track.EmptiedAt,
&i.Track.RemovedReason, &i.Track.RemovedReason,
&i.Track.RemovedBy, &i.Track.RemovedBy,
&i.Track.ArtistCredit,
&i.AlbumTitle, &i.AlbumTitle,
&i.ArtistName, &i.ArtistName,
); err != nil { ); err != nil {
+2 -1
View File
@@ -282,7 +282,7 @@ func (q *Queries) ListLikedTrackIDs(ctx context.Context, userID pgtype.UUID) ([]
} }
const listLikedTrackRows = `-- name: ListLikedTrackRows :many const listLikedTrackRows = `-- name: ListLikedTrackRows :many
SELECT t.id, t.title, t.album_id, t.artist_id, t.track_number, t.disc_number, t.duration_ms, t.file_path, t.file_size, t.file_format, t.bitrate, t.mbid, t.genre, t.added_at, t.updated_at, t.tag_source, t.tag_sources_version, t.tag_read_version, t.missing_since, t.mbid_source, t.song_id, t.song_key, t.source_verdict, t.source_verdict_at, t.emptied_at, t.removed_reason, t.removed_by FROM tracks t SELECT t.id, t.title, t.album_id, t.artist_id, t.track_number, t.disc_number, t.duration_ms, t.file_path, t.file_size, t.file_format, t.bitrate, t.mbid, t.genre, t.added_at, t.updated_at, t.tag_source, t.tag_sources_version, t.tag_read_version, t.missing_since, t.mbid_source, t.song_id, t.song_key, t.source_verdict, t.source_verdict_at, t.emptied_at, t.removed_reason, t.removed_by, t.artist_credit FROM tracks t
JOIN (SELECT DISTINCT ON (lt.song_key) l.track_id, l.liked_at JOIN (SELECT DISTINCT ON (lt.song_key) l.track_id, l.liked_at
FROM general_likes l FROM general_likes l
JOIN tracks lt ON lt.id = l.track_id JOIN tracks lt ON lt.id = l.track_id
@@ -339,6 +339,7 @@ func (q *Queries) ListLikedTrackRows(ctx context.Context, arg ListLikedTrackRows
&i.EmptiedAt, &i.EmptiedAt,
&i.RemovedReason, &i.RemovedReason,
&i.RemovedBy, &i.RemovedBy,
&i.ArtistCredit,
); err != nil { ); err != nil {
return nil, err return nil, err
} }
+1
View File
@@ -665,6 +665,7 @@ type Track struct {
EmptiedAt pgtype.Timestamptz EmptiedAt pgtype.Timestamptz
RemovedReason *string RemovedReason *string
RemovedBy pgtype.UUID RemovedBy pgtype.UUID
ArtistCredit *string
} }
type TrackAcoustidLookup struct { type TrackAcoustidLookup struct {
+1 -1
View File
@@ -18,7 +18,7 @@ SELECT
COALESCE((SELECT MAX(position) + 1 FROM playlist_tracks WHERE playlist_id = $1::uuid), 0), COALESCE((SELECT MAX(position) + 1 FROM playlist_tracks WHERE playlist_id = $1::uuid), 0),
t.id, t.id,
t.title, t.title,
artists.name, COALESCE(t.artist_credit, artists.name),
albums.title, albums.title,
(t.duration_ms / 1000)::integer, (t.duration_ms / 1000)::integer,
$2::text $2::text
+8 -4
View File
@@ -208,7 +208,7 @@ WITH plays AS (
WHERE user_id = $2 AND was_skipped = false WHERE user_id = $2 AND was_skipped = false
GROUP BY track_id GROUP BY track_id
) )
SELECT t.id, t.title, t.album_id, t.artist_id, t.track_number, t.disc_number, t.duration_ms, t.file_path, t.file_size, t.file_format, t.bitrate, t.mbid, t.genre, t.added_at, t.updated_at, t.tag_source, t.tag_sources_version, t.tag_read_version, t.missing_since, t.mbid_source, t.song_id, t.song_key, t.source_verdict, t.source_verdict_at, t.emptied_at, t.removed_reason, t.removed_by, SELECT t.id, t.title, t.album_id, t.artist_id, t.track_number, t.disc_number, t.duration_ms, t.file_path, t.file_size, t.file_format, t.bitrate, t.mbid, t.genre, t.added_at, t.updated_at, t.tag_source, t.tag_sources_version, t.tag_read_version, t.missing_since, t.mbid_source, t.song_id, t.song_key, t.source_verdict, t.source_verdict_at, t.emptied_at, t.removed_reason, t.removed_by, t.artist_credit,
albums.title AS album_title, albums.title AS album_title,
artists.name AS artist_name artists.name AS artist_name
FROM plays p FROM plays p
@@ -278,6 +278,7 @@ func (q *Queries) ListMostPlayedTracksForArtist(ctx context.Context, arg ListMos
&i.Track.EmptiedAt, &i.Track.EmptiedAt,
&i.Track.RemovedReason, &i.Track.RemovedReason,
&i.Track.RemovedBy, &i.Track.RemovedBy,
&i.Track.ArtistCredit,
&i.AlbumTitle, &i.AlbumTitle,
&i.ArtistName, &i.ArtistName,
); err != nil { ); err != nil {
@@ -298,7 +299,7 @@ WITH plays AS (
WHERE user_id = $1 AND was_skipped = false WHERE user_id = $1 AND was_skipped = false
GROUP BY track_id GROUP BY track_id
) )
SELECT t.id, t.title, t.album_id, t.artist_id, t.track_number, t.disc_number, t.duration_ms, t.file_path, t.file_size, t.file_format, t.bitrate, t.mbid, t.genre, t.added_at, t.updated_at, t.tag_source, t.tag_sources_version, t.tag_read_version, t.missing_since, t.mbid_source, t.song_id, t.song_key, t.source_verdict, t.source_verdict_at, t.emptied_at, t.removed_reason, t.removed_by, SELECT t.id, t.title, t.album_id, t.artist_id, t.track_number, t.disc_number, t.duration_ms, t.file_path, t.file_size, t.file_format, t.bitrate, t.mbid, t.genre, t.added_at, t.updated_at, t.tag_source, t.tag_sources_version, t.tag_read_version, t.missing_since, t.mbid_source, t.song_id, t.song_key, t.source_verdict, t.source_verdict_at, t.emptied_at, t.removed_reason, t.removed_by, t.artist_credit,
albums.title AS album_title, albums.title AS album_title,
artists.name AS artist_name artists.name AS artist_name
FROM plays p FROM plays p
@@ -370,6 +371,7 @@ func (q *Queries) ListMostPlayedTracksForUser(ctx context.Context, arg ListMostP
&i.Track.EmptiedAt, &i.Track.EmptiedAt,
&i.Track.RemovedReason, &i.Track.RemovedReason,
&i.Track.RemovedBy, &i.Track.RemovedBy,
&i.Track.ArtistCredit,
&i.AlbumTitle, &i.AlbumTitle,
&i.ArtistName, &i.ArtistName,
); err != nil { ); err != nil {
@@ -711,7 +713,7 @@ func (q *Queries) ListRediscoverArtistsForUser(ctx context.Context, arg ListRedi
const loadRadioCandidates = `-- name: LoadRadioCandidates :many const loadRadioCandidates = `-- name: LoadRadioCandidates :many
SELECT SELECT
t.id, t.title, t.album_id, t.artist_id, t.track_number, t.disc_number, t.duration_ms, t.file_path, t.file_size, t.file_format, t.bitrate, t.mbid, t.genre, t.added_at, t.updated_at, t.tag_source, t.tag_sources_version, t.tag_read_version, t.missing_since, t.mbid_source, t.song_id, t.song_key, t.source_verdict, t.source_verdict_at, t.emptied_at, t.removed_reason, t.removed_by, t.id, t.title, t.album_id, t.artist_id, t.track_number, t.disc_number, t.duration_ms, t.file_path, t.file_size, t.file_format, t.bitrate, t.mbid, t.genre, t.added_at, t.updated_at, t.tag_source, t.tag_sources_version, t.tag_read_version, t.missing_since, t.mbid_source, t.song_id, t.song_key, t.source_verdict, t.source_verdict_at, t.emptied_at, t.removed_reason, t.removed_by, t.artist_credit,
(l.user_id IS NOT NULL)::bool AS is_liked, (l.user_id IS NOT NULL)::bool AS is_liked,
pe.last_played_at::timestamptz AS last_played_at, pe.last_played_at::timestamptz AS last_played_at,
pe.play_count, pe.play_count,
@@ -800,6 +802,7 @@ func (q *Queries) LoadRadioCandidates(ctx context.Context, arg LoadRadioCandidat
&i.Track.EmptiedAt, &i.Track.EmptiedAt,
&i.Track.RemovedReason, &i.Track.RemovedReason,
&i.Track.RemovedBy, &i.Track.RemovedBy,
&i.Track.ArtistCredit,
&i.IsLiked, &i.IsLiked,
&i.LastPlayedAt, &i.LastPlayedAt,
&i.PlayCount, &i.PlayCount,
@@ -960,7 +963,7 @@ random_fill AS (
LIMIT $9 LIMIT $9
) )
SELECT SELECT
t.id, t.title, t.album_id, t.artist_id, t.track_number, t.disc_number, t.duration_ms, t.file_path, t.file_size, t.file_format, t.bitrate, t.mbid, t.genre, t.added_at, t.updated_at, t.tag_source, t.tag_sources_version, t.tag_read_version, t.missing_since, t.mbid_source, t.song_id, t.song_key, t.source_verdict, t.source_verdict_at, t.emptied_at, t.removed_reason, t.removed_by, t.id, t.title, t.album_id, t.artist_id, t.track_number, t.disc_number, t.duration_ms, t.file_path, t.file_size, t.file_format, t.bitrate, t.mbid, t.genre, t.added_at, t.updated_at, t.tag_source, t.tag_sources_version, t.tag_read_version, t.missing_since, t.mbid_source, t.song_id, t.song_key, t.source_verdict, t.source_verdict_at, t.emptied_at, t.removed_reason, t.removed_by, t.artist_credit,
(l.user_id IS NOT NULL)::bool AS is_liked, (l.user_id IS NOT NULL)::bool AS is_liked,
pe.last_played_at::timestamptz AS last_played_at, pe.last_played_at::timestamptz AS last_played_at,
pe.play_count, pe.play_count,
@@ -1106,6 +1109,7 @@ func (q *Queries) LoadRadioCandidatesV2(ctx context.Context, arg LoadRadioCandid
&i.Track.EmptiedAt, &i.Track.EmptiedAt,
&i.Track.RemovedReason, &i.Track.RemovedReason,
&i.Track.RemovedBy, &i.Track.RemovedBy,
&i.Track.ArtistCredit,
&i.IsLiked, &i.IsLiked,
&i.LastPlayedAt, &i.LastPlayedAt,
&i.PlayCount, &i.PlayCount,
+2 -1
View File
@@ -47,7 +47,8 @@ SELECT
t.mbid AS track_mbid, t.mbid AS track_mbid,
al.title AS album_title, al.title AS album_title,
al.mbid AS album_mbid, al.mbid AS album_mbid,
ar.name AS artist_name, -- The full credit: ListenBrainz and Last.fm match "A feat. B" as written.
COALESCE(t.artist_credit, ar.name) AS artist_name,
ar.mbid AS artist_mbid ar.mbid AS artist_mbid
FROM scrobble_queue sq FROM scrobble_queue sq
JOIN users u ON u.id = sq.user_id JOIN users u ON u.id = sq.user_id
+21 -10
View File
@@ -304,7 +304,7 @@ func (q *Queries) FlagSuspectSourceTracks(ctx context.Context, pattern string) (
} }
const getTrackByID = `-- name: GetTrackByID :one const getTrackByID = `-- name: GetTrackByID :one
SELECT id, title, album_id, artist_id, track_number, disc_number, duration_ms, file_path, file_size, file_format, bitrate, mbid, genre, added_at, updated_at, tag_source, tag_sources_version, tag_read_version, missing_since, mbid_source, song_id, song_key, source_verdict, source_verdict_at, emptied_at, removed_reason, removed_by FROM tracks WHERE id = $1 SELECT id, title, album_id, artist_id, track_number, disc_number, duration_ms, file_path, file_size, file_format, bitrate, mbid, genre, added_at, updated_at, tag_source, tag_sources_version, tag_read_version, missing_since, mbid_source, song_id, song_key, source_verdict, source_verdict_at, emptied_at, removed_reason, removed_by, artist_credit FROM tracks WHERE id = $1
` `
func (q *Queries) GetTrackByID(ctx context.Context, id pgtype.UUID) (Track, error) { func (q *Queries) GetTrackByID(ctx context.Context, id pgtype.UUID) (Track, error) {
@@ -338,12 +338,13 @@ func (q *Queries) GetTrackByID(ctx context.Context, id pgtype.UUID) (Track, erro
&i.EmptiedAt, &i.EmptiedAt,
&i.RemovedReason, &i.RemovedReason,
&i.RemovedBy, &i.RemovedBy,
&i.ArtistCredit,
) )
return i, err return i, err
} }
const getTrackByPath = `-- name: GetTrackByPath :one const getTrackByPath = `-- name: GetTrackByPath :one
SELECT id, title, album_id, artist_id, track_number, disc_number, duration_ms, file_path, file_size, file_format, bitrate, mbid, genre, added_at, updated_at, tag_source, tag_sources_version, tag_read_version, missing_since, mbid_source, song_id, song_key, source_verdict, source_verdict_at, emptied_at, removed_reason, removed_by FROM tracks WHERE file_path = $1 SELECT id, title, album_id, artist_id, track_number, disc_number, duration_ms, file_path, file_size, file_format, bitrate, mbid, genre, added_at, updated_at, tag_source, tag_sources_version, tag_read_version, missing_since, mbid_source, song_id, song_key, source_verdict, source_verdict_at, emptied_at, removed_reason, removed_by, artist_credit FROM tracks WHERE file_path = $1
` `
func (q *Queries) GetTrackByPath(ctx context.Context, filePath string) (Track, error) { func (q *Queries) GetTrackByPath(ctx context.Context, filePath string) (Track, error) {
@@ -377,12 +378,13 @@ func (q *Queries) GetTrackByPath(ctx context.Context, filePath string) (Track, e
&i.EmptiedAt, &i.EmptiedAt,
&i.RemovedReason, &i.RemovedReason,
&i.RemovedBy, &i.RemovedBy,
&i.ArtistCredit,
) )
return i, err return i, err
} }
const getTracksByIDs = `-- name: GetTracksByIDs :many const getTracksByIDs = `-- name: GetTracksByIDs :many
SELECT id, title, album_id, artist_id, track_number, disc_number, duration_ms, file_path, file_size, file_format, bitrate, mbid, genre, added_at, updated_at, tag_source, tag_sources_version, tag_read_version, missing_since, mbid_source, song_id, song_key, source_verdict, source_verdict_at, emptied_at, removed_reason, removed_by FROM tracks WHERE id = ANY($1::uuid[]) SELECT id, title, album_id, artist_id, track_number, disc_number, duration_ms, file_path, file_size, file_format, bitrate, mbid, genre, added_at, updated_at, tag_source, tag_sources_version, tag_read_version, missing_since, mbid_source, song_id, song_key, source_verdict, source_verdict_at, emptied_at, removed_reason, removed_by, artist_credit FROM tracks WHERE id = ANY($1::uuid[])
` `
// Batched lookup used by /api/library/sync to hydrate upsert payloads // Batched lookup used by /api/library/sync to hydrate upsert payloads
@@ -424,6 +426,7 @@ func (q *Queries) GetTracksByIDs(ctx context.Context, dollar_1 []pgtype.UUID) ([
&i.EmptiedAt, &i.EmptiedAt,
&i.RemovedReason, &i.RemovedReason,
&i.RemovedBy, &i.RemovedBy,
&i.ArtistCredit,
); err != nil { ); err != nil {
return nil, err return nil, err
} }
@@ -436,7 +439,7 @@ func (q *Queries) GetTracksByIDs(ctx context.Context, dollar_1 []pgtype.UUID) ([
} }
const listArtistTracksForUser = `-- name: ListArtistTracksForUser :many const listArtistTracksForUser = `-- name: ListArtistTracksForUser :many
SELECT t.id, t.title, t.album_id, t.artist_id, t.track_number, t.disc_number, t.duration_ms, t.file_path, t.file_size, t.file_format, t.bitrate, t.mbid, t.genre, t.added_at, t.updated_at, t.tag_source, t.tag_sources_version, t.tag_read_version, t.missing_since, t.mbid_source, t.song_id, t.song_key, t.source_verdict, t.source_verdict_at, t.emptied_at, t.removed_reason, t.removed_by, SELECT t.id, t.title, t.album_id, t.artist_id, t.track_number, t.disc_number, t.duration_ms, t.file_path, t.file_size, t.file_format, t.bitrate, t.mbid, t.genre, t.added_at, t.updated_at, t.tag_source, t.tag_sources_version, t.tag_read_version, t.missing_since, t.mbid_source, t.song_id, t.song_key, t.source_verdict, t.source_verdict_at, t.emptied_at, t.removed_reason, t.removed_by, t.artist_credit,
albums.title AS album_title, albums.title AS album_title,
artists.name AS artist_name artists.name AS artist_name
FROM tracks t FROM tracks t
@@ -504,6 +507,7 @@ func (q *Queries) ListArtistTracksForUser(ctx context.Context, arg ListArtistTra
&i.Track.EmptiedAt, &i.Track.EmptiedAt,
&i.Track.RemovedReason, &i.Track.RemovedReason,
&i.Track.RemovedBy, &i.Track.RemovedBy,
&i.Track.ArtistCredit,
&i.AlbumTitle, &i.AlbumTitle,
&i.ArtistName, &i.ArtistName,
); err != nil { ); err != nil {
@@ -624,7 +628,7 @@ func (q *Queries) ListMissingTracks(ctx context.Context, arg ListMissingTracksPa
} }
const listRandomTracksForUser = `-- name: ListRandomTracksForUser :many const listRandomTracksForUser = `-- name: ListRandomTracksForUser :many
SELECT t.id, t.title, t.album_id, t.artist_id, t.track_number, t.disc_number, t.duration_ms, t.file_path, t.file_size, t.file_format, t.bitrate, t.mbid, t.genre, t.added_at, t.updated_at, t.tag_source, t.tag_sources_version, t.tag_read_version, t.missing_since, t.mbid_source, t.song_id, t.song_key, t.source_verdict, t.source_verdict_at, t.emptied_at, t.removed_reason, t.removed_by, SELECT t.id, t.title, t.album_id, t.artist_id, t.track_number, t.disc_number, t.duration_ms, t.file_path, t.file_size, t.file_format, t.bitrate, t.mbid, t.genre, t.added_at, t.updated_at, t.tag_source, t.tag_sources_version, t.tag_read_version, t.missing_since, t.mbid_source, t.song_id, t.song_key, t.source_verdict, t.source_verdict_at, t.emptied_at, t.removed_reason, t.removed_by, t.artist_credit,
albums.title AS album_title, albums.title AS album_title,
artists.name AS artist_name artists.name AS artist_name
FROM tracks t FROM tracks t
@@ -689,6 +693,7 @@ func (q *Queries) ListRandomTracksForUser(ctx context.Context, arg ListRandomTra
&i.Track.EmptiedAt, &i.Track.EmptiedAt,
&i.Track.RemovedReason, &i.Track.RemovedReason,
&i.Track.RemovedBy, &i.Track.RemovedBy,
&i.Track.ArtistCredit,
&i.AlbumTitle, &i.AlbumTitle,
&i.ArtistName, &i.ArtistName,
); err != nil { ); err != nil {
@@ -864,7 +869,7 @@ func (q *Queries) ListTrackPathsForReconcile(ctx context.Context) ([]ListTrackPa
} }
const listTracksByAlbum = `-- name: ListTracksByAlbum :many const listTracksByAlbum = `-- name: ListTracksByAlbum :many
SELECT id, title, album_id, artist_id, track_number, disc_number, duration_ms, file_path, file_size, file_format, bitrate, mbid, genre, added_at, updated_at, tag_source, tag_sources_version, tag_read_version, missing_since, mbid_source, song_id, song_key, source_verdict, source_verdict_at, emptied_at, removed_reason, removed_by FROM tracks SELECT id, title, album_id, artist_id, track_number, disc_number, duration_ms, file_path, file_size, file_format, bitrate, mbid, genre, added_at, updated_at, tag_source, tag_sources_version, tag_read_version, missing_since, mbid_source, song_id, song_key, source_verdict, source_verdict_at, emptied_at, removed_reason, removed_by, artist_credit FROM tracks
WHERE album_id = $1 WHERE album_id = $1
AND NOT EXISTS ( AND NOT EXISTS (
SELECT 1 FROM quarantine q SELECT 1 FROM quarantine q
@@ -918,6 +923,7 @@ func (q *Queries) ListTracksByAlbum(ctx context.Context, arg ListTracksByAlbumPa
&i.EmptiedAt, &i.EmptiedAt,
&i.RemovedReason, &i.RemovedReason,
&i.RemovedBy, &i.RemovedBy,
&i.ArtistCredit,
); err != nil { ); err != nil {
return nil, err return nil, err
} }
@@ -1079,7 +1085,7 @@ func (q *Queries) MarkTracksRemoved(ctx context.Context, arg MarkTracksRemovedPa
} }
const searchTracks = `-- name: SearchTracks :many const searchTracks = `-- name: SearchTracks :many
SELECT id, title, album_id, artist_id, track_number, disc_number, duration_ms, file_path, file_size, file_format, bitrate, mbid, genre, added_at, updated_at, tag_source, tag_sources_version, tag_read_version, missing_since, mbid_source, song_id, song_key, source_verdict, source_verdict_at, emptied_at, removed_reason, removed_by FROM tracks SELECT id, title, album_id, artist_id, track_number, disc_number, duration_ms, file_path, file_size, file_format, bitrate, mbid, genre, added_at, updated_at, tag_source, tag_sources_version, tag_read_version, missing_since, mbid_source, song_id, song_key, source_verdict, source_verdict_at, emptied_at, removed_reason, removed_by, artist_credit FROM tracks
WHERE title ILIKE '%' || $1::text || '%' WHERE title ILIKE '%' || $1::text || '%'
AND NOT EXISTS ( AND NOT EXISTS (
SELECT 1 FROM quarantine q SELECT 1 FROM quarantine q
@@ -1140,6 +1146,7 @@ func (q *Queries) SearchTracks(ctx context.Context, arg SearchTracksParams) ([]T
&i.EmptiedAt, &i.EmptiedAt,
&i.RemovedReason, &i.RemovedReason,
&i.RemovedBy, &i.RemovedBy,
&i.ArtistCredit,
); err != nil { ); err != nil {
return nil, err return nil, err
} }
@@ -1195,9 +1202,9 @@ const upsertTrack = `-- name: UpsertTrack :one
INSERT INTO tracks ( INSERT INTO tracks (
title, album_id, artist_id, track_number, disc_number, title, album_id, artist_id, track_number, disc_number,
duration_ms, file_path, file_size, file_format, bitrate, mbid, genre, duration_ms, file_path, file_size, file_format, bitrate, mbid, genre,
tag_read_version, mbid_source tag_read_version, mbid_source, artist_credit
) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, ) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13,
CASE WHEN $11::text IS NOT NULL THEN 'tag' END) CASE WHEN $11::text IS NOT NULL THEN 'tag' END, $14)
ON CONFLICT (file_path) DO UPDATE SET ON CONFLICT (file_path) DO UPDATE SET
title = EXCLUDED.title, title = EXCLUDED.title,
album_id = EXCLUDED.album_id, album_id = EXCLUDED.album_id,
@@ -1214,11 +1221,12 @@ ON CONFLICT (file_path) DO UPDATE SET
mbid_source = CASE WHEN EXCLUDED.mbid IS NOT NULL THEN 'tag' mbid_source = CASE WHEN EXCLUDED.mbid IS NOT NULL THEN 'tag'
WHEN tracks.mbid_source = 'acoustid' THEN 'acoustid' END, WHEN tracks.mbid_source = 'acoustid' THEN 'acoustid' END,
genre = EXCLUDED.genre, genre = EXCLUDED.genre,
artist_credit = EXCLUDED.artist_credit,
-- Stamped on update too, so a tag-repair pass marks rows as done and the -- Stamped on update too, so a tag-repair pass marks rows as done and the
-- next scan can short-circuit them again. -- next scan can short-circuit them again.
tag_read_version = EXCLUDED.tag_read_version, tag_read_version = EXCLUDED.tag_read_version,
updated_at = now() updated_at = now()
RETURNING id, title, album_id, artist_id, track_number, disc_number, duration_ms, file_path, file_size, file_format, bitrate, mbid, genre, added_at, updated_at, tag_source, tag_sources_version, tag_read_version, missing_since, mbid_source, song_id, song_key, source_verdict, source_verdict_at, emptied_at, removed_reason, removed_by RETURNING id, title, album_id, artist_id, track_number, disc_number, duration_ms, file_path, file_size, file_format, bitrate, mbid, genre, added_at, updated_at, tag_source, tag_sources_version, tag_read_version, missing_since, mbid_source, song_id, song_key, source_verdict, source_verdict_at, emptied_at, removed_reason, removed_by, artist_credit
` `
type UpsertTrackParams struct { type UpsertTrackParams struct {
@@ -1235,6 +1243,7 @@ type UpsertTrackParams struct {
Mbid *string Mbid *string
Genre *string Genre *string
TagReadVersion int16 TagReadVersion int16
ArtistCredit *string
} }
// file_path is the canonical identity for library scan; mbid is secondary. // file_path is the canonical identity for library scan; mbid is secondary.
@@ -1255,6 +1264,7 @@ func (q *Queries) UpsertTrack(ctx context.Context, arg UpsertTrackParams) (Track
arg.Mbid, arg.Mbid,
arg.Genre, arg.Genre,
arg.TagReadVersion, arg.TagReadVersion,
arg.ArtistCredit,
) )
var i Track var i Track
err := row.Scan( err := row.Scan(
@@ -1285,6 +1295,7 @@ func (q *Queries) UpsertTrack(ctx context.Context, arg UpsertTrackParams) (Track
&i.EmptiedAt, &i.EmptiedAt,
&i.RemovedReason, &i.RemovedReason,
&i.RemovedBy, &i.RemovedBy,
&i.ArtistCredit,
) )
return i, err return i, err
} }
@@ -0,0 +1 @@
ALTER TABLE tracks DROP COLUMN artist_credit;
@@ -0,0 +1,6 @@
-- The artist credit a track's tags give when it names more than its filing
-- artist: "Low Tide Choir feat. Ruby Calloway", or a collaboration the file
-- lists artist by artist. The track is filed under the first artist, so the
-- guest does not become an artist of their own, and this text is what a
-- listener sees beside the track. NULL when the credit is the artist's name.
ALTER TABLE tracks ADD COLUMN artist_credit text;
+1 -1
View File
@@ -83,7 +83,7 @@ SELECT
COALESCE((SELECT MAX(position) + 1 FROM playlist_tracks WHERE playlist_id = sqlc.arg(playlist_id)::uuid), 0), COALESCE((SELECT MAX(position) + 1 FROM playlist_tracks WHERE playlist_id = sqlc.arg(playlist_id)::uuid), 0),
t.id, t.id,
t.title, t.title,
artists.name, COALESCE(t.artist_credit, artists.name),
albums.title, albums.title,
(t.duration_ms / 1000)::integer, (t.duration_ms / 1000)::integer,
sqlc.narg(pick_kind)::text sqlc.narg(pick_kind)::text
+2 -1
View File
@@ -23,7 +23,8 @@ SELECT
t.mbid AS track_mbid, t.mbid AS track_mbid,
al.title AS album_title, al.title AS album_title,
al.mbid AS album_mbid, al.mbid AS album_mbid,
ar.name AS artist_name, -- The full credit: ListenBrainz and Last.fm match "A feat. B" as written.
COALESCE(t.artist_credit, ar.name) AS artist_name,
ar.mbid AS artist_mbid ar.mbid AS artist_mbid
FROM scrobble_queue sq FROM scrobble_queue sq
JOIN users u ON u.id = sq.user_id JOIN users u ON u.id = sq.user_id
+3 -2
View File
@@ -5,9 +5,9 @@
INSERT INTO tracks ( INSERT INTO tracks (
title, album_id, artist_id, track_number, disc_number, title, album_id, artist_id, track_number, disc_number,
duration_ms, file_path, file_size, file_format, bitrate, mbid, genre, duration_ms, file_path, file_size, file_format, bitrate, mbid, genre,
tag_read_version, mbid_source tag_read_version, mbid_source, artist_credit
) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, ) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13,
CASE WHEN $11::text IS NOT NULL THEN 'tag' END) CASE WHEN $11::text IS NOT NULL THEN 'tag' END, $14)
ON CONFLICT (file_path) DO UPDATE SET ON CONFLICT (file_path) DO UPDATE SET
title = EXCLUDED.title, title = EXCLUDED.title,
album_id = EXCLUDED.album_id, album_id = EXCLUDED.album_id,
@@ -24,6 +24,7 @@ ON CONFLICT (file_path) DO UPDATE SET
mbid_source = CASE WHEN EXCLUDED.mbid IS NOT NULL THEN 'tag' mbid_source = CASE WHEN EXCLUDED.mbid IS NOT NULL THEN 'tag'
WHEN tracks.mbid_source = 'acoustid' THEN 'acoustid' END, WHEN tracks.mbid_source = 'acoustid' THEN 'acoustid' END,
genre = EXCLUDED.genre, genre = EXCLUDED.genre,
artist_credit = EXCLUDED.artist_credit,
-- Stamped on update too, so a tag-repair pass marks rows as done and the -- Stamped on update too, so a tag-repair pass marks rows as done and the
-- next scan can short-circuit them again. -- next scan can short-circuit them again.
tag_read_version = EXCLUDED.tag_read_version, tag_read_version = EXCLUDED.tag_read_version,
+140
View File
@@ -0,0 +1,140 @@
package library
import (
"io"
"regexp"
"strings"
"github.com/dhowden/tag"
)
// artistCredit is who a track is filed under, and the credit shown beside it.
//
// A track's ARTIST tag is a credit, not always one artist: "Low Tide Choir
// feat. Ruby Calloway" names a guest, and a collaboration names two artists
// equally. Filed under the whole string, each such credit became an artist of
// its own, with its own page, its own place in the artist list and its own
// "Songs like" mix, holding one or two tracks. The track is filed under its
// first artist instead, and the full credit is kept to show with it.
type artistCredit struct {
// Name is the artist the track is filed under.
Name string
// MBID is Name's MusicBrainz id, or "".
MBID string
// Credit is the full credit when it names more than Name, else "".
Credit string
}
// featuring finds where a guest credit starts: "X feat. Y", "X ft. Y",
// "X featuring Y", "X (feat. Y)". Outside brackets the abbreviations need
// their full stop, so a band called "Little Feat" is not cut short; inside
// brackets the stop is optional.
var featuring = regexp.MustCompile(`(?i)\s+(?:[(\[]\s*(?:feat\.?|ft\.?|featuring)|feat\.|ft\.|featuring)\s`)
// readArtistCredit works out a track's artist credit from its tags.
//
// - A file that lists its artists one by one (Picard's ARTISTS tag, two or
// more values) is filed under the first. This is the only way a
// collaboration is split: "A & B" may be two artists or one band
// ("Simon & Garfunkel", "St. Paul & The Broken Bones"), and only the
// list says which.
// - Otherwise a featured guest is cut from the credit: "X feat. Y" is filed
// under X.
// - Otherwise the credit is the artist.
//
// The MusicBrainz id is the first of the file's artist ids, which Picard
// writes in credit order, so it belongs to the first artist.
func readArtistCredit(meta tag.Metadata, rs io.ReadSeeker, ids TagMBIDs) artistCredit {
credit := strings.TrimSpace(meta.Artist())
listed := readTagList(meta, rs, "ARTISTS", "ARTISTS")
mbid := ids.Artist
if isVorbis(meta) {
// dhowden/tag keeps the last of a repeated Vorbis field, which on a
// credit of two artists is the second artist's id.
if all := readTagList(meta, rs, "MUSICBRAINZ_ARTISTID", ""); len(all) > 0 {
mbid = cleanMBID(all[0])
}
}
name := credit
switch {
case len(listed) >= 2:
name = listed[0]
if credit == "" {
credit = strings.Join(listed, ", ")
}
case credit != "":
name = withoutGuests(credit)
}
if name == "" {
return artistCredit{Name: "Unknown Artist"}
}
out := artistCredit{Name: name, MBID: mbid}
if credit != name {
out.Credit = credit
}
return out
}
// withoutGuests cuts a featured guest from a credit: "X feat. Y" gives X.
// Album artists go through it too, as a single's release credit often names
// its guest.
func withoutGuests(credit string) string {
if loc := featuring.FindStringIndex(credit); loc != nil && loc[0] > 0 {
return strings.TrimSpace(credit[:loc[0]])
}
return credit
}
func isVorbis(meta tag.Metadata) bool { return meta.Format() == tag.VORBIS }
// readTagList returns every value of a field that can repeat, in file order:
// the Vorbis comment vorbisKey (FLAC, Ogg Vorbis, Opus), or the user-defined
// text field called textName (ID3v2 TXXX, MP4 freeform). An empty textName
// reads Vorbis only. A file that cannot be read for it gives nil.
func readTagList(meta tag.Metadata, rs io.ReadSeeker, vorbisKey, textName string) []string {
var values []string
switch meta.Format() {
case tag.VORBIS:
if meta.FileType() == tag.OGG {
values, _ = readOggValues(rs, vorbisKey)
} else {
values, _ = readFLACValues(rs, vorbisKey)
}
case tag.MP4:
if textName != "" {
values, _ = readMP4FreeformValues(rs, textName)
}
case tag.ID3v2_2, tag.ID3v2_3, tag.ID3v2_4:
if textName != "" {
values = id3TextList(meta, textName)
}
}
return values
}
// id3TextList reads the TXXX field called name. dhowden/tag files each TXXX
// frame under "TXXX", "TXXX_0", … as a *tag.Comm. ID3v2.4 separates the
// values of one frame with NUL. ID3v2.3 has no separator, and a "/" there
// may be part of a name (AC/DC), so a v2.3 frame is one value.
func id3TextList(meta tag.Metadata, name string) []string {
var out []string
for key, v := range meta.Raw() {
if !strings.HasPrefix(key, "TXXX") {
continue
}
c, ok := v.(*tag.Comm)
if !ok || !strings.EqualFold(c.Description, name) {
continue
}
for _, part := range strings.Split(c.Text, "\x00") {
if p := strings.TrimSpace(part); p != "" {
out = append(out, p)
}
}
// One frame per field name: a tagger that wrote two would leave the
// order between them to map iteration.
break
}
return out
}
+156
View File
@@ -0,0 +1,156 @@
package library
import (
"bytes"
"testing"
"github.com/dhowden/tag"
)
func TestWithoutGuests(t *testing.T) {
tests := []struct{ credit, want string }{
{"Low Tide Choir feat. Ruby Calloway", "Low Tide Choir"},
{"Low Tide Choir ft. Ruby Calloway", "Low Tide Choir"},
{"Low Tide Choir featuring Ruby Calloway", "Low Tide Choir"},
{"Low Tide Choir (feat. Ruby Calloway)", "Low Tide Choir"},
{"Low Tide Choir [ft Ruby Calloway]", "Low Tide Choir"},
{"Low Tide Choir FEAT. Ruby Calloway & Mae", "Low Tide Choir"},
// Names that only look like a credit stay whole.
{"Little Feat", "Little Feat"},
{"Little Feat featuring Bonnie Raitt", "Little Feat"},
{"Daft Punk", "Daft Punk"},
{"Soft Cell", "Soft Cell"},
{"Featuring Fools", "Featuring Fools"},
{"Simon & Garfunkel", "Simon & Garfunkel"},
{"St. Paul & The Broken Bones", "St. Paul & The Broken Bones"},
}
for _, tc := range tests {
if got := withoutGuests(tc.credit); got != tc.want {
t.Errorf("withoutGuests(%q) = %q, want %q", tc.credit, got, tc.want)
}
}
}
// id3Meta is an ID3v2 file's tags as dhowden/tag presents them.
type id3Meta struct {
tag.Metadata
artist string
raw map[string]interface{}
}
func (m id3Meta) Format() tag.Format { return tag.ID3v2_4 }
func (m id3Meta) FileType() tag.FileType { return tag.MP3 }
func (m id3Meta) Artist() string { return m.artist }
func (m id3Meta) Raw() map[string]interface{} { return m.raw }
func TestReadArtistCredit_ID3(t *testing.T) {
tests := []struct {
name string
artist string
raw map[string]interface{}
mbid string
want artistCredit
}{
{
name: "a guest is cut from the credit",
artist: "Low Tide Choir feat. Ruby Calloway",
mbid: "id-choir",
want: artistCredit{Name: "Low Tide Choir", MBID: "id-choir", Credit: "Low Tide Choir feat. Ruby Calloway"},
},
{
name: "a collaboration the file lists is filed under its first artist",
artist: "Paper Lanterns & Ruby Calloway",
raw: map[string]interface{}{"TXXX": &tag.Comm{Description: "ARTISTS", Text: "Paper Lanterns\x00Ruby Calloway"}},
want: artistCredit{Name: "Paper Lanterns", Credit: "Paper Lanterns & Ruby Calloway"},
},
{
name: "an & the file does not list is one artist",
artist: "St. Paul & The Broken Bones",
raw: map[string]interface{}{"TXXX": &tag.Comm{Description: "ARTISTS", Text: "St. Paul & The Broken Bones"}},
want: artistCredit{Name: "St. Paul & The Broken Bones"},
},
{
name: "a v2.3 list has no separator, so a slash stays in the name",
artist: "AC/DC",
raw: map[string]interface{}{"TXXX_0": &tag.Comm{Description: "Artists", Text: "AC/DC"}},
want: artistCredit{Name: "AC/DC"},
},
{
name: "no artist at all",
want: artistCredit{Name: "Unknown Artist"},
},
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
got := readArtistCredit(id3Meta{artist: tc.artist, raw: tc.raw}, nil, TagMBIDs{Artist: tc.mbid})
if got != tc.want {
t.Errorf("readArtistCredit = %+v, want %+v", got, tc.want)
}
})
}
}
// A FLAC credited to two artists, as Picard writes it: ARTIST is the credit,
// and ARTISTS and MUSICBRAINZ_ARTISTID list the artists in credit order.
// dhowden/tag keeps the last of each repeated field, so it alone would file
// the track under the second artist's id.
func TestReadArtistCredit_FLACListsItsArtists(t *testing.T) {
data := buildFLAC(false,
"TITLE=Undertow",
"ARTIST=Paper Lanterns & Ruby Calloway",
"ARTISTS=Paper Lanterns",
"ARTISTS=Ruby Calloway",
"MUSICBRAINZ_ARTISTID=id-lanterns",
"MUSICBRAINZ_ARTISTID=id-ruby",
)
rs := bytes.NewReader(data)
meta, err := tag.ReadFrom(rs)
if err != nil {
t.Fatalf("tag.ReadFrom: %v", err)
}
got := readArtistCredit(meta, rs, ReadTagMBIDs(meta))
want := artistCredit{Name: "Paper Lanterns", MBID: "id-lanterns", Credit: "Paper Lanterns & Ruby Calloway"}
if got != want {
t.Errorf("readArtistCredit = %+v, want %+v", got, want)
}
}
func TestReadArtistCredit_FLACWithOneArtist(t *testing.T) {
data := buildFLAC(false, "ARTIST=Marina & the Kats", "ARTISTS=Marina & the Kats", "MUSICBRAINZ_ARTISTID=id-kats")
rs := bytes.NewReader(data)
meta, err := tag.ReadFrom(rs)
if err != nil {
t.Fatalf("tag.ReadFrom: %v", err)
}
got := readArtistCredit(meta, rs, ReadTagMBIDs(meta))
if want := (artistCredit{Name: "Marina & the Kats", MBID: "id-kats"}); got != want {
t.Errorf("readArtistCredit = %+v, want %+v", got, want)
}
}
func TestReadMP4FreeformValues(t *testing.T) {
freeform := func(name string, values ...string) []byte {
children := [][]byte{
mp4Box("mean", []byte{0, 0, 0, 0}, []byte("com.apple.iTunes")),
mp4Box("name", []byte{0, 0, 0, 0}, []byte(name)),
}
for _, v := range values {
children = append(children, mp4Text(v))
}
return mp4Box("----", children...)
}
data := buildMP4(true,
freeform("MusicBrainz Artist Id", "id-lanterns"),
freeform("ARTISTS", "Paper Lanterns", "Ruby Calloway"),
)
got, err := readMP4FreeformValues(bytes.NewReader(data), "artists")
if err != nil {
t.Fatalf("readMP4FreeformValues: %v", err)
}
if want := []string{"Paper Lanterns", "Ruby Calloway"}; !equalStrings(got, want) {
t.Errorf("ARTISTS = %q, want %q", got, want)
}
if got, err := readMP4FreeformValues(bytes.NewReader(buildMP4(true)), "ARTISTS"); err != nil || got != nil {
t.Errorf("no ARTISTS item: got %q, %v; want nil, nil", got, err)
}
}
+93 -40
View File
@@ -74,9 +74,92 @@ func findMP4Child(rs io.ReadSeeker, start, end int64, kind string) (mp4Atom, boo
// readMP4GenreValues returns every ©gen value, in file order. rs is seeked // readMP4GenreValues returns every ©gen value, in file order. rs is seeked
// as needed, so it is safe to call after dhowden/tag has consumed the reader. // as needed, so it is safe to call after dhowden/tag has consumed the reader.
func readMP4GenreValues(rs io.ReadSeeker) ([]string, error) { func readMP4GenreValues(rs io.ReadSeeker) ([]string, error) {
ilst, found, err := findMP4Ilst(rs)
if err != nil || !found {
return nil, err
}
var out []string
err = eachMP4Item(rs, ilst, func(kind string, body []byte) bool {
if kind != "\xa9gen" {
return true
}
values, ok := mp4DataValues(body)
out = append(out, values...)
return ok
})
return out, err
}
// readMP4FreeformValues returns the values of the freeform "----" item called
// name (com.apple.iTunes:ARTISTS is Picard's), in file order. Names compare
// case-insensitively, as taggers differ in case.
func readMP4FreeformValues(rs io.ReadSeeker, name string) ([]string, error) {
ilst, found, err := findMP4Ilst(rs)
if err != nil || !found {
return nil, err
}
var out []string
err = eachMP4Item(rs, ilst, func(kind string, body []byte) bool {
if kind != "----" || !strings.EqualFold(mp4FreeformName(body), name) {
return true
}
values, ok := mp4DataValues(body)
out = append(out, values...)
return ok
})
return out, err
}
// mp4FreeformName is the text of the "name" atom in a freeform item's body:
// size, "name", four bytes of version and flags, then the name.
func mp4FreeformName(b []byte) string {
for len(b) >= 8 {
size := binary.BigEndian.Uint32(b[0:4])
if size < 8 || uint64(size) > uint64(len(b)) {
return ""
}
if string(b[4:8]) == "name" && size >= 12 {
return string(b[12:size])
}
b = b[size:]
}
return ""
}
// eachMP4Item calls fn with the kind and body of each item in ilst, in file
// order, until fn returns false (a malformed body). Each body is capped at
// maxMP4GenreAtomSize.
func eachMP4Item(rs io.ReadSeeker, ilst mp4Atom, fn func(kind string, body []byte) bool) error {
for pos := ilst.body; pos+8 <= ilst.limit; {
a, err := readMP4Atom(rs, pos, ilst.limit)
if err != nil {
return errNoGenreFrame
}
pos = a.limit
n := a.limit - a.body
if n > maxMP4GenreAtomSize {
return errNoGenreFrame
}
if _, err := rs.Seek(a.body, io.SeekStart); err != nil {
return errNoGenreFrame
}
body := make([]byte, n)
if _, err := io.ReadFull(rs, body); err != nil {
return errNoGenreFrame
}
if !fn(a.kind, body) {
return errNoGenreFrame
}
}
return nil
}
// findMP4Ilst finds the iTunes item list, moov > udta > meta > ilst.
// found is false for a file with no iTunes metadata.
func findMP4Ilst(rs io.ReadSeeker) (ilst mp4Atom, found bool, err error) {
end, err := rs.Seek(0, io.SeekEnd) end, err := rs.Seek(0, io.SeekEnd)
if err != nil { if err != nil {
return nil, err return mp4Atom{}, false, err
} }
// moov may sit after mdat; walking headers and seeking past bodies finds // moov may sit after mdat; walking headers and seeking past bodies finds
// it either way without reading the audio. // it either way without reading the audio.
@@ -84,10 +167,10 @@ func readMP4GenreValues(rs io.ReadSeeker) ([]string, error) {
for _, kind := range []string{"moov", "udta", "meta"} { for _, kind := range []string{"moov", "udta", "meta"} {
next, found, err := findMP4Child(rs, cur.body, cur.limit, kind) next, found, err := findMP4Child(rs, cur.body, cur.limit, kind)
if err != nil { if err != nil {
return nil, errNoGenreFrame return mp4Atom{}, false, errNoGenreFrame
} }
if !found { if !found {
return nil, nil // no iTunes metadata at all return mp4Atom{}, false, nil // no iTunes metadata at all
} }
cur = next cur = next
} }
@@ -95,54 +178,24 @@ func readMP4GenreValues(rs io.ReadSeeker) ([]string, error) {
// children in the ISO layout. QuickTime-style files omit them, so the // children in the ISO layout. QuickTime-style files omit them, so the
// first child (hdlr) starts straight away. Look before skipping. // first child (hdlr) starts straight away. Look before skipping.
if _, err := rs.Seek(cur.body, io.SeekStart); err != nil { if _, err := rs.Seek(cur.body, io.SeekStart); err != nil {
return nil, errNoGenreFrame return mp4Atom{}, false, errNoGenreFrame
} }
var peek [8]byte var peek [8]byte
if _, err := io.ReadFull(rs, peek[:]); err != nil { if _, err := io.ReadFull(rs, peek[:]); err != nil {
return nil, errNoGenreFrame return mp4Atom{}, false, errNoGenreFrame
} }
if string(peek[4:8]) != "hdlr" { if string(peek[4:8]) != "hdlr" {
cur.body += 4 cur.body += 4
} }
ilst, found, err := findMP4Child(rs, cur.body, cur.limit, "ilst") ilst, found, err = findMP4Child(rs, cur.body, cur.limit, "ilst")
if err != nil { if err != nil {
return nil, errNoGenreFrame return mp4Atom{}, false, errNoGenreFrame
} }
if !found { return ilst, found, nil
return nil, nil
}
var out []string
for pos := ilst.body; pos+8 <= ilst.limit; {
a, err := readMP4Atom(rs, pos, ilst.limit)
if err != nil {
return nil, errNoGenreFrame
}
pos = a.limit
if a.kind != "\xa9gen" {
continue
}
n := a.limit - a.body
if n > maxMP4GenreAtomSize {
return nil, errNoGenreFrame
}
if _, err := rs.Seek(a.body, io.SeekStart); err != nil {
return nil, errNoGenreFrame
}
body := make([]byte, n)
if _, err := io.ReadFull(rs, body); err != nil {
return nil, errNoGenreFrame
}
values, ok := mp4DataValues(body)
if !ok {
return nil, errNoGenreFrame
}
out = append(out, values...)
}
return out, nil
} }
// mp4DataValues reads the "data" atoms in a ©gen body. Each is: size, "data", // mp4DataValues reads the "data" atoms in a ©gen or freeform item's body;
// a freeform item's "mean" and "name" atoms are skipped. Each is: size, "data",
// a 4-byte type indicator (1 = UTF-8 text), a 4-byte locale, then the value. // a 4-byte type indicator (1 = UTF-8 text), a 4-byte locale, then the value.
// Atoms of other types carry no text and are skipped. // Atoms of other types carry no text and are skipped.
func mp4DataValues(b []byte) ([]string, bool) { func mp4DataValues(b []byte) ([]string, bool) {
+18 -8
View File
@@ -84,7 +84,12 @@ var audioExtensions = map[string]bool{
// track, was split into an album per track artist; a re-read files each // track, was split into an album per track artist; a re-read files each
// track back on the one album, and the scan's tidy-up removes the rows // track back on the one album, and the scan's tidy-up removes the rows
// it leaves empty. // it leaves empty.
const tagReadVersion int16 = 9 // 10: a credit that names a guest ("X feat. Y") or lists several artists
// (Picard's ARTISTS) is filed under its first artist and kept as the
// track's credit, rather than becoming an artist of its own; the scan's
// tidy-up removes the credit-named artists it leaves empty. A Vorbis
// file's artist id is its first, not its last.
const tagReadVersion int16 = 10
type Stats struct { type Stats struct {
Scanned int `json:"scanned"` Scanned int `json:"scanned"`
@@ -367,13 +372,14 @@ func (s *Scanner) scanFile(
return pgtype.UUID{}, false, fmt.Errorf("tag read: %w", err) return pgtype.UUID{}, false, fmt.Errorf("tag read: %w", err)
} }
ids := ReadTagMBIDs(meta) ids := ReadTagMBIDs(meta)
albumMBID, artistMBID := ids.Release, ids.Artist albumMBID := ids.Release
recordingMBID, releaseGroupMBID := ids.Recording, ids.ReleaseGroup recordingMBID, releaseGroupMBID := ids.Recording, ids.ReleaseGroup
artistName := meta.Artist() // A guest or a second artist in the credit does not get an artist of
if artistName == "" { // their own: the track is filed under the first, and the full credit is
artistName = "Unknown Artist" // kept to show with it (artistcredit.go).
} credit := readArtistCredit(meta, f, ids)
artistName := credit.Name
albumTitle := meta.Album() albumTitle := meta.Album()
if albumTitle == "" { if albumTitle == "" {
albumTitle = "Unknown Album" albumTitle = "Unknown Album"
@@ -383,7 +389,7 @@ func (s *Scanner) scanFile(
trackTitle = strings.TrimSuffix(filepath.Base(path), filepath.Ext(path)) trackTitle = strings.TrimSuffix(filepath.Base(path), filepath.Ext(path))
} }
artist, err := s.resolveArtist(ctx, q, artistName, artistMBID) artist, err := s.resolveArtist(ctx, q, artistName, credit.MBID)
if err != nil { if err != nil {
return pgtype.UUID{}, false, fmt.Errorf("artist: %w", err) return pgtype.UUID{}, false, fmt.Errorf("artist: %w", err)
} }
@@ -392,7 +398,7 @@ func (s *Scanner) scanFile(
// lands on one album instead of one per track artist. The track keeps // lands on one album instead of one per track artist. The track keeps
// its own artist. // its own artist.
albumArtist := artist albumArtist := artist
if name := strings.TrimSpace(meta.AlbumArtist()); name != "" && name != artistName { if name := withoutGuests(strings.TrimSpace(meta.AlbumArtist())); name != "" && name != artistName {
albumArtist, err = s.resolveArtist(ctx, q, name, ids.AlbumArtist) albumArtist, err = s.resolveArtist(ctx, q, name, ids.AlbumArtist)
if err != nil { if err != nil {
return pgtype.UUID{}, false, fmt.Errorf("album artist: %w", err) return pgtype.UUID{}, false, fmt.Errorf("album artist: %w", err)
@@ -479,6 +485,10 @@ func (s *Scanner) scanFile(
// Stamped so a future extraction fix can find this row again. // Stamped so a future extraction fix can find this row again.
TagReadVersion: tagReadVersion, TagReadVersion: tagReadVersion,
} }
if credit.Credit != "" {
c := credit.Credit
params.ArtistCredit = &c
}
if trackNum > 0 { if trackNum > 0 {
v := int32(trackNum) v := int32(trackNum)
params.TrackNumber = &v params.TrackNumber = &v
+44 -9
View File
@@ -630,25 +630,60 @@ func TestScanner_AlbumArtistKeepsAnAlbumTogether_Integration(t *testing.T) {
if got["Summer Hits"].tracks != 2 || got["Summer Hits"].trackArtists != 2 { if got["Summer Hits"].tracks != 2 || got["Summer Hits"].trackArtists != 2 {
t.Errorf("Summer Hits = %+v, want 2 tracks by 2 artists on one album", got["Summer Hits"]) t.Errorf("Summer Hits = %+v, want 2 tracks by 2 artists on one album", got["Summer Hits"])
} }
if got["Night Drive"].tracks != 2 || got["Night Drive"].trackArtists != 2 { // The guest is a credit on the track, not an artist of their own.
t.Errorf("Night Drive = %+v, want 2 tracks by 2 artists on one album", got["Night Drive"]) if got["Night Drive"].tracks != 2 || got["Night Drive"].trackArtists != 1 {
t.Errorf("Night Drive = %+v, want 2 tracks, both filed under Paper Lanterns", got["Night Drive"])
}
const guestCredit = "Paper Lanterns feat. Low Tide Choir"
creditOf := func() (artist string, credit *string) {
t.Helper()
if err := pool.QueryRow(ctx, `
SELECT ar.name, t.artist_credit FROM tracks t JOIN artists ar ON ar.id = t.artist_id
WHERE t.file_path = $1`, guest).Scan(&artist, &credit); err != nil {
t.Fatal(err)
}
return artist, credit
}
if artist, credit := creditOf(); artist != "Paper Lanterns" || credit == nil || *credit != guestCredit {
t.Errorf("guest track filed under %q with credit %v, want Paper Lanterns with credit %q", artist, credit, guestCredit)
}
creditArtists := func() int {
t.Helper()
var n int
if err := pool.QueryRow(ctx, `SELECT count(*) FROM artists WHERE name = $1`, guestCredit).Scan(&n); err != nil {
t.Fatal(err)
}
return n
}
if n := creditArtists(); n != 0 {
t.Errorf("%d artists named %q, want none", n, guestCredit)
} }
// The guest track as the old filing left it: on an album of its own, // The guest track as the old filing left it: under an artist named for
// made long enough ago for the tidy-up, under an older tag-read version. // the whole credit, on an album of its own, both made long enough ago for
// the tidy-up, under an older tag-read version.
if _, err := pool.Exec(ctx, ` if _, err := pool.Exec(ctx, `
WITH g AS (SELECT artist_id FROM tracks WHERE file_path = $1), WITH ar AS (INSERT INTO artists (name, sort_name, created_at)
VALUES ($2, lower($2), now() - interval '1 day') RETURNING id),
a AS (INSERT INTO albums (title, sort_title, artist_id, created_at) a AS (INSERT INTO albums (title, sort_title, artist_id, created_at)
SELECT 'Night Drive', 'night drive', artist_id, now() - interval '1 day' FROM g SELECT 'Night Drive', 'night drive', id, now() - interval '1 day' FROM ar
RETURNING id) RETURNING id)
UPDATE tracks SET album_id = (SELECT id FROM a), tag_read_version = 8 WHERE file_path = $1`, guest); err != nil { UPDATE tracks SET album_id = (SELECT id FROM a), artist_id = (SELECT id FROM ar),
artist_credit = NULL, tag_read_version = 8
WHERE file_path = $1`, guest, guestCredit); err != nil {
t.Fatal(err) t.Fatal(err)
} }
if _, err := scanner.Scan(ctx, nil); err != nil { if _, err := scanner.Scan(ctx, nil); err != nil {
t.Fatalf("rescan: %v", err) t.Fatalf("rescan: %v", err)
} }
if got := albums(); got["Night Drive"].tracks != 2 { if got := albums(); got["Night Drive"].tracks != 2 || got["Night Drive"].trackArtists != 1 {
t.Errorf("after the re-read, Night Drive = %+v, want both tracks back on one album", got["Night Drive"]) t.Errorf("after the re-read, Night Drive = %+v, want both tracks back on one album under Paper Lanterns", got["Night Drive"])
}
if artist, credit := creditOf(); artist != "Paper Lanterns" || credit == nil || *credit != guestCredit {
t.Errorf("after the re-read, guest track filed under %q with credit %v, want Paper Lanterns with credit %q", artist, credit, guestCredit)
}
if n := creditArtists(); n != 0 {
t.Errorf("after the re-read, %d artists named %q, want the tidy-up to remove it", n, guestCredit)
} }
var empty int var empty int
if err := pool.QueryRow(ctx, if err := pool.QueryRow(ctx,
+33 -22
View File
@@ -22,7 +22,9 @@ import (
// other seven would never be seen by browse or the taste profile. // other seven would never be seen by browse or the taste profile.
// //
// The comment block is read here directly, as the ID3v2 genre frame is in // The comment block is read here directly, as the ID3v2 genre frame is in
// id3v2genre.go. Every other field still comes from dhowden/tag. // id3v2genre.go, for the fields where a repeat matters: GENRE, and the
// ARTISTS and MUSICBRAINZ_ARTISTID lists an artist credit is read from
// (artistcredit.go). Every other field still comes from dhowden/tag.
// maxVorbisCommentSize caps a comment block or packet. Comments are kilobytes; // maxVorbisCommentSize caps a comment block or packet. Comments are kilobytes;
// an embedded METADATA_BLOCK_PICTURE can take them to a few megabytes. The cap // an embedded METADATA_BLOCK_PICTURE can take them to a few megabytes. The cap
@@ -32,9 +34,17 @@ const maxVorbisCommentSize = 16 << 20
var errMalformedComment = errors.New("library: malformed Vorbis comment") var errMalformedComment = errors.New("library: malformed Vorbis comment")
// readFLACGenreValues returns every GENRE value in a FLAC file's comment block. // readFLACGenreValues returns every GENRE value in a FLAC file's comment block.
// (nil, nil) means the file is readable and declares no genre. rs is seeked to // (nil, nil) means the file is readable and declares no genre.
// the start, so it is safe to call after dhowden/tag has consumed the reader. func readFLACGenreValues(rs io.ReadSeeker) ([]string, error) { return readFLACValues(rs, "GENRE") }
func readFLACGenreValues(rs io.ReadSeeker) ([]string, error) {
// readOggGenreValues returns every GENRE value in an Ogg Vorbis or Opus file.
func readOggGenreValues(rs io.ReadSeeker) ([]string, error) { return readOggValues(rs, "GENRE") }
// readFLACValues returns every value of the comment field key in a FLAC
// file's comment block, in file order. (nil, nil) means the file is readable
// and has no such field. rs is seeked to the start, so it is safe to call after
// dhowden/tag has consumed the reader.
func readFLACValues(rs io.ReadSeeker, key string) ([]string, error) {
if _, err := rs.Seek(0, io.SeekStart); err != nil { if _, err := rs.Seek(0, io.SeekStart); err != nil {
return nil, err return nil, err
} }
@@ -82,7 +92,7 @@ func readFLACGenreValues(rs io.ReadSeeker) ([]string, error) {
if _, err := io.ReadFull(rs, body); err != nil { if _, err := io.ReadFull(rs, body); err != nil {
return nil, errNoGenreFrame return nil, errNoGenreFrame
} }
return vorbisCommentGenres(body) return vorbisCommentValues(body, key)
case 127: // invalid by spec; nothing after it can be trusted case 127: // invalid by spec; nothing after it can be trusted
return nil, errNoGenreFrame return nil, errNoGenreFrame
} }
@@ -95,11 +105,12 @@ func readFLACGenreValues(rs io.ReadSeeker) ([]string, error) {
} }
} }
// readOggGenreValues returns every GENRE value in an Ogg Vorbis or Opus file. // readOggValues returns every value of the comment field key in an Ogg Vorbis
// The comments are the stream's second packet, which can span several pages // or Opus file. The comments are the stream's second packet, which can span
// when it carries cover art, so pages are reassembled until it is complete. // several pages when it carries cover art, so pages are reassembled until it
// Only the first logical stream is read; pages of any other are skipped. // is complete. Only the first logical stream is read; pages of any other are
func readOggGenreValues(rs io.ReadSeeker) ([]string, error) { // skipped.
func readOggValues(rs io.ReadSeeker, key string) ([]string, error) {
if _, err := rs.Seek(0, io.SeekStart); err != nil { if _, err := rs.Seek(0, io.SeekStart); err != nil {
return nil, err return nil, err
} }
@@ -149,7 +160,7 @@ func readOggGenreValues(rs io.ReadSeeker) ([]string, error) {
continue // the packet carries on in the next segment continue // the packet carries on in the next segment
} }
if packetIdx == 1 { if packetIdx == 1 {
return oggCommentGenres(packet) return oggCommentValues(packet, key)
} }
packetIdx++ packetIdx++
packet = packet[:0] packet = packet[:0]
@@ -157,24 +168,24 @@ func readOggGenreValues(rs io.ReadSeeker) ([]string, error) {
} }
} }
// oggCommentGenres strips the codec's comment-packet prefix. Ogg FLAC and Speex // oggCommentValues strips the codec's comment-packet prefix. Ogg FLAC and Speex
// are rare enough to leave to dhowden/tag. // are rare enough to leave to dhowden/tag.
func oggCommentGenres(packet []byte) ([]string, error) { func oggCommentValues(packet []byte, key string) ([]string, error) {
switch { switch {
case bytes.HasPrefix(packet, []byte("\x03vorbis")): case bytes.HasPrefix(packet, []byte("\x03vorbis")):
return vorbisCommentGenres(packet[7:]) return vorbisCommentValues(packet[7:], key)
case bytes.HasPrefix(packet, []byte("OpusTags")): case bytes.HasPrefix(packet, []byte("OpusTags")):
return vorbisCommentGenres(packet[8:]) return vorbisCommentValues(packet[8:], key)
} }
return nil, errNoGenreFrame return nil, errNoGenreFrame
} }
// vorbisCommentGenres reads a comment block (vendor string, then a count of // vorbisCommentValues reads a comment block (vendor string, then a count of
// length-prefixed "KEY=value" entries, little-endian lengths throughout) and // length-prefixed "KEY=value" entries, little-endian lengths throughout) and
// returns the GENRE values in file order. Field names are case-insensitive by // returns the values of field key in file order. Field names are
// spec. Anything after the last entry, such as Vorbis's framing bit, is // case-insensitive by spec. Anything after the last entry, such as Vorbis's
// ignored. // framing bit, is ignored.
func vorbisCommentGenres(b []byte) ([]string, error) { func vorbisCommentValues(b []byte, key string) ([]string, error) {
next := func() ([]byte, bool) { next := func() ([]byte, bool) {
if len(b) < 4 { if len(b) < 4 {
return nil, false return nil, false
@@ -203,8 +214,8 @@ func vorbisCommentGenres(b []byte) ([]string, error) {
if !ok { if !ok {
return nil, errMalformedComment return nil, errMalformedComment
} }
key, value, found := strings.Cut(string(field), "=") name, value, found := strings.Cut(string(field), "=")
if !found || !strings.EqualFold(key, "GENRE") { if !found || !strings.EqualFold(name, key) {
continue continue
} }
if value = strings.TrimSpace(value); value != "" { if value = strings.TrimSpace(value); value != "" {
+2 -1
View File
@@ -8,6 +8,7 @@ import (
"github.com/jackc/pgx/v5/pgtype" "github.com/jackc/pgx/v5/pgtype"
"git.fabledsword.com/bvandeusen/minstrel/internal/db"
"git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq" "git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq"
"git.fabledsword.com/bvandeusen/minstrel/internal/library" "git.fabledsword.com/bvandeusen/minstrel/internal/library"
) )
@@ -308,7 +309,7 @@ func songRef(t dbq.Track, albumTitle, artistName string, g library.ReplayGain) S
Parent: uuidToID(t.AlbumID), Parent: uuidToID(t.AlbumID),
Title: t.Title, Title: t.Title,
Album: albumTitle, Album: albumTitle,
Artist: artistName, Artist: db.TrackCredit(t, artistName),
AlbumID: uuidToID(t.AlbumID), AlbumID: uuidToID(t.AlbumID),
ArtistID: uuidToID(t.ArtistID), ArtistID: uuidToID(t.ArtistID),
CoverArt: uuidToID(t.AlbumID), CoverArt: uuidToID(t.AlbumID),