Debian Codegraph @

experimental/rust_bmp/ffi/FFI.rs

raw
1 // Copyright 2025 Google LLC
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4
5 //! C++/Rust FFI for BMP decoder using the image-rs crate.
6
7 #[cxx::bridge(namespace = "rust_bmp")]
8 mod ffi {
9 #[derive(Debug, Clone, Copy)]
10 enum DecodingResult {
11 Success,
12 FormatError,
13 ParameterError,
14 UnsupportedFeature,
15 IncompleteInput,
16 MemoryError,
17 OtherError,
18 }
19
20 /// BMP color type matching SkEncodedInfo::Color values.
21 /// Static assertions in C++ validate these match at compile time.
22 #[repr(i32)]
23 #[derive(Debug, Clone, Copy, PartialEq)]
24 enum BmpColor {
25 RGB = 5,
26 RGBA = 6,
27 BGR = 7,
28 BGRA = 9,
29 }
30
31 /// BMP alpha type matching SkEncodedInfo::Alpha values.
32 /// Static assertions in C++ validate these match at compile time.
33 #[repr(i32)]
34 #[derive(Debug, Clone, Copy, PartialEq)]
35 enum BmpAlpha {
36 Opaque = 0,
37 Unpremul = 1,
38 }
39
40 unsafe extern "C++" {
41 include!("rust/common/SkStreamAdapter.h");
42
43 #[namespace = "rust::stream"]
44 type SkStreamAdapter = skia_rust_common::SkStreamAdapter;
45 }
46
47 extern "Rust" {
48 fn is_bmp_data(data: &[u8]) -> bool;
49
50 fn new_reader(input: UniquePtr<SkStreamAdapter>) -> Box<ResultOfReader>;
51
52 type ResultOfReader;
53 fn err(self: &ResultOfReader) -> DecodingResult;
54 fn unwrap(self: &mut ResultOfReader) -> Box<Reader>;
55
56 type Reader;
57 fn width(self: &Reader) -> u32;
58 fn height(self: &Reader) -> u32;
59 fn color(self: &Reader) -> BmpColor;
60 fn alpha(self: &Reader) -> BmpAlpha;
61 fn next_row(self: &mut Reader, buffer: &mut [u8]) -> DecodingResult;
62 fn reset_decode_state(self: &mut Reader);
63 }
64 }
65
66 pub use ffi::*;
67
68 #[derive(Debug)]
69 enum BmpError {
70 InsufficientData,
71 InvalidData,
72 UnsupportedFeature,
73 InvalidHeader,
74 IoError,
75 FormatError,
76 }
77
78 impl From<image::ImageError> for BmpError {
79 fn from(err: image::ImageError) -> Self {
80 match err {
81 image::ImageError::Decoding(_) => BmpError::FormatError,
82 image::ImageError::Encoding(_) => BmpError::FormatError,
83 image::ImageError::Parameter(_) => {
84 panic!(
85 "Internal bug in how Skia Rust BMP calls image crate: {:?}",
86 err
87 )
88 }
89 image::ImageError::Limits(_) => BmpError::UnsupportedFeature,
90 image::ImageError::Unsupported(_) => BmpError::UnsupportedFeature,
91 image::ImageError::IoError(_) => BmpError::IoError,
92 }
93 }
94 }
95
96 impl From<std::io::Error> for BmpError {
97 fn from(err: std::io::Error) -> Self {
98 use std::io::ErrorKind;
99 match err.kind() {
100 ErrorKind::UnexpectedEof => BmpError::InsufficientData,
101 _ => BmpError::IoError,
102 }
103 }
104 }
105
106 pub fn is_bmp_data(data: &[u8]) -> bool {
107 // "IC", "PT", "CI", "CP", "BA" are not yet supported by image crate.
108 data.len() >= 2 && data[0] == b'B' && data[1] == b'M'
109 }
110
111 pub struct ResultOfReader {
112 result: Result<Reader, BmpError>,
113 }
114
115 impl ResultOfReader {
116 pub fn err(&self) -> DecodingResult {
117 match &self.result {
118 Ok(_) => DecodingResult::Success,
119 Err(BmpError::InvalidHeader) => DecodingResult::FormatError,
120 Err(BmpError::InsufficientData) => DecodingResult::IncompleteInput,
121 Err(BmpError::UnsupportedFeature) => DecodingResult::UnsupportedFeature,
122 Err(BmpError::InvalidData) => DecodingResult::FormatError,
123 Err(BmpError::IoError) => DecodingResult::OtherError,
124 Err(BmpError::FormatError) => DecodingResult::FormatError,
125 }
126 }
127
128 pub fn unwrap(&mut self) -> Box<Reader> {
129 match std::mem::replace(&mut self.result, Err(BmpError::InvalidHeader)) {
130 Ok(reader) => Box::new(reader),
131 Err(_) => panic!("Called unwrap on an error ResultOfReader"),
132 }
133 }
134 }
135
136 /// Image-rs BMP decoder doesn't support true row-by-row streaming, so this
137 /// Reader decodes the entire image upfront and provides row access via next_row().
138 pub struct Reader {
139 pixels: Vec<u8>,
140 width: u32,
141 height: u32,
142 color: BmpColor,
143 alpha: BmpAlpha,
144 bytes_per_pixel: u32,
145 current_row: u32,
146 }
147
148 impl Reader {
149 fn new(mut input: cxx::UniquePtr<ffi::SkStreamAdapter>) -> Result<Self, BmpError> {
150 use std::io::{Cursor, Read};
151
152 // TODO(crbug.com/452666425): Support incremental decoding for incomplete data. Currently we
153 // read the entire stream upfront because image-rs BmpDecoder requires
154 // seekable input (std::io::Seek). This means if the stream has incomplete
155 // data, we fail during MakeFromStream and the caller must retry from scratch.
156 // For better streaming: buffer data incrementally and retry BmpDecoder::new()
157 // when more data arrives (similar to SkPngRustCodec).
158
159 let mut data = Vec::new();
160 input
161 .as_mut()
162 .expect("input should not be null")
163 .read_to_end(&mut data)
164 .map_err(|_| BmpError::InsufficientData)?;
165
166 let mut cursor = Cursor::new(&data);
167 let decoder = image::codecs::bmp::BmpDecoder::new(&mut cursor)
168 .map_err(|_| BmpError::InvalidHeader)?;
169
170 let (width, height) = image::ImageDecoder::dimensions(&decoder);
171 let image_color_type = image::ImageDecoder::color_type(&decoder);
172
173 // image-rs converts BGR→RGB internally. BmpColor also supports BGR for
174 // future decoders that might preserve native order.
175 let (color, alpha, bytes_per_pixel) = match image_color_type {
176 image::ColorType::Rgb8 => (BmpColor::RGB, BmpAlpha::Opaque, 3),
177 image::ColorType::Rgba8 => (BmpColor::RGBA, BmpAlpha::Unpremul, 4),
178 _ => {
179 return Err(BmpError::UnsupportedFeature);
180 }
181 };
182
183 // TODO(crbug.com/452666425): Extract ICC profile for color-managed decoding. BMP files can
184 // embed ICC profiles in BITMAPV5HEADER format at offset 0x7A, but
185 // image-rs doesn't expose this. Once rust/icc module lands, parse the
186 // BMP header manually to extract profile bytes, validate with
187 // rust/icc::parse_icc_profile(), and pass to C++ via ResultOfReader
188 // for SkEncodedInfo integration.
189
190 let total_bytes = image::ImageDecoder::total_bytes(&decoder) as usize;
191 let mut pixels = vec![0u8; total_bytes];
192 image::ImageDecoder::read_image(decoder, &mut pixels).map_err(|_| BmpError::InvalidData)?;
193
194 Ok(Reader {
195 pixels,
196 width,
197 height,
198 color,
199 alpha,
200 bytes_per_pixel,
201 current_row: 0,
202 })
203 }
204
205 pub fn width(&self) -> u32 {
206 self.width
207 }
208
209 pub fn height(&self) -> u32 {
210 self.height
211 }
212
213 pub fn color(&self) -> BmpColor {
214 self.color
215 }
216
217 pub fn alpha(&self) -> BmpAlpha {
218 self.alpha
219 }
220
221 pub fn reset_decode_state(&mut self) {
222 self.current_row = 0;
223 }
224
225 pub fn next_row(&mut self, buffer: &mut [u8]) -> DecodingResult {
226 if self.current_row >= self.height {
227 return DecodingResult::Success;
228 }
229
230 let row_bytes = (self.width * self.bytes_per_pixel) as usize;
231
232 if buffer.len() < row_bytes {
233 return DecodingResult::ParameterError;
234 }
235
236 let row_offset = (self.current_row as usize) * row_bytes;
237 buffer[..row_bytes].copy_from_slice(&self.pixels[row_offset..row_offset + row_bytes]);
238
239 self.current_row += 1;
240 DecodingResult::Success
241 }
242 }
243
244 pub fn new_reader(input: cxx::UniquePtr<ffi::SkStreamAdapter>) -> Box<ResultOfReader> {
245 let result = Reader::new(input);
246 Box::new(ResultOfReader { result })
247 }
248
249 #[cfg(test)]
250 mod tests {
251 use super::*;
252
253 #[test]
254 fn test_is_bmp_data() {
255 // Valid BMP signature (BM)
256 let valid_bmp = vec![b'B', b'M', 0x00, 0x00];
257 assert!(is_bmp_data(&valid_bmp));
258
259 // BA signature not yet supported by image crate
260 let valid_ba = vec![b'B', b'A', 0x00, 0x00];
261 assert!(!is_bmp_data(&valid_ba));
262
263 // Invalid signature
264 let invalid = vec![0x89, b'P', b'N', b'G']; // PNG signature
265 assert!(!is_bmp_data(&invalid));
266
267 // Too short
268 let too_short = vec![b'B'];
269 assert!(!is_bmp_data(&too_short));
270
271 // Empty
272 assert!(!is_bmp_data(&[]));
273 }
274 }