-
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathwaxtap_test.go
More file actions
1637 lines (1530 loc) · 59.4 KB
/
Copy pathwaxtap_test.go
File metadata and controls
1637 lines (1530 loc) · 59.4 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
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package waxtap
import (
"bytes"
"context"
"encoding/json"
"errors"
"io"
"math"
"os"
"path/filepath"
"slices"
"strings"
"testing"
"time"
"github.com/colespringer/waxtap/v3/download"
"github.com/colespringer/waxtap/v3/format"
"github.com/colespringer/waxtap/v3/internal/cutrange"
"github.com/colespringer/waxtap/v3/internal/media"
"github.com/colespringer/waxtap/v3/internal/mediatest"
"github.com/colespringer/waxtap/v3/internal/pipeline"
"github.com/colespringer/waxtap/v3/sponsorblock"
"github.com/colespringer/waxtap/v3/waxerr"
"github.com/colespringer/waxtap/v3/youtube"
)
func TestTranscodeCodecMapping(t *testing.T) {
cases := []struct {
f TranscodeFormat
want media.Codec
}{
{FormatCopy, media.CodecCopy},
{FormatFLAC, media.CodecFLAC},
{FormatALAC, media.CodecALAC},
{FormatWAV, media.CodecWAV},
{FormatMP3, media.CodecMP3},
{FormatAAC, media.CodecAAC},
{FormatOpus, media.CodecOpus},
{FormatVorbis, media.CodecVorbis},
}
for _, c := range cases {
if got := transcodeCodec(c.f); got != c.want {
t.Errorf("transcodeCodec(%v) = %v, want %v", c.f, got, c.want)
}
}
}
func TestTranscodeTargetMapping(t *testing.T) {
cases := []struct {
name string
spec *TranscodeSpec
want format.Target
}{
{"nil", nil, format.Target{}},
{"copy", &TranscodeSpec{Format: FormatCopy}, format.Target{}},
{"flac-lossless", &TranscodeSpec{Format: FormatFLAC}, format.Target{Lossless: true}},
{"wav-lossless", &TranscodeSpec{Format: FormatWAV}, format.Target{Lossless: true}},
{"aac-family", &TranscodeSpec{Format: FormatAAC}, format.Target{Codec: "aac"}},
{"opus-family", &TranscodeSpec{Format: FormatOpus}, format.Target{Codec: "opus"}},
{"vorbis-family", &TranscodeSpec{Format: FormatVorbis}, format.Target{Codec: "vorbis"}},
{"mp3-no-native", &TranscodeSpec{Format: FormatMP3}, format.Target{}},
}
for _, c := range cases {
t.Run(c.name, func(t *testing.T) {
if got := transcodeTarget(c.spec); got != c.want {
t.Errorf("transcodeTarget = %+v, want %+v", got, c.want)
}
})
}
}
func TestCutModeMapping(t *testing.T) {
if cutMode(CutSmart).String() != "smart" {
t.Error("CutSmart should map to smart")
}
if cutMode(CutCopy).String() != "copy" {
t.Error("CutCopy should map to copy")
}
if cutMode(CutAccurate).String() != "accurate" {
t.Error("CutAccurate should map to accurate")
}
}
func TestCutRangesMapping(t *testing.T) {
if cutRanges(nil) != nil {
t.Error("nil ranges should map to nil")
}
rs := cutRanges([]TimeRange{{Start: time.Second, End: 2 * time.Second}})
if len(rs) != 1 || rs[0].Start != time.Second || rs[0].End != 2*time.Second {
t.Errorf("cutRanges = %+v", rs)
}
}
func TestNeedsProcessing(t *testing.T) {
cases := []struct {
name string
spec ProcessSpec
want bool
}{
{"empty", ProcessSpec{}, false},
{"explicit-copy-remux", ProcessSpec{Transcode: &TranscodeSpec{Format: FormatCopy}}, true},
{"transcode", ProcessSpec{Transcode: &TranscodeSpec{Format: FormatMP3}}, true},
{"cut-ranges", ProcessSpec{Cut: &CutSpec{Ranges: []TimeRange{{0, time.Second}}}}, true},
{"cut-empty-no-sb", ProcessSpec{Cut: &CutSpec{}}, false},
{"cut-sb-empty-slice", ProcessSpec{Cut: &CutSpec{SponsorBlock: []sponsorblock.Category{}}}, true},
{"loudness", ProcessSpec{Loudness: &LoudnessSpec{Mode: LoudnessMeasureOnly}}, true},
}
for _, c := range cases {
t.Run(c.name, func(t *testing.T) {
if got := needsProcessing(c.spec); got != c.want {
t.Errorf("needsProcessing = %v, want %v", got, c.want)
}
})
}
}
func TestPipelineSpecRemux(t *testing.T) {
if ps := pipelineSpec(ProcessSpec{Transcode: &TranscodeSpec{Format: FormatCopy}}, nil); !ps.Remux {
t.Error("explicit FormatCopy should set pipeline Remux")
}
if ps := pipelineSpec(ProcessSpec{Transcode: &TranscodeSpec{Format: FormatMP3}}, nil); ps.Remux {
t.Error("a re-encode should not set Remux")
}
if ps := pipelineSpec(ProcessSpec{}, nil); ps.Remux {
t.Error("nil Transcode should not set Remux")
}
}
func TestSourceExtAndOutputExt(t *testing.T) {
if got := sourceExt(Format{Extension: "m4a"}); got != ".m4a" {
t.Errorf("sourceExt = %q, want .m4a", got)
}
if got := sourceExt(Format{}); got != ".webm" {
t.Errorf("sourceExt fallback = %q, want .webm", got)
}
if got := outputExt(&TranscodeSpec{Format: FormatMP3}, ".webm"); got != ".mp3" {
t.Errorf("outputExt transcode = %q, want .mp3", got)
}
if got := outputExt(&TranscodeSpec{Format: FormatCopy}, ".webm"); got != ".webm" {
t.Errorf("outputExt copy = %q, want .webm (source)", got)
}
if got := outputExt(nil, ".m4a"); got != ".m4a" {
t.Errorf("outputExt nil = %q, want .m4a (source)", got)
}
}
func TestToSourceRangeStrategy(t *testing.T) {
gv := toSource(youtube.ResolvedStream{URL: "https://rr3---sn-abc.googlevideo.com/videoplayback?x=1"})
if _, ok := gv.RangeStrategy.(download.QueryRange); !ok {
t.Errorf("googlevideo host should use QueryRange, got %T", gv.RangeStrategy)
}
other := toSource(youtube.ResolvedStream{URL: "https://cdn.example.com/a.webm"})
if other.RangeStrategy != nil {
t.Errorf("non-googlevideo host should use default (nil) strategy, got %T", other.RangeStrategy)
}
}
func TestSelectIndex(t *testing.T) {
formats := []Format{
{Itag: 140, MIMEType: `audio/mp4; codecs="mp4a.40.2"`, Codec: "mp4a.40.2", AverageBitrate: 128000, IsOriginal: format.Yes},
{Itag: 251, MIMEType: `audio/webm; codecs="opus"`, Codec: "opus", AverageBitrate: 160000, IsOriginal: format.Yes},
}
// Best audio prefers the higher effective bitrate (opus 251).
idx, err := selectIndex(BestAudio(), MinimizeLoss(), format.Target{}, formats)
if err != nil {
t.Fatalf("selectIndex: %v", err)
}
if formats[idx].Itag != 251 {
t.Errorf("best audio itag = %d, want 251", formats[idx].Itag)
}
// Itag override.
idx, err = selectIndex(Itag(140), MinimizeLoss(), format.Target{}, formats)
if err != nil || formats[idx].Itag != 140 {
t.Errorf("itag(140) = %d (err %v), want 140", formats[idx].Itag, err)
}
// Empty list -> ErrNoAudioFormats.
if _, err := selectIndex(BestAudio(), MinimizeLoss(), format.Target{}, nil); !errors.Is(err, waxerr.ErrNoAudioFormats) {
t.Errorf("empty list err = %v, want ErrNoAudioFormats", err)
}
// An explicit itag miss names the available itags.
_, err = selectIndex(Itag(99), MinimizeLoss(), format.Target{}, formats)
if !errors.Is(err, waxerr.ErrRequestedFormatUnavailable) {
t.Errorf("itag miss err = %v, want ErrRequestedFormatUnavailable", err)
}
if errors.Is(err, waxerr.ErrNoAudioFormats) {
t.Errorf("itag miss err = %v, must not be ErrNoAudioFormats (formats exist)", err)
}
if rfe, ok := errors.AsType[*waxerr.RequestedFormatError](err); !ok {
t.Errorf("itag miss err = %v, want *RequestedFormatError", err)
} else if len(rfe.Itags) != 2 || len(rfe.Codecs) != 0 {
t.Errorf("RequestedFormatError = %+v, want the two available itags named (no codecs for an itag miss)", rfe)
}
// An explicit codec miss names the available codecs, not itags.
_, err = selectIndex(Codec("flac"), MinimizeLoss(), format.Target{}, formats)
rfe, ok := errors.AsType[*waxerr.RequestedFormatError](err)
if !ok {
t.Fatalf("codec miss err = %v, want *RequestedFormatError", err)
}
if len(rfe.Codecs) == 0 || len(rfe.Itags) != 0 {
t.Errorf("RequestedFormatError = %+v, want available codecs named (no itags for a codec miss)", rfe)
}
if msg := rfe.Error(); !strings.Contains(msg, "available codecs") {
t.Errorf("codec miss message = %q, want it to list available codecs", msg)
}
// A best-audio miss on a non-empty but ineligible list stays ErrNoAudioFormats.
videoOnly := []Format{{Itag: 137, MIMEType: `video/mp4; codecs="avc1.640028"`, Codec: "avc1.640028"}}
if _, err := selectIndex(BestAudio(), MinimizeLoss(), format.Target{}, videoOnly); !errors.Is(err, waxerr.ErrNoAudioFormats) {
t.Errorf("best-audio miss err = %v, want ErrNoAudioFormats", err)
}
}
func TestSponsorBlockContributed(t *testing.T) {
const total = 60 * time.Second
r := func(s, e int) cutrange.Range {
return cutrange.Range{Start: time.Duration(s) * time.Second, End: time.Duration(e) * time.Second}
}
cut1 := pipeline.Result{Cut: true, SourceDuration: total}
cases := []struct {
name string
explicit []cutrange.Range
sb []cutrange.Range
pres pipeline.Result
want bool
}{
{"sb-only-removes", nil, []cutrange.Range{r(0, 5)}, cut1, true},
{"sb-adds-to-explicit", []cutrange.Range{r(0, 5)}, []cutrange.Range{r(50, 55)}, cut1, true},
{"sb-covered-by-explicit", []cutrange.Range{r(0, 10)}, []cutrange.Range{r(2, 6)}, cut1, false},
{"sb-clamps-away", nil, []cutrange.Range{r(100, 200)}, cut1, false},
{"no-sb", []cutrange.Range{r(0, 5)}, nil, cut1, false},
{"no-effective-cut", nil, []cutrange.Range{r(0, 5)}, pipeline.Result{Cut: false, SourceDuration: total}, false},
{"unknown-duration", nil, []cutrange.Range{r(0, 5)}, pipeline.Result{Cut: true, SourceDuration: 0}, false},
}
for _, c := range cases {
t.Run(c.name, func(t *testing.T) {
if got := sponsorBlockContributed(c.explicit, c.sb, c.pres); got != c.want {
t.Errorf("sponsorBlockContributed = %v, want %v", got, c.want)
}
})
}
}
func TestEmitterAccumulatesAndDelivers(t *testing.T) {
var got []Event
em := newEmitter(func(e Event) { got = append(got, e) }, "vid123")
em.stage(StageExtracting)
em.progress(50, 100)
em.warn(WarnSponsorBlockEmpty, "none")
res := &Result{}
em.finish(res, nil)
if len(got) != 4 {
t.Fatalf("got %d events, want 4: %+v", len(got), got)
}
if got[0].Stage != StageExtracting || got[0].VideoID != "vid123" {
t.Errorf("event[0] = %+v", got[0])
}
if got[1].Stage != StageDownloading || got[1].Bytes != 50 || got[1].Total != 100 {
t.Errorf("event[1] = %+v", got[1])
}
if got[2].Stage != StageWarning || got[2].Warning == nil || got[2].Warning.Code != WarnSponsorBlockEmpty {
t.Errorf("event[2] = %+v", got[2])
}
if got[3].Stage != StageDone {
t.Errorf("terminal event = %+v, want StageDone", got[3])
}
if len(res.Warnings) != 1 || res.Warnings[0].Code != WarnSponsorBlockEmpty {
t.Errorf("res.Warnings = %+v", res.Warnings)
}
}
func TestEmitterFailedTerminal(t *testing.T) {
var got []Event
em := newEmitter(func(e Event) { got = append(got, e) }, "")
sentinel := errors.New("boom")
em.finish(nil, sentinel)
if len(got) != 1 || got[0].Stage != StageFailed || !errors.Is(got[0].Err, sentinel) {
t.Fatalf("failed terminal = %+v", got)
}
}
func TestEmitterRecoversPanic(t *testing.T) {
em := newEmitter(func(e Event) { panic("callback blew up") }, "")
// Must not panic.
em.stage(StageExtracting)
em.finish(&Result{}, nil)
}
func TestEmitterNilCallback(t *testing.T) {
em := newEmitter(nil, "")
em.stage(StageExtracting)
em.warn(WarnThrottled, "x")
res := &Result{}
em.finish(res, nil)
if len(res.Warnings) != 1 {
t.Errorf("warnings still accumulate with a nil callback: %+v", res.Warnings)
}
}
// errReadCloser yields data then a non-EOF error, to model a mid-stream failure.
type errReadCloser struct {
data []byte
err error
pos int
}
func (e *errReadCloser) Read(p []byte) (int, error) {
if e.pos < len(e.data) {
n := copy(p, e.data[e.pos:])
e.pos += n
return n, nil
}
return 0, e.err
}
func (e *errReadCloser) Close() error { return nil }
func TestDoneReaderEmitsDoneOnCleanRead(t *testing.T) {
var got []Event
em := newEmitter(func(e Event) { got = append(got, e) }, "v")
r := &doneReader{ReadCloser: &errReadCloser{data: []byte("abc"), err: io.EOF}, ctx: t.Context(), em: em}
if _, err := io.ReadAll(r); err != nil {
t.Fatalf("ReadAll: %v", err)
}
if err := r.Close(); err != nil {
t.Fatalf("Close: %v", err)
}
if len(got) != 1 || got[0].Stage != StageDone {
t.Fatalf("clean stream events = %+v, want one StageDone", got)
}
}
func TestDoneReaderEmitsFailedOnReadError(t *testing.T) {
var got []Event
em := newEmitter(func(e Event) { got = append(got, e) }, "v")
boom := errors.New("network stall")
r := &doneReader{ReadCloser: &errReadCloser{data: []byte("abc"), err: boom}, ctx: t.Context(), em: em}
// Drain; the reader surfaces the error instead of EOF.
_, _ = io.ReadAll(r)
_ = r.Close()
if len(got) != 1 || got[0].Stage != StageFailed || !errors.Is(got[0].Err, boom) {
t.Fatalf("failed stream events = %+v, want one StageFailed carrying the error", got)
}
}
func TestMapPipelineStage(t *testing.T) {
cases := map[pipeline.Stage]Stage{
pipeline.StageProbing: StageProbing,
pipeline.StageAnalyzing: StageAnalyzing,
pipeline.StageCutting: StageCutting,
pipeline.StageNormalizing: StageNormalizing,
pipeline.StageTranscoding: StageTranscoding,
pipeline.StageRemuxing: StageRemuxing,
}
for in, want := range cases {
if got := mapPipelineStage(in); got != want {
t.Errorf("mapPipelineStage(%v) = %v, want %v", in, got, want)
}
}
// The public label is part of the event contract; a copy remux reports it
// instead of "transcoding".
if got := StageRemuxing.String(); got != "remuxing" {
t.Errorf("StageRemuxing.String() = %q, want %q", got, "remuxing")
}
}
func newOfflineClient(t *testing.T) *Client {
t.Helper()
c, err := New(Options{})
if err != nil {
t.Fatalf("New: %v", err)
}
return c
}
// TestVideoMetadataForMapsChannelAndChapters checks the metadata mapping: with
// IncludeMetadata the result carries ChannelID and the (FullMetadata-populated)
// Chapters; without IncludeMetadata it is nil.
func TestVideoMetadataForMapsChannelAndChapters(t *testing.T) {
v := &youtube.Video{
Author: "A",
ChannelID: "UCabcdefghijklmnopqrstuv",
Chapters: []youtube.Chapter{{Title: "Intro", Start: 0, End: 30 * time.Second}},
}
if got := videoMetadataFor(Request{}, v); got != nil {
t.Errorf("videoMetadataFor without IncludeMetadata = %+v, want nil", got)
}
req := Request{ProcessSpec: ProcessSpec{IncludeMetadata: true}}
md := videoMetadataFor(req, v)
if md == nil {
t.Fatal("videoMetadataFor with IncludeMetadata = nil")
}
if md.ChannelID != "UCabcdefghijklmnopqrstuv" {
t.Errorf("ChannelID = %q", md.ChannelID)
}
if len(md.Chapters) != 1 || md.Chapters[0].Title != "Intro" {
t.Errorf("Chapters = %+v, want one Intro chapter", md.Chapters)
}
}
func TestDownloadRejectsPlaylistURL(t *testing.T) {
c := newOfflineClient(t)
_, err := c.Download(context.Background(), Request{
URL: "https://www.youtube.com/playlist?list=PLabcdefghij",
ProcessSpec: ProcessSpec{Output: ToFile("out.opus")},
})
if !errors.Is(err, waxerr.ErrIsPlaylist) {
t.Errorf("Download(playlist) err = %v, want ErrIsPlaylist", err)
}
}
func TestDownloadRequiresOutput(t *testing.T) {
c := newOfflineClient(t)
_, err := c.Download(context.Background(), Request{URL: "testVideo01"})
if err == nil {
t.Fatal("Download without Output should error")
}
}
func TestDownloadInvalidURL(t *testing.T) {
c := newOfflineClient(t)
_, err := c.Download(context.Background(), Request{URL: "!!!", ProcessSpec: ProcessSpec{Output: ToFile("o")}})
if err == nil {
t.Fatal("invalid URL should error")
}
}
func TestDownloadSkipIfExists(t *testing.T) {
c := newOfflineClient(t)
dir := t.TempDir()
out := filepath.Join(dir, "exists.opus")
if err := os.WriteFile(out, []byte("present"), 0o644); err != nil {
t.Fatal(err)
}
res, err := c.Download(context.Background(), Request{
URL: "testVideo01",
ProcessSpec: ProcessSpec{Output: ToFile(out), SkipIfExists: true},
})
if err != nil {
t.Fatalf("skip-if-exists Download: %v", err)
}
if res.OutputPath != out {
t.Errorf("skipped OutputPath = %q, want %q", res.OutputPath, out)
}
}
func TestProcessValidation(t *testing.T) {
c := newOfflineClient(t)
ctx := context.Background()
if _, err := c.Process(ctx, ProcessRequest{ProcessSpec: ProcessSpec{Output: ToFile("o")}}); err == nil {
t.Error("empty Input should error")
}
if _, err := c.Process(ctx, ProcessRequest{Input: "in.flac"}); err == nil {
t.Error("missing Output should error")
}
if _, err := c.Process(ctx, ProcessRequest{Input: "same.flac", ProcessSpec: ProcessSpec{Output: ToFile("same.flac")}}); !errors.Is(err, waxerr.ErrIncompatibleSpec) {
t.Errorf("output==input err = %v, want ErrIncompatibleSpec", err)
}
}
func TestProcessSkipIfExists(t *testing.T) {
c := newOfflineClient(t)
dir := t.TempDir()
in := filepath.Join(dir, "in.flac")
out := filepath.Join(dir, "out.mp3")
if err := os.WriteFile(in, []byte("x"), 0o644); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(out, []byte("present"), 0o644); err != nil {
t.Fatal(err)
}
res, err := c.Process(context.Background(), ProcessRequest{
Input: in,
ProcessSpec: ProcessSpec{Output: ToFile(out), SkipIfExists: true, Transcode: &TranscodeSpec{Format: FormatMP3}},
})
if err != nil {
t.Fatalf("Process skip: %v", err)
}
if res.SourceKind != SourceLocalFile || res.OutputPath != out {
t.Errorf("skipped result = %+v", res)
}
}
// synthCodec maps a fixture codec name to a media.Codec.
func synthCodec(name string) media.Codec {
switch name {
case "flac":
return media.CodecFLAC
case "aac":
return media.CodecAAC
case "opus":
return media.CodecOpus
case "vorbis":
return media.CodecVorbis
case "mp3":
return media.CodecMP3
case "alac":
return media.CodecALAC
case "aiff":
return media.CodecAIFF
default:
return media.CodecWAV
}
}
// TestProbeAudioReportsChannels: the channel count decides whether a --downmix
// has anything to fold, so a caller that only learns the codec has to assume the
// worst and re-encode.
func TestProbeAudioReportsChannels(t *testing.T) {
dir := t.TempDir()
c, err := New(Options{})
if err != nil {
t.Fatal(err)
}
for _, tc := range []struct {
name string
channels int
}{{"mono.flac", 1}, {"stereo.flac", 2}, {"surround.flac", 6}} {
path := filepath.Join(dir, tc.name)
src := filepath.Join(t.TempDir(), "src.wav")
if err := os.WriteFile(src, mediatest.SineWAV(1, tc.channels), 0o644); err != nil {
t.Fatal(err)
}
r := media.NewRunner(media.RunnerConfig{})
if _, err := r.Transcode(context.Background(), src, path, media.Spec{Codec: media.CodecFLAC}); err != nil {
t.Fatalf("synth %s: %v", tc.name, err)
}
got, err := c.ProbeAudio(context.Background(), path)
if err != nil {
t.Fatalf("ProbeAudio(%s): %v", tc.name, err)
}
if got.Codec != "flac" || got.Channels != tc.channels {
t.Errorf("ProbeAudio(%s) = %+v, want codec flac with %d channels", tc.name, got, tc.channels)
}
}
// A file with no audio stream is still reported as unsupported input.
empty := filepath.Join(dir, "empty.flac")
if err := os.WriteFile(empty, []byte("not flac"), 0o644); err != nil {
t.Fatal(err)
}
if _, err := c.ProbeAudio(context.Background(), empty); err == nil {
t.Error("ProbeAudio accepted a file with no audio stream")
}
}
// synthSine writes a steady stereo sine fixture in codec, via the in-process
// engine over a pure-Go WAV (no external tools).
func synthSine(t *testing.T, dir, name string, seconds int, codec string) string {
t.Helper()
out := filepath.Join(dir, name)
wav := mediatest.SineWAV(seconds, 2)
if codec == "wav" {
if err := os.WriteFile(out, wav, 0o644); err != nil {
t.Fatal(err)
}
return out
}
src := filepath.Join(t.TempDir(), "src.wav") // separate dir: never pollute the fixture dir
if err := os.WriteFile(src, wav, 0o644); err != nil {
t.Fatal(err)
}
r := media.NewRunner(media.RunnerConfig{})
if _, err := r.Transcode(context.Background(), src, out, media.Spec{Codec: synthCodec(codec)}); err != nil {
t.Fatalf("synth %s (%s): %v", name, codec, err)
}
return out
}
// TestIsMP4FileSniffsContainer covers the embed flatten reading the container the
// file holds rather than its extension. An ALAC encode is MP4 whatever it is
// named, and skipping the flatten there leaves the tags unwritten.
func TestIsMP4FileSniffsContainer(t *testing.T) {
c := newOfflineClient(t)
dir := t.TempDir()
ctx := context.Background()
// MP4 content under names an extension check would misread. A keep-source
// download is never container-checked (validateOutputContainer returns early
// with no Transcode spec), so `download URL -o out.flac --embed-metadata` does
// put AAC-in-MP4 bytes in a file named .flac. Deciding on the extension would
// skip the flatten and lose the tags.
for _, name := range []string{"mp4.alac", "mp4_noext", "mp4.m4a", "mp4.flac", "mp4.opus", "mp4.wav"} {
if got := c.isMP4File(ctx, synthSine(t, dir, name, 1, "alac")); !got {
t.Errorf("isMP4File(%q) = false, want true (ALAC always muxes into MP4)", name)
}
}
for _, name := range []string{"plain.flac", "plain.aiff", "plain.wav"} {
if got := c.isMP4File(ctx, synthSine(t, dir, name, 1, strings.TrimPrefix(filepath.Ext(name), "."))); got {
t.Errorf("isMP4File(%q) = true, want false", name)
}
}
// An unreadable file falls back to the extension. The embed pass only warns on
// error, so reporting false on a probe failure would cost the user their tags
// on a file whose name said MP4 all along.
if got := c.isMP4File(ctx, filepath.Join(dir, "missing.m4a")); !got {
t.Error("isMP4File(missing .m4a) = false; want the extension fallback")
}
if got := c.isMP4File(ctx, filepath.Join(dir, "missing.flac")); got {
t.Error("isMP4File(missing .flac) = true, want false")
}
// A truncated file will not probe but is still named MP4.
trunc := filepath.Join(dir, "trunc.m4a")
if err := os.WriteFile(trunc, []byte("not an mp4"), 0o644); err != nil {
t.Fatal(err)
}
if got := c.isMP4File(ctx, trunc); !got {
t.Error("isMP4File(unprobeable .m4a) = false; want the extension fallback")
}
}
func TestProcessLocalTranscode(t *testing.T) {
c := newOfflineClient(t)
dir := t.TempDir()
in := synthSine(t, dir, "in.flac", 2, "flac")
out := filepath.Join(dir, "out.mp3")
res, err := c.Process(context.Background(), ProcessRequest{
Input: in,
ProcessSpec: ProcessSpec{Output: ToFile(out), Transcode: &TranscodeSpec{Format: FormatMP3}},
})
if err != nil {
t.Fatalf("Process: %v", err)
}
if res.SourceKind != SourceLocalFile || res.InputPath != in {
t.Errorf("result source = %+v", res)
}
if !res.Transcoded || res.OutputFormat.Codec != "mp3" {
t.Errorf("Transcoded=%v OutputFormat=%+v, want mp3", res.Transcoded, res.OutputFormat)
}
if !fileExists(out) || res.OutputBytes <= 0 {
t.Errorf("output not written: exists=%v bytes=%d", fileExists(out), res.OutputBytes)
}
}
func TestProcessLocalCutTranscode(t *testing.T) {
c := newOfflineClient(t)
dir := t.TempDir()
in := synthSine(t, dir, "in.flac", 4, "flac")
out := filepath.Join(dir, "out.flac")
res, err := c.Process(context.Background(), ProcessRequest{
Input: in,
ProcessSpec: ProcessSpec{
Output: ToFile(out),
Cut: &CutSpec{Ranges: []TimeRange{{Start: time.Second, End: 2 * time.Second}}},
Transcode: &TranscodeSpec{Format: FormatFLAC},
},
})
if err != nil {
t.Fatalf("Process: %v", err)
}
if !res.CutApplied {
t.Error("CutApplied = false, want true")
}
runner := c.engine()
probe, err := runner.Probe(context.Background(), out)
if err != nil {
t.Fatalf("probe output: %v", err)
}
// 4s minus a 1s cut => ~3s.
if d := probe.Format.Duration; d < 2500*time.Millisecond || d > 3500*time.Millisecond {
t.Errorf("output duration = %v, want ~3s", d)
}
}
func TestEnumerateRejectsNegativeMaxItems(t *testing.T) {
c := newOfflineClient(t)
// The guard runs before any network work, so a negative cap fails fast and is
// classified as invalid config (exit 2 for the CLI), not a generic error.
_, err := c.Enumerate(context.Background(), "https://www.youtube.com/playlist?list=PLxxxxxxxxxxxx", EnumerateOptions{MaxItems: -1})
if !errors.Is(err, ErrInvalidConfig) {
t.Errorf("Enumerate with MaxItems < 0 = %v, want ErrInvalidConfig", err)
}
}
func TestWarnEmptyCut(t *testing.T) {
const dur = 200 * time.Second
warned := func(cs *CutSpec, pres pipeline.Result, sbHadSegments bool) bool {
var got bool
em := newEmitter(func(e Event) {
if e.Stage == StageWarning && e.Warning != nil && e.Warning.Code == WarnRangesEmpty {
got = true
}
}, "")
warnEmptyCut(em, cs, pres, sbHadSegments)
return got
}
sbOnly := &CutSpec{SponsorBlock: []sponsorblock.Category{}}
// SponsorBlock returned segments but they all fell outside the media: warn.
if !warned(sbOnly, pipeline.Result{SourceDuration: dur}, true) {
t.Error("SponsorBlock segments outside the media should emit WarnRangesEmpty")
}
// SponsorBlock returned no segments: WarnSponsorBlockEmpty already covered it,
// so do not emit a duplicate WarnRangesEmpty.
if warned(sbOnly, pipeline.Result{SourceDuration: dur}, false) {
t.Error("no SponsorBlock segments must not also emit WarnRangesEmpty")
}
// Do not warn after an effective cut, for explicit ranges, without a cut, with
// unknown duration, or for an empty CutSpec.
if warned(sbOnly, pipeline.Result{SourceDuration: dur, Cut: true}, true) {
t.Error("an effective cut must not warn")
}
if warned(&CutSpec{Ranges: []TimeRange{{Start: 0, End: time.Second}}}, pipeline.Result{SourceDuration: dur}, false) {
t.Error("explicit ranges are handled in the pipeline, not warned here")
}
if warned(&CutSpec{}, pipeline.Result{SourceDuration: dur}, false) {
t.Error("an empty CutSpec (no ranges, no SponsorBlock) is not a cut and must not warn")
}
if warned(nil, pipeline.Result{SourceDuration: dur}, false) {
t.Error("nil cut must not warn")
}
if warned(sbOnly, pipeline.Result{}, true) {
t.Error("unknown duration must not warn")
}
}
func TestValidateProcessSpec_Downmix(t *testing.T) {
// Downmix requires a fixed mono or stereo target.
for _, layout := range []ChannelLayout{LayoutSurround, LayoutAny} {
if err := validateProcessSpec(ProcessSpec{Downmix: true, Channels: layout}); !errors.Is(err, ErrIncompatibleSpec) {
t.Errorf("Downmix+%s = %v, want ErrIncompatibleSpec", layout, err)
}
}
for _, layout := range []ChannelLayout{LayoutMono, LayoutStereo} {
if err := validateProcessSpec(ProcessSpec{Downmix: true, Channels: layout}); err != nil {
t.Errorf("Downmix+%s = %v, want nil", layout, err)
}
}
// Without Downmix the layout is only a selection hint, never rejected.
if err := validateProcessSpec(ProcessSpec{Channels: LayoutSurround}); err != nil {
t.Errorf("no downmix = %v, want nil", err)
}
}
func TestValidateProcessSpec_CoverArt(t *testing.T) {
// A shape with nothing to shape: the picture is never fetched, so report it
// rather than ignoring the field.
if err := validateProcessSpec(ProcessSpec{CoverArt: CoverArtSquare}); !errors.Is(err, ErrIncompatibleSpec) {
t.Errorf("square without EmbedThumbnail = %v, want ErrIncompatibleSpec", err)
}
if err := validateProcessSpec(ProcessSpec{CoverArt: CoverArtSquare, EmbedThumbnail: true}); err != nil {
t.Errorf("square with EmbedThumbnail = %v, want nil", err)
}
if err := validateProcessSpec(ProcessSpec{CoverArt: 7, EmbedThumbnail: true}); !errors.Is(err, ErrIncompatibleSpec) {
t.Errorf("unknown cover art mode = %v, want ErrIncompatibleSpec", err)
}
// The zero value is today's behavior and never needs EmbedThumbnail.
if err := validateProcessSpec(ProcessSpec{}); err != nil {
t.Errorf("zero CoverArt = %v, want nil", err)
}
}
// TestValidateProcessSpec_CopyCutWithTranscode covers F4 at the facade, where it
// fails before any media transfer. The coherent combinations must keep working:
// FormatCopy is a container remux, not an encode, and a copy cut with no
// TranscodeSpec is the plain lossless case the mode exists for.
func TestValidateProcessSpec_CopyCutWithTranscode(t *testing.T) {
copyCut := func(t *TranscodeSpec) ProcessSpec {
return ProcessSpec{
Cut: &CutSpec{Ranges: []TimeRange{{Start: 0, End: time.Second}}, Mode: CutCopy},
Transcode: t,
Output: ToFile("out.flac"),
}
}
for _, f := range []TranscodeFormat{FormatFLAC, FormatMP3, FormatOpus, FormatWAV} {
if err := validateProcessSpec(copyCut(&TranscodeSpec{Format: f})); !errors.Is(err, ErrIncompatibleSpec) {
t.Errorf("CutCopy + format %d = %v, want ErrIncompatibleSpec", f, err)
}
}
// A copy cut with --downmix and a format is rejected too: the check sits ahead
// of the Downmix skip, and both halves re-encode.
withDownmix := copyCut(&TranscodeSpec{Format: FormatFLAC})
withDownmix.Downmix, withDownmix.Channels = true, LayoutStereo
if err := validateProcessSpec(withDownmix); !errors.Is(err, ErrIncompatibleSpec) {
t.Errorf("CutCopy + downmix + format = %v, want ErrIncompatibleSpec", err)
}
// FormatCopy is a remux, so the pairing is coherent.
if err := validateProcessSpec(copyCut(&TranscodeSpec{Format: FormatCopy})); err != nil {
t.Errorf("CutCopy + FormatCopy = %v, want nil (container remux)", err)
}
// No transcode target at all: the output extension carries the container.
if err := validateProcessSpec(copyCut(nil)); err != nil {
t.Errorf("CutCopy + no transcode = %v, want nil", err)
}
// Other cut modes are unaffected.
smart := copyCut(&TranscodeSpec{Format: FormatFLAC})
smart.Cut.Mode = CutSmart
if err := validateProcessSpec(smart); err != nil {
t.Errorf("CutSmart + format flac = %v, want nil", err)
}
}
func TestValidateProcessSpec_LoudnessAndBitrate(t *testing.T) {
apply := func(target float64) ProcessSpec {
return ProcessSpec{Loudness: &LoudnessSpec{Mode: LoudnessApply, Target: target}}
}
for _, target := range []float64{-4, -71, math.NaN(), math.Inf(1), math.Inf(-1)} {
if err := validateProcessSpec(apply(target)); !errors.Is(err, ErrIncompatibleSpec) {
t.Errorf("apply target %v = %v, want ErrIncompatibleSpec", target, err)
}
}
for _, target := range []float64{-5, -70, -14} {
if err := validateProcessSpec(apply(target)); err != nil {
t.Errorf("apply target %v = %v, want nil", target, err)
}
}
// Measure-only mode does not use the target.
if err := validateProcessSpec(ProcessSpec{Loudness: &LoudnessSpec{Mode: LoudnessMeasureOnly, Target: 999}}); err != nil {
t.Errorf("measure-only target = %v, want nil", err)
}
if err := validateProcessSpec(ProcessSpec{Transcode: &TranscodeSpec{Format: FormatMP3, Bitrate: -1}}); !errors.Is(err, ErrIncompatibleSpec) {
t.Errorf("negative bitrate = %v, want ErrIncompatibleSpec", err)
}
if err := validateProcessSpec(ProcessSpec{Transcode: &TranscodeSpec{Format: FormatMP3, Bitrate: 0}}); err != nil {
t.Errorf("zero bitrate = %v, want nil", err)
}
if err := validateProcessSpec(ProcessSpec{Transcode: &TranscodeSpec{Format: FormatMP3, Bitrate: maxBitrate + 1}}); !errors.Is(err, ErrIncompatibleSpec) {
t.Errorf("excessive lossy bitrate = %v, want ErrIncompatibleSpec", err)
}
if err := validateProcessSpec(ProcessSpec{Transcode: &TranscodeSpec{Format: FormatMP3, Bitrate: 320000}}); err != nil {
t.Errorf("realistic 320 kbps bitrate = %v, want nil", err)
}
// A kbps value or a 1-10 quality scale mistakenly passed as bps is implausibly
// low; reject it so the encoder does not silently fall back to a default rate.
for _, bps := range []int{1, 5, 128, 320} {
if err := validateProcessSpec(ProcessSpec{Transcode: &TranscodeSpec{Format: FormatMP3, Bitrate: bps}}); !errors.Is(err, ErrIncompatibleSpec) {
t.Errorf("implausibly low bitrate %d = %v, want ErrIncompatibleSpec", bps, err)
}
}
// The floor itself is a permitted (if tiny) intentional encode.
if err := validateProcessSpec(ProcessSpec{Transcode: &TranscodeSpec{Format: FormatMP3, Bitrate: minPlausibleBitrate}}); err != nil {
t.Errorf("bitrate at the plausibility floor = %v, want nil", err)
}
// bitrate is ignored for lossless targets, so neither bound applies.
if err := validateProcessSpec(ProcessSpec{Transcode: &TranscodeSpec{Format: FormatFLAC, Bitrate: maxBitrate + 1}}); err != nil {
t.Errorf("high bitrate on a lossless target = %v, want nil (ignored, not an error)", err)
}
if err := validateProcessSpec(ProcessSpec{Transcode: &TranscodeSpec{Format: FormatFLAC, Bitrate: 1}}); err != nil {
t.Errorf("low bitrate on a lossless target = %v, want nil (ignored, not an error)", err)
}
}
// TestTranscodeCodecParity is the waxtap-side half of the format-parity check
// (the CLI-side half is TestTranscodeFormatParity). transcodeCodec's default arm
// returns CodecCopy, so a TranscodeFormat added without a case here degrades
// silently into a remux instead of failing: the caller asks for an encode and
// gets the source bytes. The table is pinned to the engine's own format list, so
// a row registered upstream cannot pass unnoticed.
func TestTranscodeCodecParity(t *testing.T) {
byEngineName := map[string]TranscodeFormat{
"flac": FormatFLAC,
"alac": FormatALAC,
"wav": FormatWAV,
"aiff": FormatAIFF,
"mp3": FormatMP3,
"aac": FormatAAC,
"he-aac": FormatHEAAC,
"opus": FormatOpus,
"vorbis": FormatVorbis,
"wavpack": FormatWavPack,
"ape": FormatAPE,
}
for _, name := range media.OutputFormats() {
f, ok := byEngineName[name]
if !ok {
t.Errorf("the engine produces %q but no TranscodeFormat maps to it", name)
continue
}
c := transcodeCodec(f)
if c == media.CodecCopy {
t.Errorf("transcodeCodec(%q) degraded to CodecCopy; the caller would get a remux, not an encode", name)
continue
}
if c.String() != name {
t.Errorf("transcodeCodec(%q).String() = %q, want the engine's own name", name, c.String())
}
}
for name := range byEngineName {
if !slices.Contains(media.OutputFormats(), name) {
t.Errorf("the table maps %q, which the engine no longer produces", name)
}
}
// Copy is the one format that must map to CodecCopy.
if c := transcodeCodec(FormatCopy); c != media.CodecCopy {
t.Errorf("transcodeCodec(FormatCopy) = %v, want CodecCopy", c)
}
}
func TestValidateProcessSpec_BitDepth(t *testing.T) {
spec := func(depth int) ProcessSpec {
return ProcessSpec{Transcode: &TranscodeSpec{Format: FormatFLAC, BitDepth: depth}}
}
// 16 and 24 are the policy, not the codec limit: WAV/AIFF take 2..32 and ALAC
// 16/20/24/32, but neither 32-bit integer nor the odd depths serve the reason
// the knob exists.
for _, d := range []int{0, 16, 24} {
if err := validateProcessSpec(spec(d)); err != nil {
t.Errorf("bit depth %d = %v, want nil", d, err)
}
}
for _, d := range []int{-1, 8, 20, 32, 1000} {
err := validateProcessSpec(spec(d))
if !errors.Is(err, ErrIncompatibleSpec) {
t.Errorf("bit depth %d = %v, want ErrIncompatibleSpec", d, err)
}
if err != nil && !strings.Contains(err.Error(), "want 16 or 24") {
t.Errorf("bit depth %d message = %q, want it to name the accepted depths", d, err)
}
}
// A lossy target ignores the depth, but an out-of-range request is still a
// mistake worth reporting rather than silently dropping.
if err := validateProcessSpec(ProcessSpec{Transcode: &TranscodeSpec{Format: FormatMP3, BitDepth: 8}}); !errors.Is(err, ErrIncompatibleSpec) {
t.Errorf("bit depth 8 on a lossy target = %v, want ErrIncompatibleSpec", err)
}
}
func TestValidateProcessSpec_NegativeCrossfade(t *testing.T) {
if err := validateProcessSpec(ProcessSpec{Cut: &CutSpec{Crossfade: -1}}); !errors.Is(err, ErrIncompatibleSpec) {
t.Errorf("negative crossfade = %v, want ErrIncompatibleSpec (parity with the CLI)", err)
}
if err := validateProcessSpec(ProcessSpec{Cut: &CutSpec{Crossfade: 500 * time.Millisecond}}); err != nil {
t.Errorf("non-negative crossfade = %v, want nil", err)
}
}
func TestValidateProcessSpec_CheckOutputContainer(t *testing.T) {
spec := func(f TranscodeFormat, out string) ProcessSpec {
return ProcessSpec{Transcode: &TranscodeSpec{Format: f}, Output: ToFile(out)}
}
reject := []struct {
name string
f TranscodeFormat
out string
}{
{"mp3 in flac", FormatMP3, "out.flac"},
{"mp3 in wav", FormatMP3, "out.wav"},
{"flac in opus", FormatFLAC, "out.opus"},
{"opus in m4a", FormatOpus, "out.m4a"},
// .aiff is a real container now and is checked like any other. These three
// used to pass unchecked and write mismatched bytes.
{"flac in aiff", FormatFLAC, "out.aiff"},
{"wav in aiff", FormatWAV, "out.aiff"},
{"aiff in wav", FormatAIFF, "out.wav"},
// The aiff row has no alternate container, so Matroska cannot hold it.
{"aiff in mka", FormatAIFF, "out.mka"},
}
for _, c := range reject {
if err := validateProcessSpec(spec(c.f, c.out)); !errors.Is(err, ErrIncompatibleSpec) {
t.Errorf("%s: err = %v, want ErrIncompatibleSpec", c.name, err)
}
}
pass := []struct {
name string
f TranscodeFormat
out string
}{
{"mp3 in mp3", FormatMP3, "out.mp3"},
{"flac in flac", FormatFLAC, "out.flac"},
{"aac in m4a", FormatAAC, "out.m4a"},
{"aac in mp4", FormatAAC, "out.mp4"},
{"opus in webm", FormatOpus, "out.webm"},
{"opus in mka", FormatOpus, "out.mka"},
// WAV dual-name: canonical "wav" must satisfy the PCM-accepting branches.
{"wav in mka", FormatWAV, "out.mka"},
// Extension outside the table passes unchecked (the muxer validates).
{"wav in w64", FormatWAV, "out.w64"},
{"aiff in aiff", FormatAIFF, "out.aiff"},
{"aiff in aif", FormatAIFF, "out.aif"},
// Force-muxed: codec-named and extensionless outputs are unconstrained.
{"alac in .alac", FormatALAC, "out.alac"},
{"flac extensionless", FormatFLAC, "out"},
// Copy follows the source container, so it is never rejected here.
{"copy in flac", FormatCopy, "out.flac"},
}
for _, c := range pass {
if err := validateProcessSpec(spec(c.f, c.out)); err != nil {
t.Errorf("%s: err = %v, want nil", c.name, err)
}
}
// A writer sink is not container-checked (it stages with a derived extension).
if err := validateProcessSpec(ProcessSpec{Transcode: &TranscodeSpec{Format: FormatMP3}, Output: ToWriter(io.Discard)}); err != nil {
t.Errorf("writer sink: err = %v, want nil (no path to check)", err)
}
}
func TestValidateProcessSpec_CutWithoutExtension(t *testing.T) {
// Extensionless copy-cut to a file output needs a container or --format.
extensionless := ProcessSpec{