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
//! Image content analyzers for adaptive codec decisions.
//!
//! Computes the numeric features used by oracle-trained decision trees
//! (originally `coefficient::scripts/fit_oracle_tree.py`) to drive
//! per-image encoder configuration. Every shipped feature is wired
//! into at least one fitted tree's splits per the 2026-04-25 audit.
//!
//! # Public API
//!
//! All public types are opaque. Construction goes through the
//! [`feature`] module:
//!
//! - [`feature::AnalysisFeature`]: stable identifier per feature
//! (`#[non_exhaustive]`, `#[repr(u16)]`, sequential discriminants —
//! ids are immutable once shipped).
//! - [`feature::FeatureValue`]: `F32` / `U32` / `Bool` tagged value
//! with `to_f32` lossless coercion.
//! - [`feature::FeatureSet`]: opaque bitset with full `const fn` set
//! math. The only "all features" entry is
//! [`feature::FeatureSet::SUPPORTED`] — there is intentionally no
//! `all()`. Production callers enumerate what they need.
//! - [`feature::AnalysisQuery`]: opaque request handle. Sampling
//! budgets are crate invariants, not per-call knobs.
//! - [`feature::ImageGeometry`]: opaque `width`/`height`/
//! `pixels`/`megapixels`/`aspect_ratio` accessors.
//! - [`feature::AnalysisResults`]: opaque queryable container.
//!
//! # Entry points
//!
//! - [`analyze_features`] — preferred. Takes any [`PixelSlice`] and
//! an [`feature::AnalysisQuery`]. Native zero-copy on RGB8/RGB8_SRGB
//! inputs; one-row scratch + `RowConverter` on anything else (every
//! `zenpixels` descriptor: RGBA/BGRA u8/u16, GRAY u8/u16, RGB/RGBA
//! f32 linear, PQ/HLG/Bt709, BT.709/DisplayP3/BT.2020/AdobeRGB).
//! - [`analyze_features_rgb8`] — convenience for packed RGB8 buffers.
//!
//! # Composition pattern
//!
//! ```ignore
//! use zenanalyze::feature::{AnalysisFeature, AnalysisQuery, FeatureSet};
//!
//! const JPEG_FEATURES: FeatureSet = FeatureSet::new()
//! .with(AnalysisFeature::Variance)
//! .with(AnalysisFeature::EdgeDensity)
//! .with(AnalysisFeature::DctCompressibilityY);
//! const WEBP_FEATURES: FeatureSet = FeatureSet::new()
//! .with(AnalysisFeature::Variance)
//! .with(AnalysisFeature::AlphaPresent);
//!
//! // Orchestrator unions, runs once, hands results down.
//! let needed = JPEG_FEATURES.union(WEBP_FEATURES);
//! let r = zenanalyze::analyze_features(slice, &AnalysisQuery::new(needed))?;
//! let var = r.get_f32(AnalysisFeature::Variance);
//! ```
//!
//! # Threshold contract — iterating during 0.1.x
//!
//! Numeric thresholds and normalization scales in this crate are
//! converging during the 0.1.x line. Downstream consumers that
//! compile-in fitted models (oracle decision trees, content
//! selectors) must pin to a specific zenanalyze patch version and
//! re-validate / retrain whenever they bump it — feature outputs
//! change between patches whenever a real bug is fixed.
//!
//! Every breaking numeric change ships with a CHANGELOG entry under
//! the version it landed in. When the algorithm stabilizes (1.0),
//! the contract will freeze. Sampling budgets (Tier 1/2 stripe step,
//! Tier 3 block cap) are part of that contract — not exposed as
//! per-call knobs.
//!
//! # Tier architecture
//!
//! Five passes, each gated by what the requested [`feature::FeatureSet`]
//! actually needs. None of them materialize a full RGB8 buffer:
//!
//! | Pass | Iterates over | Reads | Cost (4 MP) | Drives |
//! |-------------|--------------------------|---------------------|-------------|-------------------------------------------|
//! | Tier 1 | Stripe-sampled rows | RGB8 (via RowStream) | ~1 ms | luma stats, edges, chroma, uniformity, grayscale_score |
//! | Tier 2 | 3-row sliding window | RGB8 | ~2 ms | per-axis Cb/Cr sharpness |
//! | Tier 3 | Sampled 8×8 DCT blocks | RGB8 | ~3 ms | DCT energy, entropy, AQ map, noise floor, line-art, patch fraction |
//! | Palette | Full-image (every pixel) | RGB8 | ~1 ms | distinct_color_bins |
//! | Alpha | Stride-sampled rows | **Source bytes** | ~0.3 ms | alpha presence / used / bimodal |
//! | tier_depth | Stride-sampled rows | **Source bytes** | ~0.5 ms HDR / ~0 ms SDR | peak nits, headroom, bit depth, HDR-present |
//!
//! Tier 1/2/3 + Palette read RGB8, going through `RowStream`'s `Native`
//! zero-copy path on RGB8 layouts and `RowConverter` row-by-row on
//! everything else. Alpha and `tier_depth` read source samples
//! directly — that's load-bearing for HDR (RowConverter doesn't
//! tonemap PQ/HLG; its narrowing clips to [0, 1] sRGB-display) and
//! for the alpha pass (avoids a precision-losing pre-multiply round-
//! trip on u16/f32 alpha).
//!
//! ## Why a separate `tier_depth`
//!
//! The standard tiers' threshold contract is calibrated on display-
//! space RGB8 bytes. HDR content's source samples encode dynamic
//! range that the RGB8 narrowing destroys; a 4000-nit PQ source and
//! a 100-nit-clipped SDR source produce byte-identical RGB8 streams.
//! Routing the depth tier through RowStream would have made it
//! literally impossible to surface HDR-aware features.
//!
//! Adding `tier_depth` as a fifth `const bool` axis to the dispatch
//! table would have doubled it from 16 to 32 monomorphizations for
//! near-zero benefit — the depth tier reads source bytes, not RGB8
//! rows, and shares no inner loop with T1/T2/T3 to specialize. So
//! it's wired as a runtime branch outside the const-bool dispatch.
//!
//! ## Empirical calibration (corpus-eval 2026-04-27)
//!
//! Pre-0.1.0-ship calibration baseline measured on a 219-image
//! labeled corpus from `coefficient/benchmarks/classifier-eval/labels.tsv`
//! (174 photo, 36 screen, 9 illustration, 44 marked synthetic;
//! pooled from cid22-train/val, clic2025-1024, gb82, gb82-sc,
//! imageflow, kadid10k, qoi-benchmark). Full per-class
//! distributions, ROC-AUC ranking for every feature, recommended
//! operating thresholds, and the recalibration candidates that
//! were considered and rejected are recorded in
//! `docs/calibration-corpus-2026-04-27.md`.
//!
//! Top-line empirical findings:
//!
//! - **Strongest single screen-vs-photo discriminator**:
//! [`feature::AnalysisFeature::PatchFraction`] (AUC = 0.880,
//! F1 = 0.769 at `>= 0.27`).
//! - **Strongest photo classifier**:
//! [`feature::AnalysisFeature::NaturalLikelihood`] (F1 = 0.924
//! at `>= 0.06`).
//! - **Near-deterministic line-art signal**:
//! [`feature::AnalysisFeature::LineArtScore`] `> 0`
//! (F1 = 0.978).
//! - **Derived likelihoods empirically saturate at ~0.70**, not
//! 1.0 — operating thresholds live in the 0.3–0.6 band, not 0.8+.
//!
//! Spearman ρ |≥ 0.85| pairs (mostly structural, all kept):
//!
//! - `distinct_color_bins` ↔ `palette_density`: ρ = +1.00 — derived.
//! - `flat_color_block_ratio` ↔ `screen_content_likelihood`: ρ =
//! +0.99 — structural, the former is the latter's primary input.
//! - `uniformity` ↔ `aq_map_mean`: ρ = −0.97. Both measure block
//! flatness; drive different knobs (T1 fast-path vs T3 AQ-driven
//! trellis-λ).
//! - `chroma_complexity` ↔ `colourfulness`: ρ = +0.97. Both
//! quantify chroma spread; one is normalised, the other is the
//! raw Hasler-Süsstrunk M3 published scale — keep both for
//! ergonomics.
//! - `aq_map_mean` ↔ `noise_floor_y`: ρ = +0.91. Both fall when
//! blocks are flat. Different downstream knobs (zenjpeg trellis-λ
//! vs `pre_blur`), keep both.
//! - `noise_floor_y` ↔ `screen_content_likelihood`: ρ = −0.89.
//! Screen content is clean-by-construction; photos carry sensor
//! noise. Different passes, different knobs.
//! - `cb_sharpness` ↔ `cr_sharpness`: ρ = +0.89. Co-vary by
//! construction in natural content.
//!
//! No deletion candidates were found. Numeric drift in 0.1.x
//! patches is permitted by the threshold contract above; the
//! committed `docs/calibration-corpus-2026-04-27.md` is the
//! pre-ship baseline against which patch drift can be compared.
// `#[archmage::autoversion]` generates dispatch trampolines that
// don't always reference the unversioned base function.
pub
pub
pub
pub
pub
pub
use fmt;
use ;
use RowStream;
/// Errors returned from the public analyzer entries.
///
/// Variants are stable; new variants will be added behind
/// `#[non_exhaustive]` so a `match` on this type must include a `_`
/// arm. The `Display` form is suitable for surfacing to end users
/// (concise, no internal type names); the `source()` chain points at
/// the underlying cause for `Convert` and `Internal` variants.
/// Run the analyzer over any [`PixelSlice`] for the requested feature
/// set. Returns an opaque [`feature::AnalysisResults`] holding only
/// the features the query asked for.
///
/// `query` is built from a [`feature::FeatureSet`] composed via
/// `const fn` set math:
///
/// ```ignore
/// use zenanalyze::feature::{AnalysisFeature, AnalysisQuery, FeatureSet};
/// const MY_FEATURES: FeatureSet = FeatureSet::new()
/// .with(AnalysisFeature::Variance)
/// .with(AnalysisFeature::EdgeDensity);
/// let results = zenanalyze::analyze_features(slice, &AnalysisQuery::new(MY_FEATURES))?;
/// let var = results.get_f32(AnalysisFeature::Variance);
/// ```
///
/// Sampling budgets (Tier 1/2 stripe sampling, Tier 3 block cap) are
/// crate invariants — see [`feature::AnalysisQuery`] for the rationale
/// and the `#[doc(hidden)]` `__internal_with_overrides` backdoor for
/// tests / oracle re-extraction.
///
/// # Dispatch
///
/// Inspects the requested [`feature::FeatureSet`] and computes four
/// `const bool` axes (`PAL`/`T2`/`T3`/`ALPHA`). Sixteen
/// monomorphized [`analyze_specialized`] instantiations cover every
/// combination; inside each, unrequested tiers become straight-line
/// const-eval'd dead code. A caller asking for only `Variance` runs
/// Tier 1 and nothing else.
///
/// # Layered defense against garbage outputs
///
/// 1. Dispatch axes are unioned with derived-feature dependency
/// closures ([`feature::T3_NEEDED_BY`], [`feature::PAL_NEEDED_BY`])
/// so e.g. asking for `ScreenContentLikelihood` correctly gates
/// the palette pass on (it reads `distinct_color_bins`).
/// 2. [`tier3::compute_derived_likelihoods`] is itself const-bool
/// gated — even if the dispatch axes drift, a likelihood whose
/// deps weren't computed is left at default and never written.
/// 3. [`feature::AnalysisResults::get`] only returns values that
/// were both requested and written. Unrequested or unwritten
/// features come back as `None`. **Caller never sees garbage.**
///
/// # Wide gamut, HDR, and bit-depth policy
///
/// **The analyzer accepts every layout `zenpixels_convert::RowConverter`
/// can ingest.** Specifically:
///
/// - **24-bpp packed RGB** (RGB8 / RGB8_SRGB / RGB8 with Display P3 /
/// Rec.2020 / AdobeRGB primaries / non-sRGB transfer) — passes through
/// the zero-copy [`row_stream::RowStream`] `Native` path, byte-for-byte.
/// The analyzer's BT.601 luma weights produce slightly-different
/// numbers for non-sRGB primaries, and that's the principled outcome
/// — wide-gamut content has more saturated colour, so chroma /
/// colourfulness signals legitimately read higher.
/// - **RGBA8 / BGRA8 / Rgbx8 / Bgrx8** — alpha is analysed by the
/// separate alpha pass that reads the source descriptor directly.
/// The RGB tiers see a row-converted RGB8 view; for opaque pixels
/// that's identity, for translucent pixels it depends on the
/// converter's straight-alpha policy.
/// - **RGB16 / RGBA16** — converted to RGB8 by taking the high byte of
/// each channel. Crucially: an 8-bit image promoted to 16 bits via
/// the standard `u8 * 257` (or `u8 << 8`) doubling produces the same
/// high byte back, so analyzer features on a u8-promoted u16 source
/// are *bit-identical* to the original u8 (locked by tests). Genuine
/// 16-bit content's extra precision feeds derived signals where
/// it's algorithmically meaningful (palette bins are 5-bit-per-
/// channel; sub-LSB drift in the bottom 8 bits doesn't change
/// uniformity / variance categorically).
/// - **f32 RGB / RGBA (linear or HDR)** — converted to display-space
/// RGB8 via the descriptor's transfer function. For SDR f32 content
/// normalized to `[0, 1]`, the round-trip from a u8 promotion is
/// bit-identical. For PQ / HLG / linear-light HDR, the analyzer
/// measures the SDR rendition — that's the principled choice for
/// features whose threshold contract is calibrated on display-space
/// bytes; HDR-aware analysis (peak luminance, HDR pixel fraction,
/// wide-gamut peak) lives in the future `tier_depth` work
/// (issue #120) and is computed directly on the source samples.
/// - **Gray8 / Gray16 / GrayF32 / GrayA{8,16,F32}** — converted to RGB8
/// by replicating the luma channel. Chroma signals are then trivially
/// zero, which is correct.
///
/// The point: per-image codec decisions don't usually break on a few
/// LSBs of luma drift. They break on the analyzer refusing to run.
/// The previous "opt-in via `analyze_features_lossy_convert`" gate was
/// over-defensive — every supported wide-gamut / HDR / 16-bit source
/// either round-trips through conversion as identity (u8-promoted) or
/// produces a rendering that is the legitimate signal for SDR-
/// calibrated features. We accept everything, document the cases
/// where the rendering differs from a byte-for-byte input, and give
/// codecs a stable feature surface.
///
/// # Errors
///
/// - [`AnalyzeError::Convert`] if `RowConverter` doesn't support the
/// source descriptor (e.g. CMYK without a CMS plugin loaded). The
/// set of accepted descriptors is `zenpixels-convert`'s problem,
/// not the analyzer's.
/// - [`AnalyzeError::Internal`] for unexpected failures (e.g. a
/// malformed `PixelSlice` whose row stride doesn't match its
/// declared format).
/// Const-bool-monomorphized analyzer body. Returns the dense
/// [`feature::RawAnalysis`] + [`feature::ImageGeometry`] — the public
/// [`analyze_features`] entry post-converts via
/// [`feature::RawAnalysis::into_results`] using the caller's
/// [`feature::FeatureSet`]. Each `if PAL { … }` arm is dead code in
/// instantiations where the axis is `false`; LLVM const-evals the
/// predicate and DCEs the branch entirely.
///
/// Tier 1 is always-on: if a caller dispatches through here they
/// almost always want at least one Tier 1 feature (variance /
/// edge_density / colourfulness / etc.). Adding a fifth axis to skip
/// it doubles the dispatch table for marginal benefit; defer until
/// there's data showing real callers asking for zero T1 features.
///
/// Sampling budgets `pixel_budget` / `hf_max_blocks` are runtime
/// values for the test / oracle override path. `analyze_features`
/// always passes the canonical [`feature::DEFAULT_PIXEL_BUDGET`] /
/// [`feature::DEFAULT_HF_MAX_BLOCKS`] constants.
/// **Unstable. Tests / oracle re-extraction only.** Run every tier
/// with caller-supplied sampling budgets, returning the dense
/// internal record. No stable API, no public path.
/// Crate-internal full-fat analysis for tests: always runs every
/// tier so test assertions can read any field. Returns the dense
/// record + geometry; tests wrap it in `tests::TestOutput`.
pub
/// Convenience entry for callers holding a packed RGB8 buffer plus a
/// query. **Panics** on length mismatch or stride-construction failure.
///
/// Use this when the input is known-good (e.g. coming from a freshly
/// decoded image where length and stride are guaranteed by
/// construction). For untrusted input — anything where the buffer
/// length or dimensions came in over a wire / from disk / from an
/// FFI boundary — prefer [`try_analyze_features_rgb8`], which surfaces
/// the same problems through [`AnalyzeError::InvalidInput`] /
/// [`AnalyzeError::OutOfMemory`] instead of unwinding.
/// Fallible parallel of [`analyze_features_rgb8`]. Returns
/// [`AnalyzeError::InvalidInput`] when the buffer length doesn't
/// match `width * height * 3` or the resulting stride is invalid;
/// returns [`AnalyzeError::OutOfMemory`] when (in a future fallible-
/// allocation build) the analyzer's working buffers can't be reserved.
///
/// **Recommended for production code that handles untrusted images.**
/// The internals share an analyzer pass with [`analyze_features_rgb8`];
/// the only difference is the error-reporting contract.
///
/// Today this fn never returns `OutOfMemory` because every internal
/// allocation is infallible — but the variant is part of the
/// [`AnalyzeError`] surface (it's `#[non_exhaustive]`) so that a
/// future minor release can tighten the internals to use
/// `Vec::try_reserve` / `Box::try_new` without breaking the public
/// signature. Production callers should match it explicitly today.
///
/// # Errors
///
/// - [`AnalyzeError::InvalidInput`] for buffer-length mismatches or
/// slice-construction failures.
/// - [`AnalyzeError::OutOfMemory`] from future fallible-alloc paths.
/// - [`AnalyzeError::Convert`] / [`AnalyzeError::Internal`] are not
/// reachable on the RGB8 fast path today, but listed here so a
/// `match` over the enum stays complete.