package library import ( "fmt" "math" "path/filepath" "regexp" "strconv" "strings" "unicode/utf8" "go.senan.xyz/taglib" ) // UnknownArtist is used when a file has no artist tag. const UnknownArtist = "Unknown Artist" // TaglibReader reads tags and audio properties with TagLib (compiled to // WebAssembly, so there is no CGO). It is safe for concurrent use. type TaglibReader struct{} // Read implements TagReader. func (TaglibReader) Read(path string) (Metadata, error) { tags, err := taglib.ReadTags(path) if err != nil { return Metadata{}, fmt.Errorf("%w: %v", ErrUnreadable, err) } props, err := taglib.ReadProperties(path) if err != nil { return Metadata{}, fmt.Errorf("%w: %v", ErrUnreadable, err) } // TagLib does not fail on random bytes named .mp3; it just finds no audio. if props.SampleRate == 0 || props.Length <= 0 { return Metadata{}, fmt.Errorf("%w: no audio stream found", ErrUnreadable) } artists := nonEmpty(tags["ARTIST"]) albumArtist := first(tags, "ALBUMARTIST") albumArtistID := "" if albumArtist != "" { // The id belongs to the album artist tag: when the tag is missing the name // below is only a fallback, and an id would land on the wrong artist. albumArtistID = singleID(tags["MUSICBRAINZ_ALBUMARTISTID"]) } albumID := "" if first(tags, "ALBUM") != "" { // Like the album artist's id, it belongs to a tag: a file with no album has none to put it on. albumID = singleID(tags["MUSICBRAINZ_RELEASEGROUPID"]) } m := Metadata{ Tags: Tags{ Genres: CleanGenres(tags["GENRE"]), Title: first(tags, "TITLE"), Album: first(tags, "ALBUM"), AlbumArtist: albumArtist, Artists: artists, ArtistMBIDs: pairArtistIDs(artists, tags["MUSICBRAINZ_ARTISTID"]), AlbumArtistMBID: albumArtistID, AlbumMBID: albumID, TrackNo: leadingInt(first(tags, "TRACKNUMBER")), DiscNo: leadingInt(first(tags, "DISCNUMBER")), Year: yearOf(tags), ReplayGain: ReplayGain{ TrackGain: parseGain(first(tags, "REPLAYGAIN_TRACK_GAIN")), AlbumGain: parseGain(first(tags, "REPLAYGAIN_ALBUM_GAIN")), TrackPeak: parsePeak(first(tags, "REPLAYGAIN_TRACK_PEAK")), AlbumPeak: parsePeak(first(tags, "REPLAYGAIN_ALBUM_PEAK")), }, }, Properties: Properties{ Format: strings.ToLower(props.Format), DurationMs: props.Length.Milliseconds(), SampleRate: int(props.SampleRate), BitRate: int(props.BitRate), }, } if m.Title == "" { base := filepath.Base(path) m.Title = strings.TrimSuffix(base, filepath.Ext(base)) } if len(m.Artists) == 0 { m.Artists = []string{UnknownArtist} m.ArtistMBIDs = nil // an id for an artist the file never named is not ours to use } if m.AlbumArtist == "" { m.AlbumArtist = m.Artists[0] } return m, nil } // yearOf reads the year a song came out: the original date when the file has one (a reissue says when it was // reissued in DATE), then the date. Both are written as 1997, 1997-05-21 or 1997-05-21T10:00:00; anything that does // not start with four digits that make a plausible year is no year. func yearOf(tags map[string][]string) int { for _, key := range []string{"ORIGINALDATE", "ORIGINALYEAR", "DATE", "YEAR"} { v := strings.TrimSpace(first(tags, key)) if len(v) < 4 { continue } if y, err := strconv.Atoi(v[:4]); err == nil && y >= MinYear && y <= MaxYear && (len(v) == 4 || v[4] < '0' || v[4] > '9') { return y } } return 0 } // maxGainDB bounds a gain that is believed: a tag that asks for more than this is a mistake, and playing it would // be either silence or a blast. const maxGainDB = 60 // maxPeak bounds a peak that is believed. A real peak is a little above 1 at most (a file that was clipped when it // was decoded); anything near this is not a peak. const maxPeak = 1000 // parseGain reads a ReplayGain gain: a number of decibels, written as "-6.54 dB", "+3.2 dB" or only "-6.54" (some // taggers write a comma). Anything else is no gain. func parseGain(s string) *float64 { v, ok := parseDecimal(strings.TrimSpace(strings.TrimSuffix(strings.ToLower(strings.TrimSpace(s)), "db"))) if !ok || math.Abs(v) > maxGainDB { return nil } return &v } // parsePeak reads a ReplayGain peak: a positive number, 1 meaning full scale. Anything else is no peak. func parsePeak(s string) *float64 { v, ok := parseDecimal(strings.TrimSpace(s)) if !ok || v <= 0 || v > maxPeak { return nil } return &v } // parseDecimal reads a number written with a point or a comma, and refuses NaN and infinity. func parseDecimal(s string) (float64, bool) { v, err := strconv.ParseFloat(strings.ReplaceAll(s, ",", "."), 64) if err != nil || math.IsNaN(v) || math.IsInf(v, 0) { return 0, false } return v, true } // maxGenreLen bounds one genre; a longer one is a sentence, not a genre. const maxGenreLen = 100 // CleanGenres turns the values of the GENRE tag into a short list of lower case // genres without repeats. A tagger may write several genres as several values or // as one value joined with ";". A slash is not a separator: "R&B/Soul" is one genre. func CleanGenres(values []string) []string { var out []string seen := map[string]bool{} for _, v := range values { for _, g := range strings.Split(v, ";") { g = strings.ToLower(strings.TrimSpace(g)) if g == "" || utf8.RuneCountInString(g) > maxGenreLen || seen[g] { continue } seen[g] = true out = append(out, g) if len(out) == MaxGenresPerTrack { return out } } } return out } var mbidRe = regexp.MustCompile(`^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$`) // splitIDs reads the MusicBrainz ids out of the values of one tag. Taggers write // several artists either as several values or as one value joined with "/" or ";". // ok is false when any piece is not a MusicBrainz id. func splitIDs(values []string) (ids []string, ok bool) { for _, v := range values { for _, piece := range strings.FieldsFunc(v, func(r rune) bool { return r == '/' || r == ';' || r == ',' }) { piece = strings.TrimSpace(piece) if piece == "" { continue } if !mbidRe.MatchString(piece) { return nil, false } ids = append(ids, strings.ToLower(piece)) } } return ids, true } // pairArtistIDs returns one id per artist, in order, or nothing. Fewer or more // ids than artists, or an id that is not one, means the pairing would be a guess, // and a wrong id on an artist is worse than none. func pairArtistIDs(artists, values []string) []string { ids, ok := splitIDs(values) if !ok || len(ids) == 0 || len(ids) != len(artists) { return nil } // One credit with one id ("X feat. Y" with the id of X) is the usual way a // tagger writes the id of the first artist only. Without a way to tell, no id. if len(artists) == 1 && looksLikeCredit(artists[0]) { return nil } return ids } // creditWords are the separators of a credit that names several artists. A slash // is not one: AC/DC is a band. var creditWords = []string{" feat.", " feat ", " featuring ", " ft.", " ft ", " with ", " & ", " and ", " vs ", " vs. ", " x ", ",", ";"} // looksLikeCredit says whether a name seems to credit more than one artist. It // errs on the side of "yes": a missing id costs a lookup, a wrong one a wrong artist. func looksLikeCredit(name string) bool { n := " " + strings.ToLower(name) + " " for _, w := range creditWords { // Text must stand on both sides: a band called "X" is not a credit. if i := strings.Index(n, w); i > 1 && i+len(w) < len(n)-1 { return true } } return false } // singleID returns the id when the tag holds exactly one valid id. func singleID(values []string) string { ids, ok := splitIDs(values) if !ok || len(ids) != 1 { return "" } return ids[0] } func first(tags map[string][]string, key string) string { for _, v := range tags[key] { if v = strings.TrimSpace(v); v != "" { return v } } return "" } func nonEmpty(values []string) []string { var out []string for _, v := range values { if v = strings.TrimSpace(v); v != "" { out = append(out, v) } } return out } // leadingInt parses "3" or "3/12" and returns 0 when there is no number. func leadingInt(s string) int { if i := strings.IndexByte(s, '/'); i >= 0 { s = s[:i] } n, err := strconv.Atoi(strings.TrimSpace(s)) if err != nil || n < 0 { return 0 } return n }