fix(library): a UTF-16 tag frame with a stray trailing zero no longer hides the whole file (#8060)
release / go (push) Successful in 2m4s
release / web (push) Successful in 1m21s
release / govulncheck (push) Successful in 20s
release / integration (push) Successful in 4m9s
release / android (push) Successful in 4m28s
release / Build signed APK (push) Successful in 4m56s
release / Attach APK to the Release (tag releases only) (push) Skipped
release / Build + push container image (push) Successful in 14s
release / Verify release artifacts (tag releases only) (push) Skipped

Some taggers end a UTF-16 text frame with a two-byte terminator and then
one more zero byte, so the frame holds an odd number of bytes.
dhowden/tag refuses the whole tag when it meets one, and the scanner
then skipped the file: 61 tracks on dev (whole albums from one tagger,
with a genre or year frame written this way) never reached the library.

internal/tagread.ReadFrom reads with dhowden/tag first. When that fails
on an ID3v2.3/2.4 tag, it rebuilds the tag in memory with the stray
byte trimmed from each such frame and reads it again. Anything else
still fails with dhowden/tag's own error. The scanner, both MBID
backfills, embedded cover art and Subsonic lyrics all read through it.

The ID3v2 primitives (syncsafe and frame sizes, the extended header,
unsynchronisation) move from library/id3v2genre.go into tagread, so the
genre reader and the repair share one copy.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-26 14:05:55 -05:00
co-authored by Claude Opus 5.5
parent 17a9052acb
commit c9e058b3c9
9 changed files with 334 additions and 95 deletions
+2 -2
View File
@@ -5,7 +5,7 @@ import (
"fmt" "fmt"
"os" "os"
"github.com/dhowden/tag" "git.fabledsword.com/bvandeusen/minstrel/internal/tagread"
) )
// ErrNoEmbeddedArt indicates the audio file has no embedded picture. // ErrNoEmbeddedArt indicates the audio file has no embedded picture.
@@ -33,7 +33,7 @@ func ExtractEmbeddedAlbumArt(path string) ([]byte, error) {
} }
defer func() { _ = f.Close() }() defer func() { _ = f.Close() }()
meta, err := tag.ReadFrom(f) meta, err := tagread.ReadFrom(f)
if err != nil { if err != nil {
return nil, fmt.Errorf("tag read: %w", err) return nil, fmt.Errorf("tag read: %w", err)
} }
+9 -85
View File
@@ -6,6 +6,8 @@ import (
"io" "io"
"strings" "strings"
"unicode/utf16" "unicode/utf16"
"git.fabledsword.com/bvandeusen/minstrel/internal/tagread"
) )
// Why this file exists at all: github.com/dhowden/tag reads every other field // Why this file exists at all: github.com/dhowden/tag reads every other field
@@ -27,12 +29,6 @@ import (
// So the TCON frame is parsed here directly. Only the genre frame — everything // So the TCON frame is parsed here directly. Only the genre frame — everything
// else still comes from dhowden/tag, which handles it fine. // else still comes from dhowden/tag, which handles it fine.
// maxID3TagSize caps how much of a file we'll buffer looking for TCON. Real
// tags are kilobytes; embedded cover art pushes them to a few megabytes. The
// cap exists so a corrupt or hostile size field can't make the scanner
// allocate wildly on a file it was only asked to index.
const maxID3TagSize = 16 << 20
// errNoGenreFrame means the file carries no readable genre frame. It is an // errNoGenreFrame means the file carries no readable genre frame. It is an
// expected outcome (plenty of files are untagged), not a failure. // expected outcome (plenty of files are untagged), not a failure.
var errNoGenreFrame = errors.New("library: no ID3v2 genre frame") var errNoGenreFrame = errors.New("library: no ID3v2 genre frame")
@@ -62,8 +58,8 @@ func readID3v2GenreValues(rs io.ReadSeeker) ([]string, error) {
return nil, errNoGenreFrame return nil, errNoGenreFrame
} }
tagFlags := hdr[5] tagFlags := hdr[5]
size := syncsafeInt(hdr[6:10]) size := tagread.SyncsafeInt(hdr[6:10])
if size <= 0 || size > maxID3TagSize { if size <= 0 || size > tagread.MaxTagSize {
return nil, errNoGenreFrame return nil, errNoGenreFrame
} }
@@ -83,11 +79,11 @@ func readID3v2GenreValues(rs io.ReadSeeker) ([]string, error) {
// Whole-tag unsynchronisation (2.2/2.3). 2.4 moved this per-frame, but // Whole-tag unsynchronisation (2.2/2.3). 2.4 moved this per-frame, but
// some writers still set it at tag level, and undoing it twice is // some writers still set it at tag level, and undoing it twice is
// harmless: after the first pass no 0xFF 0x00 pairs remain. // harmless: after the first pass no 0xFF 0x00 pairs remain.
body = undoUnsynchronisation(body) body = tagread.UndoUnsynchronisation(body)
} }
if major >= 3 && tagFlags&0x40 != 0 { if major >= 3 && tagFlags&0x40 != 0 {
var ok bool var ok bool
if body, ok = skipExtendedHeader(body, major); !ok { if body, ok = tagread.SkipExtendedHeader(body, major); !ok {
return nil, errNoGenreFrame return nil, errNoGenreFrame
} }
} }
@@ -99,7 +95,7 @@ func readID3v2GenreValues(rs io.ReadSeeker) ([]string, error) {
func findGenreFrame(body []byte, major byte) ([]string, error) { func findGenreFrame(body []byte, major byte) ([]string, error) {
// 2.2 frames: 3-byte id + 3-byte size, no flags. 2.3/2.4: 4-byte id + // 2.2 frames: 3-byte id + 3-byte size, no flags. 2.3/2.4: 4-byte id +
// 4-byte size + 2-byte flags. The size field is the other difference that // 4-byte size + 2-byte flags. The size field is the other difference that
// matters — see frameSize. // matters — see tagread.FrameSize.
idLen, sizeLen, flagLen := 4, 4, 2 idLen, sizeLen, flagLen := 4, 4, 2
wantID := "TCON" wantID := "TCON"
if major == 2 { if major == 2 {
@@ -115,7 +111,7 @@ func findGenreFrame(body []byte, major byte) ([]string, error) {
if body[off] == 0 { if body[off] == 0 {
break break
} }
size := frameSize(body[off+idLen:off+idLen+sizeLen], major) size := tagread.FrameSize(body[off+idLen:off+idLen+sizeLen], major)
if size <= 0 || off+hdrLen+size > len(body) { if size <= 0 || off+hdrLen+size > len(body) {
// Bogus length — we can't trust any offset past this point. // Bogus length — we can't trust any offset past this point.
break break
@@ -136,25 +132,6 @@ func findGenreFrame(body []byte, major byte) ([]string, error) {
return nil, errNoGenreFrame return nil, errNoGenreFrame
} }
// frameSize decodes a frame's length field. 2.4 made it syncsafe (7 bits per
// byte); 2.2 and 2.3 are plain big-endian. Reading a 2.3 size as syncsafe (or
// the reverse) yields a plausible-looking wrong offset rather than an obvious
// error, which is exactly how frame-walking bugs go unnoticed.
func frameSize(b []byte, major byte) int {
switch major {
case 2:
return int(b[0])<<16 | int(b[1])<<8 | int(b[2])
case 3:
n := binary.BigEndian.Uint32(b)
if n > maxID3TagSize {
return -1
}
return int(n)
default:
return syncsafeInt(b)
}
}
// frameData strips per-frame wrappers and reports whether the payload is // frameData strips per-frame wrappers and reports whether the payload is
// readable at all. Compressed and encrypted frames are not (we have no // readable at all. Compressed and encrypted frames are not (we have no
// zlib-in-frame or key handling, and neither is meaningful for a genre tag). // zlib-in-frame or key handling, and neither is meaningful for a genre tag).
@@ -192,7 +169,7 @@ func frameData(data []byte, major byte, flags uint16) ([]byte, bool) {
data = data[4:] // syncsafe expanded size; we don't need it data = data[4:] // syncsafe expanded size; we don't need it
} }
if flags&0x0002 != 0 { if flags&0x0002 != 0 {
data = undoUnsynchronisation(data) data = tagread.UndoUnsynchronisation(data)
} }
return data, true return data, true
} }
@@ -333,56 +310,3 @@ func decodeUTF16(b []byte, bigEndian bool) string {
} }
return string(utf16.Decode(units)) return string(utf16.Decode(units))
} }
// skipExtendedHeader advances past the optional extended header. The two
// versions disagree about whether the size field counts itself, which is worth
// spelling out because getting it wrong offsets the entire frame list by four
// bytes and makes every frame id look like padding.
func skipExtendedHeader(body []byte, major byte) ([]byte, bool) {
if len(body) < 4 {
return nil, false
}
if major == 3 {
// 2.3: size EXCLUDES the four size bytes themselves.
size := int(binary.BigEndian.Uint32(body[0:4]))
if size < 0 || 4+size > len(body) {
return nil, false
}
return body[4+size:], true
}
// 2.4: syncsafe size INCLUDING the size bytes.
size := syncsafeInt(body[0:4])
if size < 4 || size > len(body) {
return nil, false
}
return body[size:], true
}
// syncsafeInt decodes a 4-byte synchsafe integer (7 significant bits per byte).
func syncsafeInt(b []byte) int {
if len(b) < 4 {
return -1
}
// A set high bit means this isn't a valid synchsafe integer. Some writers
// emit a plain big-endian size here; refusing is safer than silently
// dropping bits and walking to a wrong offset.
for _, c := range b[:4] {
if c&0x80 != 0 {
return -1
}
}
return int(b[0])<<21 | int(b[1])<<14 | int(b[2])<<7 | int(b[3])
}
// undoUnsynchronisation collapses the 0xFF 0x00 pairs that unsynchronisation
// inserts to stop a tag from looking like an MPEG frame sync.
func undoUnsynchronisation(b []byte) []byte {
out := make([]byte, 0, len(b))
for i := 0; i < len(b); i++ {
out = append(out, b[i])
if b[i] == 0xFF && i+1 < len(b) && b[i+1] == 0x00 {
i++
}
}
return out
}
+3 -3
View File
@@ -6,11 +6,11 @@ import (
"log/slog" "log/slog"
"os" "os"
"github.com/dhowden/tag"
"github.com/jackc/pgx/v5/pgxpool" "github.com/jackc/pgx/v5/pgxpool"
"git.fabledsword.com/bvandeusen/minstrel/internal/db" "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/tagread"
) )
// BackfillMBIDsResult tallies what the one-shot worker did. // BackfillMBIDsResult tallies what the one-shot worker did.
@@ -147,7 +147,7 @@ func readMBIDsForFile(path string, logger *slog.Logger) (albumMBID, artistMBID s
} }
defer func() { _ = f.Close() }() defer func() { _ = f.Close() }()
meta, err := tag.ReadFrom(f) meta, err := tagread.ReadFrom(f)
if err != nil { if err != nil {
logger.Warn("mbid backfill: tag read failed", "path", path, "err", err) logger.Warn("mbid backfill: tag read failed", "path", path, "err", err)
return "", "" return "", ""
@@ -241,7 +241,7 @@ func readRecordingMBIDForFile(path string, logger *slog.Logger) string {
} }
defer func() { _ = f.Close() }() defer func() { _ = f.Close() }()
meta, err := tag.ReadFrom(f) meta, err := tagread.ReadFrom(f)
if err != nil { if err != nil {
logger.Warn("track mbid backfill: tag read failed", "path", path, "err", err) logger.Warn("track mbid backfill: tag read failed", "path", path, "err", err)
return "" return ""
+2 -2
View File
@@ -15,7 +15,6 @@ import (
"sync" "sync"
"time" "time"
"github.com/dhowden/tag"
"github.com/jackc/pgx/v5" "github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgtype" "github.com/jackc/pgx/v5/pgtype"
"github.com/jackc/pgx/v5/pgxpool" "github.com/jackc/pgx/v5/pgxpool"
@@ -23,6 +22,7 @@ import (
"git.fabledsword.com/bvandeusen/minstrel/internal/db" "git.fabledsword.com/bvandeusen/minstrel/internal/db"
"git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq" "git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq"
syncpkg "git.fabledsword.com/bvandeusen/minstrel/internal/sync" syncpkg "git.fabledsword.com/bvandeusen/minstrel/internal/sync"
"git.fabledsword.com/bvandeusen/minstrel/internal/tagread"
) )
// audioExtensions is the set the scanner indexes. Keep in sync with // audioExtensions is the set the scanner indexes. Keep in sync with
@@ -368,7 +368,7 @@ func (s *Scanner) scanFile(
} }
defer func() { _ = f.Close() }() defer func() { _ = f.Close() }()
meta, err := tag.ReadFrom(f) meta, err := tagread.ReadFrom(f)
if err != nil { if err != nil {
return pgtype.UUID{}, false, fmt.Errorf("tag read: %w", err) return pgtype.UUID{}, false, fmt.Errorf("tag read: %w", err)
} }
+3 -1
View File
@@ -7,6 +7,8 @@ import (
"errors" "errors"
"io" "io"
"strings" "strings"
"git.fabledsword.com/bvandeusen/minstrel/internal/tagread"
) )
// Why this file exists: Vorbis comments (FLAC, Ogg Vorbis, Opus) say a field // Why this file exists: Vorbis comments (FLAC, Ogg Vorbis, Opus) say a field
@@ -59,7 +61,7 @@ func readFLACValues(rs io.ReadSeeker, key string) ([]string, error) {
if _, err := io.ReadFull(rs, rest[:]); err != nil { if _, err := io.ReadFull(rs, rest[:]); err != nil {
return nil, errNoGenreFrame return nil, errNoGenreFrame
} }
size := syncsafeInt(rest[2:6]) size := tagread.SyncsafeInt(rest[2:6])
if size < 0 { if size < 0 {
return nil, errNoGenreFrame return nil, errNoGenreFrame
} }
+2 -2
View File
@@ -11,11 +11,11 @@ import (
"strconv" "strconv"
"strings" "strings"
"github.com/dhowden/tag"
"github.com/jackc/pgx/v5" "github.com/jackc/pgx/v5"
"git.fabledsword.com/bvandeusen/minstrel/internal/db" "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/tagread"
) )
// Lyrics are read from the music files when an app asks, not stored: a .lrc // Lyrics are read from the music files when an app asks, not stored: a .lrc
@@ -97,7 +97,7 @@ func readLyrics(path string) (songLyrics, bool) {
return songLyrics{}, false return songLyrics{}, false
} }
defer func() { _ = f.Close() }() defer func() { _ = f.Close() }()
meta, err := tag.ReadFrom(f) meta, err := tagread.ReadFrom(f)
if err != nil { if err != nil {
return songLyrics{}, false return songLyrics{}, false
} }
+84
View File
@@ -0,0 +1,84 @@
package tagread
import "encoding/binary"
// The ID3v2 primitives both tag readers share: this package's repair pass
// and the library's own multi-value genre reader (library/id3v2genre.go).
// MaxTagSize caps how much of a file we'll buffer while reading a tag. Real
// tags are kilobytes; embedded cover art pushes them to a few megabytes. The
// cap exists so a corrupt or hostile size field can't make the scanner
// allocate wildly on a file it was only asked to index.
const MaxTagSize = 16 << 20
// SyncsafeInt decodes a 4-byte synchsafe integer (7 significant bits per byte).
func SyncsafeInt(b []byte) int {
if len(b) < 4 {
return -1
}
// A set high bit means this isn't a valid synchsafe integer. Some writers
// emit a plain big-endian size here; refusing is safer than silently
// dropping bits and walking to a wrong offset.
for _, c := range b[:4] {
if c&0x80 != 0 {
return -1
}
}
return int(b[0])<<21 | int(b[1])<<14 | int(b[2])<<7 | int(b[3])
}
// FrameSize decodes a frame's length field. 2.4 made it syncsafe (7 bits per
// byte); 2.2 and 2.3 are plain big-endian. Reading a 2.3 size as syncsafe (or
// the reverse) yields a plausible-looking wrong offset rather than an obvious
// error, which is exactly how frame-walking bugs go unnoticed.
func FrameSize(b []byte, major byte) int {
switch major {
case 2:
return int(b[0])<<16 | int(b[1])<<8 | int(b[2])
case 3:
n := binary.BigEndian.Uint32(b)
if n > MaxTagSize {
return -1
}
return int(n)
default:
return SyncsafeInt(b)
}
}
// SkipExtendedHeader advances past the optional extended header. The two
// versions disagree about whether the size field counts itself, which is worth
// spelling out because getting it wrong offsets the entire frame list by four
// bytes and makes every frame id look like padding.
func SkipExtendedHeader(body []byte, major byte) ([]byte, bool) {
if len(body) < 4 {
return nil, false
}
if major == 3 {
// 2.3: size EXCLUDES the four size bytes themselves.
size := int(binary.BigEndian.Uint32(body[0:4]))
if size < 0 || 4+size > len(body) {
return nil, false
}
return body[4+size:], true
}
// 2.4: syncsafe size INCLUDING the size bytes.
size := SyncsafeInt(body[0:4])
if size < 4 || size > len(body) {
return nil, false
}
return body[size:], true
}
// UndoUnsynchronisation collapses the 0xFF 0x00 pairs that unsynchronisation
// inserts to stop a tag from looking like an MPEG frame sync.
func UndoUnsynchronisation(b []byte) []byte {
out := make([]byte, 0, len(b))
for i := 0; i < len(b); i++ {
out = append(out, b[i])
if b[i] == 0xFF && i+1 < len(b) && b[i+1] == 0x00 {
i++
}
}
return out
}
+147
View File
@@ -0,0 +1,147 @@
// Package tagread reads a music file's tags. It is github.com/dhowden/tag
// with one repair: dhowden/tag refuses a whole file when a single UTF-16 text
// frame holds an odd number of bytes, and some taggers end a UTF-16 frame
// with one zero byte too many (a two-byte terminator followed by a stray
// single one). Those files then read as having no tags at all, and the
// scanner skipped them. When dhowden/tag fails, ReadFrom rebuilds the ID3v2
// tag in memory without the stray byte and reads it again.
package tagread
import (
"bytes"
"encoding/binary"
"io"
"github.com/dhowden/tag"
)
// ReadFrom reads rs's tags, as tag.ReadFrom does. When that fails on an ID3v2
// tag with a stray trailing zero in a UTF-16 text frame, it answers from a
// copy of the tag with that byte removed. Any other failure returns
// tag.ReadFrom's own error.
func ReadFrom(rs io.ReadSeeker) (tag.Metadata, error) {
start, err := rs.Seek(0, io.SeekCurrent)
if err != nil {
return nil, err
}
meta, err := tag.ReadFrom(rs)
if err == nil {
return meta, nil
}
if _, serr := rs.Seek(start, io.SeekStart); serr != nil {
return nil, err
}
fixed, ok := repairID3v2(rs)
if !ok {
return nil, err
}
repaired, rerr := tag.ReadFrom(bytes.NewReader(fixed))
if rerr != nil {
return nil, err
}
return repaired, nil
}
// repairID3v2 reads the ID3v2 tag at rs's position and returns it rebuilt
// with each stray trailing zero trimmed (trimStrayNul). It reports false
// when there is no ID3v2.3 or 2.4 tag, the tag can't be walked safely, or
// nothing needed trimming, so the caller keeps the original error.
//
// Only the tag is returned: dhowden/tag reads an ID3v2 file's tags without
// touching the audio after them.
func repairID3v2(rs io.Reader) ([]byte, bool) {
var hdr [10]byte
if _, err := io.ReadFull(rs, hdr[:]); err != nil || string(hdr[0:3]) != "ID3" {
return nil, false
}
major, flags := hdr[3], hdr[5]
// A whole-tag unsynchronised tag would have to be re-synchronised after
// the edit; 2.2 has a different frame layout. Neither is worth the risk
// for a repair.
if (major != 3 && major != 4) || flags&0x80 != 0 {
return nil, false
}
size := SyncsafeInt(hdr[6:10])
if size <= 0 || size > MaxTagSize {
return nil, false
}
body := make([]byte, size)
if _, err := io.ReadFull(rs, body); err != nil {
return nil, false
}
frames := body
if flags&0x40 != 0 {
var ok bool
if frames, ok = SkipExtendedHeader(body, major); !ok {
return nil, false
}
}
out := make([]byte, 0, len(body))
out = append(out, body[:len(body)-len(frames)]...) // the extended header, unchanged
changed := false
off := 0
for off+10 <= len(frames) && frames[off] != 0 {
n := FrameSize(frames[off+4:off+8], major)
if n < 0 || off+10+n > len(frames) {
return nil, false
}
id := string(frames[off : off+4])
frameFlags := frames[off+8 : off+10]
data := frames[off+10 : off+10+n]
if frameFlags[0] == 0 && frameFlags[1] == 0 {
if trimmed, ok := trimStrayNul(id, data); ok {
data, changed = trimmed, true
}
}
out = append(out, frames[off:off+4]...)
out = appendFrameSize(out, len(data), major)
out = append(out, frameFlags...)
out = append(out, data...)
off += 10 + n
}
if !changed {
return nil, false
}
out = append(out, frames[off:]...) // padding
tagBytes := make([]byte, 0, 10+len(out))
tagBytes = append(tagBytes, hdr[:6]...)
tagBytes = appendSyncsafe(tagBytes, len(out))
return append(tagBytes, out...), true
}
// trimStrayNul drops the last byte of a UTF-16 text frame whose text runs
// to an odd number of bytes and ends in zero: the stray terminator. A UTF-16
// frame of odd length that ends any other way is left alone.
func trimStrayNul(id string, data []byte) ([]byte, bool) {
textStart := 1 // the encoding byte
switch {
case id == "COMM" || id == "USLT":
textStart = 4 // encoding, then a three-letter language
case id[0] != 'T':
return nil, false
}
if len(data) <= textStart || (data[0] != 1 && data[0] != 2) {
return nil, false
}
if (len(data)-textStart)%2 == 0 || data[len(data)-1] != 0 {
return nil, false
}
return data[:len(data)-1], true
}
// appendFrameSize writes a frame's length field: syncsafe in 2.4, plain
// big-endian in 2.3 (FrameSize reads both).
func appendFrameSize(b []byte, n int, major byte) []byte {
if major == 4 {
return appendSyncsafe(b, n)
}
return binary.BigEndian.AppendUint32(b, uint32(n))
}
// appendSyncsafe writes n as a 4-byte syncsafe integer (SyncsafeInt reads
// it). n is at most MaxTagSize, well inside the 28 bits it can hold.
func appendSyncsafe(b []byte, n int) []byte {
return append(b, byte(n>>21&0x7f), byte(n>>14&0x7f), byte(n>>7&0x7f), byte(n&0x7f))
}
+82
View File
@@ -0,0 +1,82 @@
package tagread
import (
"bytes"
"encoding/binary"
"testing"
"github.com/dhowden/tag"
)
// frame builds one ID3v2 frame for the given major version.
func frame(major byte, id string, data []byte) []byte {
b := []byte(id)
b = appendFrameSize(b, len(data), major)
b = append(b, 0, 0)
return append(b, data...)
}
// id3 wraps frames in an ID3v2 header and ten bytes of padding.
func id3(major byte, frames ...[]byte) []byte {
body := bytes.Join(frames, nil)
body = append(body, make([]byte, 10)...)
b := []byte{'I', 'D', '3', major, 0, 0}
b = appendSyncsafe(b, len(body))
return append(b, body...)
}
// utf16BE encodes s as encoding-1 frame data: the encoding byte, a
// big-endian BOM, the text, and the two-byte terminator.
func utf16BE(s string) []byte {
b := []byte{1, 0xFE, 0xFF}
for _, r := range s {
b = binary.BigEndian.AppendUint16(b, uint16(r))
}
return append(b, 0, 0)
}
func utf8Text(s string) []byte { return append(append([]byte{3}, s...), 0) }
// The frames a real file in the library carried: a UTF-16 genre ending in
// three zero bytes, which dhowden/tag rejects for the whole file.
func TestReadFrom_TrimsAStrayZeroAfterAUTF16Frame(t *testing.T) {
for _, major := range []byte{3, 4} {
strayGenre := append(utf16BE("Punk Rock"), 0)
file := id3(major,
frame(major, "TCON", strayGenre),
frame(major, "TIT2", utf8Text("A Million Miles")),
frame(major, "TPE1", utf8Text("Goldfinger")),
)
if _, err := tag.ReadFrom(bytes.NewReader(file)); err == nil {
t.Fatalf("v2.%d: dhowden/tag read the fixture; it no longer reproduces the fault", major)
}
meta, err := ReadFrom(bytes.NewReader(file))
if err != nil {
t.Fatalf("v2.%d: ReadFrom: %v", major, err)
}
if meta.Title() != "A Million Miles" || meta.Artist() != "Goldfinger" || meta.Genre() != "Punk Rock" {
t.Fatalf("v2.%d: title %q artist %q genre %q", major, meta.Title(), meta.Artist(), meta.Genre())
}
}
}
func TestReadFrom_LeavesOtherFailuresAlone(t *testing.T) {
// Odd-length UTF-16 that doesn't end in zero is not the stray
// terminator, so it is not guessed at.
odd := append(utf16BE("Rock"), 'x')
file := id3(4, frame(4, "TCON", odd))
if _, err := ReadFrom(bytes.NewReader(file)); err == nil {
t.Fatal("ReadFrom read a frame it should not have repaired")
}
if _, err := ReadFrom(bytes.NewReader([]byte("not a music file at all"))); err == nil {
t.Fatal("ReadFrom read a file with no tags")
}
}
func TestReadFrom_AWellFormedTagIsReadAsIs(t *testing.T) {
file := id3(4, frame(4, "TCON", utf16BE("Ska")), frame(4, "TIT2", utf8Text("Beacon")))
meta, err := ReadFrom(bytes.NewReader(file))
if err != nil || meta.Genre() != "Ska" || meta.Title() != "Beacon" {
t.Fatalf("meta %v err %v", meta, err)
}
}