temporal-vision 0.2.0

Deterministic temporal visual analysis: storyboards, difference maps, motion history images, and region filmstrips from frame sequences
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
use std::num::NonZeroUsize;

use png::{ColorType, Decoder};
use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};
use temporal_vision::{
    ArtifactKind, ArtifactManifest, BinaryMask, DeclaredGap, DifferenceMapLimits,
    DifferenceMapParameters, ErrorCode, EvidenceClass, Frame, FrameRegion, FrameSequence,
    FrequencyMode, IntegerScale, Marker, MeasurementParameters, NormalizationParameters,
    PixelDimensions, PixelFormat, PixelRect, ProcessingLimits, Rgb8, TimePalette, TimeRange,
    Timestamp, analyze_adjacent_pairs, normalize_sequence, render_difference_map,
    render_difference_map_with_analysis,
};

#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
struct FrameId(String);
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
struct MarkerId(String);
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
struct GapId(String);
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
struct ArtifactId(String);

type Source = FrameSequence<FrameId, MarkerId, GapId, Box<[u8]>>;

fn rgba(pixels: [[u8; 3]; 4]) -> Box<[u8]> {
    pixels
        .into_iter()
        .flat_map(|pixel| [pixel[0], pixel[1], pixel[2], 255])
        .collect::<Vec<_>>()
        .into_boxed_slice()
}

fn fixture() -> (Source, temporal_vision::NormalizedSequence<FrameId>) {
    let dimensions = PixelDimensions::new(4, 1).unwrap();
    let black = [0, 0, 0];
    let frames = [
        ("f0", 0, [black, black, black, black]),
        (
            "f1",
            10,
            [[255, 255, 255], [64, 64, 64], black, [255, 0, 0]],
        ),
        (
            "f2",
            20,
            [[255, 255, 255], [64, 64, 64], black, [0, 255, 0]],
        ),
        ("f3", 40, [black, [128, 128, 128], [0, 0, 255], [0, 0, 255]]),
    ]
    .into_iter()
    .map(|(id, time, pixels)| {
        Frame::new(
            FrameId(id.into()),
            Timestamp::from_nanos(time),
            dimensions,
            PixelFormat::Rgba8SrgbStraight,
            rgba(pixels),
        )
        .unwrap()
    })
    .collect();
    let marker = Marker::new(
        MarkerId("m0".into()),
        Timestamp::from_nanos(10),
        "action",
        "open",
    )
    .unwrap();
    let gap = DeclaredGap::new(
        GapId("g0".into()),
        TimeRange::new(Timestamp::from_nanos(15), Timestamp::from_nanos(15)).unwrap(),
        "capture loss",
        None,
    )
    .unwrap();
    let region = FrameRegion::new(PixelRect::new(0, 0, 4, 1).unwrap(), dimensions).unwrap();
    let mask = BinaryMask::new(dimensions, [0xe0]).unwrap();
    let source =
        FrameSequence::new(frames, vec![marker], vec![gap], Some(region), Some(mask)).unwrap();
    let normalized = normalize_sequence(
        &source,
        NormalizationParameters::new(
            Rgb8::new(7, 9, 11),
            None,
            IntegerScale::IDENTITY,
            ProcessingLimits::default(),
        ),
    )
    .unwrap();
    (source, normalized)
}

fn parameters(limits: DifferenceMapLimits) -> DifferenceMapParameters {
    DifferenceMapParameters::new(
        0,
        FrequencyMode::Count,
        TimePalette::Spectral,
        Some(Timestamp::from_nanos(20)),
        MeasurementParameters::new(0),
        Rgb8::new(7, 9, 11),
        limits,
    )
}

#[test]
fn browser_free_public_contract_is_traceable_bounded_and_deterministic() {
    let (source, normalized) = fixture();
    let first = render_difference_map(
        ArtifactId("difference-a".into()),
        &source,
        &normalized,
        parameters(DifferenceMapLimits::default()),
    )
    .unwrap();
    let second = render_difference_map(
        ArtifactId("difference-a".into()),
        &source,
        &normalized,
        parameters(DifferenceMapLimits::default()),
    )
    .unwrap();
    assert_eq!(first, second);
    let shared = analyze_adjacent_pairs(&normalized, MeasurementParameters::new(0), true).unwrap();
    let shared_result = render_difference_map_with_analysis(
        ArtifactId("difference-a".into()),
        &source,
        &normalized,
        parameters(DifferenceMapLimits::default()),
        Some(&shared),
    )
    .unwrap();
    assert_eq!(first, shared_result);
    let mismatched =
        analyze_adjacent_pairs(&normalized, MeasurementParameters::new(1), true).unwrap();
    let mismatched_result = render_difference_map_with_analysis(
        ArtifactId("difference-a".into()),
        &source,
        &normalized,
        parameters(DifferenceMapLimits::default()),
        Some(&mismatched),
    )
    .unwrap();
    assert_eq!(first, mismatched_result);

    let manifest = first.manifest();
    assert_eq!(manifest.artifact_kind(), ArtifactKind::DifferenceMap);
    assert_eq!(manifest.evidence_class(), EvidenceClass::SourceDerived);
    assert_eq!(manifest.algorithm().name(), "temporal-difference-map");
    assert_eq!(manifest.algorithm().version(), "v1");
    assert_eq!(manifest.source_frame_count(), 4);
    // All four frames were analyzed; only the reference frame is referenced in the
    // output. Referencing one frame is not the same as omitting the other three.
    assert_eq!(manifest.analyzed_frame_count(), 4);
    assert_eq!(manifest.omitted_frame_count(), 0);
    assert_eq!(manifest.analyzed_frame_ids().len(), 4);
    assert_eq!(manifest.selected_frame_ids(), &[FrameId("f0".into())]);
    assert_eq!(manifest.markers().len(), 1);
    assert_eq!(manifest.gaps().len(), 1);
    assert_eq!(manifest.region(), source.region());
    assert_eq!(manifest.mask(), source.mask());
    assert_eq!(
        manifest.output_dimensions(),
        PixelDimensions::new(76, 261).unwrap()
    );

    let image = first.image();
    assert_eq!(image.media_type(), "image/png");
    assert_eq!(image.dimensions(), manifest.output_dimensions());
    assert_eq!(&image.bytes()[..8], b"\x89PNG\r\n\x1a\n");
    let digest: [u8; 32] = Sha256::digest(image.bytes()).into();
    assert_eq!(manifest.output_hash().as_bytes(), &digest);

    let json = serde_json::to_vec(manifest).unwrap();
    let decoded: ArtifactManifest<ArtifactId, FrameId, MarkerId, GapId> =
        serde_json::from_slice(&json).unwrap();
    assert_eq!(&decoded, manifest);

    let (dimensions, pixels) = decode_rgb(image.bytes());
    assert_eq!(dimensions, manifest.output_dimensions());
    // Fixed panel origins are x=16/36/56 and y=112 for this 4x1 fixture.
    assert_eq!(rgb_at(&pixels, dimensions, 16, 112), [0, 0, 0]);
    assert_eq!(rgb_at(&pixels, dimensions, 36, 112), [255, 255, 255]);
    assert_eq!(rgb_at(&pixels, dimensions, 38, 112), [127, 127, 127]);
    assert_eq!(rgb_at(&pixels, dimensions, 39, 112), [62, 68, 79]);
    assert_eq!(rgb_at(&pixels, dimensions, 56, 112), [255, 78, 142]);
    assert_eq!(rgb_at(&pixels, dimensions, 58, 112), [250, 190, 48]);
    assert_eq!(rgb_at(&pixels, dimensions, 59, 112), [62, 68, 79]);
    assert!(region_has_color(
        &pixels,
        dimensions,
        16,
        223,
        44,
        18,
        [255, 196, 64]
    ));

    let tiny_output = DifferenceMapLimits::new(
        NonZeroUsize::new(1024).unwrap(),
        NonZeroUsize::new(1).unwrap(),
    );
    assert_eq!(
        render_difference_map(
            ArtifactId("too-large".into()),
            &source,
            &normalized,
            parameters(tiny_output),
        )
        .unwrap_err()
        .code,
        ErrorCode::ResourceLimitExceeded
    );
}

fn decode_rgb(bytes: &[u8]) -> (PixelDimensions, Vec<u8>) {
    let mut reader = Decoder::new(bytes).read_info().unwrap();
    let mut output = vec![0_u8; reader.output_buffer_size()];
    let info = reader.next_frame(&mut output).unwrap();
    assert_eq!(info.color_type, ColorType::Rgb);
    output.truncate(info.buffer_size());
    (
        PixelDimensions::new(info.width, info.height).unwrap(),
        output,
    )
}

fn rgb_at(pixels: &[u8], dimensions: PixelDimensions, x: u32, y: u32) -> [u8; 3] {
    let index = (y as usize * dimensions.width() as usize + x as usize) * 3;
    [pixels[index], pixels[index + 1], pixels[index + 2]]
}

#[allow(clippy::too_many_arguments)]
fn region_has_color(
    pixels: &[u8],
    dimensions: PixelDimensions,
    x: u32,
    y: u32,
    width: u32,
    height: u32,
    color: [u8; 3],
) -> bool {
    (y..y + height)
        .any(|row| (x..x + width).any(|column| rgb_at(pixels, dimensions, column, row) == color))
}

/// Attach source provenance describing `source_len` retained frames, of which the
/// fixture's four decoded frames sit at `indices`.
fn with_provenance(source: Source, source_len: usize, indices: [usize; 4]) -> Source {
    let ids: Vec<FrameId> = (0..source_len)
        .map(|position| {
            indices
                .iter()
                .position(|index| *index == position)
                .map_or_else(
                    || FrameId(format!("dropped-{position}")),
                    |decoded| source.frames()[decoded].id().clone(),
                )
        })
        .collect();
    let range = TimeRange::new(Timestamp::from_nanos(0), Timestamp::from_nanos(100)).unwrap();
    source
        .with_source_provenance(ids, indices.to_vec(), range)
        .unwrap()
}

fn sampling_block(
    manifest: &ArtifactManifest<ArtifactId, FrameId, MarkerId, GapId>,
) -> Option<&temporal_vision::ParameterValue> {
    manifest.parameters().get("analysis_sampling")
}

#[test]
fn decimated_analysis_manifest_counts_agree_with_its_sampling_disclosure() {
    let (source, normalized) = fixture();
    let source = with_provenance(source, 9, [0, 3, 5, 8]);
    let manifest = render_difference_map(
        ArtifactId("difference-sampled".into()),
        &source,
        &normalized,
        parameters(DifferenceMapLimits::default()),
    )
    .unwrap()
    .manifest()
    .clone();

    // The four analyzed frames are what contributed; five source frames were dropped.
    // Referencing only the reference frame must not be reported as omitting the rest.
    assert_eq!(manifest.source_frame_count(), 9);
    assert_eq!(manifest.analyzed_frame_count(), 4);
    assert_eq!(manifest.omitted_frame_count(), 5);
    assert_eq!(manifest.selected_frame_ids(), &[FrameId("f0".into())]);

    // The disclosure agent surfaces read for their sampling warning must describe
    // the same evidence as the counts above.
    let Some(temporal_vision::ParameterValue::Object(values)) = sampling_block(&manifest) else {
        panic!("a decimated analysis must disclose analysis_sampling");
    };
    assert_eq!(
        values.get("source_frame_count"),
        Some(&temporal_vision::ParameterValue::Unsigned(
            manifest.source_frame_count()
        ))
    );
    assert_eq!(
        values.get("analyzed_frame_count"),
        Some(&temporal_vision::ParameterValue::Unsigned(
            manifest.analyzed_frame_count()
        ))
    );
    assert_eq!(
        values.get("mode"),
        Some(&temporal_vision::ParameterValue::Text(
            "uniform_bounded".into()
        ))
    );
}

#[test]
fn undecimated_analysis_manifest_claims_no_sampling_mode() {
    let (source, normalized) = fixture();
    // Production always attaches source provenance, so an exhaustive run reaches the
    // same code path as a sampled one. It must not claim `uniform_bounded` anyway.
    let source = with_provenance(source, 4, [0, 1, 2, 3]);
    let manifest = render_difference_map(
        ArtifactId("difference-exhaustive".into()),
        &source,
        &normalized,
        parameters(DifferenceMapLimits::default()),
    )
    .unwrap()
    .manifest()
    .clone();

    assert_eq!(manifest.source_frame_count(), 4);
    assert_eq!(manifest.analyzed_frame_count(), 4);
    assert_eq!(manifest.omitted_frame_count(), 0);
    assert_eq!(sampling_block(&manifest), None);
}

#[test]
fn a_manifest_may_not_be_deserialized_with_a_contradictory_sampling_disclosure() {
    let (source, normalized) = fixture();
    let source = with_provenance(source, 9, [0, 3, 5, 8]);
    let manifest = render_difference_map(
        ArtifactId("difference-sampled".into()),
        &source,
        &normalized,
        parameters(DifferenceMapLimits::default()),
    )
    .unwrap()
    .manifest()
    .clone();

    let encoded = serde_json::to_vec(&manifest).unwrap();
    serde_json::from_slice::<ArtifactManifest<ArtifactId, FrameId, MarkerId, GapId>>(&encoded)
        .unwrap();

    // Every field of the disclosure is a claim about the analysis, so every field
    // has to be defended independently. A validator that only reconciled the
    // counts would accept a block that agreed about how many frames were examined
    // while naming the wrong frames, the wrong selection rule, or none at all.
    /// One independent edit to the disclosure block, and the rejection it must
    /// provoke.
    struct Tampering {
        name: &'static str,
        apply: fn(&mut serde_json::Value),
        expected: &'static str,
    }
    let tamperings: [Tampering; 9] = [
        Tampering {
            name: "analyzed count",
            apply: |block| block["analyzed_frame_count"]["value"] = serde_json::json!(1),
            expected: "contradicts the manifest frame counts",
        },
        Tampering {
            name: "source count",
            apply: |block| block["source_frame_count"]["value"] = serde_json::json!(4),
            expected: "contradicts the manifest frame counts",
        },
        Tampering {
            name: "removed indices",
            apply: |block| {
                block
                    .as_object_mut()
                    .unwrap()
                    .remove("analyzed_source_indices");
            },
            expected: "must list its analyzed source indices",
        },
        Tampering {
            name: "short index list",
            apply: |block| {
                block["analyzed_source_indices"]["value"] =
                    serde_json::json!([{"type": "unsigned", "value": 0}]);
            },
            expected: "contradicts the manifest frame counts",
        },
        Tampering {
            name: "out-of-range index",
            apply: |block| {
                block["analyzed_source_indices"]["value"][3]["value"] = serde_json::json!(99);
            },
            expected: "outside the manifest source frames",
        },
        Tampering {
            name: "reordered indices",
            apply: |block| {
                block["analyzed_source_indices"]["value"][1]["value"] = serde_json::json!(0);
            },
            expected: "strictly increasing",
        },
        Tampering {
            // The shape-only failure: [0, 1, 5, 8] is the right length, in range,
            // and strictly increasing, so every structural check passes — but
            // source position 1 is a frame the analysis dropped, so the
            // disclosure names a frame that never contributed to the artifact.
            name: "shape-valid indices naming unanalyzed frames",
            apply: |block| {
                block["analyzed_source_indices"]["value"][1]["value"] = serde_json::json!(1);
            },
            expected: "does not identify the analyzed frame",
        },
        Tampering {
            name: "invented mode",
            apply: |block| block["mode"]["value"] = serde_json::json!("every_other_tuesday"),
            expected: "sampling scheme this crate does not produce",
        },
        Tampering {
            name: "invented spacing",
            apply: |block| block["spacing"]["value"] = serde_json::json!("logarithmic"),
            expected: "sampling scheme this crate does not produce",
        },
    ];

    for tampering in tamperings {
        let mut tampered: serde_json::Value = serde_json::from_slice(&encoded).unwrap();
        (tampering.apply)(&mut tampered["parameters"]["analysis_sampling"]["value"]);
        let bytes = serde_json::to_vec(&tampered).unwrap();
        let error =
            serde_json::from_slice::<ArtifactManifest<ArtifactId, FrameId, MarkerId, GapId>>(
                &bytes,
            )
            .unwrap_err();
        assert!(
            error.to_string().contains(tampering.expected),
            "tampering with the {} was accepted or rejected for the wrong reason: {error}",
            tampering.name
        );
    }
}