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
//! Overlapped long-audio chunking: [`WindowPlan`] turns a clip length into a
//! list of [`Span`]s the [`AudioEncoder`](crate::embeddings::clap::AudioEncoder) embeds one at a
//! time, and [`WindowEmbedding`] pairs each resulting embedding with the [`Span`]
//! it came from (start, real length, and tail-padding-aware coverage) so an
//! [`AggregatePolicy`](crate::embeddings::clap::aggregate::AggregatePolicy) can weight by time,
//! overlap, or coverage.
//!
//! # windit engine + two clap-contract guards
//!
//! The window GEOMETRY and per-window AGGREGATION are the generic `windit`
//! windowed-sequence engine: [`Span`] is `windit::plan::Span`, [`WindowEmbedding`]
//! is `windit::windowed::WindowEmbedding<Embedding>`, and [`WindowPlan::spans`]
//! plans the head through `windit::plan::WindowPlan`. Two behaviours are clap's
//! own contract, reproduced as thin guards on top of the windit plan so the
//! pinned geometry stays bit-for-bit what it always was:
//!
//! 1. **Short clip** (`total <= WINDOW_SAMPLES`): exactly one span, whatever the
//! hop AND tail policy — windit's `DropBelowMin` would drop the sole span of a
//! short clip, but clap never drops a clip's only representation.
//! 2. **Multi-tail continuation**: windit stops at the first ragged tail, whereas
//! clap's overlapped plan (`hop < window`) keeps striding, emitting
//! progressively shorter tails until the stride passes the clip end.
//!
//! For `total > W`, windit visits starts `0, H, 2H, …` and stops at the first
//! `start` with `total − start ≤ W`, i.e. `first_tail_start = ceil((total − W)/H)·H`;
//! head spans and that first tail match clap's old loop term for term, and the
//! continuation reproduces its remaining iterations verbatim.
//!
//! # What windit does NOT replace: the mel `repeatpad`
//!
//! windit owns geometry and aggregation ONLY. The audio path still slices
//! `&samples[span.start()..span.end()]` and hands the (possibly short) slice to
//! the encoder, whose mel front-end `repeatpad`s it up to the fixed window —
//! windit's constant-right-pad helper is not used, and the mel path is untouched.
//!
//! # Wire format
//!
//! [`TailPolicy`] and [`WindowPlan`] keep their own clap-owned serde
//! representations (windit's `serde` feature is off), so the validated
//! deserialization is clap's own and was unchanged by the windit port. The
//! [`TailPolicy`] SPELLINGS did change once since: they were realigned onto the
//! adjacently tagged form windit 0.4 adopted, so a consumer holding both reads
//! one shape. See that type's "Wire form".
//!
//! The window length is **fixed** at [`WINDOW_SAMPLES`] (480 000 = 10 s at
//! 48 kHz) — the model's geometry, not a knob. The hop, the tail policy, and the
//! [`WindowPlan::max_windows`] resource cap are configurable. This module holds
//! no audio and touches no model, so its offsets and coverages are hermetically
//! pinned (see the sibling `tests.rs`).
//!
//! # Resource cap
//!
//! [`WindowPlan::spans`] counts its plan in O(1) and refuses one exceeding
//! [`WindowPlan::max_windows`] ([`DEFAULT_MAX_WINDOWS`], default-on) with a typed
//! [`Error::Windowing`]`(`[`WinditError::TooManyWindows`]`)` BEFORE materializing
//! any span — so a serde-supplied `hop_samples: 1` over a modest clip (a hop
//! every sample plans ~`total_samples` windows, gigabytes of retained embeddings
//! and one CoreML inference each) is a typed refusal, not an unbounded
//! allocation or a `.expect()` panic on the allocator's refusal.
use crate;
/// windit's window span (`windit::plan::Span`), re-exported as clap's window
/// geometry unit — the half-open real range `[start, end)` a [`WindowPlan`]
/// plans and the [`AudioEncoder`](crate::embeddings::clap::AudioEncoder) embeds. Every
/// clap-produced span carries `window() == `[`WINDOW_SAMPLES`], so
/// [`Span::coverage`] is the padding-aware `real length / 480_000` fraction a
/// coverage-weighting policy uses. (`Span::new` is 3-arg — `(start, len,
/// window)` — and reports `len()`/`end()`; there is no `real_len()`.)
pub use Span;
/// A per-window embedding paired with the [`Span`] it was computed from — the
/// input unit to aggregation, `windit::windowed::WindowEmbedding<Embedding>`.
/// Carrying the span (and thus [`Span::coverage`]) alongside the embedding is
/// what lets a policy weight windows by time, overlap, or tail coverage. Build
/// one with [`WindowEmbedding::new`](windit::windowed::Windowed::new); read it
/// back with [`value`](windit::windowed::Windowed::value) and
/// [`span`](windit::windowed::Windowed::span).
pub type WindowEmbedding = WindowEmbedding;
/// The fixed inference-window length in samples (480 000 = 10 s at 48 kHz).
///
/// The CLAP HTSAT graph consumes exactly this many samples per inference (via
/// the mel front-end, which `repeatpad`s a shorter tail up to it), so it is the
/// window every [`Span`] is measured against — the geometry, not a tunable
/// preference. Equal to [`crate::embeddings::clap::audio::TARGET_SAMPLES`].
pub const WINDOW_SAMPLES: usize = TARGET_SAMPLES;
/// Default [`WindowPlan::hop_samples`]: one full window (no overlap), so the
/// default plan tiles a clip into back-to-back 10 s chunks — matching textclap's
/// `ChunkingOptions` default (`window == hop == 480_000`).
pub const DEFAULT_HOP_SAMPLES: u32 = WINDOW_SAMPLES as u32;
/// Default minimum real length (samples) for [`TailPolicy::DropBelowMin`]: a
/// quarter window (120 000 = 2.5 s), matching textclap's `embed_chunked`
/// `window / 4` keep threshold.
pub const DEFAULT_TAIL_MIN_SAMPLES: u32 = as u32;
/// Default [`WindowPlan::max_windows`]: 100 000 windows.
///
/// The cap is a resource rail, not a latency policy: each planned window costs
/// one full CoreML inference, and
/// [`AudioEncoder::embed_windows`](crate::embeddings::clap::AudioEncoder::embed_windows) retains a
/// [`Embedding`] ([`EMBEDDING_DIM`](crate::embeddings::clap::embedding::EMBEDDING_DIM) = 512 floats,
/// ~2 KiB) per window, so 100 000 caps that retention at ~200 MiB. It admits
/// every realistic clip — 24 h of audio at a 1 s hop is 86 400 windows; at the
/// default no-overlap hop the cap is ~11 days of audio — while rejecting
/// hop-abuse: at `hop_samples == 1` ANY clip long enough to window at all
/// (> 10 s) plans more than 480 000 windows and fails typed. Latency-sensitive
/// services should lower it; raising it is a deliberate opt-in to more memory
/// and inference work. Mirrors the CED classifier's identical rail.
pub const DEFAULT_MAX_WINDOWS: u32 = 100_000;
/// Drop a final chunk whose real length is below `min_samples`, so a trailing
/// sliver dominated by padding never contributes. A chunk at or above the
/// threshold is kept. The single window a clip shorter than one full window
/// produces is never dropped (there is nothing else to represent it).
///
/// A payload STRUCT, not a bare `u32` newtype: [`TailPolicy`] carries a serde
/// representation, and a struct puts the threshold on the wire under its own
/// `min_samples` name — `{"kind":"drop_below_min","value":{"min_samples":N}}`
/// — rather than as a bare integer whose meaning lives only in the variant
/// tag, and it leaves room for a second field without reshaping the document.
///
/// Payload of [`TailPolicy::DropBelowMin`].
/// What [`WindowPlan`] does with a final chunk whose real samples fall short of a
/// full [`WINDOW_SAMPLES`] window.
///
/// A short tail is embedded by `repeatpad`ing it up to the fixed window, so a
/// kept tail's [`Span::coverage`] is `< 1.0` — the padding-aware fraction a
/// coverage-weighting policy uses to down-weight it. This policy chooses whether
/// such a tail is kept at all.
///
/// # Wire form
///
/// Under the `serde` feature this has TWO representations, chosen by
/// [`is_human_readable`](serde::Serializer::is_human_readable):
///
/// - **Human-readable** (JSON, TOML — the formats a config file is written in):
/// **adjacently tagged**, snake_case, `kind` naming the variant and `value`
/// carrying [`DropBelowMin`]'s payload — `{"kind":"pad"}` and
/// `{"kind":"drop_below_min","value":{"min_samples":N}}`. That is the form
/// `windit` 0.4 gave its own `TailPolicy`, adopted here (and by `audio::ced::window::TailPolicy`, which is feature-gated
/// separately) so a
/// consumer holding several of them reads one shape. It REPLACES the
/// externally tagged `"pad"` / `{"drop_below_min":{"min_samples":N}}` form: a
/// document written against the old spelling no longer deserializes, and
/// `tail_policy_wire_spellings_are_pinned` asserts both halves of that — the
/// new form round-trips, the old one is refused.
/// - **Binary** (postcard and every other non-self-describing format): the
/// plain enum protocol — a variant index, plus the payload for
/// [`DropBelowMin`](Self::DropBelowMin). serde's adjacent tagging cannot
/// survive such a format at all: it writes the tag as a struct FIELD and
/// reads it back through `deserialize_identifier`, which a format carrying no
/// field names refuses, so EVERY variant fails to deserialize — not only the
/// unit one, whose content serde additionally reads through
/// `deserialize_any`. Without this branch a default [`WindowPlan`] would
/// serialize to bytes it could not then read back.
///
/// Only the choice is hand-written: each branch delegates to a derived mirror
/// in `tail_policy_serde`, so the document above is still serde's own spelling
/// and this enum stays the single source of truth for the variants.
/// The two derived mirrors of [`TailPolicy`]: its human-readable document and
/// its binary form. [`TailPolicy`]'s own impls pick between them on
/// `is_human_readable` — see that type's "Wire form" for why one representation
/// cannot serve both.
///
/// Mirrors rather than hand-written `Serialize`/`Deserialize` impls: the
/// adjacently tagged document stays serde's own spelling rather than a
/// hand-rolled imitation of it, and the wildcard-free conversions below fail to
/// compile until a new variant is spelled in both forms.
/// The adjacently tagged document in a human-readable format, the plain enum
/// protocol in every other — see the type's "Wire form".
/// The inverse of [`Serialize`](serde::Serialize) above, split on the same
/// question, so what a format wrote is what it reads back.
/// Whether `hop_samples` is in the valid `1..=WINDOW_SAMPLES` range: positive
/// (a zero hop never advances) and no larger than one window (a hop past the
/// window would leave gaps of un-embedded audio between chunks). `hop ==
/// WINDOW_SAMPLES` means contiguous, non-overlapping chunks; a smaller hop
/// overlaps.
const
/// Whether a [`TailPolicy::DropBelowMin`] `min_samples` is in `1..=WINDOW_SAMPLES`
/// (a zero threshold would drop nothing yet mean "drop below one sample", and a
/// threshold above the window can never be met by a sub-window tail).
const
/// Whether `max_windows` is a usable cap: strictly positive. A zero cap would
/// admit no plan at all (even the single-span short clip), so a default-carrying
/// field that can never embed anything is a misconfiguration, the same class as
/// `hop == 0`. `u32::MAX` is the deliberate "effectively uncapped" escape hatch.
const
/// Overlapped-chunking plan: a validated hop and tail policy over the fixed
/// [`WINDOW_SAMPLES`] window, plus a [`Self::max_windows`] resource cap
/// (rust-options-pattern).
///
/// [`Self::spans`] is the pure-geometry core — it maps a clip length to the list
/// of [`Span`]s to embed, with no audio and no model involved, so the offsets
/// and coverages are hermetically testable. `max_windows` bounds that count in
/// O(1) BEFORE any span is materialized, so an untrusted length + hop cannot
/// expand into an out-of-memory allocation or a flood of inferences.
///
/// # Validated deserialization
///
/// `Deserialize` routes through a private `WindowPlanRepr` via
/// `serde(try_from)`, holding a config-file or hand-written `WindowPlan` to the
/// SAME `hop_samples`/`min_samples`/`max_windows` invariants the checked setters
/// enforce. Deriving `Deserialize` on the fields directly would bypass
/// [`Self::set_hop_samples`]: `{"hop_samples": 0}` would deserialize and then
/// loop forever (a zero hop never advances), `{"hop_samples": 960000}` would
/// silently leave 10 s gaps of un-embedded audio between chunks, and
/// `{"max_windows": 0}` could never embed anything. Invalid input now fails to
/// deserialize instead (mirrors speakerkit's `WindowOptions`). An omitted
/// `max_windows` fills [`DEFAULT_MAX_WINDOWS`], so the cap is default-on for
/// every deserialized plan.
///
/// UNKNOWN KEYS ARE REFUSED. Defaulted fields and a tolerated stray key compose
/// into a silent hole: `{"max_window": 1}` — the plural dropped — would
/// otherwise deserialize with the typo discarded and `max_windows` filled from
/// [`DEFAULT_MAX_WINDOWS`], so a caller capping this door at ONE window would
/// get 100 000 and a misspelled RESOURCE LIMIT would silently become up to
/// 100 000 CoreML inferences; a misspelled `hop_samples` or `tail` would
/// silently change the embedded geometry the same way. The misspelling is a
/// hard error naming the key instead.
///
/// That refusal makes this type UNFLATTENABLE: serde's `deny_unknown_fields`
/// and `flatten` do not compose (a flattened field sees the outer struct's
/// other keys and rejects them), so a config type composing a plan must NEST it
/// under a key of its own — `window_plan = { … }` — not `#[serde(flatten)]` it
/// into itself.
/// The plain wire form [`WindowPlan`]'s `Deserialize` deserializes FIRST
/// (carrying the field defaults), before [`WindowPlan::try_from`] applies the
/// range checks. Its whole purpose is to make the validated setters unbypassable
/// via serde — it is never constructed or exposed otherwise.
///
/// `deny_unknown_fields` lives HERE rather than on [`WindowPlan`], because this
/// is the type whose fields serde actually visits: the public plan's
/// `Deserialize` is a `try_from` wrapper around this one.