package waveform import ( "context" "errors" "os" "path/filepath" "sync" "sync/atomic" "testing" "time" "codeberg.org/squidd/sonda/internal/streaming" ) func mean(p []byte) float64 { var sum float64 for _, v := range p { sum += float64(v) } return sum / float64(len(p)) } func TestTheShapeOfARisingToneRisesInMp3AndFlac(t *testing.T) { for _, name := range []string{"ramp.mp3", "ramp.flac"} { f, err := os.Open(filepath.Join("testdata", name)) if err != nil { t.Fatal(err) } peaks, err := Decode(f, filepath.Ext(name)) _ = f.Close() if err != nil { t.Fatalf("%s: %v", name, err) } if len(peaks) != Count { t.Fatalf("%s: %d levels, want %d", name, len(peaks), Count) } third := Count / 3 first, middle, last := mean(peaks[:third]), mean(peaks[third:2*third]), mean(peaks[2*third:]) if !(first < middle && middle < last) { t.Errorf("%s: the thirds are %.0f, %.0f, %.0f: a tone that rises must make a shape that rises", name, first, middle, last) } if peaks[Count-1] < 230 || peaks[0] > 40 { t.Errorf("%s: starts at %d and ends at %d", name, peaks[0], peaks[Count-1]) } var top byte for _, v := range peaks { top = max(top, v) } if top != 255 { t.Errorf("%s: the loudest level is %d, want 255: a quiet track still fills the bar", name, top) } } } func TestASilentTrackIsFlatAndNothingDividesByZero(t *testing.T) { f, err := os.Open(filepath.Join("testdata", "silence.flac")) if err != nil { t.Fatal(err) } defer f.Close() peaks, err := Decode(f, ".flac") if err != nil || len(peaks) != Count { t.Fatalf("Decode = %d levels, %v", len(peaks), err) } for i, v := range peaks { if v != 0 { t.Fatalf("level %d is %d in a silent track", i, v) } } } func TestWhatCannotBeDecodedIsAnErrorAndNotAPanic(t *testing.T) { dir := t.TempDir() junk := filepath.Join(dir, "junk") if err := os.WriteFile(junk, []byte("this is not audio at all, not even a little bit"), 0o644); err != nil { t.Fatal(err) } for _, ext := range []string{".mp3", ".flac"} { f, _ := os.Open(junk) if _, err := Decode(f, ext); err == nil { t.Errorf("%s: no error for text", ext) } _ = f.Close() } f, _ := os.Open(junk) defer f.Close() if _, err := Decode(f, ".ogg"); !errors.Is(err, ErrUnsupported) { t.Errorf("an ogg file: %v, want ErrUnsupported", err) } } // memStore keeps the shapes in memory. type memStore struct { mu sync.Mutex recs map[int64]Record } func (m *memStore) Get(_ context.Context, id int64) (Record, bool, error) { m.mu.Lock() defer m.mu.Unlock() r, ok := m.recs[id] return r, ok, nil } func (m *memStore) Save(_ context.Context, id int64, r Record) error { m.mu.Lock() defer m.mu.Unlock() if m.recs == nil { m.recs = map[int64]Record{} } m.recs[id] = r return nil } // files serves real files of testdata under track ids, and says what the last open found. type files struct { byID map[int64]string as map[int64]string // the name a track reports, when it is not the name of its file modtime time.Time } func (f *files) Open(_ context.Context, id int64) (*streaming.Stream, error) { name, ok := f.byID[id] if !ok { return nil, streaming.ErrNotFound } file, err := os.Open(filepath.Join("testdata", name)) if err != nil { return nil, err } if reported, ok := f.as[id]; ok { name = reported } return &streaming.Stream{File: file, Name: name, ModTime: f.modtime}, nil } func newService(t *testing.T) (*Service, *memStore, *files, *atomic.Int32) { t.Helper() st := &memStore{} fs := &files{byID: map[int64]string{1: "ramp.mp3", 2: "ramp.flac", 3: "silence.flac"}, modtime: time.Unix(1_700_000_000, 0)} s := NewService(st, fs) var calls atomic.Int32 real := s.decode s.decode = func(f *os.File, ext string) ([]byte, error) { calls.Add(1) return real(f, ext) } return s, st, fs, &calls } func TestTheShapeIsWorkedOutOnceAndRememberedForTheFile(t *testing.T) { ctx := context.Background() s, st, fs, calls := newService(t) peaks, err := s.Peaks(ctx, 1) if err != nil || len(peaks) != Count { t.Fatalf("Peaks = %d levels, %v", len(peaks), err) } again, err := s.Peaks(ctx, 1) if err != nil || string(again) != string(peaks) || calls.Load() != 1 { t.Errorf("second ask: %v, decoded %d times, want once", err, calls.Load()) } if rec := st.recs[1]; rec.SizeBytes == 0 || rec.MTimeUnix != 1_700_000_000 || len(rec.Peaks) != Count { t.Errorf("record = %+v", rec) } // The file changes: its shape is worked out again. fs.modtime = fs.modtime.Add(time.Hour) if _, err := s.Peaks(ctx, 1); err != nil || calls.Load() != 2 { t.Errorf("after the file changed: %v, decoded %d times, want 2", err, calls.Load()) } // Another track is another job. if _, err := s.Peaks(ctx, 2); err != nil || calls.Load() != 3 { t.Errorf("another track: %v, decoded %d times", err, calls.Load()) } } func TestATrackThatIsNotThereOrCannotBeReadIsSaidOnceAndNotTriedAgain(t *testing.T) { ctx := context.Background() s, _, fs, calls := newService(t) if _, err := s.Peaks(ctx, 99); !errors.Is(err, streaming.ErrNotFound) { t.Errorf("a track that is not there: %v", err) } fs.byID[4], fs.as = "ramp.mp3", map[int64]string{4: "song.ogg"} if _, err := s.Peaks(ctx, 4); !errors.Is(err, ErrUnsupported) { t.Errorf("a format that is not read: %v, want ErrUnsupported", err) } if calls.Load() != 0 { t.Errorf("decoded %d times a format that has no decoder", calls.Load()) } // A file that is broken: the failure is kept for that file, so it is not decoded at every request. dir := t.TempDir() if err := os.WriteFile(filepath.Join(dir, "broken.mp3"), []byte("not an mp3"), 0o644); err != nil { t.Fatal(err) } broken := &brokenFiles{path: filepath.Join(dir, "broken.mp3"), modtime: fs.modtime} s2 := NewService(&memStore{}, broken) var n atomic.Int32 real := s2.decode s2.decode = func(f *os.File, ext string) ([]byte, error) { n.Add(1); return real(f, ext) } for i := 0; i < 3; i++ { if _, err := s2.Peaks(ctx, 1); !errors.Is(err, ErrUnsupported) { t.Fatalf("ask %d: %v, want ErrUnsupported", i, err) } } if n.Load() != 1 { t.Errorf("a broken file was decoded %d times, want once", n.Load()) } } type brokenFiles struct { path string modtime time.Time } func (b *brokenFiles) Open(context.Context, int64) (*streaming.Stream, error) { f, err := os.Open(b.path) if err != nil { return nil, err } return &streaming.Stream{File: f, Name: filepath.Base(b.path), ModTime: b.modtime}, nil } func TestWhileTheShapeIsBeingWorkedOutTheAnswerIsNotReadyAndTheWorkGoesOn(t *testing.T) { ctx := context.Background() s, _, _, _ := newService(t) s.wait = 30 * time.Millisecond release := make(chan struct{}) real := s.decode s.decode = func(f *os.File, ext string) ([]byte, error) { <-release return real(f, ext) } if _, err := s.Peaks(ctx, 1); !errors.Is(err, ErrNotReady) { t.Fatalf("while it works: %v, want ErrNotReady", err) } close(release) deadline := time.Now().Add(3 * time.Second) for { peaks, err := s.Peaks(ctx, 1) if err == nil { if len(peaks) != Count { t.Fatalf("%d levels", len(peaks)) } return } if !errors.Is(err, ErrNotReady) || time.Now().After(deadline) { t.Fatalf("it never came: %v", err) } time.Sleep(10 * time.Millisecond) } } func TestManyAsksForOneTrackAreOneJobAndTracksAreWorkedOutOneAtATime(t *testing.T) { ctx := context.Background() s, _, _, calls := newService(t) var running, most atomic.Int32 real := s.decode s.decode = func(f *os.File, ext string) ([]byte, error) { now := running.Add(1) for { m := most.Load() if now <= m || most.CompareAndSwap(m, now) { break } } time.Sleep(60 * time.Millisecond) defer running.Add(-1) return real(f, ext) } s.wait = 5 * time.Second var wg sync.WaitGroup for _, id := range []int64{1, 1, 1, 2, 3} { wg.Add(1) go func() { defer wg.Done() if _, err := s.Peaks(ctx, id); err != nil { t.Errorf("track %d: %v", id, err) } }() } wg.Wait() if calls.Load() != 3 { t.Errorf("decoded %d times for 3 tracks asked 5 times", calls.Load()) } if most.Load() != 1 { t.Errorf("%d tracks were decoded at the same time, want 1", most.Load()) } }