j2k-transcode 0.7.0

JPEG-to-HTJ2K coefficient-domain transcode primitives for j2k
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
// SPDX-License-Identifier: MIT OR Apache-2.0
// j2k-coverage: shared-accelerator-host

use super::{ErrorMetrics, JpegToHtj2kCoefficientPath};

/// Aggregate report for multi-tile transcode.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct BatchTranscodeReport {
    /// Number of input tiles.
    pub tile_count: usize,
    /// Number of successfully encoded output tiles.
    pub successful_tiles: usize,
    /// Number of tile-local failures.
    pub failed_tiles: usize,
    /// Number of transformed components across successful extracted tiles.
    pub transformed_components: usize,
    /// Number of same-geometry reversible 5/3 batches submitted.
    pub reversible_dwt53_batches: usize,
    /// Number of reversible 5/3 component jobs in submitted batches.
    pub reversible_dwt53_batch_jobs: usize,
    /// Batch extraction time in microseconds.
    pub extract_us: u128,
    /// Batch DCT-to-wavelet time in microseconds.
    pub transform_us: u128,
    /// Batch HTJ2K encode time in microseconds.
    pub encode_us: u128,
    /// Detailed stage timings for the batch. Batch-accelerated 5/3 transform
    /// timings stay here instead of being copied into every tile report.
    pub timings: TranscodeTimingReport,
    /// Coefficient path used by the batch.
    pub coefficient_path: JpegToHtj2kCoefficientPath,
}

/// Stable profile request label for transcode batch telemetry.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TranscodeBatchProfileRequest {
    /// CPU-only transcode request.
    Cpu,
    /// Auto-routing request that may use an accelerator.
    MetalAuto,
    /// Explicit Metal request.
    MetalExplicit,
}

impl TranscodeBatchProfileRequest {
    /// Stable `request` label emitted in `j2k_profile` rows.
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Cpu => "cpu",
            Self::MetalAuto => "metal_auto",
            Self::MetalExplicit => "metal_explicit",
        }
    }

    /// Stable `transform_processor` label for this request and timing report.
    #[must_use]
    pub fn transform_processor(self, timings: &TranscodeTimingReport) -> &'static str {
        if matches!(self, Self::MetalAuto | Self::MetalExplicit)
            && timings.accelerator_work_observed()
        {
            "metal"
        } else {
            "cpu"
        }
    }

    /// Stable `path` label for this request and timing report.
    #[must_use]
    pub fn profile_path(self, timings: &TranscodeTimingReport) -> &'static str {
        if self.transform_processor(timings) != "metal" {
            return "cpu";
        }
        match self {
            Self::Cpu => "cpu",
            Self::MetalAuto => "auto",
            Self::MetalExplicit => "metal",
        }
    }
}

const TRANSCODE_PROFILE_FIELD_COUNT: usize = 65;

macro_rules! push_labels {
    ($builder:ident; $($key:literal => $value:expr),+ $(,)?) => {
        $($builder.label($key, $value)?;)+
    };
}

macro_rules! push_metrics {
    ($builder:ident; $($key:literal => $value:expr),+ $(,)?) => {
        $($builder.metric($key, $value)?;)+
    };
}

/// Shared transcode batch profile row fields.
#[derive(Debug, PartialEq, Eq)]
pub struct TranscodeBatchProfileRow {
    fields: Vec<(&'static str, String)>,
    path: &'static str,
}

pub(super) type TranscodeBatchProfileFields = Vec<(&'static str, String)>;

impl TranscodeBatchProfileRow {
    /// Builds bounded profile fields for a batch transcode report.
    pub fn new(
        report: &BatchTranscodeReport,
        context: impl AsRef<str>,
        request: TranscodeBatchProfileRequest,
    ) -> j2k_profile::ProfileResult<Self> {
        let timings = report.timings;
        let total_us = report
            .extract_us
            .checked_add(report.transform_us)
            .and_then(|value| value.checked_add(report.encode_us))
            .ok_or(j2k_profile::ProfileError::SizeOverflow {
                what: "transcode batch total profile time",
            })?;
        let transform_processor = request.transform_processor(&timings);
        let path = request.profile_path(&timings);
        let mut builder = TranscodeProfileRowBuilder::new()?;

        push_labels!(builder;
            "codec" => "transcode",
            "op" => "transcode_batch",
            "request" => request.as_str(),
            "path" => path,
            "pipeline" => "jpeg_to_htj2k",
            "context" => SanitizedContext(context.as_ref()),
            "coefficient_path" => coefficient_path_label(report.coefficient_path),
            "extract_processor" => "cpu",
            "transform_processor" => transform_processor,
            "encode_processor" => "cpu",
        );
        Self::push_batch_fields(&mut builder, report, total_us)?;
        Self::push_input_timing_fields(&mut builder, &timings)?;
        Self::push_dwt97_timing_fields(&mut builder, &timings)?;
        Self::push_transfer_fields(&mut builder, &timings)?;
        Self::push_encode_timing_fields(&mut builder, &timings)?;
        Self::push_accelerator_fields(&mut builder, &timings)?;

        Ok(Self {
            fields: builder.finish()?,
            path,
        })
    }

    fn push_batch_fields(
        builder: &mut TranscodeProfileRowBuilder,
        report: &BatchTranscodeReport,
        total_us: u128,
    ) -> j2k_profile::ProfileResult<()> {
        push_metrics!(builder;
            "tile_count" => report.tile_count,
            "successful_tiles" => report.successful_tiles,
            "failed_tiles" => report.failed_tiles,
            "transformed_components" => report.transformed_components,
            "reversible_dwt53_batches" => report.reversible_dwt53_batches,
            "reversible_dwt53_batch_jobs" => report.reversible_dwt53_batch_jobs,
            "extract_us" => report.extract_us,
            "transform_us" => report.transform_us,
            "encode_us" => report.encode_us,
            "total_us" => total_us,
        );
        Ok(())
    }

    fn push_input_timing_fields(
        builder: &mut TranscodeProfileRowBuilder,
        timings: &TranscodeTimingReport,
    ) -> j2k_profile::ProfileResult<()> {
        push_metrics!(builder;
            "source_raw_probe_us" => timings.source_raw_probe_us,
            "read_region_decode_us" => timings.read_region_decode_us,
            "compose_pad_us" => timings.compose_pad_us,
            "generated_jpeg_encode_us" => timings.generated_jpeg_encode_us,
            "jpeg_dct_extract_us" => timings.jpeg_dct_extract_us,
            "jpeg_dct_repack_us" => timings.jpeg_dct_repack_us,
            "dct_to_wavelet_total_us" => timings.dct_to_wavelet_total_us,
            "dct_to_wavelet_accelerator_us" => timings.dct_to_wavelet_accelerator_us,
            "dct_to_wavelet_cpu_fallback_us" => timings.dct_to_wavelet_cpu_fallback_us,
            "dwt_decompose_us" => timings.dwt_decompose_us,
        );
        Ok(())
    }

    fn push_dwt97_timing_fields(
        builder: &mut TranscodeProfileRowBuilder,
        timings: &TranscodeTimingReport,
    ) -> j2k_profile::ProfileResult<()> {
        push_metrics!(builder;
            "dwt97_batch_pack_upload_us" => timings.dwt97_batch_pack_upload_us,
            "dwt97_batch_pack_upload_transfers" => timings.dwt97_batch_pack_upload_transfers,
            "dwt97_batch_pack_upload_bytes" => timings.dwt97_batch_pack_upload_bytes,
            "dwt97_batch_resident_dct_handoff_count" => timings.dwt97_batch_resident_dct_handoff_count,
            "dwt97_batch_idct_row_lift_us" => timings.dwt97_batch_idct_row_lift_us,
            "dwt97_batch_column_lift_us" => timings.dwt97_batch_column_lift_us,
            "dwt97_batch_resident_dwt_handoff_count" => timings.dwt97_batch_resident_dwt_handoff_count,
            "dwt97_batch_quantize_codeblock_us" => timings.dwt97_batch_quantize_codeblock_us,
            "dwt97_batch_ht_encode_us" => timings.dwt97_batch_ht_encode_us,
            "dwt97_batch_ht_codeblock_dispatches" => timings.dwt97_batch_ht_codeblock_dispatches,
        );
        Ok(())
    }

    fn push_transfer_fields(
        builder: &mut TranscodeProfileRowBuilder,
        timings: &TranscodeTimingReport,
    ) -> j2k_profile::ProfileResult<()> {
        let device_to_host_transfer_count = timings
            .dwt97_batch_readback_transfers
            .checked_add(timings.dwt97_batch_ht_status_readback_transfers)
            .and_then(|value| value.checked_add(timings.dwt97_batch_ht_output_readback_transfers))
            .ok_or(j2k_profile::ProfileError::SizeOverflow {
                what: "device-to-host profile transfer count",
            })?;
        let device_to_host_transfer_bytes = timings
            .dwt97_batch_readback_bytes
            .checked_add(timings.dwt97_batch_ht_status_readback_bytes)
            .and_then(|value| value.checked_add(timings.dwt97_batch_ht_output_readback_bytes))
            .ok_or(j2k_profile::ProfileError::SizeOverflow {
                what: "device-to-host profile transfer bytes",
            })?;
        push_metrics!(builder;
            "dwt97_batch_ht_status_readback_us" => timings.dwt97_batch_ht_status_readback_us,
            "dwt97_batch_ht_status_readback_transfers" => timings.dwt97_batch_ht_status_readback_transfers,
            "dwt97_batch_ht_status_readback_bytes" => timings.dwt97_batch_ht_status_readback_bytes,
            "dwt97_batch_ht_output_readback_us" => timings.dwt97_batch_ht_output_readback_us,
            "dwt97_batch_ht_output_readback_transfers" => timings.dwt97_batch_ht_output_readback_transfers,
            "dwt97_batch_ht_output_readback_bytes" => timings.dwt97_batch_ht_output_readback_bytes,
            "dwt97_batch_readback_us" => timings.dwt97_batch_readback_us,
            "dwt97_batch_readback_transfers" => timings.dwt97_batch_readback_transfers,
            "dwt97_batch_readback_bytes" => timings.dwt97_batch_readback_bytes,
            "host_to_device_transfer_count" => timings.dwt97_batch_pack_upload_transfers,
            "host_to_device_transfer_bytes" => timings.dwt97_batch_pack_upload_bytes,
            "device_to_host_transfer_count" => device_to_host_transfer_count,
            "device_to_host_transfer_bytes" => device_to_host_transfer_bytes,
        );
        Ok(())
    }

    fn push_encode_timing_fields(
        builder: &mut TranscodeProfileRowBuilder,
        timings: &TranscodeTimingReport,
    ) -> j2k_profile::ProfileResult<()> {
        push_metrics!(builder;
            "htj2k_encode_us" => timings.htj2k_encode_us,
            "htj2k_encode_accelerator_dispatches" => timings.htj2k_encode_accelerator_dispatches,
            "htj2k_encode_ht_code_block_dispatches" => timings.htj2k_encode_ht_code_block_dispatches,
            "htj2k_encode_packetization_dispatches" => timings.htj2k_encode_packetization_dispatches,
            "component_count" => timings.component_count,
            "batch_count" => timings.batch_count,
            "batch_jobs" => timings.batch_jobs,
        );
        Ok(())
    }

    fn push_accelerator_fields(
        builder: &mut TranscodeProfileRowBuilder,
        timings: &TranscodeTimingReport,
    ) -> j2k_profile::ProfileResult<()> {
        push_metrics!(builder;
            "accelerator_attempts" => timings.accelerator_attempts,
            "accelerator_jobs" => timings.accelerator_jobs,
            "accelerator_dispatches" => timings.accelerator_dispatches,
            "accelerator_dispatched_jobs" => timings.accelerator_dispatched_jobs,
            "cpu_fallback_jobs" => timings.cpu_fallback_jobs,
        );
        Ok(())
    }

    /// Ordered profile row fields.
    #[must_use]
    pub fn fields(&self) -> &[(&'static str, String)] {
        &self.fields
    }

    /// Stable profile codec label.
    #[must_use]
    pub const fn codec(&self) -> &'static str {
        "transcode"
    }

    /// Stable profile operation label.
    #[must_use]
    pub const fn op(&self) -> &'static str {
        "transcode_batch"
    }

    /// Stable profile path label.
    #[must_use]
    pub const fn path(&self) -> &'static str {
        self.path
    }
}

struct TranscodeProfileRowBuilder {
    fields: TranscodeBatchProfileFields,
    limits: j2k_profile::ProfileLimits,
    input_bytes: usize,
    retained_bytes: usize,
}

impl TranscodeProfileRowBuilder {
    fn new() -> j2k_profile::ProfileResult<Self> {
        let limits = j2k_profile::ProfileLimits::default();
        if TRANSCODE_PROFILE_FIELD_COUNT > limits.max_fields() {
            return Err(j2k_profile::ProfileError::LimitExceeded {
                what: "transcode profile field count",
                requested: TRANSCODE_PROFILE_FIELD_COUNT,
                limit: limits.max_fields(),
            });
        }
        let mut fields = Vec::new();
        fields
            .try_reserve_exact(TRANSCODE_PROFILE_FIELD_COUNT)
            .map_err(|_| j2k_profile::ProfileError::AllocationFailed {
                what: "transcode profile field storage",
                requested: TRANSCODE_PROFILE_FIELD_COUNT,
            })?;
        let retained_bytes = fields
            .capacity()
            .checked_mul(core::mem::size_of::<(&'static str, String)>())
            .ok_or(j2k_profile::ProfileError::SizeOverflow {
                what: "transcode profile field storage",
            })?;
        if retained_bytes > limits.max_retained_bytes() {
            return Err(j2k_profile::ProfileError::LimitExceeded {
                what: "transcode profile retained bytes",
                requested: retained_bytes,
                limit: limits.max_retained_bytes(),
            });
        }
        Ok(Self {
            fields,
            limits,
            input_bytes: 0,
            retained_bytes,
        })
    }

    fn label(
        &mut self,
        key: &'static str,
        value: impl core::fmt::Display,
    ) -> j2k_profile::ProfileResult<()> {
        let field = j2k_profile::ProfileField::label_with_limits(key, value, self.limits)?;
        self.push(key, field.into_value())
    }

    fn metric(
        &mut self,
        key: &'static str,
        value: impl core::fmt::Display,
    ) -> j2k_profile::ProfileResult<()> {
        let field = j2k_profile::ProfileField::metric_with_limits(key, value, self.limits)?;
        self.push(key, field.into_value())
    }

    fn push(&mut self, key: &'static str, value: String) -> j2k_profile::ProfileResult<()> {
        let field_count =
            self.fields
                .len()
                .checked_add(1)
                .ok_or(j2k_profile::ProfileError::SizeOverflow {
                    what: "transcode profile field count",
                })?;
        if field_count > self.limits.max_fields() {
            return Err(j2k_profile::ProfileError::LimitExceeded {
                what: "transcode profile field count",
                requested: field_count,
                limit: self.limits.max_fields(),
            });
        }
        let input_bytes = self
            .input_bytes
            .checked_add(key.len())
            .and_then(|bytes| bytes.checked_add(value.len()))
            .ok_or(j2k_profile::ProfileError::SizeOverflow {
                what: "transcode profile input bytes",
            })?;
        if input_bytes > self.limits.max_input_bytes() {
            return Err(j2k_profile::ProfileError::LimitExceeded {
                what: "transcode profile input bytes",
                requested: input_bytes,
                limit: self.limits.max_input_bytes(),
            });
        }
        let retained_bytes = self.retained_bytes.checked_add(value.capacity()).ok_or(
            j2k_profile::ProfileError::SizeOverflow {
                what: "transcode profile retained bytes",
            },
        )?;
        if retained_bytes > self.limits.max_retained_bytes() {
            return Err(j2k_profile::ProfileError::LimitExceeded {
                what: "transcode profile retained bytes",
                requested: retained_bytes,
                limit: self.limits.max_retained_bytes(),
            });
        }
        if self.fields.len() == self.fields.capacity() {
            return Err(j2k_profile::ProfileError::InvalidInput {
                what: "transcode profile field reservation exhausted",
            });
        }
        self.fields.push((key, value));
        self.input_bytes = input_bytes;
        self.retained_bytes = retained_bytes;
        Ok(())
    }

    fn finish(self) -> j2k_profile::ProfileResult<TranscodeBatchProfileFields> {
        if self.fields.len() != TRANSCODE_PROFILE_FIELD_COUNT {
            return Err(j2k_profile::ProfileError::InvalidInput {
                what: "transcode profile field schema is incomplete",
            });
        }
        Ok(self.fields)
    }
}

struct SanitizedContext<'a>(&'a str);

impl core::fmt::Display for SanitizedContext<'_> {
    fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        let mut parts = self.0.split(' ');
        if let Some(first) = parts.next() {
            formatter.write_str(first)?;
        }
        for part in parts {
            formatter.write_str("_")?;
            formatter.write_str(part)?;
        }
        Ok(())
    }
}

const fn coefficient_path_label(path: JpegToHtj2kCoefficientPath) -> &'static str {
    match path {
        JpegToHtj2kCoefficientPath::IntegerDirect53 => "IntegerDirect53",
        JpegToHtj2kCoefficientPath::FloatDirectLinear53 => "FloatDirectLinear53",
        JpegToHtj2kCoefficientPath::FloatDirectLinear97 => "FloatDirectLinear97",
    }
}

impl BatchTranscodeReport {
    /// Builds bounded shared profile fields for a batch transcode report.
    pub fn profile_row(
        &self,
        context: impl AsRef<str>,
        request: TranscodeBatchProfileRequest,
    ) -> j2k_profile::ProfileResult<TranscodeBatchProfileRow> {
        TranscodeBatchProfileRow::new(self, context, request)
    }
}

/// Detailed timing and dispatch counters for JPEG-to-HTJ2K transcode.
///
/// Durations are wall-clock microseconds measured around the current Rust API
/// boundaries. Accelerator time includes backend submission and wait overhead
/// visible to this crate; backend-specific hardware counters are not exposed
/// here.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct TranscodeTimingReport {
    /// Raw compressed-tile probe/read time before JPEG DCT extraction.
    pub source_raw_probe_us: u128,
    /// Source region decode time for strip/retile workflows.
    pub read_region_decode_us: u128,
    /// Region compose/pad time for generated regular tiles.
    pub compose_pad_us: u128,
    /// JPEG encode time when the workflow generates regular JPEG tiles.
    pub generated_jpeg_encode_us: u128,
    /// JPEG DCT extraction time in microseconds.
    pub jpeg_dct_extract_us: u128,
    /// Time spent repacking integer DCT coefficients into float block grids.
    pub jpeg_dct_repack_us: u128,
    /// Total wall time spent producing DWT bands from JPEG DCT coefficients.
    pub dct_to_wavelet_total_us: u128,
    /// Wall time spent inside accelerator hook calls.
    pub dct_to_wavelet_accelerator_us: u128,
    /// Wall time spent in scalar CPU fallback transforms.
    pub dct_to_wavelet_cpu_fallback_us: u128,
    /// Time spent decomposing first-level DWT output into requested levels.
    pub dwt_decompose_us: u128,
    /// Backend 9/7 batch host pack/upload time in microseconds.
    pub dwt97_batch_pack_upload_us: u128,
    /// Logical host-to-device transfers during backend 9/7 batch pack/upload.
    pub dwt97_batch_pack_upload_transfers: usize,
    /// Host-to-device bytes during backend 9/7 batch pack/upload.
    pub dwt97_batch_pack_upload_bytes: u64,
    /// Resident JPEG DCT-grid descriptors validated during backend 9/7 batches.
    pub dwt97_batch_resident_dct_handoff_count: usize,
    /// Backend 9/7 batch IDCT plus horizontal row-lift time in microseconds.
    pub dwt97_batch_idct_row_lift_us: u128,
    /// Backend 9/7 batch vertical column-lift time in microseconds.
    pub dwt97_batch_column_lift_us: u128,
    /// Resident DWT subband descriptors validated during backend 9/7 batches.
    pub dwt97_batch_resident_dwt_handoff_count: usize,
    /// Backend 9/7 batch quantize/code-block layout time in microseconds.
    pub dwt97_batch_quantize_codeblock_us: u128,
    /// Backend 9/7 resident HT code-block encode time in microseconds.
    pub dwt97_batch_ht_encode_us: u128,
    /// Backend 9/7 resident HT cleanup-pass encode kernel time in microseconds.
    pub dwt97_batch_ht_kernel_us: u128,
    /// Backend 9/7 resident HT status-buffer device-to-host readback time in microseconds.
    pub dwt97_batch_ht_status_readback_us: u128,
    /// Logical device-to-host status readbacks after resident HT encode.
    pub dwt97_batch_ht_status_readback_transfers: usize,
    /// Device-to-host status bytes after resident HT encode.
    pub dwt97_batch_ht_status_readback_bytes: u64,
    /// Backend 9/7 resident HT encoded-byte compaction kernel time in microseconds.
    pub dwt97_batch_ht_compact_us: u128,
    /// Backend 9/7 resident HT compacted encoded-byte device-to-host readback time in microseconds.
    pub dwt97_batch_ht_output_readback_us: u128,
    /// Logical device-to-host output readbacks after resident HT compaction.
    pub dwt97_batch_ht_output_readback_transfers: usize,
    /// Device-to-host output bytes after resident HT compaction.
    pub dwt97_batch_ht_output_readback_bytes: u64,
    /// Backend 9/7 resident HT code-block encode dispatches.
    pub dwt97_batch_ht_codeblock_dispatches: usize,
    /// Backend 9/7 batch output readback/unpack time in microseconds.
    pub dwt97_batch_readback_us: u128,
    /// Logical device-to-host transfers during backend 9/7 batch output readback.
    pub dwt97_batch_readback_transfers: usize,
    /// Device-to-host bytes during backend 9/7 batch output readback.
    pub dwt97_batch_readback_bytes: u64,
    /// HTJ2K encode time in microseconds.
    pub htj2k_encode_us: u128,
    /// Encode-stage accelerator dispatches during HTJ2K encode.
    pub htj2k_encode_accelerator_dispatches: usize,
    /// HT cleanup code-block accelerator dispatches during HTJ2K encode.
    pub htj2k_encode_ht_code_block_dispatches: usize,
    /// Packetization accelerator dispatches during HTJ2K encode.
    pub htj2k_encode_packetization_dispatches: usize,
    /// Time spent writing compressed frames to a DICOM `PixelData` spool.
    pub dicom_spool_write_us: u128,
    /// Time spent writing final DICOM instances.
    pub dicom_final_write_us: u128,
    /// Number of source tiles represented by this timing report.
    pub tile_count: usize,
    /// Number of components transformed into wavelet bands.
    pub component_count: usize,
    /// Number of same-geometry transform batches offered to the accelerator.
    pub batch_count: usize,
    /// Number of component jobs in same-geometry transform batches.
    pub batch_jobs: usize,
    /// Number of accelerator hook calls.
    pub accelerator_attempts: usize,
    /// Number of component jobs offered through accelerator hook calls.
    pub accelerator_jobs: usize,
    /// Number of accelerator hook calls that returned an accelerated result.
    pub accelerator_dispatches: usize,
    /// Number of component jobs completed by accelerated results.
    pub accelerator_dispatched_jobs: usize,
    /// Number of component jobs completed by scalar CPU fallback transforms.
    pub cpu_fallback_jobs: usize,
}

impl TranscodeTimingReport {
    /// Returns true when the report contains evidence that accelerator-backed
    /// work executed for the transcode transform path.
    pub fn accelerator_work_observed(&self) -> bool {
        self.accelerator_dispatches > 0
            || self.dwt97_batch_pack_upload_transfers > 0
            || self.dwt97_batch_pack_upload_bytes > 0
            || self.dwt97_batch_resident_dct_handoff_count > 0
            || self.dwt97_batch_idct_row_lift_us > 0
            || self.dwt97_batch_column_lift_us > 0
            || self.dwt97_batch_resident_dwt_handoff_count > 0
            || self.dwt97_batch_quantize_codeblock_us > 0
            || self.dwt97_batch_ht_encode_us > 0
            || self.dwt97_batch_ht_kernel_us > 0
            || self.dwt97_batch_ht_compact_us > 0
            || self.dwt97_batch_ht_codeblock_dispatches > 0
            || self.dwt97_batch_readback_transfers > 0
            || self.dwt97_batch_readback_bytes > 0
            || self.dwt97_batch_ht_status_readback_transfers > 0
            || self.dwt97_batch_ht_status_readback_bytes > 0
            || self.dwt97_batch_ht_output_readback_transfers > 0
            || self.dwt97_batch_ht_output_readback_bytes > 0
    }

    pub(super) fn add_assign(&mut self, other: Self) {
        macro_rules! saturating_add_fields {
            ($($field:ident),+ $(,)?) => {
                $(
                    self.$field = self.$field.saturating_add(other.$field);
                )+
            };
        }

        saturating_add_fields!(
            source_raw_probe_us,
            read_region_decode_us,
            compose_pad_us,
            generated_jpeg_encode_us,
            jpeg_dct_extract_us,
            jpeg_dct_repack_us,
            dct_to_wavelet_total_us,
            dct_to_wavelet_accelerator_us,
            dct_to_wavelet_cpu_fallback_us,
            dwt_decompose_us,
            dwt97_batch_pack_upload_us,
            dwt97_batch_pack_upload_transfers,
            dwt97_batch_pack_upload_bytes,
            dwt97_batch_resident_dct_handoff_count,
            dwt97_batch_idct_row_lift_us,
            dwt97_batch_column_lift_us,
            dwt97_batch_resident_dwt_handoff_count,
            dwt97_batch_quantize_codeblock_us,
            dwt97_batch_ht_encode_us,
            dwt97_batch_ht_kernel_us,
            dwt97_batch_ht_status_readback_us,
            dwt97_batch_ht_status_readback_transfers,
            dwt97_batch_ht_status_readback_bytes,
            dwt97_batch_ht_compact_us,
            dwt97_batch_ht_output_readback_us,
            dwt97_batch_ht_output_readback_transfers,
            dwt97_batch_ht_output_readback_bytes,
            dwt97_batch_ht_codeblock_dispatches,
            dwt97_batch_readback_us,
            dwt97_batch_readback_transfers,
            dwt97_batch_readback_bytes,
            htj2k_encode_us,
            htj2k_encode_accelerator_dispatches,
            htj2k_encode_ht_code_block_dispatches,
            htj2k_encode_packetization_dispatches,
            dicom_spool_write_us,
            dicom_final_write_us,
            tile_count,
            component_count,
            batch_count,
            batch_jobs,
            accelerator_attempts,
            accelerator_jobs,
            accelerator_dispatches,
            accelerator_dispatched_jobs,
            cpu_fallback_jobs,
        );
    }
}

/// Per-component transcode geometry preserved in the generated codestream.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TranscodeComponentReport {
    /// Component index in JPEG SOF order.
    pub component_index: usize,
    /// Native component width in samples before HTJ2K SIZ expansion.
    pub width: u32,
    /// Native component height in samples before HTJ2K SIZ expansion.
    pub height: u32,
    /// Number of DCT blocks per component row, including padded edge blocks.
    pub block_cols: u32,
    /// Number of DCT block rows, including padded edge blocks.
    pub block_rows: u32,
    /// HTJ2K SIZ horizontal sampling factor.
    pub x_rsiz: u8,
    /// HTJ2K SIZ vertical sampling factor.
    pub y_rsiz: u8,
}

/// Error metrics from an optional validation oracle.
pub type TranscodeValidationMetrics = ErrorMetrics;

/// Classification for optional coefficient-validation metrics.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TranscodeValidationClassification {
    /// All compared coefficients match the selected oracle exactly.
    Exact,
    /// Coefficients satisfy the experimental one-LSB-bounded threshold:
    /// maximum absolute error is at most one LSB and at least 99.9% of
    /// coefficients match exactly.
    OneLsbBounded,
    /// Coefficients do not satisfy the exact or one-LSB-bounded thresholds.
    OutsideThreshold,
}

impl TranscodeValidationClassification {
    /// Classify validation metrics using the experimental acceptance
    /// thresholds documented for this coefficient-domain path.
    #[must_use]
    pub fn classify_metrics(metrics: &TranscodeValidationMetrics) -> Self {
        if metrics.exact_matches == metrics.total && metrics.max_abs_error == 0 {
            Self::Exact
        } else if metrics.is_one_lsb_bounded(0.999) {
            Self::OneLsbBounded
        } else {
            Self::OutsideThreshold
        }
    }
}

/// Transcode summary for validation and benchmarking.
#[derive(Debug, PartialEq, Eq)]
pub struct TranscodeReport {
    /// Source reference-grid width.
    pub width: u32,
    /// Source reference-grid height.
    pub height: u32,
    /// Number of transformed components.
    pub component_count: usize,
    /// Native transformed component geometry and SIZ sampling.
    pub components: Vec<TranscodeComponentReport>,
    /// Rounded coefficient metrics against the optional float IDCT-then-DWT
    /// oracle.
    pub float_reference_metrics: Option<TranscodeValidationMetrics>,
    /// Threshold classification for `float_reference_metrics`.
    pub float_reference_classification: Option<TranscodeValidationClassification>,
    /// Rounded direct coefficients compared with j2k-jpeg scalar
    /// ISLOW-IDCT-then-reversible-5/3 coefficients.
    pub integer_reference_metrics: Option<TranscodeValidationMetrics>,
    /// Threshold classification for `integer_reference_metrics`.
    pub integer_reference_classification: Option<TranscodeValidationClassification>,
    /// Number of DWT decomposition levels encoded.
    pub decomposition_levels: u8,
    /// Coefficient path used to generate the HTJ2K bands.
    pub coefficient_path: JpegToHtj2kCoefficientPath,
    /// Name of the experimental path used.
    pub path: &'static str,
    /// Wall-clock extraction time in microseconds.
    pub extract_us: u128,
    /// Wall-clock DCT-to-wavelet time in microseconds.
    pub transform_us: u128,
    /// Wall-clock HTJ2K encode time in microseconds.
    pub encode_us: u128,
    /// Detailed stage timings and accelerator/fallback counters.
    pub timings: TranscodeTimingReport,
}