carnelian/render/generic/forma/
image.rs

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
// Copyright 2020 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

use std::io::Read;
use std::sync::Arc;
use std::{mem, slice};

use anyhow::Error;
use fidl_fuchsia_sysmem2::{BufferCollectionSynchronousProxy, CoherencyDomain};
use fuchsia_trace::duration;
use mapped_vmo::Mapping;
use zx::prelude::*;
use zx::{self as zx, sys};

#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub struct FormaImage(pub(crate) usize);

#[derive(Debug)]
pub(crate) struct VmoImage {
    // TODO(https://fxbug.dev/42165549)
    #[allow(unused)]
    vmo: zx::Vmo,
    // TODO(https://fxbug.dev/42165549)
    #[allow(unused)]
    width: u32,
    // TODO(https://fxbug.dev/42165549)
    #[allow(unused)]
    height: u32,
    // TODO(https://fxbug.dev/42165549)
    #[allow(unused)]
    len_bytes: u64,
    mapping: Arc<Mapping>,
    stride: usize,
    pub(crate) buffer_layer_cache: Option<(usize, forma::buffer::BufferLayerCache)>,
    coherency_domain: CoherencyDomain,
    layout: forma::buffer::layout::LinearLayout,
}

impl VmoImage {
    pub fn new(width: u32, height: u32) -> Self {
        let len_bytes = (width * height * 4) as usize * mem::size_of::<u8>();
        let (mapping, vmo) = mapped_vmo::Mapping::allocate(len_bytes as usize)
            .expect("failed to allocated mapped VMO");

        Self {
            vmo,
            width,
            height,
            len_bytes: len_bytes as u64,
            mapping: Arc::new(mapping),
            stride: (width * 4) as usize,
            buffer_layer_cache: None,
            coherency_domain: CoherencyDomain::Cpu,
            layout: forma::buffer::layout::LinearLayout::new(
                width as usize,
                (width * 4) as usize,
                height as usize,
            ),
        }
    }

    pub fn from_png<R: Read>(reader: &mut png::Reader<R>) -> Result<Self, Error> {
        let info = reader.info();
        let color_type = info.color_type;
        let (width, height) = info.size();
        let stride = (width * 4) as usize * mem::size_of::<u8>();
        let len_bytes = stride * height as usize;
        let (mut mapping, vmo) = mapped_vmo::Mapping::allocate(len_bytes as usize)
            .expect("failed to allocated mapped VMO");
        let (data, len) = mapping.as_ptr_len();
        let slice = unsafe { slice::from_raw_parts_mut(data, len) };
        for dst_row in slice.chunks_mut(stride) {
            let src_row = reader.next_row()?.unwrap();
            // Transfer row and convert to BGRA.
            match color_type {
                png::ColorType::RGB | png::ColorType::Indexed => {
                    for (src, dst) in src_row.chunks(3).zip(dst_row.chunks_mut(4)) {
                        dst.copy_from_slice(&[src[2], src[1], src[0], 0xff]);
                    }
                }
                png::ColorType::RGBA => {
                    for (src, dst) in src_row.chunks(4).zip(dst_row.chunks_mut(4)) {
                        dst.copy_from_slice(&[src[2], src[1], src[0], src[3]]);
                    }
                }
                _ => panic!("unsupported color type {:#?}", color_type),
            }
        }

        Ok(Self {
            vmo,
            width,
            height,
            len_bytes: len_bytes as u64,
            mapping: Arc::new(mapping),
            stride: (width * 4) as usize,
            buffer_layer_cache: None,
            coherency_domain: CoherencyDomain::Cpu,
            layout: forma::buffer::layout::LinearLayout::new(
                width as usize,
                (width * 4) as usize,
                height as usize,
            ),
        })
    }

    pub fn from_buffer_collection(
        buffer_collection: &mut BufferCollectionSynchronousProxy,
        width: u32,
        height: u32,
        index: u32,
    ) -> Self {
        let wait_result = buffer_collection
            .wait_for_all_buffers_allocated(zx::MonotonicInstant::INFINITE)
            .expect("failed to allocate buffer collection");
        assert!(
            wait_result.is_ok(),
            "wait_for_all_buffers_allocated failed: {:?}",
            wait_result.unwrap_err()
        );

        let buffers = wait_result.unwrap().buffer_collection_info.unwrap();
        let vmo_buffer = &buffers.buffers.as_ref().unwrap()[index as usize];
        let vmo = vmo_buffer
            .vmo
            .as_ref()
            .expect("failed to get VMO buffer")
            .duplicate_handle(zx::Rights::SAME_RIGHTS)
            .expect("failed to duplicate VMO handle");

        let settings = buffers.settings.as_ref().unwrap();
        let buffer_settings = settings.buffer_settings.as_ref().unwrap();
        let len_bytes = buffer_settings.size_bytes.as_ref().unwrap();
        let mapping = Arc::new(
            mapped_vmo::Mapping::create_from_vmo(
                &vmo,
                *len_bytes as usize,
                zx::VmarFlags::PERM_READ
                    | zx::VmarFlags::PERM_WRITE
                    | zx::VmarFlags::MAP_RANGE
                    | zx::VmarFlags::REQUIRE_NON_RESIZABLE,
            )
            .expect("failed to crate mapping from VMO"),
        );

        assert!(settings.image_format_constraints.is_some());
        let image_format_constraints = settings.image_format_constraints.as_ref().unwrap();
        let bytes_per_row = image_format_constraints.min_bytes_per_row.as_ref().unwrap();
        let divisor = image_format_constraints.bytes_per_row_divisor.as_ref().unwrap();
        let bytes_per_row = ((bytes_per_row + divisor - 1) / divisor) * divisor;
        let stride = bytes_per_row as usize / mem::size_of::<u8>();

        Self {
            vmo,
            width,
            height,
            len_bytes: *len_bytes as u64,
            mapping,
            stride,
            buffer_layer_cache: None,
            coherency_domain: *buffer_settings.coherency_domain.as_ref().unwrap(),
            layout: forma::buffer::layout::LinearLayout::new(
                width as usize,
                stride,
                height as usize,
            ),
        }
    }

    pub fn bytes_per_row(&self) -> usize {
        self.stride * mem::size_of::<u8>()
    }

    pub fn coherency_domain(&self) -> CoherencyDomain {
        self.coherency_domain
    }

    pub fn as_mut_slice(&mut self) -> &mut [u8] {
        let (data, len) = Arc::get_mut(&mut self.mapping).unwrap().as_ptr_len();
        unsafe { slice::from_raw_parts_mut(data, len) }
    }

    pub fn as_buffer(
        &mut self,
    ) -> forma::buffer::Buffer<'_, '_, forma::buffer::layout::LinearLayout> {
        #[derive(Debug)]
        struct SliceFlusher;

        impl forma::buffer::layout::Flusher for SliceFlusher {
            fn flush(&self, slice: &mut [u8]) {
                unsafe {
                    sys::zx_cache_flush(
                        slice.as_ptr() as *const u8,
                        slice.len(),
                        sys::ZX_CACHE_FLUSH_DATA,
                    );
                }
            }
        }

        let (data, len) = Arc::get_mut(&mut self.mapping).unwrap().as_ptr_len();
        let raw_buffer = unsafe { slice::from_raw_parts_mut(data as *mut u8, len) };

        let mut buffer = forma::buffer::BufferBuilder::new(raw_buffer, &mut self.layout);

        if let Some(buffer_layer_cache) =
            self.buffer_layer_cache.as_ref().map(|(_, cache)| cache).cloned()
        {
            buffer = buffer.layer_cache(buffer_layer_cache);
        }

        if self.coherency_domain == CoherencyDomain::Ram {
            buffer = buffer.flusher(Box::new(SliceFlusher));
        }

        buffer.build()
    }

    pub fn clear(&mut self, clear_color: [u8; 4]) {
        duration!(c"gfx", c"VmoImage::clear");

        if let Some((_, buffer_layer_cache)) = self.buffer_layer_cache.as_ref() {
            buffer_layer_cache.clear();
        }

        let coherency_domain = self.coherency_domain;

        let (data, len) = Arc::get_mut(&mut self.mapping).unwrap().as_ptr_len();
        let buffer = unsafe { slice::from_raw_parts_mut(data as *mut u8, len) };

        forma::clear_buffer(buffer, clear_color);

        if coherency_domain == CoherencyDomain::Ram {
            unsafe {
                sys::zx_cache_flush(
                    buffer.as_ptr() as *const u8,
                    buffer.len(),
                    sys::ZX_CACHE_FLUSH_DATA,
                );
            }
        }
    }
}