-
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmapping.go
More file actions
1276 lines (1200 loc) · 51.1 KB
/
Copy pathmapping.go
File metadata and controls
1276 lines (1200 loc) · 51.1 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 (
"context"
"errors"
"fmt"
"io"
"io/fs"
"math"
"net/url"
"os"
"path/filepath"
"slices"
"strings"
"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/media/loudness"
"github.com/colespringer/waxtap/v3/internal/pipeline"
"github.com/colespringer/waxtap/v3/internal/tempfile"
"github.com/colespringer/waxtap/v3/waxerr"
"github.com/colespringer/waxtap/v3/youtube"
)
// transcodeCodec maps a public TranscodeFormat to a media.Codec.
func transcodeCodec(f TranscodeFormat) media.Codec {
switch f {
case FormatFLAC:
return media.CodecFLAC
case FormatALAC:
return media.CodecALAC
case FormatWAV:
return media.CodecWAV
case FormatAIFF:
return media.CodecAIFF
case FormatMP3:
return media.CodecMP3
case FormatAAC:
return media.CodecAAC
case FormatOpus:
return media.CodecOpus
case FormatVorbis:
return media.CodecVorbis
case FormatHEAAC:
return media.CodecHEAAC
case FormatWavPack:
return media.CodecWavPack
case FormatAPE:
return media.CodecAPE
default:
return media.CodecCopy
}
}
// transcodeTarget maps a TranscodeSpec to a format.Target so source selection can
// minimize cross-codec loss. A nil or copy spec yields the zero Target (best
// audio). Lossless targets gain nothing from a matched source. Lossy targets name
// a source codec family only when YouTube has a native equivalent (AAC, Opus,
// Vorbis); MP3 has none, so it ranks on best audio.
func transcodeTarget(t *TranscodeSpec) format.Target {
if t == nil {
return format.Target{}
}
c := transcodeCodec(t.Format)
if c == media.CodecCopy {
return format.Target{}
}
if c.IsLossless() {
return format.Target{Lossless: true}
}
switch t.Format {
case FormatAAC, FormatHEAAC:
// HE-AAC shares the AAC family: YouTube's mp4a itags are the nearest
// native source for either target.
return format.Target{Codec: "aac"}
case FormatOpus:
return format.Target{Codec: "opus"}
case FormatVorbis:
return format.Target{Codec: "vorbis"}
default:
return format.Target{}
}
}
// cutRanges maps public TimeRanges to cutrange.Ranges.
func cutRanges(rs []TimeRange) []cutrange.Range {
if len(rs) == 0 {
return nil
}
out := make([]cutrange.Range, len(rs))
for i, r := range rs {
out[i] = cutrange.Range{Start: r.Start, End: r.End}
}
return out
}
// Inclusive bounds for an applied integrated-loudness target.
const (
loudnessTargetMin = -70.0
loudnessTargetMax = -5.0
)
// maxBitrate rejects likely unit mistakes while remaining above practical lossy
// audio bitrates.
const maxBitrate = 3_000_000 // bits/sec
// minPlausibleBitrate rejects a kbps value or a 1-10 quality scale mistakenly
// passed as bits/sec (e.g. 128 or 5 instead of 128000), all of which fall well
// below 1000. It still permits an intentional sub-8-kbps voice encode.
const minPlausibleBitrate = 1000 // bits/sec
// ValidateProcessSpec checks a ProcessSpec without acquiring or processing media.
// Invalid specs return an error that wraps [ErrIncompatibleSpec].
// [Client.Download], [Client.Stream], and [Client.Process] call it automatically;
// callers may use it to fail before starting batch work.
func ValidateProcessSpec(s ProcessSpec) error { return validateProcessSpec(s) }
// validateProcessSpec rejects unsupported ProcessSpec combinations before
// acquisition or audio processing begins.
func validateProcessSpec(s ProcessSpec) error {
if s.Downmix && s.Channels != LayoutMono && s.Channels != LayoutStereo {
return fmt.Errorf("%w: downmix requires Channels mono or stereo, got %s", waxerr.ErrIncompatibleSpec, s.Channels)
}
// ValidateCrossfade treats non-positive durations as disabled, so reject
// negative values before reaching it.
if s.Cut != nil && s.Cut.Crossfade < 0 {
return fmt.Errorf("%w: crossfade must be non-negative, got %v", waxerr.ErrIncompatibleSpec, s.Cut.Crossfade)
}
if err := validateOutputContainer(s); err != nil {
return err
}
if err := validateCutEncodeNeed(s); err != nil {
return err
}
if err := validateLoudness(s.Loudness); err != nil {
return err
}
if err := validateBitrate(s.Transcode); err != nil {
return err
}
if err := validateBitDepth(s.Transcode); err != nil {
return err
}
return validateCoverArt(s)
}
// validateCoverArt rejects an unknown CoverArt value, and a cover-art mode set
// without EmbedThumbnail. The second is a spec that asks to shape a picture that
// will never be fetched, so it is reported rather than silently ignored.
func validateCoverArt(s ProcessSpec) error {
switch s.CoverArt {
case CoverArtFrame, CoverArtSquare:
default:
return fmt.Errorf("%w: cover art mode %d is not supported (want CoverArtFrame or CoverArtSquare)",
waxerr.ErrIncompatibleSpec, s.CoverArt)
}
if s.CoverArt != CoverArtFrame && !s.EmbedThumbnail {
return fmt.Errorf("%w: CoverArt needs EmbedThumbnail; there is no cover picture to shape without it",
waxerr.ErrIncompatibleSpec)
}
return nil
}
// validateOutputContainer rejects a file transcode when the output extension
// names a container that cannot hold the target codec. Extensionless, codec-
// named, and copy outputs are unconstrained. Writer sinks are not checked here
// because they stage with a derived extension.
func validateOutputContainer(s ProcessSpec) error {
if s.Transcode == nil || s.Output.kind != outputFile {
return nil
}
return media.CheckOutputContainer(transcodeCodec(s.Transcode.Format), s.Output.path)
}
// validateCutEncodeNeed rejects copy-mode cuts that cannot be described by the
// output path alone. Accurate cuts and crossfades require encoding, so copy mode
// needs an explicit target format. A plain copy cut can keep the source samples,
// but a file output still needs a container extension.
//
// The copy-plus-transcode contradiction is checked first, because the rest of the
// function only looks at specs with no transcode target.
//
// Beyond that, downmix is skipped here because the pipeline needs the probed
// channel count. When the source has more channels than the target, the pipeline
// chooses an encode after probing and the cut is valid without --format. When no
// fold is needed, the pipeline still applies its copy-mode checks before writing.
func validateCutEncodeNeed(s ProcessSpec) error {
cut := cutRequested(s.Cut)
target := transcodeCodec(specFormat(s.Transcode))
// An explicit copy cut and a transcode target contradict each other: --format
// re-encodes, which is what copy mode forbids. Reject rather than silently
// dropping the copy request. FormatCopy is media.CodecCopy, so the coherent
// cut-plus-remux case is not caught. This sits ahead of the s.Downmix term, so
// --cut-mode copy --downmix --format flac fails here too, which is correct.
if cut && s.Cut.Mode == CutCopy && target != media.CodecCopy {
return fmt.Errorf("%w: --cut-mode copy cannot be combined with --format %s, which re-encodes; drop one",
waxerr.ErrIncompatibleSpec, target)
}
if !cut || s.Downmix || target != media.CodecCopy {
return nil
}
switch {
case s.Cut.Mode == CutAccurate:
return fmt.Errorf("%w: accurate cut re-encodes; pass --format <format> (e.g. flac)", waxerr.ErrIncompatibleSpec)
case s.Cut.Crossfade > 0:
return fmt.Errorf("%w: crossfade re-encodes; pass --format <format> (e.g. flac)", waxerr.ErrIncompatibleSpec)
case s.Output.kind == outputFile && copyCutNeedsExtension(s.Output.path):
return fmt.Errorf("%w: cutting without re-encoding keeps the source codec, which needs a container extension on the output that can hold it (e.g. .opus/.m4a/.webm/.ogg/.mka), or pass --format to re-encode", waxerr.ErrIncompatibleSpec)
}
return nil
}
// copyCutNeedsExtension reports whether a stream-copy cut to path lacks a usable
// container extension. It mirrors the pipeline's runtime guard (ext "" or "copy").
func copyCutNeedsExtension(path string) bool {
ext := strings.ToLower(strings.TrimPrefix(filepath.Ext(path), "."))
return ext == "" || ext == "copy"
}
// validateLoudness checks targets used for loudness application. Measure-only
// specs do not use a target.
func validateLoudness(l *LoudnessSpec) error {
if l == nil || l.Mode != LoudnessApply {
return nil
}
if math.IsNaN(l.Target) || math.IsInf(l.Target, 0) {
return fmt.Errorf("%w: loudness target must be a finite LUFS value, got %v", waxerr.ErrIncompatibleSpec, l.Target)
}
if l.Target < loudnessTargetMin || l.Target > loudnessTargetMax {
return fmt.Errorf("%w: loudness target %g LUFS is out of range [%g, %g]", waxerr.ErrIncompatibleSpec, l.Target, loudnessTargetMin, loudnessTargetMax)
}
return nil
}
// validateBitrate rejects a negative or implausibly high transcode bitrate. Zero
// selects the preset default.
func validateBitrate(t *TranscodeSpec) error {
if t == nil {
return nil
}
if t.Bitrate < 0 {
return fmt.Errorf("%w: transcode bitrate must be >= 0, got %d", waxerr.ErrIncompatibleSpec, t.Bitrate)
}
// The bounds apply only where bitrate is used. It is ignored for lossless
// and copy targets, so an out-of-range value there is harmless, not an error.
if t.Bitrate > 0 && t.Bitrate < minPlausibleBitrate && !transcodeCodec(t.Format).IsLossless() {
return fmt.Errorf("%w: transcode bitrate %d bps is implausibly low (min %d); bitrate is in bits per second, e.g. 128000 for 128 kbps", waxerr.ErrIncompatibleSpec, t.Bitrate, minPlausibleBitrate)
}
if t.Bitrate > maxBitrate && !transcodeCodec(t.Format).IsLossless() {
return fmt.Errorf("%w: transcode bitrate %d bps is implausibly high (max %d)", waxerr.ErrIncompatibleSpec, t.Bitrate, maxBitrate)
}
return nil
}
// validateBitDepth rejects a requested output depth outside {0, 16, 24}.
//
// The honoring formats individually allow more (WAV and AIFF take 2..32, FLAC
// 4..32, ALAC 16/20/24/32), so this is policy, not a codec limit: 16 and 24 are
// the depths worth naming, and neither 32-bit integer nor the odd depths serve
// the reason the knob exists, which is forcing integer output from a float
// decode. The error says "want 16 or 24" so a rejected 32 does not read as a bug.
func validateBitDepth(t *TranscodeSpec) error {
if t == nil {
return nil
}
switch t.BitDepth {
case 0, 16, 24:
return nil
default:
return fmt.Errorf("%w: transcode bit depth %d is not supported (want 16 or 24, or 0 to follow the source)",
waxerr.ErrIncompatibleSpec, t.BitDepth)
}
}
// downmixChannels returns the requested output channel count, or 0 when downmix
// is disabled. validateProcessSpec rejects layouts without a fixed count.
func downmixChannels(layout ChannelLayout, downmix bool) int {
if !downmix {
return 0
}
return layout.ChannelCount()
}
// cutMode maps a public CutMode to a media.Mode.
func cutMode(m CutMode) media.Mode {
switch m {
case CutCopy:
return media.ModeCopy
case CutAccurate:
return media.ModeAccurate
default:
return media.ModeSmart
}
}
// pipelineSpec builds the internal pipeline spec from a ProcessSpec and the
// resolved removal ranges (explicit ranges plus any from SponsorBlock).
func pipelineSpec(s ProcessSpec, ranges []cutrange.Range) pipeline.Spec {
ps := pipeline.Spec{Remove: ranges, Downmix: downmixChannels(s.Channels, s.Downmix)}
if s.Cut != nil {
ps.CutMode = cutMode(s.Cut.Mode)
ps.Crossfade = s.Cut.Crossfade
// Explicit ranges that do not intersect the media are rejected. Empty
// SponsorBlock results are allowed and reported as a warning.
ps.RejectEmptyRemoval = len(s.Cut.Ranges) > 0
}
if s.Transcode != nil {
ps.Codec = transcodeCodec(s.Transcode.Format)
ps.Bitrate = s.Transcode.Bitrate
ps.BitDepth = s.Transcode.BitDepth
// An explicit FormatCopy is a stream-copy remux (distinct from a nil
// Transcode, which keeps the source bytes untouched).
ps.Remux = s.Transcode.Format == FormatCopy
}
if s.Loudness != nil {
ps.Loudness = &pipeline.Loudness{
Apply: s.Loudness.Mode == LoudnessApply,
Target: s.Loudness.Target,
PeakLimit: s.Loudness.PeakMode == PeakLimit,
}
}
return ps
}
// sponsorBlockContributed reports whether SponsorBlock removed additional audio
// after clamping and merging. Segments that fall outside the media duration, or
// that are already covered by explicit ranges, do not count as applied work.
func sponsorBlockContributed(explicit, sbRanges []cutrange.Range, pres pipeline.Result) bool {
if !pres.Cut || len(sbRanges) == 0 || pres.SourceDuration <= 0 {
return false
}
total := pres.SourceDuration
combined := append(append([]cutrange.Range{}, explicit...), sbRanges...)
explicitKept := cutrange.OutputDuration(cutrange.Keeps(explicit, total), 0)
combinedKept := cutrange.OutputDuration(cutrange.Keeps(combined, total), 0)
return combinedKept < explicitKept
}
// cutRequested reports whether the spec asks for any cut (explicit ranges or a
// SponsorBlock fetch). A nil SponsorBlock slice disables the fetch.
func cutRequested(c *CutSpec) bool {
return c != nil && (len(c.Ranges) > 0 || c.SponsorBlock != nil)
}
// warnEmptyCut reports a SponsorBlock-only request whose segments fell outside the
// media so nothing was removed. sbHadSegments says whether SponsorBlock returned
// any segments: when it returned none, collectRanges already emitted
// WarnSponsorBlockEmpty, so this stays silent to avoid a duplicate warning.
// Explicit ranges that do not intersect the media are rejected by the pipeline.
func warnEmptyCut(em *emitter, cs *CutSpec, pres pipeline.Result, sbHadSegments bool) {
if cs != nil && cs.SponsorBlock != nil && sbHadSegments && len(cs.Ranges) == 0 && !pres.Cut && pres.SourceDuration > 0 {
em.warn(WarnRangesEmpty, "SponsorBlock segments fell outside the media; delivered uncut")
}
}
// loudnessMissWarnDB is the miss, in LU, that turns a loudness shortfall from a
// detail into something the user needs told. Below it the miss is within the noise
// of a lossy encode.
//
// It applies to the two single-pass policies (cap, and album mode in either
// peak mode), whose miss is a clamp computed up front rather than the residue of
// a search. Limit mode uses [loudness.ConvergeToleranceDB] instead; see
// warnLimiterTargetMissed for why the two thresholds differ.
const loudnessMissWarnDB = 1.0
// warnLoudnessTargetMissed reports that normalization did not reach the requested
// loudness. The two peak policies miss for different reasons, so each is detected
// where its cause actually lives.
//
// For PeakCap the cause is the true-peak clamp, and it is read from the clamp
// rather than from the achieved loudness on purpose: pipeline.Result.OutputLoudness
// is best-effort, so comparing against it would silently drop the warning whenever
// the post-measure fails, and a lossy encode can miss by more than a LU for
// reasons that have nothing to do with the ceiling, which would make the detail
// text a lie. Asking the loudness package what its clamp held back, on the
// InputLoudness that fed it (downmix fold included), is deterministic and correctly
// attributed.
//
// For PeakLimit there is no clamp to attribute anything to: the gain aims at the
// target and the limiter gives back an amount only a measurement can reveal. So
// that branch is derived from the measured output, and stays silent when there is
// no usable measurement.
func warnLoudnessTargetMissed(em *emitter, ls *LoudnessSpec, pres pipeline.Result) {
if ls == nil || ls.Mode != LoudnessApply {
return
}
if ls.PeakMode == PeakLimit {
warnLimiterTargetMissed(em, ls, pres)
return
}
if pres.InputLoudness == nil {
return
}
// PeakShortfall reports only what the true-peak clamp cost, so the detail below
// can name that cause. It returns 0 for a non-finite measurement, so silence
// (-Inf, which would otherwise be an infinite shortfall) stays quiet.
short := loudness.PeakShortfall(ls.Target, *pres.InputLoudness)
if short <= loudnessMissWarnDB {
return
}
detail := fmt.Sprintf("true-peak capping at %g dBTP held the gain %.1f dB short of the %g LUFS target",
loudness.TruePeakCeilingDB, short, ls.Target)
if out := pres.OutputLoudness; out != nil && out.Finite() {
detail += fmt.Sprintf("; delivered %.1f LUFS", out.IntegratedLUFS)
}
// The remedy stays worded as "closer" rather than "hits the target": limit
// iterates onto the target but is still bounded by the limiter's saturation, so
// promising the target is what produced this finding in the first place.
// cmd/waxtap/batch_render.go aggregates on the code and surfaces this detail,
// which is why the "--peak-mode limit" substring belongs in it.
em.warn(WarnLoudnessTargetMissed, detail+"; use --peak-mode limit to get closer to the target")
}
// warnLimiterTargetMissed reports a limit-mode normalization the true-peak limiter
// held away from the target, in either direction: an overshoot is as much a
// silently wrong delivery as a shortfall, and the gain search can produce one.
//
// Its threshold is [loudness.ConvergeToleranceDB], not loudnessMissWarnDB, and
// the difference is the whole point of the mode. Limit is documented as
// iterating onto the target, and the search stops the moment it is inside that
// tolerance, so anything outside it is the search having given up rather than a
// miss too small to matter: a stop at 0.74 LU is precisely the case the mode
// promises to have converged and did not. The single-pass policies keep the
// wider threshold because their miss is a clamp they can name up front.
func warnLimiterTargetMissed(em *emitter, ls *LoudnessSpec, pres pipeline.Result) {
out := pres.OutputLoudness
if out == nil || !out.Finite() {
return // no measurement, nothing honest to report
}
miss := ls.Target - out.IntegratedLUFS
if math.Abs(miss) <= loudness.ConvergeToleranceDB {
return
}
// Two wordings, because an overshoot is not something the limiter "held": a
// shortfall is the limiter giving gain back, an overshoot is the gain search
// stepping past the target.
//
// The count comes from the result rather than from maxLoudnessWrites, since
// tolerance or saturation can end the search early. At this threshold a single
// pass is reachable two ways - the corrected gain pinned at WaxFlow's clamp, so
// the next write would encode the same file, and a correction write that failed
// - so the plural is not safe and the noun agrees with the number.
tmpl := "the true-peak limiter held the output %.1f LU short of the %g LUFS target after %s; delivered %.1f LUFS"
if miss < 0 {
tmpl = "normalization landed %.1f LU above the %g LUFS target after %s; delivered %.1f LUFS"
}
em.warn(WarnLoudnessTargetMissed, fmt.Sprintf(tmpl,
math.Abs(miss), ls.Target, encodePasses(pres.LoudnessPasses), out.IntegratedLUFS))
}
// encodePasses renders a completed-pass count with a noun that agrees with it.
func encodePasses(n int) string {
if n == 1 {
return "1 encode pass"
}
return fmt.Sprintf("%d encode passes", n)
}
// warnOutputClipping surfaces the pipeline's level measurement: WaxFlow read
// the delivered encode past full scale, as clamped samples or as a true peak
// the stored samples only cross between themselves. The note is WaxFlow's
// wording; WaxTap adds the policy of when it is worth a warning and what to
// suggest.
//
// A lossy source never warns. Its decoder legitimately reconstructs past full
// scale on loud masters (a brickwalled release decodes with overs on most
// commercial music), so the clamp is inherent to any faithful integer
// conversion, and the post-clamp measurement carries no signal that could
// separate that from a defect: the meter taps the chain output after the
// quantizer, so the counts and peaks of an ordinary conversion look exactly
// like a real one. The defects this warning exists for (a float master stored
// past full scale, a normalization that attenuated but not enough) all read
// from lossless sources, where a clipped sample is never the decoder's doing.
func warnOutputClipping(em *emitter, ls *LoudnessSpec, pres pipeline.Result) {
note := pres.Levels.Note()
if note == "" || lossySource(pres.SourceCodec) {
return
}
em.warn(WarnOutputClipping, note+clipRemedy(ls, pres.Levels))
}
// minGateableDuration is the length of one EBU R128 momentary block. Integrated
// loudness is the gated mean of those blocks, so audio shorter than one block
// yields nothing to gate and has no integrated loudness to report: not a
// measurement that failed, but one that does not exist.
const minGateableDuration = 400 * time.Millisecond
// unmeasurableLoudnessCause explains a non-finite integrated loudness, or ""
// when l is nil or its integrated loudness is finite.
//
// d is the duration of the audio measured; d <= 0 means it is unknown, and the
// too-short cause is then not claimed rather than guessed at. empty says the
// track holds no frames, which the duration alone cannot distinguish from an
// unstated length. The order matters: a 200 ms silence is both too short and
// silent, and the length is the more useful thing to be told, because it is the
// one the user can change. Emptiness outranks both, being the only one of the
// three that is about the file rather than the signal in it.
func unmeasurableLoudnessCause(d time.Duration, empty bool, l *loudness.Loudness) string {
if l == nil || !nonFiniteFloat(l.IntegratedLUFS) {
return ""
}
switch {
case empty:
// Without this the zero duration skips the too-short branch and a
// -Inf sample peak wins, calling a file with no frames "digital
// silence" - which describes samples, of which there are none.
return "the track contains no audio frames"
case d > 0 && d < minGateableDuration:
// Truncated, not rounded: a 399.7 ms clip must not render as "400ms,
// shorter than the 400 ms block".
return fmt.Sprintf("the clip is %s, shorter than the 400 ms block EBU R128 gating needs", d.Truncate(time.Millisecond))
case math.IsInf(l.SamplePeakDB, -1):
return "the audio is digital silence"
default:
return "the signal stays below the R128 gates (under -70 LUFS, or the relative gate removed every block)"
}
}
// nonFiniteFloat reports whether v is NaN or infinite, the two shapes an
// unusable measurement arrives in.
func nonFiniteFloat(v float64) bool { return math.IsNaN(v) || math.IsInf(v, 0) }
// warnLoudnessUnmeasurable reports each measured side whose integrated loudness
// came back non-finite, so the nulls in --json and the "n/a" in the human
// output arrive explained rather than merely blank.
//
// Both sides are reported when both are unusable. They fail for the same reason
// here but not always (a cut can leave an output shorter than its input), and
// a reader checking that a normalization landed reads the output line.
func warnLoudnessUnmeasurable(em *emitter, pres pipeline.Result) {
if pres.LoudnessMeasured && pres.InputLoudness != nil {
// The meter's own read length decides the too-short case: it is what the
// gate actually saw, where the container's declared duration can overstate
// it (a cut, or a decode that ended early on a damaged file).
d := pres.InputLoudness.Duration
if d == 0 {
d = pres.SourceDuration - pres.Removed
}
if cause := unmeasurableLoudnessCause(d, pres.SourceEmpty, pres.InputLoudness); cause != "" {
em.warn(WarnLoudnessUnmeasurable, "input integrated loudness could not be measured: "+cause)
}
}
// Gated on the measurement, not on LoudnessApplied: an unmeasurable input
// leaves LoudnessApplied false (no gain could apply) on exactly the runs whose
// output is also unmeasurable, which is the pair this warning exists to
// explain. OutputLoudness is only ever set when normalization was requested.
if pres.OutputLoudness != nil {
d := pres.OutputLoudness.Duration
if d == 0 && pres.OutputProbe != nil {
d = pres.OutputProbe.Format.Duration
}
// An empty input yields an empty output, so the same fact explains both
// sides; nothing else here can observe the output's frame count.
if cause := unmeasurableLoudnessCause(d, pres.SourceEmpty, pres.OutputLoudness); cause != "" {
em.warn(WarnLoudnessUnmeasurable, "output integrated loudness could not be measured: "+cause)
}
}
}
// warnUnboundSourcePolicy reports a prefer:<codec> that named a codec family
// this video does not carry. Such a policy is inert rather than wrong, and an
// inert one is invisible: the delivery is byte-for-byte the run the user would
// have got with no policy at all, so nothing distinguishes "the preference was
// honored" from "the preference never applied".
//
// A preference that was present but outranked stays silent. Ranking a better
// source above a preferred codec is what the soft bias documents itself as
// doing, so warning there would fire on correct behavior.
func warnUnboundSourcePolicy(em *emitter, policy SourcePolicy, formats []Format, chosen Format) {
want := policy.Preferred()
if want == "" {
return
}
// The selector's own eligibility rule decides what counts as available, so
// a family carried only by a format selection would never pick cannot
// silence the warning.
available := format.AvailableFamilies(formats)
if slices.Contains(available, want) {
return
}
have := strings.Join(available, ", ")
if have == "" {
have = "none reported"
}
em.warn(WarnSourcePolicyUnmatched, fmt.Sprintf(
"--source-policy prefer:%s matched no available source (available codecs: %s); delivering %s",
want, have, codecOrUnknown(chosen.Codec)))
}
// codecOrUnknown names a delivered codec for a warning, standing in when the
// player response omitted it.
func codecOrUnknown(codec string) string {
if fam := format.CodecFamily(codec); fam != "" {
return fam
}
return "an unnamed codec"
}
// warnInputDamage reports a local input the decoder had to work around, so a
// short output is explained rather than merely delivered. The run succeeds:
// the audio that read is real audio, and the only alternative is refusing a
// file the user can still use.
//
// Only local processing calls this. A YouTube delivery cannot produce it (the
// containers on that path either probe exactly or fail outright), and firing it
// there would blame the user's input for a delivery of ours that came up short.
func warnInputDamage(em *emitter, pres pipeline.Result) {
if note := inputDamageNote(pres.SourceWarnings); note != "" {
em.warn(WarnInputDamage, note)
}
}
// warnEmptyInput reports a local input carrying no audio frames at all. The run
// succeeds: an empty input converts faithfully to an empty output, and failing
// would take a batch down over one file the user can see for themselves.
//
// It fires alongside the loudness warning rather than instead of it. That one
// explains why a number is null; this one says the file had nothing in it,
// which is the fact a caller with no loudness request would otherwise never be
// told.
//
// Only local processing calls this, for warnInputDamage's reason: a delivery of
// ours coming back empty is our failure to report as one, not the user's input
// to warn about.
func warnEmptyInput(em *emitter, pres pipeline.Result) {
if pres.SourceEmpty {
em.warn(WarnEmptyInput, "the input contains no audio frames; the output holds no audio")
}
}
// inputDamageNote renders the source's damage notes as one detail line, or ""
// when there are none. The notes stand on their own, in the decoder's (or the
// short-decode check's) exact words: a lead like "the source is damaged" read
// well on a truncated file and lied about the rest, since the decoder's
// tolerated-damage list also carries notes about files that play fine (an extra
// stream ignored, a trailing tag skipped, a rescaled timescale).
//
// The notes are copied because capNotes truncates in place and the probe's
// slice belongs to its caller.
func inputDamageNote(notes []string) string {
if len(notes) == 0 {
return ""
}
return strings.Join(capNotes(slices.Clone(notes)), "; ")
}
// lossySource reports whether the probed source codec name is a lossy family,
// whose decode manufactures the overshoot warnOutputClipping would otherwise
// report.
func lossySource(codec string) bool {
switch codec {
case "opus", "aac", "he-aac", "mp3", "vorbis", "wma", "musepack":
return true
}
return false
}
// losslessSource reports whether the probed source codec name is a lossless
// family. It is not lossySource's complement: an unknown codec is neither, so
// each warning that keys on the distinction fails closed rather than firing on
// a codec it cannot classify. TestSourceCodecClassParity pins both tables to
// media.Codec.IsLossless.
func losslessSource(codec string) bool {
switch codec {
case "flac", "alac", "wavpack", "ape", "wav", "aiff":
return true
}
return strings.HasPrefix(codec, "pcm")
}
// warnImplicitLossy reports a lossy re-encode of a lossless source that the
// request never named: the spec asked for a copy (or nothing at all), and
// automatic processing promoted it to the output container's default encoder
// because the source codec cannot enter that container. A cut of in.wv written
// to out.mka re-encodes to Opus this way, correctly, and used to say so only in
// the result's codec field. A request that names any encode took its cost
// knowingly, lossy targets included, and does not warn.
func warnImplicitLossy(em *emitter, spec ProcessSpec, pres pipeline.Result) {
if transcodeCodec(specFormat(spec.Transcode)) != media.CodecCopy {
return
}
if !pres.Transcoded || pres.OutputCodec.IsLossless() || !losslessSource(pres.SourceCodec) {
return
}
detail := fmt.Sprintf("the request named no encode, but %s audio cannot enter the output container, so it was re-encoded to %s (lossy)",
pres.SourceCodec, pres.OutputCodec)
if exts := media.ContainersFor(pres.SourceCodec); len(exts) > 0 {
detail += fmt.Sprintf("; keep the codec with a matching extension (%s) or pass a lossless --format", strings.Join(exts, "/"))
} else {
detail += "; pass a lossless --format to avoid the quality loss"
}
em.warn(WarnImplicitLossy, detail)
}
// clipRemedy picks the suffix for an output-clipping detail: the knob the run
// has not turned yet, or nothing when every knob it has is already turned.
func clipRemedy(ls *LoudnessSpec, l media.Levels) string {
if ls == nil || ls.Mode != LoudnessApply {
// The stored samples of a true-peak-only over are all in range, so the
// remedy names the true peak rather than telling the user their level is
// past full scale.
what := "the level"
if l.ClippedSamples == 0 {
what = "the true peak"
}
return "; normalize to bring " + what + " under full scale"
}
if ls.PeakMode == PeakLimit {
// Limit mode only runs the limiter on a boosting gain, so an attenuating
// pass on a hot source can still clip. Cap derives its clamp from the
// measured peak instead, which is the knob left to turn.
return clipRemedyCap
}
// Cap already held everything it could see; suggesting more would point at
// knobs already turned.
return ""
}
// clipRemedyCap is the remedy for a normalization that still clipped: shared
// with the album path, whose runs are always normalizing.
const clipRemedyCap = "; use --peak-mode cap to hold the true peak under the ceiling"
// warnImplicitDownmix reports a channel fold the request never asked for: a
// lossy encoder that cannot hold the source layout folds it to stereo, correctly,
// and a run that halves a 5.1 master used to exit 0 with an empty warnings array
// and nothing but a raw WaxFlow log line on stderr to say so.
//
// It reads WaxTap's own probes rather than parsing that log line: SourceChannels
// is what the pipeline measured on the input and OutputProbe is what it measured
// on the written file, both already authoritative for everything else the result
// reports. A Downmix request means the caller chose the fold and does not need
// telling.
func warnImplicitDownmix(em *emitter, spec ProcessSpec, pres pipeline.Result) {
if spec.Downmix || pres.SourceChannels <= 0 || pres.OutputProbe == nil {
return
}
out, ok := pres.OutputProbe.AudioStream()
if !ok || out.Channels <= 0 || out.Channels >= pres.SourceChannels {
return
}
em.warn(WarnImplicitDownmix, fmt.Sprintf(
"%s cannot hold %d channels, so the encode folded them to %d; pass --downmix to choose the fold, or a format that keeps the layout",
outputCodecLabel(pres.OutputCodec), pres.SourceChannels, out.Channels))
}
// outputCodecLabel names the encoder a fold is attributable to, falling back to
// neutral wording for a container copy that carries no codec of its own.
func outputCodecLabel(c media.Codec) string {
if c == media.CodecCopy {
return "the output format"
}
return c.String()
}
// warnAlbumTargetMissed reports an album normalization that did not reach the
// requested loudness. Album mode used to emit no warning at all: it never calls
// em.warn, and warnLimiterTargetMissed returns early without a measured output,
// which album mode did not produce. A 1.16 LU miss on a -14 target was therefore
// silent, past the same threshold that warns loudly on a single file.
//
// The split mirrors warnLoudnessTargetMissed, and for the same reasons: the cap
// branch attributes the miss to the clamp it can compute deterministically, the
// limit branch reads it off the delivered album because there is no clamp to
// attribute anything to. What differs is the remedy, since album mode is a single
// pass by design and has no gain search to have given up.
func warnAlbumTargetMissed(em *emitter, target float64, mode PeakMode, album loudness.Loudness, perTrack []loudness.Loudness, delivered *LoudnessInfo) {
deliveredLUFS := func() (float64, bool) {
if delivered == nil || math.IsInf(delivered.IntegratedLUFS, 0) || math.IsNaN(delivered.IntegratedLUFS) {
return 0, false
}
return delivered.IntegratedLUFS, true
}
if mode == PeakCap {
short := loudness.AlbumPeakShortfall(target, album, perTrack)
if short <= loudnessMissWarnDB {
return
}
detail := fmt.Sprintf("true-peak capping at %g dBTP held the album gain %.1f dB short of the %g LUFS target",
loudness.TruePeakCeilingDB, short, target)
if lufs, ok := deliveredLUFS(); ok {
detail += fmt.Sprintf("; delivered %.1f LUFS", lufs)
}
// The trade is stated because it is the whole reason both modes exist: limit
// gets closer, and gives up the exact spacing that cap was chosen for.
em.warn(WarnLoudnessTargetMissed, detail+"; the loudest track sets the album's headroom, so drop --peak-mode cap to get closer to the target at the cost of the exact track-to-track spacing")
return
}
lufs, ok := deliveredLUFS()
if !ok {
return // no measurement, nothing honest to report
}
miss := target - lufs
// Album mode keeps loudnessMissWarnDB where the single-file limit branch
// dropped to the converge tolerance, and so leaves a band where a miss
// neither converges further nor warns: a 0.7 LU album miss is silent. That
// is the same shape as the finding this warning exists to close, so it is
// written down rather than left for the next end-to-end pass to rediscover.
// It stands because album mode has no gain search: one uniform pass is the
// design, nothing here ever aimed at 0.3 LU, and a sub-LU miss is inside the
// noise of the encode. The single-file limit path warns tighter precisely
// because it does iterate and stopping short means it gave up.
if math.Abs(miss) <= loudnessMissWarnDB {
return
}
tmpl := "the true-peak limiter held the album %.1f LU short of the %g LUFS target; delivered %.1f LUFS"
if miss < 0 {
tmpl = "the normalized album landed %.1f LU above the %g LUFS target; delivered %.1f LUFS"
}
// No "encode passes" count and no offer to iterate: album mode applies one
// uniform gain in one pass on purpose, because correcting per track is exactly
// the per-track variation it exists to remove.
em.warn(WarnLoudnessTargetMissed, fmt.Sprintf(tmpl, math.Abs(miss), target, lufs)+
"; album mode is a single uniform-gain pass and cannot iterate onto the target the way a single file does")
}
// needsProcessing reports whether the spec needs audio processing and a staged input. When
// false, a download can stream straight to the sink with no temp file. Any
// non-nil Transcode counts, including an explicit FormatCopy remux (distinct from
// a nil Transcode, which keeps the source bytes). A downmix request also counts:
// the fold needs a probe to decide and an encode to apply. An embed request also
// counts: the metadata post-pass rewrites a staged file, so even a keep-source
// download to a Writer stages first.
func needsProcessing(s ProcessSpec) bool {
return cutRequested(s.Cut) || s.Transcode != nil || s.Loudness != nil || s.Downmix || embedRequested(s)
}
// toSource maps a resolved stream to a download Source, selecting the query-range
// strategy for googlevideo media hosts (which answer &range= with a 200) and the
// default header-range strategy elsewhere.
func toSource(rs youtube.ResolvedStream) download.Source {
src := download.Source{
URL: rs.URL,
ContentLength: rs.ContentLength,
Headers: rs.Headers,
ExpiresAt: rs.ExpiresAt,
}
if isGoogleVideoHost(rs.URL) {
src.RangeStrategy = download.QueryRange{}
}
return src
}
// isGoogleVideoHost reports whether rawURL points at a googlevideo media host.
func isGoogleVideoHost(rawURL string) bool {
u, err := url.Parse(rawURL)
if err != nil {
return false
}
return strings.HasSuffix(strings.ToLower(u.Hostname()), "googlevideo.com")
}
// newProcessResult builds a Result from a pipeline outcome and the source format.
// target is the loudness target (used only when loudness was measured/applied).
func newProcessResult(kind SourceKind, p pipeline.Result, srcFmt Format, target float64) *Result {
res := &Result{
SourceKind: kind,
SourceFormat: srcFmt,
OutputFormat: srcFmt,
Transcoded: p.Transcoded,
CutApplied: p.Cut,
LoudnessMeasured: p.LoudnessMeasured,
LoudnessApplied: p.LoudnessApplied,
}
if p.Transcoded {
res.OutputFormat = outputFormat(p.OutputCodec, srcFmt)
}
if p.Cut {
// A cut shrinks the output. For a copy cut OutputFormat is still srcFmt, whose
// Duration and ContentLength describe the uncut source; for a fused cut+encode
// it is the codec/extension target with zero numerics. Either way, set the
// post-cut duration as a baseline (a probe supersedes it) and clear
// ContentLength: the cut byte size is unknown without a probe, and the source
// size would be wrong.
if d := p.SourceDuration - p.Removed; d > 0 {
res.OutputFormat.Duration = d
} else {
res.OutputFormat.Duration = 0
}
res.OutputFormat.ContentLength = 0
}
if p.OutputProbe != nil {
// Overlay authoritative rate/channels/bitrate/duration from the written file.
applyProbe(&res.OutputFormat, *p.OutputProbe)
if sz := p.OutputProbe.Format.Size; sz > 0 {
res.OutputFormat.ContentLength = sz
}
}
if p.LoudnessMeasured {
res.Loudness = &LoudnessResult{
Input: toLoudnessInfo(p.InputLoudness),
Output: toLoudnessInfo(p.OutputLoudness),
Target: target,
}
}
return res
}
// applyProbe fills a candidate Format with authoritative values from a probe of
// its resolved stream (InfoProbe depth) or written output. It overwrites only the
// measured numeric fields and duration, leaving the codec id from the player
// response, which is more specific than the probe's normalized name.
func applyProbe(f *Format, pr media.ProbeResult) {
if a, ok := pr.AudioStream(); ok {
if a.SampleRate > 0 {
f.SampleRate = a.SampleRate
}
if a.Channels > 0 {
f.Channels = a.Channels
}
if a.BitRate > 0 {
f.Bitrate = a.BitRate
}
if a.Duration > 0 {
f.Duration = a.Duration
}
}
if pr.Format.Duration > 0 {
f.Duration = pr.Format.Duration
}
// A probe often leaves the audio-stream bitrate zero for VBR/lossless. Fall back
// to the container bitrate, then a size/duration estimate, so both the
// info --probe row and a download's OutputFormat report a usable bitrate.
if f.Bitrate == 0 {
switch secs := f.Duration.Seconds(); {
case pr.Format.BitRate > 0:
f.Bitrate = pr.Format.BitRate
case secs > 0 && pr.Format.Size > 0:
f.Bitrate = int(float64(pr.Format.Size) * 8 / secs)
}
}
}
// outputFormat describes the transcode output. A copy keeps the source format;
// otherwise the codec and extension come from the target codec's preset.
func outputFormat(c media.Codec, src Format) Format {
if c == media.CodecCopy {
return src
}
return Format{Codec: c.String(), Extension: c.Extension()}
}
// toLoudnessInfo maps an internal loudness measurement to the public info type,
// preserving nil.
func toLoudnessInfo(l *loudness.Loudness) *LoudnessInfo {
if l == nil {
return nil
}
v := loudnessInfo(*l)
return &v
}
// loudnessInfo maps an internal loudness value to the public info type.
func loudnessInfo(l loudness.Loudness) LoudnessInfo {
return LoudnessInfo{
IntegratedLUFS: l.IntegratedLUFS,
TruePeakDBTP: l.TruePeakDBTP,
LRA: l.LRA,
SamplePeakDB: l.SamplePeakDB,
}
}
// withTimeout derives a child context bounded by d. A non-positive d returns the
// parent with a no-op cancel, so callers can always defer cancel.
func withTimeout(parent context.Context, d time.Duration) (context.Context, context.CancelFunc) {
if d <= 0 {
return parent, func() {}
}
return context.WithTimeout(parent, d)
}
// specFormat returns the requested output format, or FormatCopy for a nil spec.
func specFormat(t *TranscodeSpec) TranscodeFormat {
if t == nil {
return FormatCopy
}
return t.Format
}
// sourceExt returns the staging extension for a downloaded source format,
// defaulting to .webm when the format carries no extension.
func sourceExt(f Format) string {
if f.Extension != "" {
return "." + f.Extension
}
return ".webm"
}
// outputExt returns the extension the processed output should use: the target
// codec's extension for a re-encode, or the source extension for a copy.
func outputExt(t *TranscodeSpec, srcExt string) string {
c := transcodeCodec(specFormat(t))
if c == media.CodecCopy {
return srcExt
}
return "." + c.Extension()