kcode-k1-audio-classification-format 0.3.0

Binary formats for K1 audio-classification events and fragments
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
use serde::{Deserialize, Serialize};
use std::fmt::{Display, Formatter};
use std::path::{Component, Path, PathBuf};

pub use kcode_k1_transaction_id::TxId;
pub use kcode_speaker_v3_analysis::{ExecutedAnalysis, FeatureVector24, LocalSpeakerLabel};

const EVENT_VERSION: u8 = 3;
const QUEUE_TAG: u8 = 1;
const PROCESSED_TAG: u8 = 2;
const FAILED_TAG: u8 = 3;
const DISCARDED_TAG: u8 = 4;
const CONFIRMED_TAG: u8 = 5;
const FRAGMENT_VERSION: u8 = 1;
const STAGED_KIND: u8 = 1;
const FINAL_KIND: u8 = 2;
const HEADER_LEN: usize = 16;
const ANALYSIS_SLOT_OFFSET: usize = 16;
const CONFIRMATION_SLOT_OFFSET: usize = 32;
const BODY_OFFSET: usize = 48;
const BASE64_ALPHABET: &[u8; 64] =
    b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum AnalysisStageV1 {
    GeminiTranscript,
    TerraLabels,
    GeminiFeatures,
    TerraStructuring,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct QueueV2 {
    #[serde(with = "txid_serde")]
    pub audio_object_id: TxId,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ProcessedV1 {
    #[serde(with = "txid_serde")]
    pub queue_id: TxId,
    #[serde(with = "txid_serde")]
    pub audio_object_id: TxId,
    pub analysis: ExecutedAnalysis,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct FailedV1 {
    #[serde(with = "txid_serde")]
    pub queue_id: TxId,
    #[serde(with = "txid_serde")]
    pub audio_object_id: TxId,
    pub final_stage: AnalysisStageV1,
    pub final_error: String,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct DiscardedV1 {
    #[serde(with = "txid_serde")]
    pub failed_queue_id: TxId,
    #[serde(with = "txid_serde")]
    pub audio_object_id: TxId,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ConfirmedSpeakerV1 {
    pub speaker: LocalSpeakerLabel,
    pub person_id: String,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ConfirmedV1 {
    #[serde(with = "txid_serde")]
    pub queue_id: TxId,
    #[serde(with = "txid_serde")]
    pub audio_object_id: TxId,
    #[serde(with = "txid_serde")]
    pub analysis_txid: TxId,
    pub speakers: Vec<ConfirmedSpeakerV1>,
}

#[allow(clippy::large_enum_variant)]
#[derive(Debug, Clone, PartialEq)]
pub enum AudioClassificationEventV2 {
    Queue(QueueV2),
    Processed(ProcessedV1),
    Failed(FailedV1),
    Discarded(DiscardedV1),
    Confirmed(ConfirmedV1),
}

#[derive(Debug, Clone, PartialEq)]
pub struct StagedSpeakerV1 {
    pub speaker: LocalSpeakerLabel,
    pub language: String,
    pub features: FeatureVector24,
    pub usable_for_training: bool,
}

#[derive(Debug, Clone, PartialEq)]
pub struct StagedFragmentV1 {
    pub analysis_txid: TxId,
    pub transcript: String,
    pub speakers: Vec<StagedSpeakerV1>,
}

#[derive(Debug, Clone, PartialEq)]
pub struct FinalSpeakerV1 {
    pub speaker: LocalSpeakerLabel,
    pub person_id: String,
    pub language: String,
    pub features: FeatureVector24,
    pub usable_for_training: bool,
}

#[derive(Debug, Clone, PartialEq)]
pub struct FinalFragmentV1 {
    pub analysis_txid: TxId,
    pub confirmation_txid: TxId,
    pub transcript: String,
    pub speakers: Vec<FinalSpeakerV1>,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum FormatError {
    Truncated,
    LengthOverflow,
    UnsupportedVersion(u8),
    UnknownEventTag(u8),
    InvalidEventBody,
    InvalidFragmentKind(u8),
    NonZeroReserved,
    NonZeroPadding,
    NonZeroStagedConfirmation,
    InvalidTxIdSlotLength(usize),
    InvalidUtf8,
    InvalidSpeakerLabel,
    InvalidFeatureBody,
    InvalidBoolean(u8),
    TrailingBytes,
    InvalidPath,
}

impl Display for FormatError {
    fn fmt(&self, formatter: &mut Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Truncated => formatter.write_str("truncated input"),
            Self::LengthOverflow => formatter.write_str("encoded length overflow"),
            Self::UnsupportedVersion(version) => {
                write!(formatter, "unsupported format version {version}")
            }
            Self::UnknownEventTag(tag) => write!(formatter, "unknown event tag {tag}"),
            Self::InvalidEventBody => formatter.write_str("invalid event body"),
            Self::InvalidFragmentKind(kind) => write!(formatter, "invalid fragment kind {kind}"),
            Self::NonZeroReserved => formatter.write_str("nonzero reserved bytes"),
            Self::NonZeroPadding => formatter.write_str("nonzero transaction ID slot padding"),
            Self::NonZeroStagedConfirmation => {
                formatter.write_str("nonzero staged confirmation slot")
            }
            Self::InvalidTxIdSlotLength(length) => {
                write!(formatter, "invalid transaction ID slot length {length}")
            }
            Self::InvalidUtf8 => formatter.write_str("invalid UTF-8"),
            Self::InvalidSpeakerLabel => formatter.write_str("invalid speaker label"),
            Self::InvalidFeatureBody => formatter.write_str("invalid feature body"),
            Self::InvalidBoolean(value) => write!(formatter, "invalid boolean byte {value}"),
            Self::TrailingBytes => formatter.write_str("trailing bytes"),
            Self::InvalidPath => formatter.write_str("invalid transaction ID path"),
        }
    }
}
impl std::error::Error for FormatError {}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct TxIdSlot {
    txid: TxId,
}
impl TxIdSlot {
    pub const LEN: usize = 16;
    pub const PADDING_LEN: usize = 4;
    pub const fn new(txid: TxId) -> Self {
        Self { txid }
    }
    pub const fn txid(self) -> TxId {
        self.txid
    }
    pub fn encode(self) -> [u8; Self::LEN] {
        let mut encoded = [0_u8; Self::LEN];
        encoded[..12].copy_from_slice(self.txid.as_bytes());
        encoded
    }
    pub fn decode(bytes: &[u8]) -> Result<Self, FormatError> {
        if bytes.len() != Self::LEN {
            return Err(FormatError::InvalidTxIdSlotLength(bytes.len()));
        }
        if bytes[12..].iter().any(|byte| *byte != 0) {
            return Err(FormatError::NonZeroPadding);
        }
        let mut txid_bytes = [0_u8; 12];
        txid_bytes.copy_from_slice(&bytes[..12]);
        Ok(Self::new(TxId::from_bytes(txid_bytes)))
    }
}

pub fn encode_event(event: &AudioClassificationEventV2) -> Result<Vec<u8>, FormatError> {
    let (tag, body) = match event {
        AudioClassificationEventV2::Queue(value) => (QUEUE_TAG, postcard::to_allocvec(value)),
        AudioClassificationEventV2::Processed(value) => {
            (PROCESSED_TAG, postcard::to_allocvec(value))
        }
        AudioClassificationEventV2::Failed(value) => (FAILED_TAG, postcard::to_allocvec(value)),
        AudioClassificationEventV2::Discarded(value) => {
            (DISCARDED_TAG, postcard::to_allocvec(value))
        }
        AudioClassificationEventV2::Confirmed(value) => {
            (CONFIRMED_TAG, postcard::to_allocvec(value))
        }
    };
    let body = body.map_err(|_| FormatError::InvalidEventBody)?;
    let mut encoded = Vec::with_capacity(2 + body.len());
    encoded.push(EVENT_VERSION);
    encoded.push(tag);
    encoded.extend_from_slice(&body);
    Ok(encoded)
}
pub fn decode_event(bytes: &[u8]) -> Result<AudioClassificationEventV2, FormatError> {
    if bytes.len() < 2 {
        return Err(FormatError::Truncated);
    }
    if bytes[0] != EVENT_VERSION {
        return Err(FormatError::UnsupportedVersion(bytes[0]));
    }
    match bytes[1] {
        QUEUE_TAG => decode_event_body(&bytes[2..]).map(AudioClassificationEventV2::Queue),
        PROCESSED_TAG => decode_event_body(&bytes[2..]).map(AudioClassificationEventV2::Processed),
        FAILED_TAG => decode_event_body(&bytes[2..]).map(AudioClassificationEventV2::Failed),
        DISCARDED_TAG => decode_event_body(&bytes[2..]).map(AudioClassificationEventV2::Discarded),
        CONFIRMED_TAG => decode_event_body(&bytes[2..]).map(AudioClassificationEventV2::Confirmed),
        tag => Err(FormatError::UnknownEventTag(tag)),
    }
}

pub fn encode_staged_fragment(value: &StagedFragmentV1) -> Result<Vec<u8>, FormatError> {
    let mut encoded = encode_fragment_prefix(STAGED_KIND, value.analysis_txid, None);
    append_string(&mut encoded, &value.transcript)?;
    append_length(&mut encoded, value.speakers.len())?;
    for speaker in &value.speakers {
        append_string(&mut encoded, &speaker.speaker.to_string())?;
        append_string(&mut encoded, &speaker.language)?;
        append_features(&mut encoded, &speaker.features)?;
        encoded.push(u8::from(speaker.usable_for_training));
    }
    Ok(encoded)
}
pub fn decode_staged_fragment(bytes: &[u8]) -> Result<StagedFragmentV1, FormatError> {
    let (analysis_txid, _) = decode_fragment_header(bytes, STAGED_KIND, false)?;
    let mut decoder = BodyDecoder::new(&bytes[BODY_OFFSET..]);
    let transcript = decoder.read_string()?;
    let speaker_count = decoder.read_count()?;
    let mut speakers = Vec::new();
    for _ in 0..speaker_count {
        speakers.push(StagedSpeakerV1 {
            speaker: decoder.read_speaker_label()?,
            language: decoder.read_string()?,
            features: decoder.read_features()?,
            usable_for_training: decoder.read_boolean()?,
        });
    }
    decoder.finish()?;
    Ok(StagedFragmentV1 {
        analysis_txid,
        transcript,
        speakers,
    })
}
pub fn encode_final_fragment(value: &FinalFragmentV1) -> Result<Vec<u8>, FormatError> {
    let mut encoded = encode_fragment_prefix(
        FINAL_KIND,
        value.analysis_txid,
        Some(value.confirmation_txid),
    );
    append_string(&mut encoded, &value.transcript)?;
    append_length(&mut encoded, value.speakers.len())?;
    for speaker in &value.speakers {
        append_string(&mut encoded, &speaker.speaker.to_string())?;
        append_string(&mut encoded, &speaker.person_id)?;
        append_string(&mut encoded, &speaker.language)?;
        append_features(&mut encoded, &speaker.features)?;
        encoded.push(u8::from(speaker.usable_for_training));
    }
    Ok(encoded)
}
pub fn decode_final_fragment(bytes: &[u8]) -> Result<FinalFragmentV1, FormatError> {
    let (analysis_txid, confirmation_txid) = decode_fragment_header(bytes, FINAL_KIND, true)?;
    let mut decoder = BodyDecoder::new(&bytes[BODY_OFFSET..]);
    let transcript = decoder.read_string()?;
    let speaker_count = decoder.read_count()?;
    let mut speakers = Vec::new();
    for _ in 0..speaker_count {
        speakers.push(FinalSpeakerV1 {
            speaker: decoder.read_speaker_label()?,
            person_id: decoder.read_string()?,
            language: decoder.read_string()?,
            features: decoder.read_features()?,
            usable_for_training: decoder.read_boolean()?,
        });
    }
    decoder.finish()?;
    Ok(FinalFragmentV1 {
        analysis_txid,
        confirmation_txid: confirmation_txid.expect("final header has a confirmation slot"),
        transcript,
        speakers,
    })
}

pub fn txid_path(txid: TxId) -> PathBuf {
    let encoded = encode_txid_base64(txid);
    let first = String::from_utf8(encoded[..1].to_vec()).expect("base64 is ASCII");
    let remaining = String::from_utf8(encoded[1..].to_vec()).expect("base64 is ASCII");
    PathBuf::from(first).join(format!("{remaining}.dat"))
}
pub fn txid_from_path(path: impl AsRef<Path>) -> Result<TxId, FormatError> {
    let mut components = path.as_ref().components();
    let first = normal_utf8_component(components.next())?;
    let filename = normal_utf8_component(components.next())?;
    if components.next().is_some() || first.len() != 1 {
        return Err(FormatError::InvalidPath);
    }
    let remaining = filename
        .strip_suffix(".dat")
        .ok_or(FormatError::InvalidPath)?;
    if remaining.len() != 15 {
        return Err(FormatError::InvalidPath);
    }
    let mut encoded = [0_u8; 16];
    encoded[0] = first.as_bytes()[0];
    encoded[1..].copy_from_slice(remaining.as_bytes());
    decode_txid_base64(encoded)
}

fn decode_event_body<T>(bytes: &[u8]) -> Result<T, FormatError>
where
    T: for<'de> Deserialize<'de>,
{
    let (value, remaining) =
        postcard::take_from_bytes(bytes).map_err(|_| FormatError::InvalidEventBody)?;
    if !remaining.is_empty() {
        return Err(FormatError::TrailingBytes);
    }
    Ok(value)
}
fn encode_fragment_prefix(kind: u8, analysis: TxId, confirmation: Option<TxId>) -> Vec<u8> {
    let mut encoded = vec![0_u8; BODY_OFFSET];
    encoded[0] = FRAGMENT_VERSION;
    encoded[1] = kind;
    encoded[ANALYSIS_SLOT_OFFSET..ANALYSIS_SLOT_OFFSET + TxIdSlot::LEN]
        .copy_from_slice(&TxIdSlot::new(analysis).encode());
    if let Some(confirmation) = confirmation {
        encoded[CONFIRMATION_SLOT_OFFSET..CONFIRMATION_SLOT_OFFSET + TxIdSlot::LEN]
            .copy_from_slice(&TxIdSlot::new(confirmation).encode());
    }
    encoded
}
fn decode_fragment_header(
    bytes: &[u8],
    expected_kind: u8,
    needs_confirmation: bool,
) -> Result<(TxId, Option<TxId>), FormatError> {
    if bytes.len() < BODY_OFFSET {
        return Err(FormatError::Truncated);
    }
    if bytes[0] != FRAGMENT_VERSION {
        return Err(FormatError::UnsupportedVersion(bytes[0]));
    }
    if bytes[1] != expected_kind {
        return Err(FormatError::InvalidFragmentKind(bytes[1]));
    }
    if bytes[2..HEADER_LEN].iter().any(|byte| *byte != 0) {
        return Err(FormatError::NonZeroReserved);
    }
    let analysis =
        TxIdSlot::decode(&bytes[ANALYSIS_SLOT_OFFSET..ANALYSIS_SLOT_OFFSET + TxIdSlot::LEN])?
            .txid();
    let confirmation_bytes =
        &bytes[CONFIRMATION_SLOT_OFFSET..CONFIRMATION_SLOT_OFFSET + TxIdSlot::LEN];
    let confirmation = if needs_confirmation {
        Some(TxIdSlot::decode(confirmation_bytes)?.txid())
    } else {
        if confirmation_bytes.iter().any(|byte| *byte != 0) {
            return Err(FormatError::NonZeroStagedConfirmation);
        }
        None
    };
    Ok((analysis, confirmation))
}
fn append_length(encoded: &mut Vec<u8>, length: usize) -> Result<(), FormatError> {
    encoded.extend_from_slice(
        &u64::try_from(length)
            .map_err(|_| FormatError::LengthOverflow)?
            .to_le_bytes(),
    );
    Ok(())
}
fn append_bytes(encoded: &mut Vec<u8>, bytes: &[u8]) -> Result<(), FormatError> {
    append_length(encoded, bytes.len())?;
    encoded.extend_from_slice(bytes);
    Ok(())
}
fn append_string(encoded: &mut Vec<u8>, value: &str) -> Result<(), FormatError> {
    append_bytes(encoded, value.as_bytes())
}
fn append_features(encoded: &mut Vec<u8>, features: &FeatureVector24) -> Result<(), FormatError> {
    append_bytes(
        encoded,
        &postcard::to_allocvec(features).map_err(|_| FormatError::InvalidFeatureBody)?,
    )
}

struct BodyDecoder<'a> {
    bytes: &'a [u8],
    position: usize,
}
impl<'a> BodyDecoder<'a> {
    fn new(bytes: &'a [u8]) -> Self {
        Self { bytes, position: 0 }
    }
    fn take(&mut self, length: usize) -> Result<&'a [u8], FormatError> {
        let end = self
            .position
            .checked_add(length)
            .ok_or(FormatError::LengthOverflow)?;
        let value = self
            .bytes
            .get(self.position..end)
            .ok_or(FormatError::Truncated)?;
        self.position = end;
        Ok(value)
    }
    fn read_u64(&mut self) -> Result<u64, FormatError> {
        let bytes = self.take(8)?;
        let mut value = [0_u8; 8];
        value.copy_from_slice(bytes);
        Ok(u64::from_le_bytes(value))
    }
    fn read_length(&mut self) -> Result<usize, FormatError> {
        usize::try_from(self.read_u64()?).map_err(|_| FormatError::LengthOverflow)
    }
    fn read_count(&mut self) -> Result<usize, FormatError> {
        self.read_length()
    }
    fn read_bytes(&mut self) -> Result<&'a [u8], FormatError> {
        let length = self.read_length()?;
        self.take(length)
    }
    fn read_string(&mut self) -> Result<String, FormatError> {
        Ok(std::str::from_utf8(self.read_bytes()?)
            .map_err(|_| FormatError::InvalidUtf8)?
            .to_owned())
    }
    fn read_speaker_label(&mut self) -> Result<LocalSpeakerLabel, FormatError> {
        self.read_string()?
            .parse()
            .map_err(|_| FormatError::InvalidSpeakerLabel)
    }
    fn read_features(&mut self) -> Result<FeatureVector24, FormatError> {
        let bytes = self.read_bytes()?;
        let (features, remaining) =
            postcard::take_from_bytes(bytes).map_err(|_| FormatError::InvalidFeatureBody)?;
        if !remaining.is_empty() {
            return Err(FormatError::InvalidFeatureBody);
        }
        Ok(features)
    }
    fn read_boolean(&mut self) -> Result<bool, FormatError> {
        match self.take(1)?[0] {
            0 => Ok(false),
            1 => Ok(true),
            value => Err(FormatError::InvalidBoolean(value)),
        }
    }
    fn finish(self) -> Result<(), FormatError> {
        if self.position == self.bytes.len() {
            Ok(())
        } else {
            Err(FormatError::TrailingBytes)
        }
    }
}
fn normal_utf8_component(component: Option<Component<'_>>) -> Result<&str, FormatError> {
    match component {
        Some(Component::Normal(value)) => value.to_str().ok_or(FormatError::InvalidPath),
        _ => Err(FormatError::InvalidPath),
    }
}
fn encode_txid_base64(txid: TxId) -> [u8; 16] {
    let bytes = txid.into_bytes();
    let mut encoded = [0_u8; 16];
    for group in 0..4 {
        let input = group * 3;
        let output = group * 4;
        encoded[output] = BASE64_ALPHABET[(bytes[input] >> 2) as usize];
        encoded[output + 1] =
            BASE64_ALPHABET[(((bytes[input] & 3) << 4) | (bytes[input + 1] >> 4)) as usize];
        encoded[output + 2] =
            BASE64_ALPHABET[(((bytes[input + 1] & 15) << 2) | (bytes[input + 2] >> 6)) as usize];
        encoded[output + 3] = BASE64_ALPHABET[(bytes[input + 2] & 63) as usize];
    }
    encoded
}
fn decode_txid_base64(encoded: [u8; 16]) -> Result<TxId, FormatError> {
    let mut bytes = [0_u8; 12];
    for group in 0..4 {
        let input = group * 4;
        let output = group * 3;
        let first = decode_base64_character(encoded[input])?;
        let second = decode_base64_character(encoded[input + 1])?;
        let third = decode_base64_character(encoded[input + 2])?;
        let fourth = decode_base64_character(encoded[input + 3])?;
        bytes[output] = (first << 2) | (second >> 4);
        bytes[output + 1] = (second << 4) | (third >> 2);
        bytes[output + 2] = (third << 6) | fourth;
    }
    Ok(TxId::from_bytes(bytes))
}
fn decode_base64_character(value: u8) -> Result<u8, FormatError> {
    match value {
        b'A'..=b'Z' => Ok(value - b'A'),
        b'a'..=b'z' => Ok(value - b'a' + 26),
        b'0'..=b'9' => Ok(value - b'0' + 52),
        b'-' => Ok(62),
        b'_' => Ok(63),
        _ => Err(FormatError::InvalidPath),
    }
}
mod txid_serde {
    use super::TxId;
    use serde::{Deserialize, Deserializer, Serialize, Serializer};
    pub fn serialize<S>(value: &TxId, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        value.into_bytes().serialize(serializer)
    }
    pub fn deserialize<'de, D>(deserializer: D) -> Result<TxId, D::Error>
    where
        D: Deserializer<'de>,
    {
        Ok(TxId::from_bytes(<[u8; 12]>::deserialize(deserializer)?))
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use kcode_speaker_v3_analysis::{
        AnalysisEnvelope, GeminiCohort, OggAudioMetadata, StructuredAnalysis, StructuredSpeaker,
        StructurerProvenance,
    };
    fn txid(seed: u8) -> TxId {
        let mut bytes = [0_u8; 12];
        for (index, byte) in bytes.iter_mut().enumerate() {
            *byte = seed.wrapping_add(index as u8);
        }
        TxId::from_bytes(bytes)
    }
    fn features(seed: f64) -> FeatureVector24 {
        FeatureVector24 {
            median_f0_hz: Some(seed),
            ..FeatureVector24::default()
        }
    }
    fn executed_analysis() -> ExecutedAnalysis {
        let mut ogg = vec![0_u8; 29];
        ogg[..4].copy_from_slice(b"OggS");
        ogg[26] = 1;
        ogg[27] = 1;
        let audio = OggAudioMetadata::from_bytes(&ogg, 1_250, Some("sample.ogg".to_owned()))
            .expect("valid Ogg metadata");
        let analysis = StructuredAnalysis {
            transcript: "Speaker 1".to_owned(),
            speakers: vec![StructuredSpeaker {
                speaker: LocalSpeakerLabel::new(1).expect("valid label"),
                language: "English".to_owned(),
                features: features(182.5),
                features_usable_for_training: true,
            }],
        };
        ExecutedAnalysis {
            envelope: AnalysisEnvelope {
                audio,
                analysis,
                gemini: GeminiCohort::new("gemini-3.1-pro"),
                structurer: StructurerProvenance::new("terra-structurer"),
            },
            label_extractor: StructurerProvenance::new("terra-labeler"),
        }
    }
    fn staged_fragment() -> StagedFragmentV1 {
        StagedFragmentV1 {
            analysis_txid: txid(20),
            transcript: "hello".to_owned(),
            speakers: vec![StagedSpeakerV1 {
                speaker: LocalSpeakerLabel::new(1).expect("valid label"),
                language: "English".to_owned(),
                features: features(201.25),
                usable_for_training: true,
            }],
        }
    }
    fn final_fragment() -> FinalFragmentV1 {
        FinalFragmentV1 {
            analysis_txid: txid(30),
            confirmation_txid: txid(40),
            transcript: "hello".to_owned(),
            speakers: vec![FinalSpeakerV1 {
                speaker: LocalSpeakerLabel::new(1).expect("valid label"),
                person_id: "person-1".to_owned(),
                language: "English".to_owned(),
                features: features(201.25),
                usable_for_training: false,
            }],
        }
    }
    #[test]
    fn txid_slot_roundtrips_and_rejects_nonzero_padding() {
        let id = txid(3);
        let encoded = TxIdSlot::new(id).encode();
        assert_eq!(encoded.len(), 16);
        assert_eq!(TxIdSlot::decode(&encoded).expect("slot").txid(), id);
        let mut corrupt = encoded;
        corrupt[12] = 1;
        assert_eq!(TxIdSlot::decode(&corrupt), Err(FormatError::NonZeroPadding));
    }
    #[test]
    fn events_use_v3_stable_tags_and_queue_has_only_audio_id() {
        let events = vec![
            AudioClassificationEventV2::Queue(QueueV2 {
                audio_object_id: txid(1),
            }),
            AudioClassificationEventV2::Processed(ProcessedV1 {
                queue_id: txid(3),
                audio_object_id: txid(4),
                analysis: executed_analysis(),
            }),
            AudioClassificationEventV2::Failed(FailedV1 {
                queue_id: txid(5),
                audio_object_id: txid(6),
                final_stage: AnalysisStageV1::GeminiFeatures,
                final_error: "failure".to_owned(),
            }),
            AudioClassificationEventV2::Discarded(DiscardedV1 {
                failed_queue_id: txid(7),
                audio_object_id: txid(8),
            }),
            AudioClassificationEventV2::Confirmed(ConfirmedV1 {
                queue_id: txid(9),
                audio_object_id: txid(10),
                analysis_txid: txid(11),
                speakers: vec![],
            }),
        ];
        for (index, event) in events.into_iter().enumerate() {
            let encoded = encode_event(&event).expect("encode event");
            assert_eq!(encoded[0], 3);
            assert_eq!(encoded[1], index as u8 + 1);
            assert_eq!(decode_event(&encoded), Ok(event));
        }
    }
    #[test]
    fn event_v2_and_invalid_bodies_are_rejected() {
        let event = AudioClassificationEventV2::Queue(QueueV2 {
            audio_object_id: txid(1),
        });
        let encoded = encode_event(&event).expect("encode");
        let mut v2 = encoded.clone();
        v2[0] = 2;
        assert_eq!(decode_event(&v2), Err(FormatError::UnsupportedVersion(2)));
        assert_eq!(
            decode_event(&encoded[..2]),
            Err(FormatError::InvalidEventBody)
        );
        let mut trailing = encoded;
        trailing.push(0);
        assert_eq!(decode_event(&trailing), Err(FormatError::TrailingBytes));
    }
    #[test]
    fn fragments_roundtrip_without_format_changes() {
        let staged = staged_fragment();
        let staged_bytes = encode_staged_fragment(&staged).expect("encode staged");
        assert_eq!(
            &staged_bytes[16..32],
            &TxIdSlot::new(staged.analysis_txid).encode()
        );
        assert_eq!(&staged_bytes[32..48], &[0; 16]);
        assert_eq!(decode_staged_fragment(&staged_bytes), Ok(staged));
        let final_value = final_fragment();
        let final_bytes = encode_final_fragment(&final_value).expect("encode final");
        assert_eq!(decode_final_fragment(&final_bytes), Ok(final_value));
    }
    #[test]
    fn fragment_corruption_is_rejected() {
        let mut bytes = encode_staged_fragment(&staged_fragment()).expect("encode");
        bytes[2] = 1;
        assert_eq!(
            decode_staged_fragment(&bytes),
            Err(FormatError::NonZeroReserved)
        );
    }
    #[test]
    fn paths_roundtrip() {
        let id = txid(99);
        assert_eq!(txid_from_path(txid_path(id)), Ok(id));
        assert_eq!(
            txid_from_path("A/invalid.dat"),
            Err(FormatError::InvalidPath)
        );
    }
}