Documentation
¶
Overview ¶
Package music is the music module's own logic: the audio quality ladder and profiles, the release-name parser for music, naming, finding and matching audio files, scanning an existing music folder, and the artists/albums/tracks tables. It knows nothing about MusicBrainz or the download pipeline; internal/api wires those together.
Index ¶
- Constants
- Variables
- func AlbumFolder(album string, year int, clean Sanitizer) string
- func AlbumPath(root, artist, album string, year int, clean Sanitizer) string
- func ArtistFolder(artist string, clean Sanitizer) string
- func BestAlbum(title string, year int, candidates []AlbumCandidate) int
- func BestArtist(name string, candidates []NameCandidate) int
- func FindArtwork(dir string) ([]string, error)
- func FindAudioFiles(dir string) ([]string, error)
- func IsArtwork(path string) bool
- func IsAudioFile(path string) bool
- func NormalizeName(s string) string
- func ParseAlbumFolder(name, artist string) (title string, year int)
- func Rank(t Tier) int
- func ReleaseMatch(r Release, artist, album string, albumYear int) (ok bool, reason string)
- func SameAlbum(a, b string) bool
- func SameArtist(a, b string) bool
- func TrackFileName(disc, position int, title string, multiDisc bool, ext string, clean Sanitizer) string
- func ValidTier(s string) bool
- type Album
- type AlbumCandidate
- type Artist
- type ArtistSummary
- type AudioInfo
- type Counts
- type FileInfo
- type FileTagReader
- type Format
- type Match
- type NameCandidate
- type Profile
- func (p Profile) AcceptedBy(t Tier) (by Profile, fallback, ok bool)
- func (p Profile) Accepts(t Tier) bool
- func (p Profile) Chain() []Profile
- func (p Profile) IsUpgrade(current, candidate Tier) bool
- func (p Profile) OnFallback(t Tier) bool
- func (p Profile) ReachedCutoff(t Tier) bool
- func (p Profile) Rejections(t Tier, current Tier) []string
- func (p Profile) WantsUpgrade(current Tier) bool
- type Release
- type Repo
- func (r *Repo) AddAlbums(artistID int64, albums []Album) ([]Album, error)
- func (r *Repo) AddArtist(a Artist, albums []Album) (Artist, []Album, error)
- func (r *Repo) AlbumsByMBID(mbids []string) (map[string]Album, error)
- func (r *Repo) ArtistsByMBID(mbids []string) (map[string]Artist, error)
- func (r *Repo) BulkSetArtists(ids []int64, follow *bool, profileID *int64) (missing []int64, err error)
- func (r *Repo) Counts() (Counts, error)
- func (r *Repo) CreateProfile(p Profile) (Profile, error)
- func (r *Repo) DeleteArtist(id int64) error
- func (r *Repo) DeleteProfile(id, defaultID int64) error
- func (r *Repo) GetAlbum(id int64) (Album, error)
- func (r *Repo) GetArtist(id int64) (Artist, error)
- func (r *Repo) GetArtistByMBID(mbid string) (Artist, bool, error)
- func (r *Repo) GetProfile(id int64) (Profile, error)
- func (r *Repo) ListAlbums(artistID int64) ([]Album, error)
- func (r *Repo) ListAllAlbums() ([]Album, error)
- func (r *Repo) ListArtists() ([]ArtistSummary, error)
- func (r *Repo) ListProfiles() ([]Profile, error)
- func (r *Repo) ListTracks(albumID int64) ([]Track, error)
- func (r *Repo) ProfileUsage() (map[int64]int, error)
- func (r *Repo) ReplaceTracks(albumID int64, tracks []Track) error
- func (r *Repo) SeedPresets() error
- func (r *Repo) SetAlbumImported(id int64, quality Tier, path string) error
- func (r *Repo) SetAlbumMonitored(id int64, monitored bool) error
- func (r *Repo) SetAlbumRelease(id int64, releaseMBID string) error
- func (r *Repo) SetAlbumReleaseDate(id int64, date string) error
- func (r *Repo) SetAlbumStatus(id int64, status Status) error
- func (r *Repo) SetArtistFollow(id int64, follow bool) error
- func (r *Repo) SetArtistMonitored(id int64, monitored bool) error
- func (r *Repo) SetArtistProfile(artistID, profileID int64) error
- func (r *Repo) SetTrackFile(trackID int64, path string) error
- func (r *Repo) UpdateProfile(p Profile) (Profile, error)
- type Sanitizer
- type ScannedAlbum
- type ScannedArtist
- type Status
- type TagConsensus
- type TagReader
- type Tier
- type Track
- type TrackSlot
Constants ¶
const ( PresetLossless = "Lossless (FLAC)" PresetLossy = "Lossy (MP3 320)" )
Names of the built-in profiles.
const ( TypeAlbum = "album" TypeEP = "ep" TypeSingle = "single" )
Album types.
Variables ¶
var ( // ErrProfileInvalid wraps validation failures so the API can report them // as user errors. ErrProfileInvalid = errors.New("invalid music profile") // ErrProfileInUse is returned when deleting a profile that is the default // or is assigned to artists. ErrProfileInUse = errors.New("music profile is in use") )
var ErrArtistExists = errors.New("artist is already in the library")
ErrArtistExists is returned when adding an artist already in the library.
var ErrUnknownAudio = errors.New("not a recognised audio file")
ErrUnknownAudio is returned for a file whose header is not one of the formats read here.
var NamingPresets = []string{"plex", "jellyfin", "navidrome"}
Naming: one layout that Plex, Jellyfin and Navidrome all read without help (each also reads the embedded tags, which this layout does not depend on):
<music>/<Artist>/<Album> (<Year>)/<track> - <Title>.<ext> one disc <music>/<Artist>/<Album> (<Year>)/<disc>-<track> - <Title>.<ext> several discs
Track numbers have two digits ("07"), the disc number none ("2-07"). NamingPresets lists the media servers the layout is meant for, so a settings screen can name them.
Functions ¶
func AlbumFolder ¶
AlbumFolder is the album's folder name: "Album (Year)", or just "Album" when the year is not known.
func ArtistFolder ¶
ArtistFolder is the artist's folder name.
func BestAlbum ¶
func BestAlbum(title string, year int, candidates []AlbumCandidate) int
BestAlbum picks the candidate that is the named album: the same name, and of those the one from the same year when the year is known; -1 when none has the name.
func BestArtist ¶
func BestArtist(name string, candidates []NameCandidate) int
BestArtist picks the candidate whose name (or sort name) is the given name, the highest search score first; -1 when none is.
func FindArtwork ¶
FindArtwork returns the cover images (cover.jpg, folder.jpg...) under dir, at most one per lowercased name, shallowest first.
func FindAudioFiles ¶
FindAudioFiles returns every audio file under dir, sorted by path (so CD1 comes before CD2 and track 01 before 02). Hidden folders and macOS resource forks are skipped.
func IsAudioFile ¶
IsAudioFile reports whether path has an audio file extension.
func NormalizeName ¶
NormalizeName reduces an artist, album or track name to lowercase letters and digits for comparing: accents folded, "&" read as "and", a leading "The" dropped and "Name, The" (a sort name) read as "Name".
func ParseAlbumFolder ¶
ParseAlbumFolder reads an album folder name: "Album (2020)", "Album [2020] [FLAC]", "2020 - Album", "(2020) Album" or "Artist - Album (2020)" (the artist part is dropped when it is the artist's own name).
func Rank ¶
Rank is a tier's position on the ladder (higher is better); unknown strings rank as TierUnknown.
func ReleaseMatch ¶
ReleaseMatch checks that a release found on an indexer is this album by this artist. The reason says why not, in words for the album's activity log and the interactive search list.
func SameAlbum ¶
SameAlbum reports whether two album names are the same album: equal once normalized, or equal once editions ("Deluxe", "(2011 Remaster)") are left out.
func SameArtist ¶
SameArtist reports whether two artist names are the same artist.
Types ¶
type Album ¶
type Album struct {
ID int64
ArtistID int64
MBID string // release-group id
ReleaseMBID string // the release whose tracklist is used; "" until fetched
Title string
Type string // album, ep or single
ReleaseDate string // "YYYY[-MM[-DD]]", "" if unknown
Monitored bool
Status Status
Quality string // a Tier once downloaded
Path string // the album's folder once imported
}
Album is one album, EP or single of an artist (a MusicBrainz release group).
type AlbumCandidate ¶
AlbumCandidate is an album a folder might be (an artist's release group).
type Artist ¶
type Artist struct {
ID int64
MBID string
Name string
SortName string
Disambiguation string
Monitored bool
MonitorNew bool // albums found later start monitored
ProfileID int64 // 0 = the default profile
AddedAt string
AddedBy int64 // account that added it; 0 = unknown
}
Artist is an artist in the library.
type ArtistSummary ¶
type ArtistSummary struct {
Artist
Albums int
Monitored int // monitored albums
Downloaded int // downloaded albums
}
ArtistSummary is an artist with counts of its albums.
type AudioInfo ¶
type AudioInfo struct {
Codec string // flac, alac, mp3, aac, vorbis or opus
SampleRate int // Hz, 0 if unknown
BitDepth int // bits per sample of a lossless file, 0 if unknown or lossy
Channels int
DurationSec float64 // 0 if unknown
BitrateKbps int // average, 0 if unknown
VBR bool // variable bitrate (an MP3 with a Xing or VBRI header)
Lossless bool
}
AudioInfo is what the header of an audio file says about its encoding: the codec, sample rate, bit depth of a lossless file and the average bitrate. It is read by small readers of our own because the tag library reads artist, album and title but nothing about the audio itself. Nothing here writes to a file.
func ParseAudioInfo ¶
ParseAudioInfo is ReadAudioInfo for any reader of size bytes.
func ReadAudioInfo ¶
ReadAudioInfo reads the encoding details of an audio file from its header. The format is taken from the file's first bytes, not its extension.
func (AudioInfo) Tier ¶
Tier classifies the encoding onto the quality ladder. It is Unknown when the header does not say enough (no bitrate, no known codec), which keeps such a file out of automatic upgrades.
Lossless files are FLAC, or FLAC 24bit from 24 bits per sample. MP3: a constant bitrate from its rate (320, 256, else 192); a variable-bitrate file by its average, where LAME V0 averages about 220-260 kbps and is counted with 320. AAC is AAC-256 from 224 kbps and below that ranks with the lowest MP3. Ogg Vorbis and Opus are placed by average bitrate on the MP3 steps: a rough guide only.
type Counts ¶
type Counts struct {
Artists int
Albums int
Downloaded int // albums with their files in the library
Missing int // albums not downloaded and not downloading now
}
Counts are the totals the dashboard shows for the music library.
type FileInfo ¶
type FileInfo struct {
Path string
Disc int
Track int
Title string
Artist string // the track artist tag
AlbumArtist string
Album string
Year int
HasPicture bool // a cover picture is embedded
FileType string // FLAC, MP3, M4A, ALAC, OGG, ... as the tag reader names it
}
FileInfo is what is known about one audio file: where it sits on the album (disc, track), its title and, when its tags were read, who made it and which album it is on. Zero values mean unknown.
func IdentifyFile ¶
IdentifyFile works out a file's disc, track and title: from its name ("07 - Title.flac", "2-07 Title.flac", "Artist - 07 - Title.mp3", "107-artist-title.mp3") and its folder ("CD2/07 - Title.flac"); then from its tags when a TagReader is given, whose values win where they are set.
type FileTagReader ¶
type FileTagReader struct{}
FileTagReader reads the tags embedded in audio files (ID3, Vorbis comments, MP4 atoms) with github.com/dhowden/tag. It only ever reads: nothing in a user's files is written or rewritten.
type Match ¶
Match pairs a file with a track slot (both by index).
func MatchTracks ¶
MatchTracks pairs downloaded files with the album's tracklist, each slot and each file used at most once:
- by disc and track number when the file's title agrees (or it has none); on a one-disc album a missing disc number is disc 1, and on a several-disc album a file without a disc number may count through the discs ("13" is the first track of disc 2 after a 12-track disc 1);
- then by title, for files whose numbers did not fit;
- then by number alone, for what is left.
It returns the matches and the files that fit no track.
type NameCandidate ¶
NameCandidate is an artist a name might be (a MusicBrainz search result).
type Profile ¶
type Profile struct {
ID int64
Name string
Allowed []Tier
Cutoff Tier
UpgradeAllowed bool
// Fallback lists other profiles (by id) tried in order when nothing is
// acceptable to this one; FallbackProfiles is that list resolved.
Fallback []int64
FallbackProfiles []Profile
}
Profile is an audio quality profile: which tiers are acceptable, where upgrading stops, and which other profiles an automatic search falls back to when nothing it finds is acceptable. It mirrors the movie/TV profiles (internal/quality) on the music ladder.
func Presets ¶
func Presets() []Profile
Presets are the built-in profiles, in the order they are created. The first, Lossy, is the default because MP3 is the most common format: it takes MP3 320/V0 or AAC 256. Lossless takes FLAC (24-bit accepted when it is what turns up, but not hunted for) and falls back to Lossy when no lossless release exists.
func ResolveProfile ¶
ResolveProfile picks the profile with id from profiles, or the default (the first) when id is 0 or unknown. ok is false only when there are no profiles at all.
func ValidateProfile ¶
ValidateProfile checks a profile is coherent and returns it cleaned: the name trimmed, the allowed tiers de-duplicated and ordered worst to best, the fallback list without zero, self and repeated ids.
func (Profile) AcceptedBy ¶
AcceptedBy returns the first profile of the chain that accepts t, and whether it is a fallback.
func (Profile) IsUpgrade ¶
IsUpgrade reports whether a candidate tier replaces current: acceptable to this profile and either replacing a fallback file or better and below the cutoff.
func (Profile) OnFallback ¶
OnFallback reports whether a file of tier t is there only because of a fallback: this profile does not accept it but a fallback does. Such an album is always searched for a release the profile itself accepts.
func (Profile) ReachedCutoff ¶
ReachedCutoff reports whether t is at or above the cutoff.
func (Profile) Rejections ¶
Rejections explains why automation would not take a release of tier t for an album (downloaded with quality current, or "" when missing).
func (Profile) WantsUpgrade ¶
WantsUpgrade reports whether an album on disk at tier current should still be searched for something better.
type Release ¶
type Release struct {
Artist string
Album string // for a discography, what the title calls it ("Discography")
Year int // 0 if none (or a range, as in a discography)
Format Format // "" if not named
Bitrate string // "320", "256", "192", "V0", "V2", ... ; "" if not named
BitDepth int // 24 or 16; 0 if not named
Source string // "WEB", "CD", "Vinyl"; "" if not named
Discography bool // a discography, collection, anthology or box set rather than one album
Group string // scene release group, when the title has one
}
Release is what a music release title says about itself.
func ParseRelease ¶
ParseRelease reads a music release title: the artist, the album, the year, and what the title says about the audio (format, bitrate, bit depth, source). It understands the common shapes:
Artist - Album (2020) [FLAC 24bit-96kHz] (P2P, with spaces) Artist_Name-Album_Title-(CAT001)-WEB-2020-GROUP (scene, no spaces) Artist.Name-Album.Title-24BIT-WEB-FLAC-2021-GRP (scene with dots) Artist - Discography (1990-2020) [MP3 320] (a discography)
Anything it cannot make out is left empty; it never guesses a format.
type Repo ¶
type Repo struct {
// contains filtered or unexported fields
}
Repo stores artists, albums, tracks and music profiles.
func (*Repo) AddAlbums ¶
AddAlbums adds albums to an artist that already has some, skipping the ones it has (same MusicBrainz id). It returns only the albums it added, with ids.
func (*Repo) AddArtist ¶
AddArtist adds an artist with its albums in one step. Albums get their ids and ArtistID filled in.
func (*Repo) AlbumsByMBID ¶
AlbumsByMBID returns the library's albums whose release-group id is in mbids, by that id. When two artists share a release group (a split release), the album with the lowest id wins.
func (*Repo) ArtistsByMBID ¶
ArtistsByMBID returns the library's artists whose id is in mbids, by that id.
func (*Repo) BulkSetArtists ¶
func (r *Repo) BulkSetArtists(ids []int64, follow *bool, profileID *int64) (missing []int64, err error)
BulkSetArtists follows or unfollows (follow) and/or gives a quality profile (profileID, 0 = the default) to every artist in ids in one transaction. Either may be nil to leave that setting alone. It returns the ids that are not in the library (any more); the rest are still changed. A database error undoes the whole change.
func (*Repo) CreateProfile ¶
CreateProfile validates and stores a new profile.
func (*Repo) DeleteArtist ¶
DeleteArtist removes an artist with its albums and tracks (not files).
func (*Repo) DeleteProfile ¶
DeleteProfile removes a profile nothing references. defaultID is the profile that is currently the default, which cannot be deleted. The profile is also taken out of every other profile's fallback list.
func (*Repo) GetAlbum ¶
GetAlbum returns one album; the error wraps sql.ErrNoRows when there is no such album.
func (*Repo) GetArtist ¶
GetArtist returns one artist; the error wraps sql.ErrNoRows when there is no such artist.
func (*Repo) GetArtistByMBID ¶
GetArtistByMBID looks an artist up by MusicBrainz id.
func (*Repo) GetProfile ¶
GetProfile returns one profile (its fallback ids, not resolved); the error wraps sql.ErrNoRows when there is none.
func (*Repo) ListAlbums ¶
ListAlbums lists an artist's albums, oldest first (unknown dates last).
func (*Repo) ListAllAlbums ¶
ListAllAlbums lists every album of every artist.
func (*Repo) ListArtists ¶
func (r *Repo) ListArtists() ([]ArtistSummary, error)
ListArtists lists every artist with album counts, by sort name.
func (*Repo) ListProfiles ¶
ListProfiles lists every music profile by id (the first is the default), each with its fallbacks resolved.
func (*Repo) ListTracks ¶
ListTracks lists an album's tracks in order.
func (*Repo) ProfileUsage ¶
ProfileUsage returns how many artists are explicitly assigned each profile (artists on the default profile are not counted).
func (*Repo) ReplaceTracks ¶
ReplaceTracks sets an album's tracklist. Tracks already there (same disc and position) keep their file; tracks no longer listed are removed.
func (*Repo) SeedPresets ¶
SeedPresets creates the built-in profiles on first use (an empty table): Lossy (the default), then Lossless with Lossy as its fallback. Profiles already there are left alone, so a saved choice never changes.
func (*Repo) SetAlbumImported ¶
SetAlbumImported marks an album downloaded, with its quality and folder.
func (*Repo) SetAlbumMonitored ¶
SetAlbumMonitored switches one album's monitoring.
func (*Repo) SetAlbumRelease ¶
SetAlbumRelease records which release's tracklist the album uses.
func (*Repo) SetAlbumReleaseDate ¶
SetAlbumReleaseDate records a release date MusicBrainz now gives for an album (an announced album gets its day).
func (*Repo) SetAlbumStatus ¶
SetAlbumStatus changes only an album's status (a grab starting, or one that failed going back).
func (*Repo) SetArtistFollow ¶
SetArtistFollow switches whether an artist is followed: whether albums found later (see AddAlbums) are picked up and monitored. It never touches the monitored flag of any album that is already listed.
func (*Repo) SetArtistMonitored ¶
SetArtistMonitored switches an artist's monitoring.
func (*Repo) SetArtistProfile ¶
SetArtistProfile assigns a profile to an artist (0 = the default profile).
func (*Repo) SetTrackFile ¶
SetTrackFile records the file a track was imported to ("" clears it).
type Sanitizer ¶
Sanitizer cleans one path component (a name) of characters the file system or a media server cannot take. internal/organizer.Sanitize with the configured mode fits; it is passed in so this package does not depend on the video organizer.
type ScannedAlbum ¶
type ScannedAlbum struct {
Folder string // the folder's name as found
Path string // full path
Title string // album name read from the folder name
Year int // year read from the folder name, 0 if none
Files []string // audio files inside (also in CD1/CD2 sub-folders), sorted
}
ScannedAlbum is one album folder found in an existing music folder.
type ScannedArtist ¶
type ScannedArtist struct {
Name string // the folder's name
Path string
Albums []ScannedAlbum
// Loose are audio files directly in the artist folder (not in an album
// folder): they cannot be told apart, so they are reported, not imported.
Loose []string
}
ScannedArtist is one artist folder with its album folders.
func ScanLibrary ¶
func ScanLibrary(root string) ([]ScannedArtist, error)
ScanLibrary reads an existing music folder laid out the usual way, root/Artist/Album/tracks, without changing anything. Hidden folders are skipped, and album folders without audio files are left out.
type Status ¶
type Status string
Status is where an album stands, the same lifecycle as movies and episodes.
type TagConsensus ¶
type TagConsensus struct {
Artist string // the album artist, else the track artist; never "Various Artists"
Album string
Year int
}
TagConsensus is what most of an album's files say about it. Empty or zero fields are ones the files do not agree on (or do not have).
func ConsensusOf ¶
func ConsensusOf(infos []FileInfo) TagConsensus
ConsensusOf reads the album, artist and year most of the files agree on: a value counts only when more than half of the files that have one say it. The album artist tag wins over the track artist (a compilation's tracks each have their own artist).
type TagReader ¶
TagReader reads the tags embedded in an audio file. ok is false when the file has none. FileTagReader is the one used in the app; when a reader is nil, or a file has no tags, files are identified by their folder and file names alone (see IdentifyFile).
type Tier ¶
type Tier string
Tier is one audio quality level. Music has its own ladder: the video tiers in internal/quality (resolution and source) mean nothing for audio.
const ( TierUnknown Tier = "Unknown" TierMP3192 Tier = "MP3-192" TierMP3256 Tier = "MP3-256" TierAAC256 Tier = "AAC-256" TierMP3320 Tier = "MP3-320/V0" // 320 kbit/s CBR or the V0 VBR preset: transparent for most listeners TierFLAC Tier = "FLAC" // lossless, CD quality (16 bit); ALAC counts as FLAC TierFLAC24 Tier = "FLAC 24bit" // lossless hi-res (24 bit) )
func AlbumTier ¶
AlbumTier is the quality of a set of files: the lowest tier among those whose header could be read, so a folder with one MP3 among its FLACs is never rated as FLAC. It is Unknown when no file could be read (or there are none); a file that cannot be read is left out of the count rather than poisoning the album.
func Classify ¶
Classify maps a parsed release onto the ladder. A release that names no format is Unknown; an MP3 release that names no bitrate is taken as the lowest MP3 tier rather than guessed upwards.
func TierForExtension ¶
TierForExtension is the tier a file's extension alone suggests, for files whose release name said nothing: lossless formats are FLAC, an MP3 is the lowest MP3 tier, AAC is AAC-256. Without a tag reader (see TagReader) the real bitrate and bit depth are not known.