phasm-core 0.2.4

Pure-Rust steganography engine — hide encrypted messages in JPEG photos
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
// Copyright (c) 2026 Christoph Gaffga
// SPDX-License-Identifier: GPL-3.0-only
// https://github.com/cgaffga/phasmcore

//! Reference frame management for Phase 6B P-frame encoding +
//! Phase 6E-A B-frame extension.
//!
//! **Single-slot DPB (Phase 6B, default)**: holds the most-recently-
//! encoded frame's reconstructed pixels. The next P-frame's motion
//! compensation reads from this. IDR frames clear the slot.
//!
//! **Multi-slot DPB (Phase 6E-A1, opt-in)**: holds up to 3 slots
//! to support B-frame encoding under M=2 IBPBP. Slot 0 = previous
//! P (L0 ref for the current B and the next P). Slot 1 = next P
//! encoded BEFORE the displayed-between B (L1 ref for that B).
//! Slot 2 = IDR carry-over slack at GOP boundaries.
//!
//! See `docs/design/h264-encoder-algorithms/reference-management.md`
//! and `docs/design/h264-encoder-algorithms/b-frames.md`.
//!
//! ## Backwards compatibility
//!
//! The legacy `ReferenceBuffer { last_ref, last_ref_frame_num }`
//! API stays — Phase 6B P-frame paths are bit-identical. The
//! multi-slot extension lives in a sibling type `MultiSlotDpb`
//! exposed under the same module. Phase 6E-A2+ wires the encoder
//! to use `MultiSlotDpb` for B-slice encoding paths only; P-only
//! encodes continue using the legacy `ReferenceBuffer`.

use super::reconstruction::ReconBuffer;

/// Immutable snapshot of reconstructed YUV420p planes.
#[derive(Debug, Clone)]
pub struct ReconFrame {
    pub width: u32,
    pub height: u32,
    pub y: Vec<u8>,
    pub cb: Vec<u8>,
    pub cr: Vec<u8>,
}

impl ReconFrame {
    /// Snapshot a `ReconBuffer`'s current state.
    pub fn snapshot(recon: &ReconBuffer) -> Self {
        Self {
            width: recon.width,
            height: recon.height,
            y: recon.y.clone(),
            cb: recon.cb.clone(),
            cr: recon.cr.clone(),
        }
    }

    /// Read a single luma pixel. Panics if out of bounds.
    pub fn y_at(&self, x: u32, y: u32) -> u8 {
        self.y[(y * self.width + x) as usize]
    }

    /// Read a single chroma pixel. Panics if out of bounds.
    pub fn chroma_at(&self, component: u8, x: u32, y: u32) -> u8 {
        let stride = self.width / 2;
        let plane = if component == 0 { &self.cb } else { &self.cr };
        plane[(y * stride + x) as usize]
    }
}

/// Single-slot DPB. Holds the previous frame for P-frame prediction.
#[derive(Debug, Default)]
pub struct ReferenceBuffer {
    pub last_ref: Option<ReconFrame>,
    /// `frame_num` of the last-emitted reference, wraps at
    /// `1 << log2_max_frame_num`. `None` when `last_ref.is_none()`.
    pub last_ref_frame_num: Option<u8>,
}

impl ReferenceBuffer {
    pub fn new() -> Self {
        Self {
            last_ref: None,
            last_ref_frame_num: None,
        }
    }

    /// Clear the DPB — called on every IDR.
    pub fn reset(&mut self) {
        self.last_ref = None;
        self.last_ref_frame_num = None;
    }

    /// Replace the current reference with a snapshot of the
    /// just-encoded frame.
    pub fn promote(&mut self, recon: &ReconBuffer, frame_num: u8) {
        self.last_ref = Some(ReconFrame::snapshot(recon));
        self.last_ref_frame_num = Some(frame_num);
    }

    /// True when a P-frame can be encoded (reference is available).
    pub fn has_reference(&self) -> bool {
        self.last_ref.is_some()
    }
}

// ─── Phase 6E-A1: multi-slot DPB for B-frames ────────────────────

/// Role hint attached to a DPB slot. Distinguishes the temporally-
/// earlier vs later anchor when filling reference lists for a
/// B-slice. The decoder side uses POC ordering; this hint mirrors
/// that on the encoder side without the encoder having to compute
/// full POC for every reference look-up.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SlotRole {
    /// Temporally-earlier reference relative to the slice being
    /// encoded. Becomes List 0 entry 0 for B-slices, and the sole
    /// reference for P-slices.
    Past,
    /// Temporally-later reference relative to the slice being
    /// encoded. Becomes List 1 entry 0 for B-slices. Unused for
    /// P-slices.
    Future,
}

/// One occupied slot in the multi-slot DPB. Bundles the
/// reconstructed frame, its `frame_num`, the FULL POC (so we can
/// order references for List 0 / List 1 construction), and the
/// role hint.
#[derive(Debug, Clone)]
pub struct DpbSlot {
    pub recon: ReconFrame,
    pub frame_num: u8,
    /// Full (un-wrapped) POC for this reference, mod 2^32. Used
    /// to compute List 0 / List 1 ordering relative to the
    /// current slice's POC.
    pub full_poc: u32,
    pub role: SlotRole,
}

/// Multi-slot DPB. Capacity is fixed at construction; sliding-
/// window MMCO retires the oldest slot when a new one is promoted
/// past capacity. For Phase 6E-A1 M=2 IBPBP, capacity = 3 is
/// adequate (Past P + Future P encoded ahead of the B between
/// them + IDR carry slack).
#[derive(Debug)]
pub struct MultiSlotDpb {
    slots: Vec<Option<DpbSlot>>,
}

impl MultiSlotDpb {
    /// Build a DPB with `capacity` slots, all initially empty.
    pub fn with_capacity(capacity: usize) -> Self {
        assert!(capacity > 0, "MultiSlotDpb capacity must be > 0");
        Self {
            slots: vec![None; capacity],
        }
    }

    /// Number of slots (occupied or empty).
    pub fn capacity(&self) -> usize {
        self.slots.len()
    }

    /// Number of occupied slots.
    pub fn occupied(&self) -> usize {
        self.slots.iter().filter(|s| s.is_some()).count()
    }

    /// Clear all slots — called on every IDR.
    pub fn reset(&mut self) {
        for s in self.slots.iter_mut() {
            *s = None;
        }
    }

    /// Promote a freshly-reconstructed frame into the DPB.
    /// Sliding-window MMCO: if all slots are occupied, the slot
    /// with the OLDEST `full_poc` value is evicted to make room.
    pub fn promote(
        &mut self,
        recon: &ReconBuffer,
        frame_num: u8,
        full_poc: u32,
        role: SlotRole,
    ) {
        let new_slot = DpbSlot {
            recon: ReconFrame::snapshot(recon),
            frame_num,
            full_poc,
            role,
        };

        // First-fit: place into any empty slot.
        if let Some(empty) = self.slots.iter_mut().find(|s| s.is_none()) {
            *empty = Some(new_slot);
            return;
        }

        // All full → evict oldest (smallest full_poc).
        let oldest_idx = self
            .slots
            .iter()
            .enumerate()
            .filter_map(|(i, s)| s.as_ref().map(|sl| (i, sl.full_poc)))
            .min_by_key(|(_, poc)| *poc)
            .map(|(i, _)| i)
            .expect("DPB is non-empty (capacity > 0)");
        self.slots[oldest_idx] = Some(new_slot);
    }

    /// Borrow the slot at `idx`. Returns `None` if the slot is
    /// empty or `idx` exceeds capacity.
    pub fn get(&self, idx: usize) -> Option<&DpbSlot> {
        self.slots.get(idx).and_then(|s| s.as_ref())
    }

    /// Find the most-recent Past slot (highest full_poc among
    /// `Past` role). For P-slices this is the L0 reference; for
    /// B-slices this is the L0 reference too.
    pub fn most_recent_past(&self) -> Option<&DpbSlot> {
        self.slots
            .iter()
            .filter_map(|s| s.as_ref())
            .filter(|s| s.role == SlotRole::Past)
            .max_by_key(|s| s.full_poc)
    }

    /// Find the soonest Future slot (smallest full_poc among
    /// `Future` role > current_poc). For B-slices this is the L1
    /// reference. Returns `None` if no Future slot is available.
    pub fn soonest_future(&self, current_poc: u32) -> Option<&DpbSlot> {
        self.slots
            .iter()
            .filter_map(|s| s.as_ref())
            .filter(|s| s.role == SlotRole::Future && s.full_poc > current_poc)
            .min_by_key(|s| s.full_poc)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn make_recon(width: u32, height: u32, y_fill: u8, c_fill: u8) -> ReconBuffer {
        let mut b = ReconBuffer::new(width, height).unwrap();
        for v in b.y.iter_mut() {
            *v = y_fill;
        }
        for v in b.cb.iter_mut() {
            *v = c_fill;
        }
        for v in b.cr.iter_mut() {
            *v = c_fill;
        }
        b
    }

    #[test]
    fn reference_buffer_new_is_empty() {
        let rb = ReferenceBuffer::new();
        assert!(!rb.has_reference());
        assert!(rb.last_ref.is_none());
        assert!(rb.last_ref_frame_num.is_none());
    }

    #[test]
    fn promote_captures_pixels() {
        let mut rb = ReferenceBuffer::new();
        let recon = make_recon(32, 32, 100, 128);
        rb.promote(&recon, 0);
        assert!(rb.has_reference());
        assert_eq!(rb.last_ref_frame_num, Some(0));
        let frame = rb.last_ref.as_ref().unwrap();
        assert_eq!(frame.width, 32);
        assert_eq!(frame.height, 32);
        assert_eq!(frame.y_at(5, 5), 100);
        assert_eq!(frame.chroma_at(0, 5, 5), 128);
        assert_eq!(frame.chroma_at(1, 5, 5), 128);
    }

    #[test]
    fn reset_clears_dpb() {
        let mut rb = ReferenceBuffer::new();
        let recon = make_recon(32, 32, 100, 128);
        rb.promote(&recon, 5);
        rb.reset();
        assert!(!rb.has_reference());
        assert_eq!(rb.last_ref_frame_num, None);
    }

    #[test]
    fn promote_replaces_previous() {
        let mut rb = ReferenceBuffer::new();
        rb.promote(&make_recon(32, 32, 50, 128), 0);
        rb.promote(&make_recon(32, 32, 200, 100), 1);
        let frame = rb.last_ref.as_ref().unwrap();
        assert_eq!(frame.y_at(0, 0), 200);
        assert_eq!(frame.chroma_at(0, 0, 0), 100);
        assert_eq!(rb.last_ref_frame_num, Some(1));
    }

    #[test]
    fn snapshot_is_independent_of_source() {
        let mut recon = make_recon(32, 32, 100, 128);
        let mut rb = ReferenceBuffer::new();
        rb.promote(&recon, 0);
        // Mutate the source after snapshot.
        for v in recon.y.iter_mut() {
            *v = 200;
        }
        // Snapshot should be unaffected.
        let frame = rb.last_ref.as_ref().unwrap();
        assert_eq!(frame.y_at(0, 0), 100);
    }

    // ─── Phase 6E-A1 multi-slot DPB tests ────────────────────────

    #[test]
    fn multi_slot_dpb_starts_empty() {
        let dpb = MultiSlotDpb::with_capacity(3);
        assert_eq!(dpb.capacity(), 3);
        assert_eq!(dpb.occupied(), 0);
        assert!(dpb.get(0).is_none());
        assert!(dpb.most_recent_past().is_none());
        assert!(dpb.soonest_future(0).is_none());
    }

    #[test]
    fn multi_slot_dpb_promote_fills_empty_slots() {
        let mut dpb = MultiSlotDpb::with_capacity(3);
        let recon0 = make_recon(32, 32, 50, 128);
        dpb.promote(&recon0, 0, /* poc */ 0, SlotRole::Past);
        assert_eq!(dpb.occupied(), 1);

        let recon1 = make_recon(32, 32, 100, 128);
        dpb.promote(&recon1, 1, /* poc */ 4, SlotRole::Future);
        assert_eq!(dpb.occupied(), 2);

        let past = dpb.most_recent_past().unwrap();
        assert_eq!(past.full_poc, 0);
        let future = dpb.soonest_future(0).unwrap();
        assert_eq!(future.full_poc, 4);
    }

    #[test]
    fn multi_slot_dpb_evicts_oldest_when_full() {
        let mut dpb = MultiSlotDpb::with_capacity(2);
        let r = make_recon(32, 32, 0, 128);

        dpb.promote(&r, 0, 0, SlotRole::Past);
        dpb.promote(&r, 1, 4, SlotRole::Past);
        assert_eq!(dpb.occupied(), 2);

        // Slots full; promote a 3rd → evicts poc=0.
        dpb.promote(&r, 2, 8, SlotRole::Past);
        assert_eq!(dpb.occupied(), 2);
        assert_eq!(dpb.most_recent_past().unwrap().full_poc, 8);

        // poc=0 should be gone.
        let pocs: Vec<u32> = (0..dpb.capacity())
            .filter_map(|i| dpb.get(i).map(|s| s.full_poc))
            .collect();
        assert!(!pocs.contains(&0));
        assert!(pocs.contains(&4));
        assert!(pocs.contains(&8));
    }

    #[test]
    fn multi_slot_dpb_reset_clears() {
        let mut dpb = MultiSlotDpb::with_capacity(3);
        let r = make_recon(32, 32, 100, 128);
        dpb.promote(&r, 0, 0, SlotRole::Past);
        dpb.promote(&r, 1, 4, SlotRole::Future);
        assert_eq!(dpb.occupied(), 2);

        dpb.reset();
        assert_eq!(dpb.occupied(), 0);
        assert!(dpb.most_recent_past().is_none());
    }

    #[test]
    fn multi_slot_dpb_filters_role_correctly() {
        let mut dpb = MultiSlotDpb::with_capacity(3);
        let r = make_recon(32, 32, 0, 128);

        dpb.promote(&r, 0, 0, SlotRole::Past);
        dpb.promote(&r, 1, 4, SlotRole::Future);
        dpb.promote(&r, 2, 2, SlotRole::Past);

        // most_recent_past picks highest-poc Past slot only
        // (ignores Future).
        assert_eq!(dpb.most_recent_past().unwrap().full_poc, 2);

        // soonest_future at current_poc=2 picks the Future slot
        // with smallest poc > 2.
        assert_eq!(dpb.soonest_future(2).unwrap().full_poc, 4);

        // soonest_future at current_poc=4 returns None (no future
        // slot beyond 4).
        assert!(dpb.soonest_future(4).is_none());
    }

    #[test]
    fn multi_slot_dpb_capacity_one_acts_like_single_slot() {
        // Sanity: capacity=1 behaves like the legacy ReferenceBuffer.
        let mut dpb = MultiSlotDpb::with_capacity(1);
        let r0 = make_recon(32, 32, 50, 128);
        let r1 = make_recon(32, 32, 200, 100);
        dpb.promote(&r0, 0, 0, SlotRole::Past);
        assert_eq!(dpb.occupied(), 1);
        assert_eq!(dpb.get(0).unwrap().recon.y_at(0, 0), 50);

        // Second promote evicts the first.
        dpb.promote(&r1, 1, 2, SlotRole::Past);
        assert_eq!(dpb.occupied(), 1);
        assert_eq!(dpb.get(0).unwrap().recon.y_at(0, 0), 200);
    }
}