mirx 0.45.0

MIRX binary image format — flat & chunk-based container for ahead-of-time UI assets
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
use core::iter::FusedIterator;

use super::{DecodeUnitRef, GroupPlanes, Region, SurfaceDescriptor};
use crate::image::{
    BufferRequirements, PlaneGeometry, PlaneMemoryLayout, SurfacePlanError, SurfaceRequirements,
};

/// Local decoded storage and the source-plane region represented by one unit.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct UnitPlane {
    index: u8,
    source_region: Region,
    geometry: PlaneGeometry,
    memory: PlaneMemoryLayout,
}

impl UnitPlane {
    pub const fn index(self) -> u8 {
        self.index
    }
    pub const fn source_region(self) -> Region {
        self.source_region
    }
    pub const fn geometry(self) -> PlaneGeometry {
        self.geometry
    }
    pub const fn memory(self) -> PlaneMemoryLayout {
        self.memory
    }
}

/// Caller-owned decoded-unit allocation, independent of encoded input storage.
///
/// Only selected planes are allocated. Source origins are retained for later
/// placement; this is not an in-place writeback plan for a full-surface buffer.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct UnitMemoryPlan {
    surface: SurfaceDescriptor,
    region: Region,
    planes: GroupPlanes,
    requirements: SurfaceRequirements,
    buffer: BufferRequirements,
}

impl DecodeUnitRef<'_> {
    pub fn memory_plan(
        self,
        requirements: SurfaceRequirements,
    ) -> Result<UnitMemoryPlan, SurfacePlanError> {
        requirements.validate()?;
        let alignment = requirements
            .base_alignment()
            .max(requirements.plane_alignment());
        let mut plan = UnitMemoryPlan {
            surface: self.surface,
            region: self.region,
            planes: self.planes,
            requirements,
            buffer: BufferRequirements::new(0, alignment)?,
        };
        let mut end = 0;
        for index in 0..self.surface.plane_count() {
            if let Some(plane) = plan.planned_plane(index, end)? {
                end = plane.memory.data_end();
            }
        }
        plan.buffer = BufferRequirements::new(end, alignment)?;
        Ok(plan)
    }
}

impl UnitMemoryPlan {
    /// Original logical surface; output planes have their own local extents.
    pub const fn source_surface(self) -> SurfaceDescriptor {
        self.surface
    }

    pub(crate) fn sample_byte_len(self) -> usize {
        self.planes().fold(0usize, |total, plane| {
            let geometry = plane.geometry();
            (geometry.minimum_stride().expect("planned sample row") as usize)
                .checked_mul(geometry.height() as usize)
                .and_then(|bytes| total.checked_add(bytes))
                .expect("logical rows fit the checked unit allocation")
        })
    }

    pub const fn requirements(self) -> SurfaceRequirements {
        self.requirements
    }
    pub const fn buffer_requirements(self) -> BufferRequirements {
        self.buffer
    }
    pub const fn byte_len(self) -> u32 {
        self.buffer.byte_len() as u32
    }
    pub const fn base_alignment(self) -> crate::ByteAlignment {
        self.buffer.base_alignment()
    }
    pub fn plane_count(self) -> u8 {
        match self.planes {
            GroupPlanes::Joint(mask) => mask.count_ones() as u8,
            GroupPlanes::Plane(_) => 1,
        }
    }
    /// Looks up the original surface plane index, not a renumbered output slot.
    pub fn plane(self, index: u8) -> Option<UnitPlane> {
        if index >= self.surface.plane_count() || !self.planes.contains(index) {
            return None;
        }
        let mut end = 0;
        for current in 0..=index {
            if let Some(plane) = self
                .planned_plane(current, end)
                .expect("validated unit memory plan")
            {
                if current == index {
                    return Some(plane);
                }
                end = plane.memory.data_end();
            }
        }
        None
    }

    pub fn planes(self) -> UnitPlanes {
        UnitPlanes {
            plan: self,
            front: 0,
            back: self.surface.plane_count(),
            remaining: self.plane_count(),
        }
    }

    fn planned_plane(
        self,
        index: u8,
        previous_end: u32,
    ) -> Result<Option<UnitPlane>, SurfacePlanError> {
        let Some(source_region) = self.planes.plane_region(self.surface, self.region, index) else {
            return Ok(None);
        };
        let geometry = self
            .surface
            .plane(index)
            .expect("selected surface plane")
            .with_extent(source_region.width(), source_region.height());
        let memory = self
            .requirements
            .plan_plane(geometry, index, previous_end)?;
        Ok(Some(UnitPlane {
            index,
            source_region,
            geometry,
            memory,
        }))
    }
}

/// Iterates selected output planes, retaining their original surface indices.
#[derive(Clone, Debug)]
pub struct UnitPlanes {
    plan: UnitMemoryPlan,
    front: u8,
    back: u8,
    remaining: u8,
}
impl Iterator for UnitPlanes {
    type Item = UnitPlane;
    fn next(&mut self) -> Option<Self::Item> {
        while self.front < self.back {
            let index = self.front;
            self.front += 1;
            if let Some(plane) = self.plan.plane(index) {
                self.remaining -= 1;
                return Some(plane);
            }
        }
        None
    }
    fn size_hint(&self) -> (usize, Option<usize>) {
        let len = self.remaining as usize;
        (len, Some(len))
    }
}
impl DoubleEndedIterator for UnitPlanes {
    fn next_back(&mut self) -> Option<Self::Item> {
        while self.front < self.back {
            self.back -= 1;
            if let Some(plane) = self.plan.plane(self.back) {
                self.remaining -= 1;
                return Some(plane);
            }
        }
        None
    }
}
impl ExactSizeIterator for UnitPlanes {
    fn len(&self) -> usize {
        self.remaining as usize
    }
}
impl FusedIterator for UnitPlanes {}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{
        coding::CodingId,
        image::{ColorDescription, SampleLayout, UnitGroup},
        media::CodingRecord,
    };

    fn coding() -> CodingRecord<'static> {
        CodingRecord::new(CodingId::new(19), 1, &[])
    }

    #[test]
    fn odd_joint_edges_keep_source_regions_and_independent_output_alignment() {
        let surface = SurfaceDescriptor::new(
            5,
            3,
            SampleLayout::NV12,
            ColorDescription::BT709_YUV_LIMITED,
        )
        .unwrap();
        let group = UnitGroup::builder(surface, coding(), &[1; 6])
            .with_tiles(2, 2)
            .build()
            .unwrap();
        let plan = group
            .get(5)
            .unwrap()
            .memory_plan(
                SurfaceRequirements::new()
                    .with_base_alignment(crate::ByteAlignment::new(64).unwrap())
                    .with_plane_alignment(crate::ByteAlignment::new(64).unwrap())
                    .with_stride_multiple(64),
            )
            .unwrap();
        let y = plan.plane(0).unwrap();
        let uv = plan.plane(1).unwrap();
        assert_eq!(y.source_region(), Region::new(4, 2, 1, 1).unwrap());
        assert_eq!(uv.source_region(), Region::new(2, 1, 1, 1).unwrap());
        assert_eq!(y.memory().stride(), 64);
        assert_eq!(uv.memory().stride(), 64);
        assert_eq!(uv.geometry().bits_per_element(), 16);
        assert_eq!(
            (y.memory().data_offset(), uv.memory().data_offset()),
            (0, 64)
        );
        assert_eq!(plan.byte_len(), 128);
        assert_eq!(plan.base_alignment(), 64);
        #[repr(align(64))]
        struct Buffer([u8; 256]);
        let bytes = Buffer([0; 256]);
        assert_eq!(plan.buffer_requirements().validate(&bytes.0), Ok(()));
        assert!(plan.buffer_requirements().validate(&bytes.0[1..]).is_err());
        assert!(
            plan.buffer_requirements()
                .validate(&bytes.0[..127])
                .is_err()
        );
    }

    #[test]
    fn planar_units_keep_original_indices_without_allocating_absent_planes() {
        let surface = SurfaceDescriptor::new(
            5,
            3,
            SampleLayout::NV12,
            ColorDescription::BT709_YUV_LIMITED,
        )
        .unwrap();
        for (planes, width, height) in
            [(GroupPlanes::Joint(2), 2, 2), (GroupPlanes::Plane(1), 1, 1)]
        {
            let group = UnitGroup::builder(surface, coding(), &[1; 6])
                .with_planes(planes)
                .with_tiles(width, height)
                .build()
                .unwrap();
            let plan = group
                .get(5)
                .unwrap()
                .memory_plan(SurfaceRequirements::new())
                .unwrap();
            assert_eq!(plan.plane_count(), 1);
            assert_eq!(plan.byte_len(), 2);
            assert_eq!(plan.plane(0), None);
            let plane = plan.plane(1).unwrap();
            assert_eq!(plane.source_region(), Region::new(2, 1, 1, 1).unwrap());
            assert_eq!(plane.memory().data_offset(), 0);
            let mut planes = plan.planes();
            assert_eq!(planes.len(), 1);
            assert_eq!(planes.next_back(), Some(plane));
            assert_eq!(planes.len(), 0);
            assert_eq!(planes.next(), None);
        }
    }

    #[test]
    fn input_alignment_and_sub_byte_origins_do_not_change_output_rules() {
        let rgba =
            SurfaceDescriptor::new(20, 12, SampleLayout::RGBA8888, ColorDescription::SRGB).unwrap();
        let unit = UnitGroup::builder(rgba, coding(), &[1])
            .with_input_alignment(crate::ByteAlignment::new(64).unwrap())
            .build()
            .unwrap()
            .get(0)
            .unwrap();
        let tight = unit.memory_plan(SurfaceRequirements::new()).unwrap();
        assert_eq!(tight.base_alignment(), 1);
        assert_eq!(tight.plane(0).unwrap().memory().stride(), 80);
        let padded = unit
            .memory_plan(
                SurfaceRequirements::new()
                    .with_base_alignment(crate::ByteAlignment::new(64).unwrap())
                    .with_stride_multiple(64),
            )
            .unwrap();
        assert_eq!(padded.plane(0).unwrap().memory().allocation_width(), 20);
        assert_eq!(padded.plane(0).unwrap().memory().stride(), 128);
        let bits = SurfaceDescriptor::new(9, 2, SampleLayout::A1, ColorDescription::NONE).unwrap();
        let bit_unit = UnitGroup::builder(bits, coding(), &[1; 6])
            .with_tiles(3, 1)
            .build()
            .unwrap()
            .get(1)
            .unwrap();
        let plane = bit_unit
            .memory_plan(SurfaceRequirements::new())
            .unwrap()
            .plane(0)
            .unwrap();
        assert_eq!(plane.source_region().x(), 3);
        assert_eq!(plane.geometry().width(), 3);
        assert_eq!(plane.memory().stride(), 1);
        assert_eq!(
            unit.memory_plan(SurfaceRequirements::new().with_stride_multiple(0)),
            Err(SurfacePlanError::InvalidStrideMultiple)
        );
        let huge =
            SurfaceDescriptor::new(u32::MAX, 1, SampleLayout::RGBA8888, ColorDescription::SRGB)
                .unwrap();
        assert_eq!(
            UnitGroup::builder(huge, coding(), &[1])
                .build()
                .unwrap()
                .get(0)
                .unwrap()
                .memory_plan(SurfaceRequirements::new()),
            Err(SurfacePlanError::SizeOverflow)
        );
    }

    #[test]
    fn whole_unit_and_surface_plans_share_all_layout_rules() {
        let layouts = (0..=255)
            .filter_map(crate::ColorFormat::from_u8)
            .map(SampleLayout::from_color_format)
            .chain([
                SampleLayout::I420,
                SampleLayout::YV12,
                SampleLayout::NV12,
                SampleLayout::NV21,
                SampleLayout::P010,
                SampleLayout::P016,
            ]);
        for layout in layouts {
            let color = if layout.is_alpha() {
                ColorDescription::NONE
            } else if layout.is_yuv() {
                ColorDescription::BT709_YUV_LIMITED
            } else {
                ColorDescription::SRGB
            };
            let surface = SurfaceDescriptor::new(5, 3, layout, color).unwrap();
            let unit = UnitGroup::builder(surface, coding(), &[1])
                .build()
                .unwrap()
                .get(0)
                .unwrap();
            for requirements in [
                SurfaceRequirements::new(),
                SurfaceRequirements::new()
                    .with_plane_alignment(crate::ByteAlignment::new(64).unwrap())
                    .with_stride_multiple(64)
                    .with_width_multiple(8)
                    .with_height_multiple(2),
            ] {
                let complete = surface.memory_plan(requirements).unwrap();
                let unit = unit.memory_plan(requirements).unwrap();
                assert_eq!(unit.buffer_requirements(), complete.buffer_requirements());
                for plane in 0..surface.plane_count() {
                    assert_eq!(
                        unit.plane(plane).unwrap().memory(),
                        complete.plane(plane).unwrap()
                    );
                    assert_eq!(
                        unit.plane(plane).unwrap().geometry(),
                        surface.plane(plane).unwrap()
                    );
                }
                assert_eq!(unit.planes().count(), surface.plane_count() as usize);
            }
        }
    }
}