mediaschema 0.2.0

Product-agnostic media-primitive schema (buffa-generated)
Documentation
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
//! Mediaschema-owned enums (locked `schema/enums.md` r4).
//!
//! **Boundary:** media-stream *descriptor* vocabulary (codec/format/layout
//! enums + `TrackDisposition`) lives in **`::mediaframe`**, not here — those
//! become extern types when mediaframe ships the post-`0.1.0` minor; this
//! module defines only the **findit pipeline / analysis** enums.
//!
//! `#[non_exhaustive]` is applied to enums with a future-extension story
//! (engines / pipelines may add stages). Closed enums (`MediaKind`,
//! `ScanStatus`, the coarse `*IndexStage`s, `SubtitleKind`,
//! `AudioContentKind`) are explicitly closed per the locked spec.

use derive_more::{Display, IsVariant};

// The bitflags imports + `ErrorCode` / `ErrorInfo` are referenced only
// by the `{Video,Audio,Subtitle}IndexStage::from_status` impl blocks
// below, which are themselves `any(std, alloc)`-gated (they take
// `&[ErrorInfo]` and `ErrorInfo` is heap-tier). Gating the imports too
// keeps `--no-default-features` warning-clean under `-D warnings`.
#[cfg(any(feature = "std", feature = "alloc"))]
use crate::domain::{
  bitflags::{AudioIndexStatus, SubtitleIndexStatus, VideoIndexStatus},
  primitives::{ErrorCode, ErrorInfo},
};

// ===========================================================================
// MediaKind — the kind of media (drives which facets are created)
// ===========================================================================

/// Top-level media classification. **Closed** — `kind` is set at probe and
/// drives which facets (`Video`/`Audio`/`Subtitle`) the schema creates;
/// pre-probe is a different lifecycle, not an `Unknown` arm here.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default, IsVariant, Display)]
#[display("{}", self.as_str())]
pub enum MediaKind {
  #[default]
  Video,
  Audio,
}

impl MediaKind {
  /// Stable snake_case slug — the canonical string form of every variant.
  /// Used for `Display`, serde tags, log keys, schema-doc references.
  #[inline(always)]
  pub const fn as_str(&self) -> &'static str {
    match self {
      Self::Video => "video",
      Self::Audio => "audio",
    }
  }
  /// Inverse of [`as_str`](Self::as_str). Returns `None` for any input
  /// that isn't an exact match of one of the slugs.
  #[inline]
  pub fn from_str(s: &str) -> Option<Self> {
    Some(match s {
      "video" => Self::Video,
      "audio" => Self::Audio,
      _ => return None,
    })
  }
}

// ===========================================================================
// SceneDetector — which of the `scenesdetect` engine modules produced a Scene
// ===========================================================================

/// Which `scenesdetect` engine module raised a `Scene` boundary. Mirrors the
/// 5 detection modules + a manual escape hatch. `#[non_exhaustive]` —
/// `scenesdetect` may add detectors.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, IsVariant, Display)]
#[display("{}", self.as_str())]
#[non_exhaustive]
pub enum SceneDetector {
  Histogram,
  Phash,
  Threshold,
  Content,
  Adaptive,
  /// User-created / imported boundary (not from a detector).
  Manual,
}

impl SceneDetector {
  /// Stable snake_case slug — the canonical string form of every variant.
  #[inline(always)]
  pub const fn as_str(&self) -> &'static str {
    match self {
      Self::Histogram => "histogram",
      Self::Phash => "phash",
      Self::Threshold => "threshold",
      Self::Content => "content",
      Self::Adaptive => "adaptive",
      Self::Manual => "manual",
    }
  }
  /// Inverse of [`as_str`](Self::as_str). Returns `None` for any input
  /// that isn't an exact match of one of the slugs.
  #[inline]
  pub fn from_str(s: &str) -> Option<Self> {
    Some(match s {
      "histogram" => Self::Histogram,
      "phash" => Self::Phash,
      "threshold" => Self::Threshold,
      "content" => Self::Content,
      "adaptive" => Self::Adaptive,
      "manual" => Self::Manual,
      _ => return None,
    })
  }
}

// ===========================================================================
// KeyframeExtractor — which extractor produced a Keyframe
// ===========================================================================

/// Which extractor produced a `Keyframe`. A scene-detector boundary frame is
/// a keyframe too, so this enum is a **superset** of [`SceneDetector`] plus
/// the dedicated keyframe-extractor variants. `#[non_exhaustive]`.
///
/// Replaces the dropped closed `KeyframeKind` (locked `enums.md` r4).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, IsVariant, Display)]
#[display("{}", self.as_str())]
#[non_exhaustive]
pub enum KeyframeExtractor {
  // All SceneDetector variants — scene-boundary frames are also keyframes.
  Histogram,
  Phash,
  Threshold,
  Content,
  Adaptive,
  // Dedicated keyframe-extractor variants.
  CompositeQuality,
  Interval,
  IFrame,
  SceneRepresentative,
  Manual,
}

impl KeyframeExtractor {
  /// Stable snake_case slug — the canonical string form of every variant.
  /// `IFrame` slugs to `"i_frame"` (digit-snake-case is uniform with the
  /// rest of the codebase; `"iframe"` would be a compound-word
  /// exception).
  #[inline(always)]
  pub const fn as_str(&self) -> &'static str {
    match self {
      Self::Histogram => "histogram",
      Self::Phash => "phash",
      Self::Threshold => "threshold",
      Self::Content => "content",
      Self::Adaptive => "adaptive",
      Self::CompositeQuality => "composite_quality",
      Self::Interval => "interval",
      Self::IFrame => "i_frame",
      Self::SceneRepresentative => "scene_representative",
      Self::Manual => "manual",
    }
  }
  /// Inverse of [`as_str`](Self::as_str). Returns `None` for any input
  /// that isn't an exact match of one of the slugs.
  #[inline]
  pub fn from_str(s: &str) -> Option<Self> {
    Some(match s {
      "histogram" => Self::Histogram,
      "phash" => Self::Phash,
      "threshold" => Self::Threshold,
      "content" => Self::Content,
      "adaptive" => Self::Adaptive,
      "composite_quality" => Self::CompositeQuality,
      "interval" => Self::Interval,
      "i_frame" => Self::IFrame,
      "scene_representative" => Self::SceneRepresentative,
      "manual" => Self::Manual,
      _ => return None,
    })
  }
}

// ===========================================================================
// SubtitleKind — subtitle role (a findit selection/search facet)
// ===========================================================================

/// Subtitle role — *not* a raw stream property (those live in
/// `::mediaframe`); a findit selection/search facet used for default-track
/// picking and faceted UI.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default, IsVariant, Display)]
#[display("{}", self.as_str())]
pub enum SubtitleKind {
  #[default]
  FullDialogue,
  /// Forced narrative (FFmpeg `AV_DISPOSITION_FORCED`).
  ForcedNarrative,
  /// Commentary text (FFmpeg `AV_DISPOSITION_COMMENT`).
  CommentaryText,
}

impl SubtitleKind {
  /// Stable snake_case slug — the canonical string form of every variant.
  #[inline(always)]
  pub const fn as_str(&self) -> &'static str {
    match self {
      Self::FullDialogue => "full_dialogue",
      Self::ForcedNarrative => "forced_narrative",
      Self::CommentaryText => "commentary_text",
    }
  }
  /// Inverse of [`as_str`](Self::as_str). Returns `None` for any input
  /// that isn't an exact match of one of the slugs.
  #[inline]
  pub fn from_str(s: &str) -> Option<Self> {
    Some(match s {
      "full_dialogue" => Self::FullDialogue,
      "forced_narrative" => Self::ForcedNarrative,
      "commentary_text" => Self::CommentaryText,
      _ => return None,
    })
  }
}

// ===========================================================================
// AudioContentKind — coarse content classification (analyze stage output)
// ===========================================================================

/// Coarse audio-track content classification — drives whether to
/// transcribe/diarize this track at all. Output of the audio `CLASSIFIED`
/// stage; **closed** vocabulary.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default, IsVariant, Display)]
#[display("{}", self.as_str())]
pub enum AudioContentKind {
  #[default]
  Speech,
  Music,
  Mixed,
  Silence,
}

impl AudioContentKind {
  /// Stable snake_case slug — the canonical string form of every variant.
  #[inline(always)]
  pub const fn as_str(&self) -> &'static str {
    match self {
      Self::Speech => "speech",
      Self::Music => "music",
      Self::Mixed => "mixed",
      Self::Silence => "silence",
    }
  }
  /// Inverse of [`as_str`](Self::as_str). Returns `None` for any input
  /// that isn't an exact match of one of the slugs.
  #[inline]
  pub fn from_str(s: &str) -> Option<Self> {
    Some(match s {
      "speech" => Self::Speech,
      "music" => Self::Music,
      "mixed" => Self::Mixed,
      "silence" => Self::Silence,
      _ => return None,
    })
  }
}

// ===========================================================================
// ScanStatus — WatchedLocation reconcile-sweep status
// ===========================================================================

/// Status of a `WatchedLocation` reconcile sweep (bootstrap / after-downtime
/// / volume-remount catch-up). Closed.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default, IsVariant, Display)]
#[display("{}", self.as_str())]
pub enum ScanStatus {
  #[default]
  Ok,
  Partial,
  Failed,
}

impl ScanStatus {
  /// Stable snake_case slug — the canonical string form of every variant.
  #[inline(always)]
  pub const fn as_str(&self) -> &'static str {
    match self {
      Self::Ok => "ok",
      Self::Partial => "partial",
      Self::Failed => "failed",
    }
  }
  /// Inverse of [`as_str`](Self::as_str). Returns `None` for any input
  /// that isn't an exact match of one of the slugs.
  #[inline]
  pub fn from_str(s: &str) -> Option<Self> {
    Some(match s {
      "ok" => Self::Ok,
      "partial" => Self::Partial,
      "failed" => Self::Failed,
      _ => return None,
    })
  }
}

// ===========================================================================
// VideoIndexStage — derived coarse stage from VideoIndexStatus + errors
// ===========================================================================

/// Coarse derived stage for a `VideoTrack`'s indexing lifecycle.
///
/// **Derived** from [`VideoIndexStatus`] + `index_errors` (the source of
/// truth) — *not* an independently stored field. `Failed` has precedence:
/// any non-empty `index_errors` short-circuits to `Failed`; otherwise the
/// stage advances through the locked progression matching the verified
/// 7-bit `VideoIndexStatus`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default, IsVariant, Display)]
#[display("{}", self.as_str())]
pub enum VideoIndexStage {
  /// No stage bits set yet.
  #[default]
  Pending,
  /// `PROBED`.
  Probed,
  /// `PROBED | SCENE_DETECTED`.
  SceneDetected,
  /// + `KEYFRAME_EXTRACTED`.
  KeyframeExtracted,
  /// + at least one of `VLM_ANALYZED` / `APPLE_VISION_ANALYZED`.
  Analyzed,
  /// + at least one of `TEXT_EMBEDDING_FINISHED` / `SCENE_EMBEDDING_FINISHED`.
  Embedded,
  /// All `is_fully_indexed()` bits set.
  Done,
  /// `index_errors` non-empty (precedence over any progression).
  Failed,
}

impl VideoIndexStage {
  /// Stable snake_case slug — the canonical string form of every variant.
  #[inline(always)]
  pub const fn as_str(&self) -> &'static str {
    match self {
      Self::Pending => "pending",
      Self::Probed => "probed",
      Self::SceneDetected => "scene_detected",
      Self::KeyframeExtracted => "keyframe_extracted",
      Self::Analyzed => "analyzed",
      Self::Embedded => "embedded",
      Self::Done => "done",
      Self::Failed => "failed",
    }
  }
  /// Inverse of [`as_str`](Self::as_str). Returns `None` for any input
  /// that isn't an exact match of one of the slugs.
  #[inline]
  pub fn from_str(s: &str) -> Option<Self> {
    Some(match s {
      "pending" => Self::Pending,
      "probed" => Self::Probed,
      "scene_detected" => Self::SceneDetected,
      "keyframe_extracted" => Self::KeyframeExtracted,
      "analyzed" => Self::Analyzed,
      "embedded" => Self::Embedded,
      "done" => Self::Done,
      "failed" => Self::Failed,
      _ => return None,
    })
  }
}

// The stage-derivation methods take `&[ErrorInfo]`, which is itself
// `feature = "alloc"`-gated. Gate the whole impl block accordingly —
// the bare `VideoIndexStage` enum + `IsVariant` predicates remain
// available in pure no-std no-alloc.
#[cfg(any(feature = "std", feature = "alloc"))]
#[cfg_attr(docsrs, doc(cfg(any(feature = "std", feature = "alloc"))))]
impl VideoIndexStage {
  /// Map a video-pipeline `ErrorCode` to its stage success bit, so a
  /// retained error whose corresponding bit is now set can be filtered
  /// out as **stale** (the retry succeeded after this error landed in
  /// the history). Returns `None` for errors with no clean stage
  /// mapping — those are always treated as live.
  fn error_stage_bit(code: ErrorCode) -> Option<VideoIndexStatus> {
    use VideoIndexStatus as S;
    match code {
      ErrorCode::ProbeCorrupt
      | ErrorCode::ProbeUnsupportedFormat
      | ErrorCode::ProbeNoVideoStream
      | ErrorCode::ProbeNoAudioStream => Some(S::PROBED),
      ErrorCode::SceneDetectionFailed | ErrorCode::SceneDetectionModelError => {
        Some(S::SCENE_DETECTED)
      }
      ErrorCode::VlmFailed | ErrorCode::VlmModelError => Some(S::VLM_ANALYZED),
      ErrorCode::AppleVisionFailed | ErrorCode::AppleVisionRequestFailed => {
        Some(S::APPLE_VISION_ANALYZED)
      }
      ErrorCode::EmbeddingFailed
      | ErrorCode::EmbeddingModelError
      | ErrorCode::EmbeddingModelLoadFailed
      | ErrorCode::EmbeddingPreprocessFailed
      | ErrorCode::EmbeddingInferenceFailed
      | ErrorCode::EmbeddingOutputInvalid => {
        // Either embedding stage clears this error (the locked schema
        // treats them as equivalent embedding completion signals).
        Some(S::TEXT_EMBEDDING_FINISHED | S::SCENE_EMBEDDING_FINISHED)
      }
      _ => None,
    }
  }

  /// Is the error currently **live** against `status`? An error is
  /// considered resolved (stale) iff its mapped stage success bit is set
  /// in `status` — i.e. a retry of that stage has since landed
  /// successfully.
  fn is_live(status: VideoIndexStatus, e: &ErrorInfo) -> bool {
    match Self::error_stage_bit(e.code()) {
      // For OR'd masks, "stage succeeded" iff *any* of the bits are
      // set; this matches the OR semantics of the analyzed /
      // embedded stages where either producer satisfies the stage.
      Some(bit) => !status.intersects(bit),
      None => true,
    }
  }

  /// Derive the coarse stage from the verified-bit status + the
  /// structured `index_errors` history. **Failed** precedence applies
  /// only to *live* errors (errors whose stage success bit isn't set —
  /// see `VideoIndexStage::is_live`); a successful retry clears a
  /// stale error without requiring the caller to mutate the history.
  ///
  /// The non-failed walk is **contiguous**: each next stage requires
  /// its *prerequisite* bits to be set, so an out-of-order bit (e.g.
  /// `TEXT_EMBEDDING_FINISHED` without `KEYFRAME_EXTRACTED`) does not
  /// jump to `Embedded` — it stays at the furthest contiguous stage.
  pub fn from_status(status: VideoIndexStatus, errors: &[ErrorInfo]) -> Self {
    use VideoIndexStatus as S;
    if errors.iter().any(|e| Self::is_live(status, e)) {
      return Self::Failed;
    }
    if status.is_fully_indexed() {
      return Self::Done;
    }
    // Contiguous stage walk — return at the first prerequisite gap.
    if !status.contains(S::PROBED) {
      return Self::Pending;
    }
    if !status.contains(S::SCENE_DETECTED) {
      return Self::Probed;
    }
    if !status.contains(S::KEYFRAME_EXTRACTED) {
      return Self::SceneDetected;
    }
    if !status.intersects(S::VLM_ANALYZED | S::APPLE_VISION_ANALYZED) {
      return Self::KeyframeExtracted;
    }
    if !status.intersects(S::TEXT_EMBEDDING_FINISHED | S::SCENE_EMBEDDING_FINISHED) {
      return Self::Analyzed;
    }
    Self::Embedded
  }
}

// ===========================================================================
// AudioIndexStage — derived from the verified 11-bit ProcessingStage
// ===========================================================================

/// Coarse derived stage for an `AudioTrack`'s indexing lifecycle.
///
/// Derived from [`AudioIndexStatus`] (the real 11-bit `ProcessingStage` from
/// `findit-proto::database::audio`) + `index_errors`. `Failed` precedence.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default, IsVariant, Display)]
#[display("{}", self.as_str())]
pub enum AudioIndexStage {
  #[default]
  Pending,
  /// `EXTRACTED` set.
  Extracted,
  /// + at least one of `CLASSIFIED` / `VAD_DONE` (analyzed for content).
  Analyzed,
  /// + `STT_DONE` (whisper transcript landed).
  Transcribed,
  /// + `SPEAKER_DONE` (pyannote / dia diarization landed).
  Diarized,
  /// + `TEXT_EMBED` (embedding pushed to LanceDB).
  Embedded,
  /// All `is_fully_indexed()` bits set.
  Done,
  Failed,
}

impl AudioIndexStage {
  /// Stable snake_case slug — the canonical string form of every variant.
  #[inline(always)]
  pub const fn as_str(&self) -> &'static str {
    match self {
      Self::Pending => "pending",
      Self::Extracted => "extracted",
      Self::Analyzed => "analyzed",
      Self::Transcribed => "transcribed",
      Self::Diarized => "diarized",
      Self::Embedded => "embedded",
      Self::Done => "done",
      Self::Failed => "failed",
    }
  }
  /// Inverse of [`as_str`](Self::as_str). Returns `None` for any input
  /// that isn't an exact match of one of the slugs.
  #[inline]
  pub fn from_str(s: &str) -> Option<Self> {
    Some(match s {
      "pending" => Self::Pending,
      "extracted" => Self::Extracted,
      "analyzed" => Self::Analyzed,
      "transcribed" => Self::Transcribed,
      "diarized" => Self::Diarized,
      "embedded" => Self::Embedded,
      "done" => Self::Done,
      "failed" => Self::Failed,
      _ => return None,
    })
  }
}

// Alloc-gated for the same reason as `VideoIndexStage`'s impl block.
#[cfg(any(feature = "std", feature = "alloc"))]
#[cfg_attr(docsrs, doc(cfg(any(feature = "std", feature = "alloc"))))]
impl AudioIndexStage {
  /// Map an audio-pipeline `ErrorCode` to its stage success bit. Same
  /// stale-error filtering rationale as [`VideoIndexStage::error_stage_bit`].
  fn error_stage_bit(code: ErrorCode) -> Option<AudioIndexStatus> {
    use AudioIndexStatus as S;
    match code {
      ErrorCode::ProbeCorrupt
      | ErrorCode::ProbeUnsupportedFormat
      | ErrorCode::ProbeNoAudioStream
      | ErrorCode::ProbeNoVideoStream => Some(S::EXTRACTED),
      ErrorCode::CedFailed | ErrorCode::CedRequestFailed | ErrorCode::CedModelError => {
        Some(S::CED_DONE)
      }
      ErrorCode::TranscriptionFailed | ErrorCode::TranscriptionModelError => Some(S::STT_DONE),
      ErrorCode::EmbeddingFailed
      | ErrorCode::EmbeddingModelError
      | ErrorCode::EmbeddingModelLoadFailed
      | ErrorCode::EmbeddingPreprocessFailed
      | ErrorCode::EmbeddingInferenceFailed
      | ErrorCode::EmbeddingOutputInvalid => Some(S::TEXT_EMBED),
      _ => None,
    }
  }

  fn is_live(status: AudioIndexStatus, e: &ErrorInfo) -> bool {
    match Self::error_stage_bit(e.code()) {
      Some(bit) => !status.intersects(bit),
      None => true,
    }
  }

  /// Derive the coarse stage from the verified 11-bit status + structured
  /// `index_errors`. `Failed` precedence applies only to live errors; the
  /// non-failed walk is contiguous (each later stage requires its
  /// prerequisite stage's bits to be set, matching the locked
  /// pipeline order).
  pub fn from_status(status: AudioIndexStatus, errors: &[ErrorInfo]) -> Self {
    use AudioIndexStatus as S;
    if errors.iter().any(|e| Self::is_live(status, e)) {
      return Self::Failed;
    }
    if status.is_fully_indexed() {
      return Self::Done;
    }
    // Contiguous stage walk: EXTRACTED → (CLASSIFIED | VAD_DONE) →
    // STT_DONE → SPEAKER_DONE → TEXT_EMBED, with the secondary stages
    // (LLM/CED/CLAP/EBUR128/FPRINT) folded into Done. Each later
    // stage requires its predecessors.
    if !status.contains(S::EXTRACTED) {
      return Self::Pending;
    }
    if !status.intersects(S::CLASSIFIED | S::VAD_DONE) {
      return Self::Extracted;
    }
    if !status.contains(S::STT_DONE) {
      return Self::Analyzed;
    }
    if !status.contains(S::SPEAKER_DONE) {
      return Self::Transcribed;
    }
    if !status.contains(S::TEXT_EMBED) {
      return Self::Diarized;
    }
    Self::Embedded
  }
}

// ===========================================================================
// SubtitleIndexStage — derived
// ===========================================================================

/// Coarse derived stage for a `SubtitleTrack`'s indexing lifecycle. Derived
/// from [`SubtitleIndexStatus`] + `index_errors`; `Failed` precedence.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default, IsVariant, Display)]
#[display("{}", self.as_str())]
pub enum SubtitleIndexStage {
  #[default]
  Pending,
  /// `TRACKS_DISCOVERED`.
  TracksDiscovered,
  /// + `CUES_EXTRACTED`.
  CuesExtracted,
  /// + `OCR_DONE` (image-based only).
  Ocr,
  /// + `SEARCH_INDEXED`.
  SearchIndexed,
  /// All `is_fully_indexed()` bits set.
  Done,
  Failed,
}

impl SubtitleIndexStage {
  /// Stable snake_case slug — the canonical string form of every variant.
  #[inline(always)]
  pub const fn as_str(&self) -> &'static str {
    match self {
      Self::Pending => "pending",
      Self::TracksDiscovered => "tracks_discovered",
      Self::CuesExtracted => "cues_extracted",
      Self::Ocr => "ocr",
      Self::SearchIndexed => "search_indexed",
      Self::Done => "done",
      Self::Failed => "failed",
    }
  }
  /// Inverse of [`as_str`](Self::as_str). Returns `None` for any input
  /// that isn't an exact match of one of the slugs.
  #[inline]
  pub fn from_str(s: &str) -> Option<Self> {
    Some(match s {
      "pending" => Self::Pending,
      "tracks_discovered" => Self::TracksDiscovered,
      "cues_extracted" => Self::CuesExtracted,
      "ocr" => Self::Ocr,
      "search_indexed" => Self::SearchIndexed,
      "done" => Self::Done,
      "failed" => Self::Failed,
      _ => return None,
    })
  }
}

// Alloc-gated for the same reason as `VideoIndexStage`'s impl block.
#[cfg(any(feature = "std", feature = "alloc"))]
#[cfg_attr(docsrs, doc(cfg(any(feature = "std", feature = "alloc"))))]
impl SubtitleIndexStage {
  // `error_stage_bit` / `is_live` / `from_status` are the building
  // blocks of `SubtitleTrack::index_stage`, which lives behind the
  // `subtitle` feature gate. Keep the helpers compiled into every heap
  // tier so the enum's public surface and test suite remain stable
  // across feature combos; allow dead-code under a no-subtitle build.
  #[allow(dead_code)]
  /// Map a subtitle-pipeline `ErrorCode` to its stage success bit. Same
  /// stale-error filtering rationale as the video / audio mappings.
  /// OCR-related errors map to `OCR_DONE` only when the caller asserts
  /// the track *requires* OCR (see [`SubtitleIndexStage::from_status`]).
  fn error_stage_bit(code: ErrorCode, requires_ocr: bool) -> Option<SubtitleIndexStatus> {
    use SubtitleIndexStatus as S;
    match code {
      // Discovery errors clear once probing succeeds (locked schema
      // uses the same family of `Probe*` codes across all kinds).
      ErrorCode::ProbeCorrupt
      | ErrorCode::ProbeUnsupportedFormat
      | ErrorCode::ProbeNoVideoStream => Some(S::TRACKS_DISCOVERED),
      // Apple Vision OCR — only meaningful for image-based tracks.
      ErrorCode::AppleVisionFailed | ErrorCode::AppleVisionRequestFailed if requires_ocr => {
        Some(S::OCR_DONE)
      }
      _ => None,
    }
  }

  #[allow(dead_code)]
  fn is_live(status: SubtitleIndexStatus, requires_ocr: bool, e: &ErrorInfo) -> bool {
    match Self::error_stage_bit(e.code(), requires_ocr) {
      Some(bit) => !status.intersects(bit),
      None => true,
    }
  }

  /// Derive the coarse stage from status + structured errors, taking
  /// `requires_ocr` into account.
  ///
  /// `requires_ocr` is `true` iff the subtitle codec is image-based
  /// (`mediaframe::SubtitleCodec::is_image_based() == Some(true)`).
  /// When `false`, `OCR_DONE` is **not** required for completion —
  /// a text subtitle that's `TRACKS_DISCOVERED | CUES_EXTRACTED |
  /// SEARCH_INDEXED` reaches `Done` without ever entering the
  /// `Ocr` stage. When `true`, OCR_DONE is required and the `Ocr`
  /// stage sits between `CuesExtracted` and `SearchIndexed`.
  ///
  /// Failed precedence applies only to *live* errors against the
  /// effective expected mask.
  ///
  /// `pub(crate)`: `requires_ocr` is an unbound caller-supplied bool, so
  /// exposing this publicly lets external code derive a `Done` stage for
  /// an unknown/image track without `OCR_DONE`. The only public stage
  /// path is [`SubtitleTrack::index_stage`], which binds `requires_ocr`
  /// from the track's codec/format internally.
  #[allow(dead_code)]
  pub(crate) fn from_status(
    status: SubtitleIndexStatus,
    requires_ocr: bool,
    errors: &[ErrorInfo],
  ) -> Self {
    use SubtitleIndexStatus as S;
    if errors
      .iter()
      .any(|e| Self::is_live(status, requires_ocr, e))
    {
      return Self::Failed;
    }
    let mask = SubtitleIndexStatus::fully_indexed_mask(requires_ocr);
    if status.contains(mask) {
      return Self::Done;
    }
    // Contiguous walk. OCR_DONE is part of the chain only when
    // requires_ocr; otherwise the chain is
    // TRACKS_DISCOVERED → CUES_EXTRACTED → SEARCH_INDEXED.
    if !status.contains(S::TRACKS_DISCOVERED) {
      return Self::Pending;
    }
    if !status.contains(S::CUES_EXTRACTED) {
      return Self::TracksDiscovered;
    }
    if requires_ocr && !status.contains(S::OCR_DONE) {
      return Self::CuesExtracted;
    }
    if !status.contains(S::SEARCH_INDEXED) {
      // Without OCR in the chain, after CUES_EXTRACTED the next
      // stage is search indexing directly.
      return if requires_ocr {
        Self::Ocr
      } else {
        Self::CuesExtracted
      };
    }
    Self::SearchIndexed
  }
}

// ===========================================================================
// Tests
// ===========================================================================

// `as_str` / `from_str` roundtrip tests — pure no-std, no heap.
// Asserts `from_str(as_str(v)) == Some(v)` for every variant of every
// unit-only enum in this module. The slug surface is locked here too:
// renaming a slug is a wire/storage break, and a missing variant would
// silently fail `Some(_)` matching.
#[cfg(test)]
mod slug_tests {
  use super::*;

  #[test]
  fn media_kind_slug_roundtrip() {
    for v in [MediaKind::Video, MediaKind::Audio] {
      assert_eq!(MediaKind::from_str(v.as_str()), Some(v), "{v:?}");
    }
    assert_eq!(MediaKind::from_str("not_a_slug"), None);
  }

  #[test]
  fn scene_detector_slug_roundtrip() {
    for v in [
      SceneDetector::Histogram,
      SceneDetector::Phash,
      SceneDetector::Threshold,
      SceneDetector::Content,
      SceneDetector::Adaptive,
      SceneDetector::Manual,
    ] {
      assert_eq!(SceneDetector::from_str(v.as_str()), Some(v), "{v:?}");
    }
    assert_eq!(SceneDetector::from_str("not_a_slug"), None);
  }

  #[test]
  fn keyframe_extractor_slug_roundtrip() {
    for v in [
      KeyframeExtractor::Histogram,
      KeyframeExtractor::Phash,
      KeyframeExtractor::Threshold,
      KeyframeExtractor::Content,
      KeyframeExtractor::Adaptive,
      KeyframeExtractor::CompositeQuality,
      KeyframeExtractor::Interval,
      KeyframeExtractor::IFrame,
      KeyframeExtractor::SceneRepresentative,
      KeyframeExtractor::Manual,
    ] {
      assert_eq!(KeyframeExtractor::from_str(v.as_str()), Some(v), "{v:?}");
    }
    assert_eq!(KeyframeExtractor::from_str("iframe"), None);
    assert_eq!(KeyframeExtractor::from_str("not_a_slug"), None);
  }

  #[test]
  fn subtitle_kind_slug_roundtrip() {
    for v in [
      SubtitleKind::FullDialogue,
      SubtitleKind::ForcedNarrative,
      SubtitleKind::CommentaryText,
    ] {
      assert_eq!(SubtitleKind::from_str(v.as_str()), Some(v), "{v:?}");
    }
    assert_eq!(SubtitleKind::from_str("not_a_slug"), None);
  }

  #[test]
  fn audio_content_kind_slug_roundtrip() {
    for v in [
      AudioContentKind::Speech,
      AudioContentKind::Music,
      AudioContentKind::Mixed,
      AudioContentKind::Silence,
    ] {
      assert_eq!(AudioContentKind::from_str(v.as_str()), Some(v), "{v:?}");
    }
    assert_eq!(AudioContentKind::from_str("not_a_slug"), None);
  }

  #[test]
  fn scan_status_slug_roundtrip() {
    for v in [ScanStatus::Ok, ScanStatus::Partial, ScanStatus::Failed] {
      assert_eq!(ScanStatus::from_str(v.as_str()), Some(v), "{v:?}");
    }
    assert_eq!(ScanStatus::from_str("not_a_slug"), None);
  }

  #[test]
  fn video_index_stage_slug_roundtrip() {
    for v in [
      VideoIndexStage::Pending,
      VideoIndexStage::Probed,
      VideoIndexStage::SceneDetected,
      VideoIndexStage::KeyframeExtracted,
      VideoIndexStage::Analyzed,
      VideoIndexStage::Embedded,
      VideoIndexStage::Done,
      VideoIndexStage::Failed,
    ] {
      assert_eq!(VideoIndexStage::from_str(v.as_str()), Some(v), "{v:?}");
    }
    assert_eq!(VideoIndexStage::from_str("not_a_slug"), None);
  }

  #[test]
  fn audio_index_stage_slug_roundtrip() {
    for v in [
      AudioIndexStage::Pending,
      AudioIndexStage::Extracted,
      AudioIndexStage::Analyzed,
      AudioIndexStage::Transcribed,
      AudioIndexStage::Diarized,
      AudioIndexStage::Embedded,
      AudioIndexStage::Done,
      AudioIndexStage::Failed,
    ] {
      assert_eq!(AudioIndexStage::from_str(v.as_str()), Some(v), "{v:?}");
    }
    assert_eq!(AudioIndexStage::from_str("not_a_slug"), None);
  }

  #[test]
  fn subtitle_index_stage_slug_roundtrip() {
    for v in [
      SubtitleIndexStage::Pending,
      SubtitleIndexStage::TracksDiscovered,
      SubtitleIndexStage::CuesExtracted,
      SubtitleIndexStage::Ocr,
      SubtitleIndexStage::SearchIndexed,
      SubtitleIndexStage::Done,
      SubtitleIndexStage::Failed,
    ] {
      assert_eq!(SubtitleIndexStage::from_str(v.as_str()), Some(v), "{v:?}");
    }
    assert_eq!(SubtitleIndexStage::from_str("not_a_slug"), None);
  }
}

// Tests exercise the `from_status` methods (which take `&[ErrorInfo]`)
// and therefore need heap-tier features. Gated on `any(std, alloc)`.
#[cfg(all(test, any(feature = "std", feature = "alloc")))]
mod tests {
  use super::*;

  #[test]
  fn media_kind_default_video() {
    assert_eq!(MediaKind::default(), MediaKind::Video);
  }

  #[test]
  fn keyframe_extractor_superset_of_scene_detector() {
    // KeyframeExtractor must carry every SceneDetector variant — a
    // scene-detector boundary frame is also a keyframe.
    let _ = SceneDetector::Histogram;
    let _ = KeyframeExtractor::Histogram;
    let _ = KeyframeExtractor::Phash;
    let _ = KeyframeExtractor::Threshold;
    let _ = KeyframeExtractor::Content;
    let _ = KeyframeExtractor::Adaptive;
    let _ = KeyframeExtractor::Manual;
    // ...plus its own variants:
    let _ = KeyframeExtractor::CompositeQuality;
    let _ = KeyframeExtractor::Interval;
    let _ = KeyframeExtractor::IFrame;
    let _ = KeyframeExtractor::SceneRepresentative;
  }

  /// One stale `ProbeCorrupt` error that should be filtered by the
  /// live-error check once `PROBED` succeeds.
  fn probe_error() -> std::vec::Vec<ErrorInfo> {
    std::vec![ErrorInfo::code_only(ErrorCode::ProbeCorrupt)]
  }

  #[test]
  fn video_index_stage_progression() {
    use VideoIndexStatus as S;
    let no_err: &[ErrorInfo] = &[];
    assert_eq!(
      VideoIndexStage::from_status(S::empty(), no_err),
      VideoIndexStage::Pending
    );
    assert_eq!(
      VideoIndexStage::from_status(S::PROBED, no_err),
      VideoIndexStage::Probed
    );
    assert_eq!(
      VideoIndexStage::from_status(S::PROBED | S::SCENE_DETECTED, no_err),
      VideoIndexStage::SceneDetected
    );
    assert_eq!(
      VideoIndexStage::from_status(
        S::PROBED | S::SCENE_DETECTED | S::KEYFRAME_EXTRACTED,
        no_err
      ),
      VideoIndexStage::KeyframeExtracted
    );
    assert_eq!(
      VideoIndexStage::from_status(
        S::PROBED | S::SCENE_DETECTED | S::KEYFRAME_EXTRACTED | S::VLM_ANALYZED,
        no_err
      ),
      VideoIndexStage::Analyzed
    );
    assert_eq!(
      VideoIndexStage::from_status(
        S::PROBED
          | S::SCENE_DETECTED
          | S::KEYFRAME_EXTRACTED
          | S::APPLE_VISION_ANALYZED
          | S::TEXT_EMBEDDING_FINISHED,
        no_err
      ),
      VideoIndexStage::Embedded
    );
    assert_eq!(
      VideoIndexStage::from_status(S::fully_indexed_mask(), no_err),
      VideoIndexStage::Done
    );
  }

  #[test]
  fn video_index_stage_contiguous_walk_does_not_jump_on_out_of_order_bits() {
    // Regression for Codex round-1 finding #2: a stray
    // TEXT_EMBEDDING_FINISHED bit without the prerequisite chain
    // (PROBED | SCENE_DETECTED | KEYFRAME_EXTRACTED | analyzed) must
    // NOT report `Embedded` — the contiguous-walk rule pins the
    // stage at the furthest gap-free progression.
    use VideoIndexStatus as S;
    let no_err: &[ErrorInfo] = &[];
    let stray = S::TEXT_EMBEDDING_FINISHED; // nothing else set
    assert_eq!(
      VideoIndexStage::from_status(stray, no_err),
      VideoIndexStage::Pending,
      "stray late bit must not advance stage"
    );
    // PROBED set, but everything else is the stray late bit:
    assert_eq!(
      VideoIndexStage::from_status(S::PROBED | S::TEXT_EMBEDDING_FINISHED, no_err),
      VideoIndexStage::Probed,
    );
  }

  #[test]
  fn video_index_stage_failed_precedence_on_live_errors_only() {
    // Failed precedence applies to live errors (stage success bit
    // not set). A stale error whose stage has since succeeded must
    // NOT mark the track Failed.
    use VideoIndexStatus as S;
    // Live error: PROBED not set → ProbeCorrupt is live.
    assert_eq!(
      VideoIndexStage::from_status(S::empty(), &probe_error()),
      VideoIndexStage::Failed
    );
    // Stale error: PROBED is set → ProbeCorrupt has been resolved.
    assert_eq!(
      VideoIndexStage::from_status(S::PROBED, &probe_error()),
      VideoIndexStage::Probed,
      "successful retry must clear stale stage errors"
    );
    // Mix: stale ProbeCorrupt + live SceneDetectionFailed → Failed.
    let mixed = std::vec![
      ErrorInfo::code_only(ErrorCode::ProbeCorrupt),
      ErrorInfo::code_only(ErrorCode::SceneDetectionFailed),
    ];
    assert_eq!(
      VideoIndexStage::from_status(S::PROBED, &mixed),
      VideoIndexStage::Failed,
    );
  }

  #[test]
  fn audio_index_stage_progression() {
    use AudioIndexStatus as S;
    let no_err: &[ErrorInfo] = &[];
    assert_eq!(
      AudioIndexStage::from_status(S::empty(), no_err),
      AudioIndexStage::Pending
    );
    assert_eq!(
      AudioIndexStage::from_status(S::EXTRACTED, no_err),
      AudioIndexStage::Extracted
    );
    assert_eq!(
      AudioIndexStage::from_status(S::EXTRACTED | S::VAD_DONE, no_err),
      AudioIndexStage::Analyzed
    );
    assert_eq!(
      AudioIndexStage::from_status(
        S::EXTRACTED | S::CLASSIFIED | S::VAD_DONE | S::STT_DONE,
        no_err
      ),
      AudioIndexStage::Transcribed
    );
    assert_eq!(
      AudioIndexStage::from_status(
        S::EXTRACTED | S::CLASSIFIED | S::VAD_DONE | S::STT_DONE | S::SPEAKER_DONE,
        no_err
      ),
      AudioIndexStage::Diarized
    );
    assert_eq!(
      AudioIndexStage::from_status(S::fully_indexed_mask(), no_err),
      AudioIndexStage::Done
    );
    // Live error on empty status → Failed.
    assert_eq!(
      AudioIndexStage::from_status(S::empty(), &probe_error()),
      AudioIndexStage::Failed
    );
  }

  #[test]
  fn audio_index_stage_contiguous_walk() {
    // STT_DONE without EXTRACTED must not jump to Transcribed.
    use AudioIndexStatus as S;
    let no_err: &[ErrorInfo] = &[];
    assert_eq!(
      AudioIndexStage::from_status(S::STT_DONE, no_err),
      AudioIndexStage::Pending,
    );
  }

  #[test]
  fn subtitle_text_track_reaches_done_without_ocr() {
    // Regression for Codex PR #10 finding #1: a text subtitle
    // (requires_ocr = false) must reach Done when
    // TRACKS_DISCOVERED | CUES_EXTRACTED | SEARCH_INDEXED are set,
    // *without* OCR_DONE.
    use SubtitleIndexStatus as S;
    let no_err: &[ErrorInfo] = &[];
    let status = S::TRACKS_DISCOVERED | S::CUES_EXTRACTED | S::SEARCH_INDEXED;
    assert_eq!(
      SubtitleIndexStage::from_status(status, /* requires_ocr = */ false, no_err),
      SubtitleIndexStage::Done,
    );
    // Same bits + requires_ocr = true must NOT be Done (OCR is
    // genuinely missing for image-based tracks).
    assert_ne!(
      SubtitleIndexStage::from_status(status, /* requires_ocr = */ true, no_err),
      SubtitleIndexStage::Done,
    );
  }

  #[test]
  fn subtitle_index_stage_progression() {
    use SubtitleIndexStatus as S;
    let no_err: &[ErrorInfo] = &[];
    assert_eq!(
      SubtitleIndexStage::from_status(S::empty(), true, no_err),
      SubtitleIndexStage::Pending
    );
    assert_eq!(
      SubtitleIndexStage::from_status(S::TRACKS_DISCOVERED, true, no_err),
      SubtitleIndexStage::TracksDiscovered
    );
    assert_eq!(
      SubtitleIndexStage::from_status(S::TRACKS_DISCOVERED | S::CUES_EXTRACTED, true, no_err),
      SubtitleIndexStage::CuesExtracted
    );
    assert_eq!(
      SubtitleIndexStage::from_status(
        S::TRACKS_DISCOVERED | S::CUES_EXTRACTED | S::OCR_DONE,
        true,
        no_err
      ),
      SubtitleIndexStage::Ocr
    );
    assert_eq!(
      SubtitleIndexStage::from_status(S::fully_indexed_mask(true), true, no_err),
      SubtitleIndexStage::Done
    );
    assert_eq!(
      SubtitleIndexStage::from_status(S::empty(), true, &probe_error()),
      SubtitleIndexStage::Failed
    );
  }
}