diff --git a/pdb/usblayout_test.go b/pdb/usblayout_test.go new file mode 100644 index 0000000..7ea1010 --- /dev/null +++ b/pdb/usblayout_test.go @@ -0,0 +1,100 @@ +// SPDX-License-Identifier: GPL-3.0-or-later + +package pdb + +import ( + "os" + "path/filepath" + "strings" + "testing" + "unicode/utf8" +) + +// TestPrepareUSBLayoutKeepsCollidingNamesApart lays out tracks whose USB file +// names collide: two mixes sharing their first 44 characters, two names that +// differ only in case (one file on FAT), and the same name from two folders. +// Before the fix each pair got one path, the second copy overwrote the first, +// and both PDB rows played the same audio. The later track of a pair gets +// rekordbox's "-1" suffix (rekordbox 7 export: "Same Name.mp3" and +// "Same Name-1.mp3", "...Shared Title .mp3" and "...Shared Titl-1.mp3"). +func TestPrepareUSBLayoutKeepsCollidingNamesApart(t *testing.T) { + src, out := t.TempDir(), t.TempDir() + const long = "Fixture Artist - A Very Long Shared Title For Two Mixes" + files := []string{ + long + " (Mix A).mp3", + long + " (Mix B).mp3", + long + " (Mix C).mp3", + "Case Test.mp3", + "CASE TEST.mp3", + "one/Same Name.mp3", + "two/Same Name.mp3", + } + want := []string{ + "Fixture Artist - A Very Long Shared Title Fo.mp3", + "Fixture Artist - A Very Long Shared Title -1.mp3", + "Fixture Artist - A Very Long Shared Title -2.mp3", + "Case Test.mp3", + "CASE TEST-1.mp3", + "Same Name.mp3", + "Same Name-1.mp3", + } + var tracks []*Track + for i, f := range files { + p := filepath.Join(src, f) + if err := os.MkdirAll(filepath.Dir(p), 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(p, []byte(f), 0o644); err != nil { + t.Fatal(err) + } + tracks = append(tracks, &Track{ID: uint32(i + 1), Artist: "Fixture Artist", Album: "Collisions", FilePath: p}) + } + + if err := PrepareUSBLayout(tracks, src, out, true); err != nil { + t.Fatal(err) + } + + for i, tr := range tracks { + if got := "/Contents/Fixture Artist/Collisions/" + want[i]; tr.FilePath != got { + t.Errorf("%s: USB path %q, want %q", files[i], tr.FilePath, got) + } + got, err := os.ReadFile(filepath.Join(out, filepath.FromSlash(tr.FilePath))) + if err != nil { + t.Fatal(err) + } + if string(got) != files[i] { + t.Errorf("%s plays %q, want %q", tr.FilePath, got, files[i]) + } + } +} + +// A cut never splits a character: a two-byte "é" that the 48-byte cap or a +// suffix would cut in half is left out whole. +func TestPrepareUSBLayoutCutsWholeCharacters(t *testing.T) { + src, out := t.TempDir(), t.TempDir() + // In the first two names "é" takes bytes 42 and 43: the 44-byte base of + // the plain cap keeps it, the 42-byte base before "-1" would split it. + // In the third it takes bytes 44 and 45, split by the plain cap. + prefix := strings.Repeat("x", 41) + var tracks []*Track + for i, f := range []string{prefix + "é one.mp3", prefix + "é two.mp3", strings.Repeat("y", 43) + "é.mp3"} { + p := filepath.Join(src, f) + if err := os.WriteFile(p, []byte(f), 0o644); err != nil { + t.Fatal(err) + } + tracks = append(tracks, &Track{ID: uint32(i + 1), Artist: "Fixture Artist", Album: "Cuts", FilePath: p}) + } + + if err := PrepareUSBLayout(tracks, src, out, true); err != nil { + t.Fatal(err) + } + + for i, want := range []string{prefix + "é .mp3", prefix + "-1.mp3", strings.Repeat("y", 43) + ".mp3"} { + name := filepath.Base(tracks[i].FilePath) + if !utf8.ValidString(name) { + t.Errorf("track %d: %q is not valid UTF-8", i+1, name) + } else if name != want { + t.Errorf("track %d: %q, want %q", i+1, name, want) + } + } +} diff --git a/pdb/writer.go b/pdb/writer.go index ecb2109..9ee62b9 100644 --- a/pdb/writer.go +++ b/pdb/writer.go @@ -8,6 +8,7 @@ import ( "fmt" "os" "path/filepath" + "strconv" "strings" "time" "unicode/utf16" @@ -1272,18 +1273,47 @@ func truncateComponent(s string, maxLen int) string { return out } -// TruncateFilename shortens a filename to maxLen chars, preserving extension. +// TruncateFilename shortens a filename to maxLen bytes, preserving extension. func TruncateFilename(name string, maxLen int) string { if len(name) <= maxLen { return name } + ext := filepath.Ext(name) + return cutName(strings.TrimSuffix(name, ext), maxLen-len(ext)) + ext +} + +// cutName cuts a file name's base to at most n bytes on a UTF-8 rune +// boundary, so the cut never splits a character. It keeps at least the first +// character. +func cutName(base string, n int) string { + if len(base) <= n { + return base + } + cut := max(n, 1) + for cut > 0 && !utf8.RuneStart(base[cut]) { + cut-- + } + if cut == 0 { + _, cut = utf8.DecodeRuneInString(base) + } + return base[:cut] +} + +// uniqueUSBName returns name, or for a name whose path under dir is already +// taken, the first of "name-1", "name-2", … that isn't (the base shortened so +// the whole name stays within maxLen), and marks the path it returns taken. +// Paths compare ignoring case, as on FAT. rekordbox names colliding files the +// same way: "Same Name.mp3" and "Same Name-1.mp3". +func uniqueUSBName(taken map[string]bool, dir, name string, maxLen int) string { ext := filepath.Ext(name) base := strings.TrimSuffix(name, ext) - keep := maxLen - len(ext) - if keep < 1 { - keep = 1 + try := name + for n := 1; taken[strings.ToLower(dir+try)]; n++ { + sfx := "-" + strconv.Itoa(n) + try = cutName(base, maxLen-len(sfx)-len(ext)) + sfx + ext } - return base[:keep] + ext + taken[strings.ToLower(dir+try)] = true + return try } // reencodeAudio runs ffmpeg to re-encode `src` into `dst`, choosing the @@ -1325,6 +1355,7 @@ func reencodeAudio(src, dst string) error { func PrepareUSBLayout(tracks []*Track, srcDir, outDir string, copyFiles bool) error { contentsDir := filepath.Join(outDir, "Contents") now := time.Now().Format("2006-01-02") + taken := make(map[string]bool, len(tracks)) // USB paths handed out so far, lower-cased for _, t := range tracks { artist := t.Artist @@ -1385,6 +1416,14 @@ func PrepareUSBLayout(tracks []*Track, srcDir, outDir string, copyFiles bool) er } } + // Two tracks can land on one path: the same file name in two + // folders, two names that share their first 44 characters once + // capped, or names that differ only in case, which FAT folds + // together. The second copy would overwrite the first and both + // rows would play it, so a later track gets "-1", "-2", … instead. + nameCap := max(min(48, maxUSBPath-fixed), len(ext)+5) + safeName = uniqueUSBName(taken, "/Contents/"+safeArtist+"/"+safeAlbum+"/", safeName, nameCap) + destDir := filepath.Join(contentsDir, safeArtist, safeAlbum) if err := os.MkdirAll(destDir, 0o755); err != nil { return fmt.Errorf("mkdir %s: %w", destDir, err)