-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtagwrite_internal_test.go
More file actions
979 lines (921 loc) · 36.3 KB
/
Copy pathtagwrite_internal_test.go
File metadata and controls
979 lines (921 loc) · 36.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
package waxbin
import (
"context"
"database/sql"
"os"
"path/filepath"
"runtime"
"testing"
"time"
"github.com/colespringer/waxbin/config"
"github.com/colespringer/waxbin/internal/testaudio"
"github.com/colespringer/waxbin/meta"
"github.com/colespringer/waxbin/model"
"github.com/colespringer/waxbin/organize"
"github.com/colespringer/waxbin/query"
waxlabel "github.com/colespringer/waxlabel"
"github.com/colespringer/waxlabel/tag"
)
// TestBookTagEditsClearDescriptionClearsTheLongForm: the reader folds DESCRIPTION and
// LONGDESCRIPTION into one description, so a clear has to empty both or the long form
// reads back as the old value. A set writes the short key alone and leaves the long
// form, which may hold a fuller text, in place.
func TestBookTagEditsClearDescriptionClearsTheLongForm(t *testing.T) {
cleared := map[string]bool{}
for _, e := range bookTagEditsForFields(map[string]string{"description": ""}, "") {
if len(e.Values) != 0 {
t.Errorf("clear wrote %s=%v, want an empty edit", e.Key, e.Values)
}
cleared[e.Key] = true
}
if !cleared["DESCRIPTION"] || !cleared["LONGDESCRIPTION"] || len(cleared) != 2 {
t.Errorf("a description clear touched %v, want DESCRIPTION and LONGDESCRIPTION", cleared)
}
set := bookTagEditsForFields(map[string]string{"description": "Short."}, "")
if len(set) != 1 || set[0].Key != "DESCRIPTION" || len(set[0].Values) != 1 || set[0].Values[0] != "Short." {
t.Errorf("a description set produced %+v, want DESCRIPTION alone", set)
}
}
func TestReplayGainEdits(t *testing.T) {
// A standalone track (no album) writes track keys and CLEARS the album keys, so
// stale album gain from a former album membership is removed on disk.
e := replayGainEdits(model.ReplayGainRow{Codec: "mp3", TrackGainDB: -6.35, TrackPeak: 0.988})
if !hasEdit(e, "REPLAYGAIN_TRACK_GAIN", "-6.35 dB") || !hasEdit(e, "REPLAYGAIN_TRACK_PEAK", "0.988000") {
t.Errorf("track-only edits wrong: %+v", e)
}
if !isClear(e, "REPLAYGAIN_ALBUM_GAIN") || !isClear(e, "REPLAYGAIN_ALBUM_PEAK") {
t.Errorf("track-only edits must clear album keys: %+v", e)
}
if hasKey(e, "R128_TRACK_GAIN") {
t.Errorf("non-opus track must not contain R128 keys: %+v", e)
}
// An album member gets track + album keys.
e = replayGainEdits(model.ReplayGainRow{Codec: "flac", TrackGainDB: -6.0, HasAlbum: true, AlbumGainDB: -5.5, AlbumPeak: 0.99})
if !hasKey(e, "REPLAYGAIN_ALBUM_GAIN") || !hasKey(e, "REPLAYGAIN_ALBUM_PEAK") {
t.Errorf("album member missing album keys: %+v", e)
}
// Opus uses R128 integer gains, not the REPLAYGAIN_* strings.
e = replayGainEdits(model.ReplayGainRow{Codec: "opus", TrackGainDB: -5.0, HasAlbum: true, AlbumGainDB: -4.0})
if !hasKey(e, "R128_TRACK_GAIN") || !hasKey(e, "R128_ALBUM_GAIN") {
t.Errorf("opus missing R128 keys: %+v", e)
}
if hasKey(e, "REPLAYGAIN_TRACK_GAIN") {
t.Errorf("opus should not use REPLAYGAIN_* keys: %+v", e)
}
}
func TestR128Gain(t *testing.T) {
// WaxBin gain references -18 LUFS; R128 references -23, so 5 dB is subtracted,
// then Q7.8: (-5 - 5) * 256 = -2560.
if got := r128Gain(-5.0); got != "-2560" {
t.Errorf("r128Gain(-5.0) = %q, want -2560", got)
}
// 5 dB gain -> (5-5)*256 = 0.
if got := r128Gain(5.0); got != "0" {
t.Errorf("r128Gain(5.0) = %q, want 0", got)
}
}
// TestReplayGainWriteBackAlbum scans two tracks of one album, records loudness,
// aggregates album gain, writes it back, and confirms each file carries both the
// track and album ReplayGain tags, and that the catalog's file row was updated so
// the scan fast-path recognizes WaxBin's own write.
func TestReplayGainWriteBackAlbum(t *testing.T) {
ctx := context.Background()
root := t.TempDir()
db := filepath.Join(t.TempDir(), "catalog.db")
lib, err := Open(ctx, Options{
DBPath: db, WriteReplayGainTags: true,
Roots: []config.Root{{Path: root, Mode: model.ModeManaged, Profile: "waxbin-native"}},
})
if err != nil {
t.Fatalf("open: %v", err)
}
defer lib.Close()
// Two distinct-essence tracks sharing one album.
writeRaw(t, filepath.Join(root, "a.mp3"), testaudio.BuildMP3WithAudio("A", "The Band", "One", 1, testaudio.AudioWithSeed(1)))
writeRaw(t, filepath.Join(root, "b.mp3"), testaudio.BuildMP3WithAudio("B", "The Band", "One", 2, testaudio.AudioWithSeed(2)))
if _, err := lib.Scan(ctx, ScanRequest{}); err != nil {
t.Fatalf("scan: %v", err)
}
// Record loudness for each track directly (no decoder needed in the test env).
items, err := lib.Query(ctx, query.New(query.EntityItems).Build(), "")
if err != nil || len(items) != 2 {
t.Fatalf("query items: %v (n=%d)", err, len(items))
}
for i, it := range items {
f, err := lib.store.FileByPID(ctx, it.FilePID)
if err != nil {
t.Fatalf("file by pid: %v", err)
}
if err := lib.store.PutAnalysis(ctx, model.AnalysisInput{
AnalysisVersion: 1,
Fingerprint: model.FingerprintInput{FilePID: it.FilePID, EssenceHash: f.EssenceHash, AlgoVersion: 1, FP: []byte{}},
Loudness: &model.LoudnessData{IntegratedLUFS: -12 - float64(i), TrackGainDB: -6 - float64(i), TrackPeak: 0.9},
}); err != nil {
t.Fatalf("put analysis: %v", err)
}
}
if err := lib.store.RefreshAlbumGain(ctx); err != nil {
t.Fatalf("album gain: %v", err)
}
c, err := lib.writeReplayGainTags(ctx)
if err != nil {
t.Fatalf("write rg tags: %v", err)
}
if c.written != 2 {
t.Fatalf("wrote %d rg tags, want 2", c.written)
}
if c.failed != 0 || c.unrepresented != 0 {
t.Fatalf("clean run reported failed=%d unrepresented=%d, want 0/0", c.failed, c.unrepresented)
}
// Each file now carries track + album ReplayGain, and its catalog row's content
// hash/mtime match the new bytes (so a rescan won't re-hash it).
for _, it := range items {
doc, err := waxlabel.ParseFile(ctx, string(it.Path))
if err != nil {
t.Fatalf("parse %s: %v", it.Path, err)
}
if v, ok := doc.Tags().First(tag.ReplayGainTrackGain); !ok || v == "" {
t.Errorf("%s missing REPLAYGAIN_TRACK_GAIN", it.Path)
}
if v, ok := doc.Tags().First(tag.ReplayGainAlbumGain); !ok || v == "" {
t.Errorf("%s missing REPLAYGAIN_ALBUM_GAIN", it.Path)
}
f, err := lib.store.FileByPID(ctx, it.FilePID)
if err != nil {
t.Fatalf("file after: %v", err)
}
info, err := os.Stat(string(it.Path))
if err != nil {
t.Fatal(err)
}
if f.Size != info.Size() || f.MTimeNS != info.ModTime().UnixNano() {
t.Errorf("catalog file state not updated after RG write: db(%d,%d) disk(%d,%d)",
f.Size, f.MTimeNS, info.Size(), info.ModTime().UnixNano())
}
}
}
// TestReplayGainWriteBackCountsFailures is the regression test for the defect this
// counter exists to fix: writeReplayGainTags used to log-and-continue on a write
// error, so a run against a read-only library reported success with nothing
// written, which is indistinguishable from a run with nothing to write.
func TestReplayGainWriteBackCountsFailures(t *testing.T) {
if os.Geteuid() == 0 {
t.Skip("root ignores the read-only bit, so the write would succeed")
}
ctx := context.Background()
root := t.TempDir()
db := filepath.Join(t.TempDir(), "catalog.db")
lib, err := Open(ctx, Options{
DBPath: db, WriteReplayGainTags: true,
Roots: []config.Root{{Path: root, Mode: model.ModeManaged, Profile: "waxbin-native"}},
})
if err != nil {
t.Fatalf("open: %v", err)
}
defer lib.Close()
writeRaw(t, filepath.Join(root, "a.mp3"), testaudio.BuildMP3WithAudio("A", "The Band", "One", 1, testaudio.AudioWithSeed(1)))
if _, err := lib.Scan(ctx, ScanRequest{}); err != nil {
t.Fatalf("scan: %v", err)
}
items, err := lib.Query(ctx, query.New(query.EntityItems).Build(), "")
if err != nil || len(items) != 1 {
t.Fatalf("query items: %v (n=%d)", err, len(items))
}
f, err := lib.store.FileByPID(ctx, items[0].FilePID)
if err != nil {
t.Fatalf("file by pid: %v", err)
}
if err := lib.store.PutAnalysis(ctx, model.AnalysisInput{
AnalysisVersion: 1,
Fingerprint: model.FingerprintInput{FilePID: items[0].FilePID, EssenceHash: f.EssenceHash, AlgoVersion: 1, FP: []byte{}},
Loudness: &model.LoudnessData{IntegratedLUFS: -12, TrackGainDB: -6, TrackPeak: 0.9},
}); err != nil {
t.Fatalf("put analysis: %v", err)
}
// The write is atomic (a rewrite into the directory), so removing the directory's
// write bit is what makes it fail. Windows ignores that bit on a directory, so
// there the blocker is an open handle on the target: WaxLabel documents that a
// handle the caller still holds on the path fails the replacing rename.
if err := os.Chmod(root, 0o555); err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _ = os.Chmod(root, 0o755) })
if runtime.GOOS == "windows" {
h, err := os.Open(string(items[0].Path))
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _ = h.Close() })
}
c, err := lib.writeReplayGainTags(ctx)
if err != nil {
t.Fatalf("write rg tags: %v", err)
}
if c.written != 0 {
t.Fatalf("wrote %d rg tags into a read-only library, want 0", c.written)
}
if c.failed != 1 {
t.Fatalf("failed = %d, want 1: a write-back that errored must not report as nothing-to-write", c.failed)
}
}
// TestReplayGainWriteBackUnwritableContainer: WaxFlow decoding WMA gave .wma files
// loudness rows, and ReplayGainWriteback has no format gate, so this pass reaches
// them. WaxLabel reads ASF but does not write it, so the gain can never land there.
// That is a value the file cannot hold, not a failure to chase, and counting it as a
// failure would report the same file as freshly broken on every run.
//
// The second half is the diagnostic sync. The write-back replaces its own rows
// wholesale, so a file that flips from unwritable to a plain failure must not keep
// the stale "cannot store" row.
func TestReplayGainWriteBackUnwritableContainer(t *testing.T) {
ctx := context.Background()
root := t.TempDir()
db := filepath.Join(t.TempDir(), "catalog.db")
lib, err := Open(ctx, Options{
DBPath: db, WriteReplayGainTags: true,
Roots: []config.Root{{Path: root, Mode: model.ModeManaged, Profile: "waxbin-native"}},
})
if err != nil {
t.Fatalf("open: %v", err)
}
defer lib.Close()
path := filepath.Join(root, "a.wma")
writeRaw(t, path, testaudio.Fixture(t, "mono-8k.wma"))
if _, err := lib.Scan(ctx, ScanRequest{}); err != nil {
t.Fatalf("scan: %v", err)
}
items, err := lib.Query(ctx, query.New(query.EntityItems).Build(), "")
if err != nil || len(items) != 1 {
t.Fatalf("query items: %v (n=%d)", err, len(items))
}
f, err := lib.store.FileByPID(ctx, items[0].FilePID)
if err != nil {
t.Fatalf("file by pid: %v", err)
}
// Parsed natively now: the ASF generation label folds to the catalog's "wma".
if f.Container != "asf" || f.Codec != "wma" {
t.Errorf("labels = %q/%q, want asf/wma", f.Container, f.Codec)
}
if err := lib.store.PutAnalysis(ctx, model.AnalysisInput{
AnalysisVersion: 1, MeasureCompleted: true,
Fingerprint: model.FingerprintInput{FilePID: f.PID, EssenceHash: f.EssenceHash, AlgoVersion: 1, FP: []byte{}},
Loudness: &model.LoudnessData{IntegratedLUFS: -12, TrackGainDB: -6, TrackPeak: 0.9},
}); err != nil {
t.Fatalf("put analysis: %v", err)
}
c, err := lib.writeReplayGainTags(ctx)
if err != nil {
t.Fatalf("write rg tags: %v", err)
}
if c.written != 0 || c.failed != 0 || c.unrepresented != 1 {
t.Fatalf("counts = {written:%d failed:%d unrepresented:%d}, want {0 0 1}: a container that cannot hold the gain is not a failure",
c.written, c.failed, c.unrepresented)
}
diags, err := lib.store.FileDiagnostics(ctx, model.DiagnosticFilter{
FilePID: f.PID, Origin: model.OriginReplayGain,
})
if err != nil {
t.Fatalf("diagnostics: %v", err)
}
if len(diags) != 1 || diags[0].Code != model.DiagTagWriteLost {
t.Fatalf("diagnostics = %+v, want one tag_write_lost", diags)
}
// The file goes away, so the same write is now a plain failure. A failure
// lands nothing and proves nothing, so the standing drift row stays: clearing
// it on a transient error would hide a true unrepresented mark from audit.
if err := os.Remove(path); err != nil {
t.Fatal(err)
}
c, err = lib.writeReplayGainTags(ctx)
if err != nil {
t.Fatalf("write rg tags after removal: %v", err)
}
if c.failed != 1 || c.unrepresented != 0 {
t.Fatalf("counts = {failed:%d unrepresented:%d}, want {1 0} for a vanished file", c.failed, c.unrepresented)
}
diags, err = lib.store.FileDiagnostics(ctx, model.DiagnosticFilter{
FilePID: f.PID, Origin: model.OriginReplayGain,
})
if err != nil {
t.Fatalf("diagnostics after removal: %v", err)
}
if len(diags) != 1 {
t.Errorf("diagnostics = %+v, want the drift row kept: a failed run must not erase what is still true", diags)
}
}
// TestOrganizeTagWriteAndPIDStamp organizes a compilation track with tag-write and
// PID stamping enabled, then confirms the moved file carries the corrected
// albumArtist ("Various Artists"), the item PID tag, organize provenance, and a
// locked field left untouched.
func TestOrganizeTagWriteAndPIDStamp(t *testing.T) {
ctx := context.Background()
root := t.TempDir()
db := filepath.Join(t.TempDir(), "catalog.db")
lib, err := Open(ctx, Options{
DBPath: db,
StampItemPID: true,
// Override the native profile to enable tag write-back.
Profiles: []config.ProfileDef{{Name: "waxbin-native", TagWrite: true}},
Roots: []config.Root{{Path: root, Mode: model.ModeManaged, Profile: "waxbin-native"}},
})
if err != nil {
t.Fatalf("open: %v", err)
}
defer lib.Close()
// A compilation track whose file tags a specific album artist; organize should
// correct it to the literal "Various Artists" on disk.
spec := testaudio.MP3Spec{Title: "Hit", Artist: "Solo", Album: "Comp", AlbumArtist: "Solo", Track: 4, Compilation: true, Audio: testaudio.AudioWithSeed(7)}
writeRaw(t, filepath.Join(root, "in.mp3"), testaudio.BuildMP3FromSpec(spec))
if _, err := lib.Scan(ctx, ScanRequest{}); err != nil {
t.Fatalf("scan: %v", err)
}
items, err := lib.Query(ctx, query.New(query.EntityItems).Build(), "")
if err != nil || len(items) != 1 {
t.Fatalf("query: %v (n=%d)", err, len(items))
}
itemPID := items[0].PID
// Lock the composer field with a curated value to prove locks are respected. (We
// lock a field organize would not otherwise write, then also lock album_artist to
// prove the write skips it.)
if err := lib.store.LockField(ctx, itemPID, "album_artist"); err != nil {
t.Fatalf("lock: %v", err)
}
plan, err := lib.PlanOrganize(ctx, query.New(query.EntityItems).Build(), "waxbin-native")
if err != nil {
t.Fatalf("plan: %v", err)
}
if !plan.TagWrite || !plan.StampPID {
t.Fatalf("plan flags: TagWrite=%v StampPID=%v, want both true", plan.TagWrite, plan.StampPID)
}
if _, err := lib.ApplyOrganize(ctx, plan); err != nil {
t.Fatalf("apply organize: %v", err)
}
// Find the moved file and read its tags.
items, _ = lib.Query(ctx, query.New(query.EntityItems).Build(), "")
moved := string(items[0].Path)
doc, err := waxlabel.ParseFile(ctx, moved)
if err != nil {
t.Fatalf("parse moved: %v", err)
}
// album_artist was LOCKED, so organize must NOT have rewritten it to "Various
// Artists"; it keeps the original tagged value.
if v, _ := doc.Tags().First(tag.AlbumArtist); v == "Various Artists" {
t.Errorf("locked album_artist was overwritten to %q", v)
}
// track number written.
if v, ok := doc.Tags().First(tag.TrackNumber); !ok || v == "" {
t.Errorf("track number not written")
}
// PID stamped.
if v, _ := doc.Tags().First(tag.Key(organize.WaxbinItemPIDKey)); v != string(itemPID) {
t.Errorf("WAXBIN_ITEM_PID = %q, want %q", v, itemPID)
}
}
// TestRebuildAdoptsStampedPID stamps an item PID during organize, then rebuilds a
// fresh catalog over the same files and confirms the item's PID is restored from the
// WAXBIN_ITEM_PID tag.
func TestRebuildAdoptsStampedPID(t *testing.T) {
ctx := context.Background()
root := t.TempDir()
lib1, err := Open(ctx, Options{
DBPath: filepath.Join(t.TempDir(), "c1.db"),
StampItemPID: true,
Roots: []config.Root{{Path: root, Mode: model.ModeManaged, Profile: "waxbin-native"}},
})
if err != nil {
t.Fatalf("open lib1: %v", err)
}
writeRaw(t, filepath.Join(root, "in.mp3"), testaudio.BuildMP3WithAudio("Song", "Artist", "Album", 1, testaudio.AudioWithSeed(3)))
if _, err := lib1.Scan(ctx, ScanRequest{}); err != nil {
t.Fatalf("scan1: %v", err)
}
plan, err := lib1.PlanOrganize(ctx, query.New(query.EntityItems).Build(), "waxbin-native")
if err != nil {
t.Fatalf("plan: %v", err)
}
if _, err := lib1.ApplyOrganize(ctx, plan); err != nil {
t.Fatalf("apply: %v", err)
}
items, _ := lib1.Query(ctx, query.New(query.EntityItems).Build(), "")
origPID := items[0].PID
lib1.Close()
// Rebuild into a fresh catalog over the same (now organized + stamped) files.
lib2, err := Open(ctx, Options{
DBPath: filepath.Join(t.TempDir(), "c2.db"),
Roots: []config.Root{{Path: root, Mode: model.ModeManaged, Profile: "waxbin-native"}},
})
if err != nil {
t.Fatalf("open lib2: %v", err)
}
defer lib2.Close()
if _, err := lib2.Scan(ctx, ScanRequest{AdoptStampedPIDs: true}); err != nil {
t.Fatalf("rebuild scan: %v", err)
}
items2, _ := lib2.Query(ctx, query.New(query.EntityItems).Build(), "")
if len(items2) != 1 {
t.Fatalf("rebuild items = %d, want 1", len(items2))
}
if items2[0].PID != origPID {
t.Errorf("rebuilt item PID = %s, want restored %s", items2[0].PID, origPID)
}
}
// TestPIDAdoptionConflictMintsFresh stamps the SAME PID on two distinct-essence
// files; a rebuild adopts it for exactly one and mints a fresh PID for the other (a
// copyable tag must never make two files claim one identity).
func TestPIDAdoptionConflictMintsFresh(t *testing.T) {
ctx := context.Background()
root := t.TempDir()
shared := model.NewPID()
w := meta.NewWriter()
for i, name := range []string{"one.mp3", "two.mp3"} {
p := filepath.Join(root, name)
writeRaw(t, p, testaudio.BuildMP3WithAudio(name, "Artist", "Album", 1, testaudio.AudioWithSeed(byte(i+1))))
if _, err := w.Apply(ctx, p, []meta.TagEdit{{Key: model.TagWaxbinItemPID, Values: []string{string(shared)}}}); err != nil {
t.Fatalf("stamp %s: %v", name, err)
}
}
lib, err := Open(ctx, Options{
DBPath: filepath.Join(t.TempDir(), "c.db"),
Roots: []config.Root{{Path: root, Mode: model.ModeManaged, Profile: "waxbin-native"}},
})
if err != nil {
t.Fatalf("open: %v", err)
}
defer lib.Close()
if _, err := lib.Scan(ctx, ScanRequest{AdoptStampedPIDs: true}); err != nil {
t.Fatalf("scan: %v", err)
}
items, _ := lib.Query(ctx, query.New(query.EntityItems).Build(), "")
if len(items) != 2 {
t.Fatalf("items = %d, want 2 distinct", len(items))
}
adopted := 0
for _, it := range items {
if it.PID == shared {
adopted++
}
if !it.PID.Valid() {
t.Errorf("item PID %q is not a valid ULID", it.PID)
}
}
if adopted != 1 {
t.Errorf("%d items adopted the shared PID, want exactly 1 (the other must mint fresh)", adopted)
}
}
func hasEdit(edits []meta.TagEdit, key, val string) bool {
for _, e := range edits {
if e.Key == key {
for _, v := range e.Values {
if v == val {
return true
}
}
}
}
return false
}
func hasKey(edits []meta.TagEdit, key string) bool {
for _, e := range edits {
if e.Key == key {
return true
}
}
return false
}
// isClear reports whether the edits contain key as a clear (present with no values).
func isClear(edits []meta.TagEdit, key string) bool {
for _, e := range edits {
if e.Key == key {
return len(e.Values) == 0
}
}
return false
}
func writeRaw(t *testing.T, path string, data []byte) {
t.Helper()
if err := os.WriteFile(path, data, 0o644); err != nil {
t.Fatal(err)
}
}
// TestReplayGainWriteBackLandsOnWavPack: WaxLabel 1.6 writes APEv2, so the gain a
// WavPack file could not hold before now lands on disk and reads back through the
// same library the scan uses, with no lost-write diagnostic left behind.
func TestReplayGainWriteBackLandsOnWavPack(t *testing.T) {
ctx := context.Background()
root := t.TempDir()
db := filepath.Join(t.TempDir(), "catalog.db")
lib, err := Open(ctx, Options{
DBPath: db, WriteReplayGainTags: true,
Roots: []config.Root{{Path: root, Mode: model.ModeManaged, Profile: "waxbin-native"}},
})
if err != nil {
t.Fatalf("open: %v", err)
}
defer lib.Close()
const rate = 8000
path := filepath.Join(root, "a.wv")
writeRaw(t, path, testaudio.EncodeAs(t, "wavpack", "", rate, testaudio.ReferenceSignal(rate, 2*time.Second)))
if _, err := lib.Scan(ctx, ScanRequest{}); err != nil {
t.Fatalf("scan: %v", err)
}
items, err := lib.Query(ctx, query.New(query.EntityItems).Build(), "")
if err != nil || len(items) != 1 {
t.Fatalf("query items: %v (n=%d)", err, len(items))
}
f, err := lib.store.FileByPID(ctx, items[0].FilePID)
if err != nil {
t.Fatalf("file by pid: %v", err)
}
if err := lib.store.PutAnalysis(ctx, model.AnalysisInput{
AnalysisVersion: 1, MeasureCompleted: true,
Fingerprint: model.FingerprintInput{FilePID: f.PID, EssenceHash: f.EssenceHash, AlgoVersion: 1, FP: []byte{}},
Loudness: &model.LoudnessData{IntegratedLUFS: -12, TrackGainDB: -6, TrackPeak: 0.9},
}); err != nil {
t.Fatalf("put analysis: %v", err)
}
c, err := lib.writeReplayGainTags(ctx)
if err != nil {
t.Fatalf("write rg tags: %v", err)
}
if c.written != 1 || c.failed != 0 || c.unrepresented != 0 {
t.Fatalf("counts = {written:%d failed:%d unrepresented:%d}, want {1 0 0}", c.written, c.failed, c.unrepresented)
}
doc, err := waxlabel.ParseFile(ctx, path)
if err != nil {
t.Fatalf("parse after write: %v", err)
}
if got, ok := doc.Get(tag.ReplayGainTrackGain); !ok || len(got) != 1 || got[0] != "-6.00 dB" {
t.Errorf("REPLAYGAIN_TRACK_GAIN on disk = %v, want [-6.00 dB]", got)
}
diags, err := lib.store.FileDiagnostics(ctx, model.DiagnosticFilter{FilePID: f.PID, Origin: model.OriginReplayGain})
if err != nil {
t.Fatalf("diagnostics: %v", err)
}
if len(diags) != 0 {
t.Errorf("diagnostics = %+v, want none for a write that landed whole", diags)
}
}
// enrichItemFields fills one item's fields as an enrichment pass would, so a write-back
// test can seed catalog-only values without a provider.
func enrichItemFields(t *testing.T, ctx context.Context, lib *Library, dbPath string, pid model.PID, fields map[string]string) {
t.Helper()
raw, err := sql.Open("sqlite", "file:"+dbPath+"?mode=ro")
if err != nil {
t.Fatalf("open raw db: %v", err)
}
defer raw.Close()
var id int64
if err := raw.QueryRowContext(ctx, "SELECT id FROM playable_item WHERE pid = ?", string(pid)).Scan(&id); err != nil {
t.Fatalf("item rowid: %v", err)
}
if err := lib.store.ApplyItemFields(ctx, model.ItemFieldsEnrichment{
ItemID: id, PID: pid, Matched: true, Provider: "test", Fields: fields,
}); err != nil {
t.Fatalf("ApplyItemFields: %v", err)
}
}
// TestEnrichmentWriteBackUnwritableContainer: a file WaxLabel refuses to write at all
// (it reads ASF and never writes it) cannot be retried into success, so it is counted
// and diagnosed as unrepresented rather than failed, and the next pass leaves it alone
// instead of reporting the same file as a fresh failure every run.
func TestEnrichmentWriteBackUnwritableContainer(t *testing.T) {
ctx := context.Background()
root := t.TempDir()
db := filepath.Join(t.TempDir(), "catalog.db")
lib, err := Open(ctx, Options{
DBPath: db, WriteEnrichmentTags: true,
Roots: []config.Root{{Path: root, Mode: model.ModeManaged, Profile: "waxbin-native"}},
})
if err != nil {
t.Fatalf("open: %v", err)
}
defer lib.Close()
writeRaw(t, filepath.Join(root, "a.wma"), testaudio.Fixture(t, "mono-8k.wma"))
if _, err := lib.Scan(ctx, ScanRequest{}); err != nil {
t.Fatalf("scan: %v", err)
}
items, err := lib.Query(ctx, query.New(query.EntityItems).Build(), "")
if err != nil || len(items) != 1 {
t.Fatalf("query items: %v (n=%d)", err, len(items))
}
enrichItemFields(t, ctx, lib, db, items[0].PID, map[string]string{"composer": "Someone"})
c, err := lib.writeEnrichmentTags(ctx, nil)
if err != nil {
t.Fatalf("write enrichment tags: %v", err)
}
if c.written != 0 || c.failed != 0 || c.unrepresented != 1 {
t.Fatalf("counts = {written:%d failed:%d unrepresented:%d}, want {0 0 1}: a container that cannot take the write is not a failure",
c.written, c.failed, c.unrepresented)
}
diags, err := lib.store.FileDiagnostics(ctx, model.DiagnosticFilter{FilePID: items[0].FilePID, Origin: model.OriginEnrichment})
if err != nil {
t.Fatalf("diagnostics: %v", err)
}
if len(diags) != 1 || diags[0].Code != model.DiagTagWriteLost {
t.Fatalf("diagnostics = %+v, want one tag_write_lost", diags)
}
// A lost value is settled, so the next pass does not reopen the file.
c, err = lib.writeEnrichmentTags(ctx, nil)
if err != nil {
t.Fatalf("write enrichment tags again: %v", err)
}
if c.written+c.failed+c.unrepresented != 0 {
t.Fatalf("counts on the next pass = {written:%d failed:%d unrepresented:%d}, want all zero", c.written, c.failed, c.unrepresented)
}
}
// TestEnrichmentWriteBackMarksAbandonedParts: when a book's primary part cannot be
// written, the parts skipped behind it stay owed and take the same drift row, so the
// next pass reopens the whole book rather than the primary alone. Written apart, the primary
// would carry an identifier the parts lack, and identity.BookKey would split the book
// on the next scan.
func TestEnrichmentWriteBackMarksAbandonedParts(t *testing.T) {
ctx := context.Background()
root := t.TempDir()
db := filepath.Join(t.TempDir(), "catalog.db")
lib, err := Open(ctx, Options{
DBPath: db, WriteEnrichmentTags: true,
Roots: []config.Root{{Path: root, Mode: model.ModeManaged, Profile: "waxbin-native"}},
})
if err != nil {
t.Fatalf("open: %v", err)
}
defer lib.Close()
bytesOf := map[string][]byte{}
for i, seed := range []byte{11, 12, 13} {
p := filepath.Join(root, "part"+string(rune('1'+i))+".m4b")
bytesOf[p] = testaudio.BuildMP3WithAudio("Chapter "+string(rune('1'+i)), "Tolkien", "The Hobbit", i+1, testaudio.AudioWithSeed(seed))
writeRaw(t, p, bytesOf[p])
}
if _, err := lib.Scan(ctx, ScanRequest{}); err != nil {
t.Fatalf("scan: %v", err)
}
books, err := lib.Query(ctx, query.New(query.EntityItems).Where("kind", query.OpIs, "book").Build(), "")
if err != nil || len(books) != 1 {
t.Fatalf("book query: %d books (err %v), want 1", len(books), err)
}
pid := books[0].PID
enrichItemFields(t, ctx, lib, db, pid, map[string]string{"asin": "B002V0QUOC"})
parts, err := lib.store.ItemFiles(ctx, pid)
if err != nil || len(parts) != 3 {
t.Fatalf("book parts: %d (err %v), want 3", len(parts), err)
}
var primary string
for _, p := range parts {
if p.Role == "primary" {
primary = p.DisplayPath
}
}
if primary == "" {
t.Fatal("no primary part")
}
// The primary vanishes, so its write fails and the parts behind it are skipped.
if err := os.Remove(primary); err != nil {
t.Fatal(err)
}
c, err := lib.writeEnrichmentTags(ctx, nil)
if err != nil {
t.Fatalf("write enrichment tags: %v", err)
}
if c.written != 0 || c.failed != 1 || c.skipped != 2 {
t.Fatalf("counts = {written:%d failed:%d skipped:%d}, want {0 1 2}", c.written, c.failed, c.skipped)
}
diags, err := lib.store.FileDiagnostics(ctx, model.DiagnosticFilter{ItemPID: pid, Origin: model.OriginEnrichment})
if err != nil {
t.Fatalf("diagnostics: %v", err)
}
if len(diags) != 3 {
t.Fatalf("diagnostics = %+v, want every part marked, the skipped ones included", diags)
}
for _, d := range diags {
if d.Code != model.DiagTagWriteUnsynced {
t.Errorf("%s: code %s, want tag_write_unsynced", d.DisplayPath, d.Code)
}
}
// The primary is back. Nothing was settled, so the next pass brings the whole book
// in, primary first.
writeRaw(t, primary, bytesOf[primary])
c, err = lib.writeEnrichmentTags(ctx, nil)
if err != nil {
t.Fatalf("write enrichment tags again: %v", err)
}
if c.written != 3 || c.failed != 0 || c.skipped != 0 {
t.Fatalf("counts on retry = {written:%d failed:%d skipped:%d}, want {3 0 0}", c.written, c.failed, c.skipped)
}
diags, err = lib.store.FileDiagnostics(ctx, model.DiagnosticFilter{ItemPID: pid, Origin: model.OriginEnrichment})
if err != nil {
t.Fatalf("diagnostics after retry: %v", err)
}
if len(diags) != 0 {
t.Errorf("diagnostics after retry = %+v, want none", diags)
}
for p := range bytesOf {
fm, err := meta.NewReader().Read(ctx, p)
if err != nil {
t.Fatalf("re-read %s: %v", p, err)
}
if fm.Tags.ASIN != "B002V0QUOC" {
t.Errorf("%s ASIN = %q, want the enriched identifier on every part", filepath.Base(p), fm.Tags.ASIN)
}
}
// The book stays whole through the scan that recomputes identity from the tags.
if _, err := lib.Scan(ctx, ScanRequest{Force: true}); err != nil {
t.Fatalf("scan --force: %v", err)
}
books, err = lib.Query(ctx, query.New(query.EntityItems).Where("kind", query.OpIs, "book").Build(), "")
if err != nil || len(books) != 1 || books[0].PID != pid {
t.Fatalf("after the rescan: %d books (err %v), want the one re-anchored book %s", len(books), err, pid)
}
}
// TestEnrichmentWriteBackSettlesAClearedValue: a value whose write failed stays owed,
// and if a retag and rescan clear it from the catalog before the retry, the next pass
// finds nothing to write. That settles the file and clears the drift row rather than
// leaving a stale mark that every later pass would scan past.
func TestEnrichmentWriteBackSettlesAClearedValue(t *testing.T) {
if os.Geteuid() == 0 {
t.Skip("root ignores the read-only bit, so the write would succeed")
}
ctx := context.Background()
root := t.TempDir()
db := filepath.Join(t.TempDir(), "catalog.db")
lib, err := Open(ctx, Options{
DBPath: db, WriteEnrichmentTags: true,
Roots: []config.Root{{Path: root, Mode: model.ModeManaged, Profile: "waxbin-native"}},
})
if err != nil {
t.Fatalf("open: %v", err)
}
defer lib.Close()
path := filepath.Join(root, "a.mp3")
audio := testaudio.AudioWithSeed(1)
writeRaw(t, path, testaudio.BuildMP3WithAudio("A", "The Band", "One", 1, audio))
if _, err := lib.Scan(ctx, ScanRequest{}); err != nil {
t.Fatalf("scan: %v", err)
}
items, err := lib.Query(ctx, query.New(query.EntityItems).Build(), "")
if err != nil || len(items) != 1 {
t.Fatalf("query items: %v (n=%d)", err, len(items))
}
enrichItemFields(t, ctx, lib, db, items[0].PID, map[string]string{"composer": "Someone"})
if err := os.Chmod(root, 0o555); err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _ = os.Chmod(root, 0o755) })
var handle *os.File
if runtime.GOOS == "windows" {
if handle, err = os.Open(path); err != nil {
t.Fatal(err)
}
}
c, err := lib.writeEnrichmentTags(ctx, nil)
if err != nil {
t.Fatalf("write enrichment tags: %v", err)
}
if c.failed != 1 {
t.Fatalf("failed = %d, want the read-only write counted", c.failed)
}
if handle != nil {
_ = handle.Close()
}
if err := os.Chmod(root, 0o755); err != nil {
t.Fatal(err)
}
// Retagged by another tool and rescanned: the composer column is rebuilt from a
// file that never carried it, and the enrichment provenance row outlives the value.
writeRaw(t, path, testaudio.BuildMP3WithAudio("A (remaster)", "The Band", "One", 1, audio))
if _, err := lib.Scan(ctx, ScanRequest{}); err != nil {
t.Fatalf("rescan: %v", err)
}
c, err = lib.writeEnrichmentTags(ctx, nil)
if err != nil {
t.Fatalf("write enrichment tags after the rescan: %v", err)
}
if c.written+c.failed+c.unrepresented != 0 {
t.Fatalf("counts = {written:%d failed:%d unrepresented:%d}, want all zero with nothing left to write",
c.written, c.failed, c.unrepresented)
}
diags, err := lib.store.FileDiagnostics(ctx, model.DiagnosticFilter{FilePID: items[0].FilePID, Origin: model.OriginEnrichment})
if err != nil {
t.Fatalf("diagnostics: %v", err)
}
if len(diags) != 0 {
t.Errorf("diagnostics = %+v, want the drift cleared once nothing is owed", diags)
}
rows, err := lib.store.EnrichmentWriteback(ctx, nil)
if err != nil {
t.Fatalf("EnrichmentWriteback: %v", err)
}
if len(rows) != 0 {
t.Errorf("owed rows = %+v, want the file settled", rows)
}
}
// TestLostBookIdentityReadsOnlyTheIdentifierKeys: a landed write that dropped an
// identifier is still a failure to the caller, since asin, isbn and edition feed
// identity.BookKey and a part written with one the primary lacks keys apart on the next
// scan. The classification is tested on its own because no container this suite can build
// refuses those keys, so there is no file that would drive the warning end to end.
func TestLostBookIdentityReadsOnlyTheIdentifierKeys(t *testing.T) {
lostASIN := []model.TagWriteWarning{{Key: "ASIN", Unrepresented: true, Message: "dropped"}}
if !lostBookIdentity(model.KindBook, lostASIN) {
t.Errorf("a book that lost its ASIN read as a clean write")
}
for _, key := range []string{"ISBN", "EDITION"} {
if !lostBookIdentity(model.KindBook, []model.TagWriteWarning{{Key: key, Unrepresented: true}}) {
t.Errorf("a book that lost its %s read as a clean write", key)
}
}
// A track has no book key to split, and the label pass borrows this same path.
if lostBookIdentity(model.KindTrack, lostASIN) {
t.Errorf("a track was read as having lost a book identifier")
}
// A key outside the three leaves the book keying the way its siblings do, and a
// keyless loss names content the rewrite destroyed rather than a value it was given.
if lostBookIdentity(model.KindBook, []model.TagWriteWarning{{Key: "GENRE", Unrepresented: true}}) {
t.Errorf("a lost genre abandoned the book's remaining parts")
}
if lostBookIdentity(model.KindBook, []model.TagWriteWarning{{Key: "", Unrepresented: true, Message: "a second LIST/INFO chunk was dropped"}}) {
t.Errorf("a keyless rewrite loss abandoned the book's remaining parts")
}
// An advisory warning on an identifier key is not a loss.
if lostBookIdentity(model.KindBook, []model.TagWriteWarning{{Key: "ASIN"}}) {
t.Errorf("an advisory warning on ASIN read as a loss")
}
}
// TestEnrichmentWriteBackRefusesASharedFile: a file whose edge carries an offset window,
// or that several items back, survives the item select's virtual-track gate. Its tags
// belong to the whole file, so the write-back refuses it the way the album-label pass and
// the edit write-back do rather than rewriting it for one item: the settle stamp is per
// file while the newest value is per item, so a rewrite would settle the file past the
// other item's value and lose it.
func TestEnrichmentWriteBackRefusesASharedFile(t *testing.T) {
ctx := context.Background()
root := t.TempDir()
db := filepath.Join(t.TempDir(), "catalog.db")
lib, err := Open(ctx, Options{
DBPath: db, WriteEnrichmentTags: true,
Roots: []config.Root{{Path: root, Mode: model.ModeManaged, Profile: "waxbin-native"}},
})
if err != nil {
t.Fatalf("open: %v", err)
}
defer lib.Close()
path := filepath.Join(root, "a.mp3")
writeRaw(t, path, testaudio.BuildMP3("Dogs", "Pink Floyd", "Animals", 1))
if _, err := lib.Scan(ctx, ScanRequest{}); err != nil {
t.Fatalf("scan: %v", err)
}
items, err := lib.Query(ctx, query.New(query.EntityItems).Build(), "")
if err != nil || len(items) != 1 {
t.Fatalf("items = %d (err %v), want 1", len(items), err)
}
pid := items[0].PID
enrichItemFields(t, ctx, lib, db, pid, map[string]string{"composer": "Roger Waters"})
// The edge takes an offset window, which is what makes the file unsafe to write per
// item while leaving it in the select the item walk reads.
raw, err := sql.Open("sqlite", "file:"+db+"?_pragma=busy_timeout(10000)")
if err != nil {
t.Fatalf("open raw db: %v", err)
}
defer raw.Close()
res, err := raw.ExecContext(ctx, `UPDATE item_file SET end_frames = 75
WHERE item_id = (SELECT id FROM playable_item WHERE pid = ?)`, string(pid))
if err != nil {
t.Fatalf("mark shared: %v", err)
}
if n, _ := res.RowsAffected(); n != 1 {
t.Fatalf("marked %d edges, want 1", n)
}
before, err := os.ReadFile(path)
if err != nil {
t.Fatal(err)
}
c, err := lib.writeEnrichmentTags(ctx, nil)
if err != nil {
t.Fatalf("write enrichment tags: %v", err)
}
if c.written != 0 || c.failed != 0 || c.unrepresented != 1 {
t.Fatalf("counts = {written:%d failed:%d unrepresented:%d}, want the file refused once",
c.written, c.failed, c.unrepresented)
}
after, err := os.ReadFile(path)
if err != nil {
t.Fatal(err)
}
if string(before) != string(after) {
t.Errorf("the shared file was rewritten")
}
diags, err := lib.store.FileDiagnostics(ctx, model.DiagnosticFilter{ItemPID: pid, Origin: model.OriginEnrichment})
if err != nil {
t.Fatalf("diagnostics: %v", err)
}
if len(diags) != 1 || diags[0].Code != model.DiagTagWriteUnsynced {
t.Fatalf("diagnostics = %+v, want the one drift row naming the refusal", diags)
}
// Settled by the refusal, so the next pass does not walk it again.
c, err = lib.writeEnrichmentTags(ctx, nil)
if err != nil {
t.Fatalf("write enrichment tags again: %v", err)
}
if c.written != 0 || c.unrepresented != 0 {
t.Errorf("counts on the next pass = %+v, want the refusal settled rather than repeated", c)
}
}