package service import ( "context" "fmt" "os" "os/exec" "path/filepath" "strings" "sync" "sync/atomic" "testing" "vidarchive/internal/models" ) // --- test helpers --- func newLibrary(t *testing.T) (*LibraryService, string) { t.Helper() dir := t.TempDir() return NewLibraryService(dir), dir } // writeItem creates an item directory with a marker and the given files // (filename -> contents). A nil/empty marker body still creates a valid item. func writeItem(t *testing.T, libraryDir, relPath, markerBody string, files map[string]string) string { t.Helper() itemDir := filepath.Join(libraryDir, filepath.FromSlash(relPath)) if err := os.MkdirAll(itemDir, 0755); err != nil { t.Fatalf("mkdir item: %v", err) } if markerBody == "" { markerBody = "duration = -1\n" } if err := os.WriteFile(filepath.Join(itemDir, itemMarkerName), []byte(markerBody), 0644); err != nil { t.Fatalf("write marker: %v", err) } for name, content := range files { if err := os.WriteFile(filepath.Join(itemDir, name), []byte(content), 0644); err != nil { t.Fatalf("write file %s: %v", name, err) } } return itemDir } func requireFFmpeg(t *testing.T) { t.Helper() if _, err := exec.LookPath("ffmpeg"); err != nil { t.Skip("ffmpeg not on PATH") } } // makeTestVideo writes a tiny real video file ffmpeg can decode a frame from. func makeTestVideo(t *testing.T, path string) { t.Helper() makeTestVideoSize(t, path, "64x64") } // makeTestVideoSize is makeTestVideo with an explicit WxH size. func makeTestVideoSize(t *testing.T, path, size string) { t.Helper() // 3s so the default 1s thumbnail seek lands on a real frame. cmd := exec.Command("ffmpeg", "-hide_banner", "-loglevel", "error", "-f", "lavfi", "-i", "testsrc=duration=3:size="+size+":rate=5", "-pix_fmt", "yuv420p", path, "-y") if out, err := cmd.CombinedOutput(); err != nil { t.Fatalf("make test video: %v\n%s", err, out) } } // makeVideoWithCoverAttachment writes an MKV at outPath with a 64x64 video and // an embedded "cover.webp" image attachment of the given size — mirroring how // yt-dlp embeds thumbnails into MKV (a true attachment stream, not an // attached_pic video stream; note ffmpeg muxes an attached .png as a video // stream, so webp/jpg must be used to get a real attachment). func makeVideoWithCoverAttachment(t *testing.T, outPath, coverSize string) { t.Helper() scratch := t.TempDir() base := filepath.Join(scratch, "base.mp4") makeTestVideoSize(t, base, "64x64") cover := filepath.Join(scratch, "cover.webp") if out, err := exec.Command("ffmpeg", "-hide_banner", "-loglevel", "error", "-f", "lavfi", "-i", "color=red:size="+coverSize+":duration=1", "-frames:v", "1", cover, "-y").CombinedOutput(); err != nil { t.Fatalf("make cover: %v\n%s", err, out) } if out, err := exec.Command("ffmpeg", "-hide_banner", "-loglevel", "error", "-i", base, "-attach", cover, "-metadata:s:t:0", "mimetype=image/webp", "-c", "copy", outPath, "-y").CombinedOutput(); err != nil { t.Fatalf("attach cover: %v\n%s", err, out) } } // probeImageSize returns the pixel dimensions of an image/video file. func probeImageSize(t *testing.T, path string) (int, int) { t.Helper() out, err := exec.Command("ffprobe", "-v", "error", "-select_streams", "v:0", "-show_entries", "stream=width,height", "-of", "csv=p=0:s=x", path).Output() if err != nil { t.Fatalf("probe %s: %v", path, err) } var w, h int if _, err := fmt.Sscanf(strings.TrimSpace(string(out)), "%dx%d", &w, &h); err != nil { t.Fatalf("parse dimensions %q: %v", out, err) } return w, h } // --- pure helper tests --- func TestInfoDuration(t *testing.T) { tests := []struct { name string in map[string]interface{} want int ok bool }{ {"float", map[string]interface{}{"duration": 149.4}, 149, true}, {"float rounds up", map[string]interface{}{"duration": 149.6}, 150, true}, {"int", map[string]interface{}{"duration": 200}, 200, true}, {"string", map[string]interface{}{"duration": "12.0"}, 12, true}, {"bad string", map[string]interface{}{"duration": "abc"}, 0, false}, {"missing", map[string]interface{}{}, 0, false}, {"nil", nil, 0, false}, } for _, tc := range tests { t.Run(tc.name, func(t *testing.T) { got, ok := infoDuration(tc.in) if ok != tc.ok || got != tc.want { t.Errorf("infoDuration(%v) = (%d,%v), want (%d,%v)", tc.in, got, ok, tc.want, tc.ok) } }) } } func TestUrlEncodePath(t *testing.T) { tests := []struct{ in, want string }{ {"a/b c", "a/b%20c"}, {"/leading/trailing/", "leading/trailing"}, {"Hatsune Miku [id]", "Hatsune%20Miku%20%5Bid%5D"}, {"plain", "plain"}, } for _, tc := range tests { if got := urlEncodePath(tc.in); got != tc.want { t.Errorf("urlEncodePath(%q) = %q, want %q", tc.in, got, tc.want) } } } func TestParseFPS(t *testing.T) { tests := []struct{ in, want string }{ {"30/1", "30"}, {"30000/1001", "29.97"}, {"0/0", ""}, {"", ""}, {"garbage", ""}, } for _, tc := range tests { if got := parseFPS(tc.in); got != tc.want { t.Errorf("parseFPS(%q) = %q, want %q", tc.in, got, tc.want) } } } func TestInfoString(t *testing.T) { if _, ok := infoString(nil, "title"); ok { t.Error("nil info should return false") } if _, ok := infoString(map[string]interface{}{}, "title"); ok { t.Error("missing key should return false") } if v, ok := infoString(map[string]interface{}{"title": "hi"}, "title"); !ok || v != "hi" { t.Errorf("string value = (%q,%v), want (hi,true)", v, ok) } if _, ok := infoString(map[string]interface{}{"title": 5}, "title"); ok { t.Error("numeric value should return false, not stringify") } if _, ok := infoString(map[string]interface{}{"title": map[string]interface{}{"a": 1}}, "title"); ok { t.Error("map value should return false, not stringify") } } func TestPrimaryMediaFile(t *testing.T) { dir := t.TempDir() write := func(name string, n int) string { p := filepath.Join(dir, name) if err := os.WriteFile(p, make([]byte, n), 0644); err != nil { t.Fatal(err) } return p } // Largest video wins over a larger audio file. mixed := &models.LibraryItem{MediaFiles: []models.MediaFile{ {Filename: "small.mp4", Filepath: write("small.mp4", 10)}, {Filename: "big.mp4", Filepath: write("big.mp4", 100)}, {Filename: "huge.mp3", Filepath: write("huge.mp3", 1000), IsAudio: true}, }} if got := primaryMediaFile(mixed); got == nil || got.Filename != "big.mp4" { t.Errorf("expected largest video big.mp4, got %v", got) } // Audio-only item falls back to the largest audio file. audio := &models.LibraryItem{MediaFiles: []models.MediaFile{ {Filename: "a.mp3", Filepath: write("a.mp3", 5), IsAudio: true}, {Filename: "b.mp3", Filepath: write("b.mp3", 50), IsAudio: true}, }} if got := primaryMediaFile(audio); got == nil || got.Filename != "b.mp3" { t.Errorf("expected largest audio b.mp3, got %v", got) } if got := primaryMediaFile(&models.LibraryItem{}); got != nil { t.Errorf("empty item should yield nil, got %v", got) } } func TestFormatBitrate(t *testing.T) { tests := []struct{ in, want string }{ {"128000", "128"}, {"", ""}, {"notanumber", ""}, } for _, tc := range tests { if got := formatBitrate(tc.in); got != tc.want { t.Errorf("formatBitrate(%q) = %q, want %q", tc.in, got, tc.want) } } } // --- listItemFiles / GetAll --- func TestListItemFilesClassification(t *testing.T) { svc, dir := newLibrary(t) itemDir := writeItem(t, dir, "item", "", map[string]string{ "video.mp4": "v", "audio.mp3": "a", "cover.jpg": "img", "thumb.webp": "img", "notes.txt": "ignored", "info.json": `{"title":"x"}`, "video.info.json": `{"title":"x"}`, }) media, infoPath, err := svc.listItemFiles(itemDir) if err != nil { t.Fatalf("listItemFiles: %v", err) } if len(media) != 2 { t.Fatalf("expected 2 media files, got %d: %+v", len(media), media) } var sawAudio, sawVideo bool for _, m := range media { switch m.Filename { case "audio.mp3": sawAudio = true if !m.IsAudio { t.Error("audio.mp3 should be IsAudio") } case "video.mp4": sawVideo = true if m.IsAudio { t.Error("video.mp4 should not be IsAudio") } default: t.Errorf("unexpected media file %q", m.Filename) } } if !sawAudio || !sawVideo { t.Error("missing expected media files") } if infoPath == "" { t.Error("expected an info.json path") } } func TestListItemFilesSortedAscending(t *testing.T) { svc, dir := newLibrary(t) itemDir := writeItem(t, dir, "item", "", map[string]string{ "03 - c.mp4": "c", "01 - a.mp4": "a", "02 - b.mp4": "b", }) media, _, err := svc.listItemFiles(itemDir) if err != nil { t.Fatalf("listItemFiles: %v", err) } got := make([]string, len(media)) for i, m := range media { got[i] = m.Filename } want := []string{"01 - a.mp4", "02 - b.mp4", "03 - c.mp4"} for i := range want { if got[i] != want[i] { t.Fatalf("media files = %v, want ascending %v", got, want) } } } func TestGetAllSeparatesFoldersAndItems(t *testing.T) { svc, dir := newLibrary(t) // An item (has marker) writeItem(t, dir, "song", "name = \"Song\"\nduration = -1\n", map[string]string{"a.mp4": "v"}) // A plain folder (no marker) containing a nested item writeItem(t, dir, "folder/nested", "name = \"Nested\"\nduration = -1\n", map[string]string{"b.mp4": "v"}) // The reserved subtitles dir at root must be ignored if err := os.MkdirAll(filepath.Join(dir, subtitlesDirName), 0755); err != nil { t.Fatal(err) } items, folders, err := svc.GetAll("", "title", "") if err != nil { t.Fatalf("GetAll: %v", err) } if len(items) != 1 || items[0].Name != "Song" { t.Errorf("expected 1 item 'Song', got %+v", items) } if len(folders) != 1 || folders[0] != "folder" { t.Errorf("expected folder 'folder', got %v", folders) } for _, f := range folders { if f == subtitlesDirName { t.Error("subtitles dir should not be listed as a folder") } } } func TestGetAllFilter(t *testing.T) { svc, dir := newLibrary(t) writeItem(t, dir, "alpha", "name = \"Alpha\"\nduration = -1\n", map[string]string{"a.mp4": "v"}) writeItem(t, dir, "beta", "name = \"Beta\"\nduration = -1\n", map[string]string{"b.mp4": "v"}) items, _, err := svc.GetAll("", "title", "alph") if err != nil { t.Fatalf("GetAll: %v", err) } if len(items) != 1 || items[0].Name != "Alpha" { t.Errorf("filter 'alph' should match only Alpha, got %+v", items) } } func TestGetAllSortByTitle(t *testing.T) { svc, dir := newLibrary(t) writeItem(t, dir, "c", "name = \"Charlie\"\nduration = -1\n", map[string]string{"c.mp4": "v"}) writeItem(t, dir, "a", "name = \"alpha\"\nduration = -1\n", map[string]string{"a.mp4": "v"}) writeItem(t, dir, "b", "name = \"Bravo\"\nduration = -1\n", map[string]string{"b.mp4": "v"}) items, _, err := svc.GetAll("", "title", "") if err != nil { t.Fatalf("GetAll: %v", err) } got := []string{items[0].Name, items[1].Name, items[2].Name} want := []string{"alpha", "Bravo", "Charlie"} // case-insensitive for i := range want { if got[i] != want[i] { t.Errorf("sort by title = %v, want %v", got, want) break } } } // --- metadata derivation + marker write behavior --- func TestScanItemDerivesMetadataFromInfoJSON(t *testing.T) { svc, dir := newLibrary(t) info := `{"title":"Real Title","webpage_url":"https://example.com/v","description":"hello","duration":149.2}` writeItem(t, dir, "x", "duration = -1\n", map[string]string{ "x.mp4": "v", "info.json": info, }) item, err := svc.GetByRelPath(context.Background(), "x") if err != nil { t.Fatalf("GetByRelPath: %v", err) } if item.Name != "Real Title" { t.Errorf("Name = %q, want derived from info.json", item.Name) } if item.SourceURL != "https://example.com/v" { t.Errorf("SourceURL = %q", item.SourceURL) } if item.Description != "hello" { t.Errorf("Description = %q", item.Description) } if item.Duration != 149 { t.Errorf("Duration = %d, want 149", item.Duration) } // Derived metadata should be persisted to the marker. markerData, _ := os.ReadFile(filepath.Join(dir, "x", itemMarkerName)) if !strings.Contains(string(markerData), "Real Title") { t.Errorf("marker not enriched with derived title: %s", markerData) } } func TestScanItemUsesFileDurations(t *testing.T) { svc, dir := newLibrary(t) marker := "name = \"M\"\n\n[file_durations]\n \"a.mp4\" = 30\n \"b.mp4\" = 12\n" writeItem(t, dir, "multi", marker, map[string]string{"a.mp4": "v", "b.mp4": "v"}) item, err := svc.GetByRelPath(context.Background(), "multi") if err != nil { t.Fatalf("GetByRelPath: %v", err) } got := map[string]int{} for _, mf := range item.MediaFiles { got[mf.Filename] = mf.Duration } if got["a.mp4"] != 30 || got["b.mp4"] != 12 { t.Errorf("per-file durations = %v, want a=30 b=12", got) } // The item duration is the sum of known per-file durations (used for sorting); // there is no single "overall" duration any more. if item.Duration != 42 { t.Errorf("item Duration = %d, want 42 (sum of file durations)", item.Duration) } } func TestScanItemDoesNotRewriteConvergedMarker(t *testing.T) { svc, dir := newLibrary(t) // Disable the scan cache so every read actually rescans — this exercises // scanItem's own idempotency rather than just a cache hit. svc.scanTTL = 0 marker := "name = \"Done\"\nsource_url = \"u\"\ndescription = \"d\"\n" itemDir := writeItem(t, dir, "y", marker, map[string]string{"y.mp4": "v"}) markerPath := filepath.Join(itemDir, itemMarkerName) // First read may enrich the marker (e.g. cache per-file durations), after // which it has converged. if _, err := svc.GetByRelPath(context.Background(), "y"); err != nil { t.Fatalf("warm-up read: %v", err) } before, err := os.Stat(markerPath) if err != nil { t.Fatal(err) } // Subsequent reads must not rewrite a converged marker. for i := 0; i < 3; i++ { if _, err := svc.GetByRelPath(context.Background(), "y"); err != nil { t.Fatalf("GetByRelPath: %v", err) } } after, err := os.Stat(markerPath) if err != nil { t.Fatal(err) } if !before.ModTime().Equal(after.ModTime()) { t.Errorf("converged marker was rewritten on read (mtime changed %v -> %v)", before.ModTime(), after.ModTime()) } } // TestScanItemEmptyInfoFieldsDoNotRewriteMarker is a regression test: an // info.json with present-but-empty "description"/"webpage_url" must not flip the // marker dirty on every scan. infoString returns ("", true) for those fields, so // the old code reassigned "" and rewrote the marker forever (e.g. clips whose // text lives only in the title). We detect any rewrite via an unknown TOML key, // which scanItem's re-encode would drop. func TestScanItemEmptyInfoFieldsDoNotRewriteMarker(t *testing.T) { svc, dir := newLibrary(t) svc.scanTTL = 0 // force a real rescan on every read info := `{"title":"#hashtags only","description":"","webpage_url":""}` marker := "name = \"#hashtags only\"\nsentinel = \"keep\"\n" writeItem(t, dir, "z", marker, map[string]string{"z.mp4": "v", "info.json": info}) markerPath := filepath.Join(dir, "z", itemMarkerName) for i := 0; i < 3; i++ { if _, err := svc.GetByRelPath(context.Background(), "z"); err != nil { t.Fatalf("GetByRelPath: %v", err) } } data, _ := os.ReadFile(markerPath) if !strings.Contains(string(data), "sentinel") { t.Errorf("marker was rewritten on read (sentinel dropped): %s", data) } } // --- scan cache --- func TestScanCacheReusesWithinTTL(t *testing.T) { svc, dir := newLibrary(t) writeItem(t, dir, "x", "name = \"X\"\nsource_url = \"u\"\n", map[string]string{"x.mp4": "v"}) // Within the TTL, repeated lookups return the same cached scan (no rescan). a, err := svc.GetByRelPath(context.Background(), "x") if err != nil { t.Fatalf("first lookup: %v", err) } b, err := svc.GetByRelPath(context.Background(), "x") if err != nil { t.Fatalf("second lookup: %v", err) } if a != b { t.Error("expected the cached scan to be reused (same pointer) within the TTL") } // Deleting the item evicts its cached scan immediately. if err := svc.Delete("x"); err != nil { t.Fatalf("Delete: %v", err) } if _, ok := svc.getCachedScan("x"); ok { t.Error("Delete should evict the cached scan") } // With caching disabled, each lookup rescans into a distinct item. svc2, dir2 := newLibrary(t) svc2.scanTTL = 0 writeItem(t, dir2, "y", "name = \"Y\"\n", map[string]string{"y.mp4": "v"}) c, _ := svc2.GetByRelPath(context.Background(), "y") d, _ := svc2.GetByRelPath(context.Background(), "y") if c == nil || d == nil || c == d { t.Error("with TTL disabled each lookup should rescan, not reuse a pointer") } } // --- path traversal --- func TestResolveItemDirRejectsTraversal(t *testing.T) { svc, dir := newLibrary(t) if _, err := svc.resolveItemDir("../../etc"); err == nil { t.Error("expected error for traversal path") } // A legitimate nested path resolves fine. got, err := svc.resolveItemDir("sub/item") if err != nil { t.Fatalf("unexpected error: %v", err) } if !strings.HasPrefix(got, dir) { t.Errorf("resolved path %q not under library %q", got, dir) } } // --- delete safety --- func TestDeleteRejectsLibraryRoot(t *testing.T) { svc, dir := newLibrary(t) writeItem(t, dir, "keep", "name = \"Keep\"\nduration = -1\n", map[string]string{"k.mp4": "v"}) for _, rel := range []string{"", "/", "//"} { if err := svc.Delete(rel); err == nil { t.Errorf("Delete(%q) should be refused", rel) } } // The guard must not have touched the library or its contents. if _, err := os.Stat(filepath.Join(dir, "keep", "k.mp4")); err != nil { t.Fatalf("library content was deleted by a root-delete attempt: %v", err) } // A real item still deletes. if err := svc.Delete("keep"); err != nil { t.Fatalf("Delete(real item): %v", err) } if _, err := os.Stat(filepath.Join(dir, "keep")); !os.IsNotExist(err) { t.Errorf("expected item dir removed, stat err = %v", err) } } // --- Thumbnail behavior --- func TestThumbnailPrefersExistingGenerated(t *testing.T) { svc, dir := newLibrary(t) writeItem(t, dir, "item", "name = \"I\"\nduration = -1\n", map[string]string{ "video.mp4": "v", "video.thumbnail.webp": "GENERATED", }) path, ok := svc.ThumbnailForFile(context.Background(), "item", "video.mp4") if !ok { t.Fatal("expected a thumbnail") } if !strings.HasSuffix(path, "video.thumbnail.webp") { t.Errorf("expected generated thumbnail, got %q", path) } } func TestThumbnailExtractsOnDemand(t *testing.T) { requireFFmpeg(t) svc, dir := newLibrary(t) itemDir := writeItem(t, dir, "vid", "name = \"V\"\nduration = -1\n", nil) makeTestVideo(t, filepath.Join(itemDir, "vid.mp4")) path, ok := svc.ThumbnailForFile(context.Background(), "vid", "vid.mp4") if !ok { t.Fatal("expected on-demand extraction to succeed") } if info, err := os.Stat(path); err != nil || info.Size() == 0 { t.Fatalf("thumbnail file missing/empty: %v", err) } if !strings.Contains(filepath.Base(path), ".thumbnail.") { t.Errorf("unexpected thumbnail name %q", path) } // No leftover temp files from the atomic-write path. entries, _ := os.ReadDir(itemDir) for _, e := range entries { if strings.Contains(e.Name(), ".tmp") { t.Errorf("leftover temp file %q", e.Name()) } } } func TestThumbnailRetriesAfterDeletion(t *testing.T) { requireFFmpeg(t) svc, dir := newLibrary(t) itemDir := writeItem(t, dir, "vid", "name = \"V\"\nduration = -1\n", nil) makeTestVideo(t, filepath.Join(itemDir, "vid.mp4")) first, ok := svc.ThumbnailForFile(context.Background(), "vid", "vid.mp4") if !ok { t.Fatal("first extraction failed") } if err := os.Remove(first); err != nil { t.Fatal(err) } // A failure/absence must not be cached permanently: re-request re-extracts. second, ok := svc.ThumbnailForFile(context.Background(), "vid", "vid.mp4") if !ok { t.Fatal("re-extraction after deletion failed (failure was cached)") } if info, err := os.Stat(second); err != nil || info.Size() == 0 { t.Fatalf("re-extracted thumbnail missing/empty: %v", err) } } func TestThumbnailConcurrentSingleExtraction(t *testing.T) { requireFFmpeg(t) svc, dir := newLibrary(t) itemDir := writeItem(t, dir, "vid", "name = \"V\"\nduration = -1\n", nil) makeTestVideo(t, filepath.Join(itemDir, "vid.mp4")) var wg sync.WaitGroup for i := 0; i < 8; i++ { wg.Add(1) go func() { defer wg.Done() if _, ok := svc.ThumbnailForFile(context.Background(), "vid", "vid.mp4"); !ok { t.Error("concurrent Thumbnail failed") } }() } wg.Wait() // Exactly one generated thumbnail, no temp leftovers despite the race. entries, _ := os.ReadDir(itemDir) var thumbs int for _, e := range entries { if strings.Contains(e.Name(), ".thumbnail.") { thumbs++ } if strings.Contains(e.Name(), ".tmp") { t.Errorf("leftover temp file %q", e.Name()) } } if thumbs != 1 { t.Errorf("expected exactly 1 generated thumbnail, got %d", thumbs) } } func TestThumbnailForFileIsPerFile(t *testing.T) { requireFFmpeg(t) svc, dir := newLibrary(t) itemDir := writeItem(t, dir, "multi", "name = \"M\"\nduration = -1\n", nil) makeTestVideo(t, filepath.Join(itemDir, "a.mp4")) makeTestVideo(t, filepath.Join(itemDir, "b.mp4")) ctx := context.Background() pa, ok := svc.ThumbnailForFile(ctx, "multi", "a.mp4") if !ok { t.Fatal("thumbnail for a.mp4 failed") } pb, ok := svc.ThumbnailForFile(ctx, "multi", "b.mp4") if !ok { t.Fatal("thumbnail for b.mp4 failed") } if pa == pb { t.Errorf("expected distinct per-file thumbnails, both = %q", pa) } if !strings.Contains(filepath.Base(pa), "a.thumbnail.") { t.Errorf("a.mp4 thumbnail name = %q", filepath.Base(pa)) } if !strings.Contains(filepath.Base(pb), "b.thumbnail.") { t.Errorf("b.mp4 thumbnail name = %q", filepath.Base(pb)) } // An unknown file yields no thumbnail (caller falls back to an icon). if _, ok := svc.ThumbnailForFile(ctx, "multi", "nope.mp4"); ok { t.Error("unknown file should not produce a thumbnail") } // Every thumbnail is keyed to a specific file: an empty filename yields none. if _, ok := svc.ThumbnailForFile(ctx, "multi", ""); ok { t.Error("empty filename should not produce a thumbnail") } } func TestGetMetadataForSelectedFile(t *testing.T) { requireFFmpeg(t) svc, dir := newLibrary(t) itemDir := writeItem(t, dir, "multi", "name = \"M\"\nduration = -1\n", nil) makeTestVideoSize(t, filepath.Join(itemDir, "small.mp4"), "64x64") makeTestVideoSize(t, filepath.Join(itemDir, "big.mp4"), "128x72") ctx := context.Background() m1, err := svc.GetMetadata(ctx, "multi", "small.mp4") if err != nil { t.Fatalf("GetMetadata small: %v", err) } if m1.Resolution != "64x64" { t.Errorf("small.mp4 resolution = %q, want 64x64", m1.Resolution) } m2, err := svc.GetMetadata(ctx, "multi", "big.mp4") if err != nil { t.Fatalf("GetMetadata big: %v", err) } if m2.Resolution != "128x72" { t.Errorf("big.mp4 resolution = %q, want 128x72", m2.Resolution) } } func TestThumbnailConcurrencyBounded(t *testing.T) { requireFFmpeg(t) svc, dir := newLibrary(t) itemDir := writeItem(t, dir, "many", "name = \"M\"\nduration = -1\n", nil) const n = 8 for i := 0; i < n; i++ { makeTestVideo(t, filepath.Join(itemDir, fmt.Sprintf("c%d.mp4", i))) } var wg sync.WaitGroup for i := 0; i < n; i++ { i := i wg.Add(1) go func() { defer wg.Done() svc.ThumbnailForFile(context.Background(), "many", fmt.Sprintf("c%d.mp4", i)) }() } wg.Wait() max := atomic.LoadInt32(&svc.extractMaxConcurrent) if max > maxConcurrentThumbnails { t.Errorf("peak concurrent extractions %d exceeded cap %d", max, maxConcurrentThumbnails) } if max < 1 { t.Error("expected at least one extraction to run") } } func TestThumbnailUsesEmbeddedAttachment(t *testing.T) { requireFFmpeg(t) svc, dir := newLibrary(t) itemDir := writeItem(t, dir, "att", "name = \"A\"\nduration = -1\n", nil) mkv := filepath.Join(itemDir, "v.mkv") // 100x100 cover so it's distinguishable from a 64x64 video frame. makeVideoWithCoverAttachment(t, mkv, "100x100") if idx := findImageAttachment(mkv); idx < 0 { t.Fatal("findImageAttachment did not find the embedded cover") } path, ok := svc.ThumbnailForFile(context.Background(), "att", "v.mkv") if !ok { t.Fatal("thumbnail extraction failed") } // The embedded cover (100x100) must be used in preference to a video frame // (which would be 64x64) — this is the regression the refactor introduced. if w, h := probeImageSize(t, path); w != 100 || h != 100 { t.Errorf("thumbnail is %dx%d, expected 100x100 from the embedded cover (got a video frame instead)", w, h) } } func TestThumbnailNegativeCacheSkipsReextraction(t *testing.T) { svc, dir := newLibrary(t) // A file ffmpeg cannot extract a thumbnail from: every attempt fails. writeItem(t, dir, "bad", "name = \"B\"\nduration = -1\n", map[string]string{ "broken.mp4": "not actually a video", }) ctx := context.Background() if _, ok := svc.ThumbnailForFile(ctx, "bad", "broken.mp4"); ok { t.Fatal("expected extraction to fail for a non-video file") } attempts1 := atomic.LoadInt32(&svc.extractAttempts) if attempts1 == 0 { t.Fatal("expected at least one extraction attempt") } // A second request is served from the in-process negative cache: no new // ffmpeg attempt. if _, ok := svc.ThumbnailForFile(ctx, "bad", "broken.mp4"); ok { t.Fatal("expected the cached failure to persist") } if attempts2 := atomic.LoadInt32(&svc.extractAttempts); attempts2 != attempts1 { t.Errorf("negative cache should prevent re-extraction; attempts %d -> %d", attempts1, attempts2) } // The cache is in-process only: a fresh service (≈ a restart) retries. fresh := NewLibraryService(dir) if _, ok := fresh.ThumbnailForFile(ctx, "bad", "broken.mp4"); ok { t.Fatal("fresh service still fails (file is unextractable)") } if atomic.LoadInt32(&fresh.extractAttempts) == 0 { t.Error("a fresh service should retry extraction, not inherit the negative cache") } } func TestThumbnailAudioOnlyHasNone(t *testing.T) { requireFFmpeg(t) svc, dir := newLibrary(t) itemDir := writeItem(t, dir, "aud", "name = \"A\"\nduration = -1\n", nil) // A real audio file with no cover art. cmd := exec.Command("ffmpeg", "-hide_banner", "-loglevel", "error", "-f", "lavfi", "-i", "sine=frequency=440:duration=1", filepath.Join(itemDir, "aud.mp3"), "-y") if out, err := cmd.CombinedOutput(); err != nil { t.Fatalf("make audio: %v\n%s", err, out) } if path, ok := svc.ThumbnailForFile(context.Background(), "aud", "aud.mp3"); ok { t.Errorf("audio-only item should have no thumbnail, got %q", path) } }