Debian Codegraph @

rust/png/FFI.rs

raw
1 // Copyright 2024 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 //! This crate provides C++ bindings for the `png` Rust crate.
6 //!
7 //! The public API of this crate is the C++ API declared by the `#[cxx::bridge]`
8 //! macro below and exposed through the auto-generated `FFI.rs.h` header.
9
10 use std::borrow::Cow;
11 use std::io::{BufReader, ErrorKind, Write};
12 use std::pin::Pin;
13
14 // No `use png::...` nor `use ffi::...` because we want the code to explicitly
15 // spell out if it means `ffi::ColorType` vs `png::ColorType` (or `Reader`
16 // vs `png::Reader`).
17
18 #[cxx::bridge(namespace = "rust_png")]
19 mod ffi {
20 /// FFI-friendly equivalent of `png::ColorType`.
21 enum ColorType {
22 Grayscale = 0,
23 Rgb = 2,
24 Indexed = 3,
25 GrayscaleAlpha = 4,
26 Rgba = 6,
27 }
28
29 /// FFI-friendly simplification of `Option<png::DecodingError>`.
30 enum DecodingResult {
31 Success,
32 FormatError,
33 ParameterError,
34 LimitsExceededError,
35 /// `IncompleteInput` is equivalent to `png::DecodingError::IoError(
36 /// std::io::ErrorKind::UnexpectedEof.into())`. It is named after
37 /// `SkCodec::Result::kIncompleteInput`.
38 IncompleteInput,
39 OtherIoError,
40 EndOfFrame,
41 }
42
43 /// FFI-friendly equivalent of `png::DisposeOp`.
44 enum DisposeOp {
45 None,
46 Background,
47 Previous,
48 }
49
50 /// FFI-friendly equivalent of `png::BlendOp`.
51 enum BlendOp {
52 Source,
53 Over,
54 }
55
56 /// FFI-friendly simplification of `png::Compression`.
57 enum Compression {
58 /// In png-0.18.0-rc `Fastest` level would fall back to `Level1WithUpFilter` when using
59 /// `StreamWriter`. See also code links below:
60 /// * In 0.18-rc2 `Fastest` initially maps to `FdeflateUltraFast`, but in the end falls back to `flate2`
61 /// when using `StreamWriter`:
62 /// - https://github.com/image-rs/image-png/blob/9294c26dc3ca7622f791e880810b575193fb6c29/src/common.rs#L414
63 /// - https://github.com/image-rs/image-png/blob/33afddab77449bcd93b1783d2d0ca8ba744cc3c3/src/encoder.rs#L1402
64 /// - https://github.com/image-rs/image-png/blob/33afddab77449bcd93b1783d2d0ca8ba744cc3c3/src/common.rs#L413
65 /// * In 0.18-rc2 `Fastest` maps to `Up`:
66 /// https://github.com/image-rs/image-png/blob/9294c26dc3ca7622f791e880810b575193fb6c29/src/filter.rs#L47
67 ///
68 /// In newer versions, `Fastest` may map to `fdeflate` backend.
69 /// We export `Level1WithUpFilter` as an explicit, separate level to preserve the M136
70 /// behavior that was tested in a field trial and approved for shipping.
71 ///
72 /// TODO(https://crbug.com/406072770): Revisit this in the future and only use the built-in
73 /// levels in the long term.
74 Level1WithUpFilter,
75 /// Maps to `png::Compression::Fastest`.
76 Fastest,
77 /// Maps to `png::Compression::Fast`.
78 Fast,
79 /// Maps to `png::Compression::Balanced`.
80 Balanced,
81 /// Maps to `png::Compression::High`.
82 High,
83 }
84
85 /// FFI-friendly simplification of `Option<png::EncodingError>`.
86 enum EncodingResult {
87 Success,
88 IoError,
89 FormatError,
90 ParameterError,
91 LimitsExceededError,
92 }
93
94 /// FFI/layering-friendly equivalent of `SkColorSpacePrimaries from C/C++.
95 struct ColorSpacePrimaries {
96 fRX: f32,
97 fRY: f32,
98 fGX: f32,
99 fGY: f32,
100 fBX: f32,
101 fBY: f32,
102 fWX: f32,
103 fWY: f32,
104 }
105
106 /// FFI/layering-friendly equivalent of `skhdr::MasteringDisplayColorVolume` from C/C++.
107 struct MasteringDisplayColorVolume {
108 fDisplayPrimaries: ColorSpacePrimaries,
109 fMaximumDisplayMasteringLuminance: f32,
110 fMinimumDisplayMasteringLuminance: f32,
111 }
112
113 /// FFI/layering-friendly equivalent of `skhdr::ContentLightLevelInformation` from C/C++.
114 struct ContentLightLevelInfo {
115 fMaxCLL: f32,
116 fMaxFALL: f32,
117 }
118
119 unsafe extern "C++" {
120 include!("rust/png/FFI.h");
121 include!("rust/common/SkStreamAdapter.h");
122
123 // Reference the SkStreamAdapter type from skia_rust_common.
124 #[namespace = "rust::stream"]
125 type SkStreamAdapter = skia_rust_common::SkStreamAdapter;
126
127 type WriteTrait;
128 fn write(self: Pin<&mut WriteTrait>, buffer: &[u8]) -> bool;
129 fn flush(self: Pin<&mut WriteTrait>);
130 }
131
132 // Rust functions, types, and methods that are exposed through FFI.
133 //
134 // To avoid duplication, there are no doc comments inside the `extern "Rust"`
135 // section. The doc comments of these items can instead be found in the
136 // actual Rust code, outside of the `#[cxx::bridge]` manifest.
137 extern "Rust" {
138 fn new_reader(input: UniquePtr<SkStreamAdapter>) -> Box<ResultOfReader>;
139
140 type ResultOfReader;
141 fn err(self: &ResultOfReader) -> DecodingResult;
142 fn unwrap(self: &mut ResultOfReader) -> Box<Reader>;
143
144 type Reader;
145 fn height(self: &Reader) -> u32;
146 fn width(self: &Reader) -> u32;
147 fn interlaced(self: &Reader) -> bool;
148 fn is_srgb(self: &Reader) -> bool;
149 fn try_get_chrm(self: &Reader, chrm: &mut ColorSpacePrimaries) -> bool;
150 fn try_get_cicp_chunk(
151 self: &Reader,
152 primaries_id: &mut u8,
153 transfer_id: &mut u8,
154 matrix_id: &mut u8,
155 is_full_range: &mut bool,
156 ) -> bool;
157 fn try_get_mdcv_chunk(self: &Reader, mdcv: &mut MasteringDisplayColorVolume) -> bool;
158 fn try_get_clli_chunk(self: &Reader, clli: &mut ContentLightLevelInfo) -> bool;
159 fn try_get_gama(self: &Reader, gamma: &mut f32) -> bool;
160 fn has_exif_chunk(self: &Reader) -> bool;
161 fn get_exif_chunk(self: &Reader) -> &[u8];
162 fn has_iccp_chunk(self: &Reader) -> bool;
163 fn get_iccp_chunk(self: &Reader) -> &[u8];
164 fn has_trns_chunk(self: &Reader) -> bool;
165 fn get_trns_chunk(self: &Reader) -> &[u8];
166 fn has_plte_chunk(self: &Reader) -> bool;
167 fn get_plte_chunk(self: &Reader) -> &[u8];
168 fn has_actl_chunk(self: &Reader) -> bool;
169 fn get_actl_num_frames(self: &Reader) -> u32;
170 fn get_actl_num_plays(self: &Reader) -> u32;
171 fn has_fctl_chunk(self: &Reader) -> bool;
172 fn get_fctl_info(
173 self: &Reader,
174 width: &mut u32,
175 height: &mut u32,
176 x_offset: &mut u32,
177 y_offset: &mut u32,
178 dispose_op: &mut DisposeOp,
179 blend_op: &mut BlendOp,
180 duration_ms: &mut u32,
181 );
182 fn has_sbit_chunk(self: &Reader) -> bool;
183 fn get_sbit_chunk(self: &Reader) -> &[u8];
184 fn output_color_type(self: &Reader) -> ColorType;
185 fn output_bits_per_component(self: &Reader) -> u8;
186 fn next_frame_info(self: &mut Reader) -> DecodingResult;
187 unsafe fn next_interlaced_row<'a>(
188 self: &'a mut Reader,
189 row: &mut &'a [u8],
190 ) -> DecodingResult;
191 fn expand_last_interlaced_row(
192 self: &Reader,
193 img: &mut [u8],
194 img_row_stride: usize,
195 row: &[u8],
196 bits_per_pixel: u8,
197 );
198 unsafe fn read_row(self: &mut Reader, output_buffer: &mut [u8]) -> DecodingResult;
199
200 fn new_writer(
201 output: UniquePtr<WriteTrait>,
202 width: u32,
203 height: u32,
204 color: ColorType,
205 bits_per_component: u8,
206 compression: Compression,
207 icc_profile: &[u8],
208 ) -> Box<ResultOfWriter>;
209
210 type ResultOfWriter;
211 fn err(self: &ResultOfWriter) -> EncodingResult;
212 fn unwrap(self: &mut ResultOfWriter) -> Box<Writer>;
213
214 type Writer;
215 fn write_text_chunk(self: &mut Writer, keyword: &[u8], text: &[u8]) -> EncodingResult;
216 fn convert_writer_into_stream_writer(writer: Box<Writer>) -> Box<ResultOfStreamWriter>;
217
218 type ResultOfStreamWriter;
219 fn err(self: &ResultOfStreamWriter) -> EncodingResult;
220 fn unwrap(self: &mut ResultOfStreamWriter) -> Box<StreamWriter>;
221
222 type StreamWriter;
223 fn write(self: &mut StreamWriter, data: &[u8]) -> EncodingResult;
224 fn finish_encoding(stream_writer: Box<StreamWriter>) -> EncodingResult;
225 }
226 }
227
228 impl From<png::ColorType> for ffi::ColorType {
229 fn from(value: png::ColorType) -> Self {
230 match value {
231 png::ColorType::Grayscale => Self::Grayscale,
232 png::ColorType::Rgb => Self::Rgb,
233 png::ColorType::Indexed => Self::Indexed,
234 png::ColorType::GrayscaleAlpha => Self::GrayscaleAlpha,
235 png::ColorType::Rgba => Self::Rgba,
236 }
237 }
238 }
239
240 impl Into<png::ColorType> for ffi::ColorType {
241 fn into(self) -> png::ColorType {
242 match self {
243 Self::Grayscale => png::ColorType::Grayscale,
244 Self::Rgb => png::ColorType::Rgb,
245 Self::GrayscaleAlpha => png::ColorType::GrayscaleAlpha,
246 Self::Rgba => png::ColorType::Rgba,
247
248 // `SkPngRustEncoderImpl` only uses the color types above.
249 _ => unreachable!(),
250 }
251 }
252 }
253
254 impl From<png::DisposeOp> for ffi::DisposeOp {
255 fn from(value: png::DisposeOp) -> Self {
256 match value {
257 png::DisposeOp::None => Self::None,
258 png::DisposeOp::Background => Self::Background,
259 png::DisposeOp::Previous => Self::Previous,
260 }
261 }
262 }
263
264 impl From<png::BlendOp> for ffi::BlendOp {
265 fn from(value: png::BlendOp) -> Self {
266 match value {
267 png::BlendOp::Source => Self::Source,
268 png::BlendOp::Over => Self::Over,
269 }
270 }
271 }
272
273 impl From<Option<&png::DecodingError>> for ffi::DecodingResult {
274 fn from(option: Option<&png::DecodingError>) -> Self {
275 match option {
276 None => Self::Success,
277 Some(decoding_error) => match decoding_error {
278 png::DecodingError::IoError(e) => {
279 if e.kind() == ErrorKind::UnexpectedEof {
280 Self::IncompleteInput
281 } else {
282 Self::OtherIoError
283 }
284 }
285 png::DecodingError::Format(_) => Self::FormatError,
286 png::DecodingError::Parameter(_) => Self::ParameterError,
287 png::DecodingError::LimitsExceeded => Self::LimitsExceededError,
288 },
289 }
290 }
291 }
292
293 impl ffi::Compression {
294 fn apply<'a, W: Write>(&self, encoder: &mut png::Encoder<'a, W>) {
295 match self {
296 &Self::Level1WithUpFilter => {
297 encoder.set_deflate_compression(png::DeflateCompression::Level(1));
298 encoder.set_filter(png::Filter::Up);
299 }
300 &Self::Fastest => encoder.set_compression(png::Compression::Fastest),
301 &Self::Fast => encoder.set_compression(png::Compression::Fast),
302 &Self::Balanced => encoder.set_compression(png::Compression::Balanced),
303 &Self::High => encoder.set_compression(png::Compression::High),
304 _ => unreachable!(),
305 }
306 }
307 }
308
309 impl From<Option<&png::EncodingError>> for ffi::EncodingResult {
310 fn from(option: Option<&png::EncodingError>) -> Self {
311 match option {
312 None => Self::Success,
313 Some(encoding_error) => match encoding_error {
314 png::EncodingError::IoError(_) => Self::IoError,
315 png::EncodingError::Format(_) => Self::FormatError,
316 png::EncodingError::Parameter(_) => Self::ParameterError,
317 png::EncodingError::LimitsExceeded => Self::LimitsExceededError,
318 },
319 }
320 }
321 }
322
323 impl<'a> Write for Pin<&'a mut ffi::WriteTrait> {
324 fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
325 if self.as_mut().write(buf) {
326 Ok(buf.len())
327 } else {
328 Err(ErrorKind::Other.into())
329 }
330 }
331
332 fn flush(&mut self) -> std::io::Result<()> {
333 self.as_mut().flush();
334 Ok(())
335 }
336 }
337
338 /// FFI-friendly wrapper around `Result<T, E>` (`cxx` can't handle arbitrary
339 /// generics, so we manually monomorphize here, but still expose a minimal,
340 /// somewhat tweaked API of the original type).
341 struct ResultOfReader(Result<Reader, png::DecodingError>);
342
343 impl ResultOfReader {
344 fn err(&self) -> ffi::DecodingResult {
345 self.0.as_ref().err().into()
346 }
347
348 fn unwrap(&mut self) -> Box<Reader> {
349 // Leaving `self` in a C++-friendly "moved-away" state.
350 let mut result = Err(png::DecodingError::LimitsExceeded);
351 std::mem::swap(&mut self.0, &mut result);
352
353 Box::new(result.unwrap())
354 }
355 }
356
357 fn compute_transformations(info: &png::Info) -> png::Transformations {
358 // There are 2 scenarios where `EXPAND` transformation may be needed:
359 //
360 // * `SkSwizzler` can handle low-bit-depth `ColorType::Indexed`, but it may not
361 // support other inputs with low bit depth (e.g. `kGray_Color` with bpp=4). We
362 // use `EXPAND` to ask the `png` crate to expand such low-bpp images to at
363 // least 8 bits.
364 // * We may need to inject an alpha channel from the `tRNS` chunk if present.
365 // Note that we can't check `info.trns.is_some()` because at this point we
366 // have not yet read beyond the `IHDR` chunk.
367 //
368 // We avoid using `EXPAND` for `ColorType::Indexed` because this results in some
369 // performance gains - see https://crbug.com/356882657 for more details.
370 let mut result = match info.color_type {
371 // Work around bpp<8 limitations of `SkSwizzler`
372 png::ColorType::Rgba | png::ColorType::GrayscaleAlpha if (info.bit_depth as u8) < 8 => {
373 png::Transformations::EXPAND
374 }
375
376 // Handle `tRNS` expansion + work around bpp<8 limitations of `SkSwizzler`
377 png::ColorType::Rgb | png::ColorType::Grayscale => png::Transformations::EXPAND,
378
379 // Otherwise there is no need to `EXPAND`.
380 png::ColorType::Indexed | png::ColorType::Rgba | png::ColorType::GrayscaleAlpha => {
381 png::Transformations::IDENTITY
382 }
383 };
384
385 // We mimic how the `libpng`-based `SkPngCodec` handles G16 and GA16.
386 //
387 // TODO(https://crbug.com/359245096): Avoid stripping least signinficant 8 bits in G16 and
388 // GA16 images.
389 result = {
390 #[cfg(not(feature = "skia_png_new_gray16_behavior_for_crbug359245096"))]
391 {
392 if info.bit_depth == png::BitDepth::Sixteen {
393 if matches!(
394 info.color_type,
395 png::ColorType::Grayscale | png::ColorType::GrayscaleAlpha
396 ) {
397 result |= png::Transformations::STRIP_16;
398 }
399 }
400
401 result
402 }
403
404 #[cfg(feature = "skia_png_new_gray16_behavior_for_crbug359245096")]
405 {
406 result
407 }
408 };
409
410 result
411 }
412
413 /// FFI-friendly wrapper around `png::Reader<R>` (`cxx` can't handle arbitrary
414 /// generics, so we manually monomorphize here, but still expose a minimal,
415 /// somewhat tweaked API of the original type).
416 struct Reader {
417 reader: png::Reader<BufReader<cxx::UniquePtr<ffi::SkStreamAdapter>>>,
418 last_interlace_info: Option<png::InterlaceInfo>,
419 }
420
421 impl Reader {
422 fn new(input: cxx::UniquePtr<ffi::SkStreamAdapter>) -> Result<Self, png::DecodingError> {
423 // The magic value of `BUF_CAPACITY` is based on `CHUNK_BUFFER_SIZE` which was
424 // used in `BufReader::with_capacity` calls by `png` crate up to version
425 // 0.17.16 - see: https://github.com/image-rs/image-png/pull/558/files#diff-c28833b65510e37441203b4256b74068f191d29ea34b6e753442e644d3a316b8L28
426 // and
427 // https://github.com/image-rs/image-png/blob/eb9b5d7f371b88f15aaca6a8d21c58b86c400d76/src/decoder/stream.rs#L21
428 const BUF_CAPACITY: usize = 32 * 1024;
429 // TODO(https://crbug.com/399894620): Consider instead implementing `BufRead` on top of
430 // `SkStream` API when/if possible in the future.
431 let input = BufReader::with_capacity(BUF_CAPACITY, input);
432
433 let mut decoder = {
434 // By default, `DecodeOptions` cap the memory usage at using 64 Mib.
435 let mut options = png::DecodeOptions::default();
436 if cfg!(FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION) {
437 options.set_ignore_checksums(true);
438 }
439 options.set_ignore_text_chunk(true);
440 png::Decoder::new_with_options(input, options)
441 };
442
443 let info = decoder.read_header_info()?;
444 let transformations = compute_transformations(info);
445 decoder.set_transformations(transformations);
446
447 Ok(Self {
448 reader: decoder.read_info()?,
449 last_interlace_info: None,
450 })
451 }
452
453 fn height(&self) -> u32 {
454 self.reader.info().height
455 }
456
457 fn width(&self) -> u32 {
458 self.reader.info().width
459 }
460
461 /// Returns whether the PNG image is interlaced.
462 fn interlaced(&self) -> bool {
463 self.reader.info().interlaced
464 }
465
466 /// Returns whether the decoded PNG image contained a `sRGB` chunk.
467 fn is_srgb(&self) -> bool {
468 self.reader.info().srgb.is_some()
469 }
470
471 /// If the decoded PNG image contained a `cHRM` chunk then `try_get_chrm`
472 /// returns `true` and populates the out parameters (`wx`, `wy`, `rx`,
473 /// etc.). Otherwise, returns `false`.
474 fn try_get_chrm(&self, chrm: &mut ffi::ColorSpacePrimaries) -> bool {
475 fn copy_channel(channel: &(png::ScaledFloat, png::ScaledFloat), x: &mut f32, y: &mut f32) {
476 *x = png_u32_into_f32(channel.0);
477 *y = png_u32_into_f32(channel.1);
478 }
479
480 match self.reader.info().chrm_chunk.as_ref() {
481 None => false,
482 Some(png_chrm) => {
483 copy_channel(&png_chrm.white, &mut chrm.fWX, &mut chrm.fWY);
484 copy_channel(&png_chrm.red, &mut chrm.fRX, &mut chrm.fRY);
485 copy_channel(&png_chrm.green, &mut chrm.fGX, &mut chrm.fGY);
486 copy_channel(&png_chrm.blue, &mut chrm.fBX, &mut chrm.fBY);
487 true
488 }
489 }
490 }
491
492 /// If the decoded PNG image contained a `cICP` chunk then
493 /// `try_get_cicp_chunk` returns `true` and populates the out
494 /// parameters. Otherwise, returns `false`.
495 fn try_get_cicp_chunk(
496 &self,
497 primaries_id: &mut u8,
498 transfer_id: &mut u8,
499 matrix_id: &mut u8,
500 is_full_range: &mut bool,
501 ) -> bool {
502 match self.reader.info().coding_independent_code_points.as_ref() {
503 None => false,
504 Some(cicp) => {
505 *primaries_id = cicp.color_primaries;
506 *transfer_id = cicp.transfer_function;
507 *matrix_id = cicp.matrix_coefficients;
508 *is_full_range = cicp.is_video_full_range_image;
509 true
510 }
511 }
512 }
513
514 /// If the decoded PNG image contained a `mDCV` chunk then
515 /// `try_get_mdcv_chunk` returns `true` and populates the out parameters
516 /// as values that are CIE 1931 xy coordinates or values in cd/m^2.
517 /// Otherwise, returns `false`.
518 fn try_get_mdcv_chunk(self: &Reader, mdcv: &mut ffi::MasteringDisplayColorVolume) -> bool {
519 match self.reader.info().mastering_display_color_volume.as_ref() {
520 None => false,
521 Some(png_mdcv) => {
522 *mdcv = ffi::MasteringDisplayColorVolume {
523 fDisplayPrimaries: ffi::ColorSpacePrimaries {
524 fRX: png_mdcv.chromaticities.red.0.into_value(),
525 fRY: png_mdcv.chromaticities.red.1.into_value(),
526 fGX: png_mdcv.chromaticities.green.0.into_value(),
527 fGY: png_mdcv.chromaticities.green.1.into_value(),
528 fBX: png_mdcv.chromaticities.blue.0.into_value(),
529 fBY: png_mdcv.chromaticities.blue.1.into_value(),
530 fWX: png_mdcv.chromaticities.white.0.into_value(),
531 fWY: png_mdcv.chromaticities.white.1.into_value(),
532 },
533 fMaximumDisplayMasteringLuminance: png_mdcv.max_luminance as f32 / 10_000.0,
534 fMinimumDisplayMasteringLuminance: png_mdcv.min_luminance as f32 / 10_000.0,
535 };
536 true
537 }
538 }
539 }
540
541 /// If the decoded PNG image contained a `cLLI` chunk then
542 /// `try_get_clli_chunk` returns `true` and populates the out
543 /// parameters as values in cd/m^2. Otherwise, returns `false`.
544 fn try_get_clli_chunk(&self, clli: &mut ffi::ContentLightLevelInfo) -> bool {
545 match self.reader.info().content_light_level.as_ref() {
546 None => false,
547 Some(png_clli) => {
548 *clli = ffi::ContentLightLevelInfo {
549 fMaxCLL: png_clli.max_content_light_level as f32 / 10_000.0,
550 fMaxFALL: png_clli.max_frame_average_light_level as f32 / 10_000.0,
551 };
552 true
553 }
554 }
555 }
556
557 /// If the decoded PNG image contained a `gAMA` chunk then `try_get_gama`
558 /// returns `true` and populates the `gamma` out parameter. Otherwise,
559 /// returns `false`.
560 fn try_get_gama(&self, gamma: &mut f32) -> bool {
561 match self.reader.info().gama_chunk.as_ref() {
562 None => false,
563 Some(&scaled_float) => {
564 *gamma = png_u32_into_f32(scaled_float);
565 true
566 }
567 }
568 }
569
570 /// Returns whether the `eXIf` chunk exists.
571 fn has_exif_chunk(&self) -> bool {
572 self.reader.info().exif_metadata.is_some()
573 }
574
575 /// Returns contents of the `eXIf` chunk. Panics if there is no `eXIf`
576 /// chunk.
577 fn get_exif_chunk(&self) -> &[u8] {
578 self.reader.info().exif_metadata.as_ref().unwrap().as_ref()
579 }
580
581 /// Returns whether the `iCCP` chunk exists.
582 fn has_iccp_chunk(&self) -> bool {
583 self.reader.info().icc_profile.is_some()
584 }
585
586 /// Returns contents of the `iCCP` chunk. Panics if there is no `iCCP`
587 /// chunk.
588 fn get_iccp_chunk(&self) -> &[u8] {
589 self.reader.info().icc_profile.as_ref().unwrap().as_ref()
590 }
591
592 /// Returns whether the `tRNS` chunk exists.
593 fn has_trns_chunk(&self) -> bool {
594 self.reader.info().trns.is_some()
595 }
596
597 /// Returns contents of the `tRNS` chunk. Panics if there is no `tRNS`
598 /// chunk.
599 fn get_trns_chunk(&self) -> &[u8] {
600 self.reader.info().trns.as_ref().unwrap().as_ref()
601 }
602
603 /// Returns whether the `PLTE` chunk exists.
604 fn has_plte_chunk(&self) -> bool {
605 self.reader.info().palette.is_some()
606 }
607
608 /// Returns contents of the `PLTE` chunk. Panics if there is no `PLTE`
609 /// chunk.
610 fn get_plte_chunk(&self) -> &[u8] {
611 self.reader.info().palette.as_ref().unwrap().as_ref()
612 }
613
614 /// Returns whether the `acTL` chunk exists.
615 fn has_actl_chunk(&self) -> bool {
616 self.reader.info().animation_control.is_some()
617 }
618
619 /// Returns `num_frames` from the `acTL` chunk. Panics if there is no
620 /// `acTL` chunk.
621 ///
622 /// The returned value is equal the number of `fcTL` chunks. (Note that it
623 /// doesn't count `IDAT` nor `fdAT` chunks. In particular, if an `fcTL`
624 /// chunk doesn't appear before an `IDAT` chunk then `IDAT` is not part
625 /// of the animation.)
626 ///
627 /// See also
628 /// <https://wiki.mozilla.org/APNG_Specification#.60acTL.60:_The_Animation_Control_Chunk>.
629 fn get_actl_num_frames(&self) -> u32 {
630 self.reader
631 .info()
632 .animation_control
633 .as_ref()
634 .unwrap()
635 .num_frames
636 }
637
638 /// Returns `num_plays` from the `acTL` chunk. Panics if there is no `acTL`
639 /// chunk.
640 ///
641 /// `0` indicates that the animation should play indefinitely. See
642 /// <https://wiki.mozilla.org/APNG_Specification#.60acTL.60:_The_Animation_Control_Chunk>.
643 fn get_actl_num_plays(&self) -> u32 {
644 self.reader
645 .info()
646 .animation_control
647 .as_ref()
648 .unwrap()
649 .num_plays
650 }
651
652 /// Returns whether a `fcTL` chunk has been parsed (and can be read using
653 /// `get_fctl_info`).
654 fn has_fctl_chunk(&self) -> bool {
655 self.reader.info().frame_control.is_some()
656 }
657
658 /// Returns `png::FrameControl` information.
659 ///
660 /// Panics if no `fcTL` chunk hasn't been parsed yet.
661 fn get_fctl_info(
662 &self,
663 width: &mut u32,
664 height: &mut u32,
665 x_offset: &mut u32,
666 y_offset: &mut u32,
667 dispose_op: &mut ffi::DisposeOp,
668 blend_op: &mut ffi::BlendOp,
669 duration_ms: &mut u32,
670 ) {
671 let frame_control = self.reader.info().frame_control.as_ref().unwrap();
672 *width = frame_control.width;
673 *height = frame_control.height;
674 *x_offset = frame_control.x_offset;
675 *y_offset = frame_control.y_offset;
676 *dispose_op = frame_control.dispose_op.into();
677 *blend_op = frame_control.blend_op.into();
678
679 // https://wiki.mozilla.org/APNG_Specification#.60fcTL.60:_The_Frame_Control_Chunk
680 // says:
681 //
682 // > "The `delay_num` and `delay_den` parameters together specify a fraction
683 // > indicating the time to display the current frame, in seconds. If the
684 // > denominator is 0, it is to be treated as if it were 100 (that is,
685 // > `delay_num` then specifies 1/100ths of a second).
686 *duration_ms = if frame_control.delay_den == 0 {
687 10 * frame_control.delay_num as u32
688 } else {
689 1000 * frame_control.delay_num as u32 / frame_control.delay_den as u32
690 };
691 }
692
693 /// Returns whether the `sBIT` chunk exists.
694 fn has_sbit_chunk(&self) -> bool {
695 self.reader.info().sbit.is_some()
696 }
697
698 /// Returns contents of the `sBIT` chunk. Panics if there is no `sBIT`
699 /// chunk.
700 fn get_sbit_chunk(&self) -> &[u8] {
701 self.reader.info().sbit.as_ref().unwrap().as_ref()
702 }
703
704 fn output_color_type(&self) -> ffi::ColorType {
705 self.reader.output_color_type().0.into()
706 }
707
708 fn output_bits_per_component(&self) -> u8 {
709 self.reader.output_color_type().1 as u8
710 }
711
712 fn next_frame_info(&mut self) -> ffi::DecodingResult {
713 self.reader.next_frame_info().as_ref().err().into()
714 }
715
716 /// Decodes the next row - see
717 /// https://docs.rs/png/latest/png/struct.Reader.html#method.next_interlaced_row
718 fn next_interlaced_row<'a>(&'a mut self, row: &mut &'a [u8]) -> ffi::DecodingResult {
719 let result = self.reader.next_interlaced_row();
720 if let Ok(maybe_row) = result.as_ref() {
721 self.last_interlace_info = maybe_row.as_ref().map(|r| r.interlace()).copied();
722 *row = maybe_row.map(|r| r.data()).unwrap_or(&[]);
723 }
724 result.as_ref().err().into()
725 }
726
727 /// Expands the last decoded interlaced row - see
728 /// https://docs.rs/png/latest/png/fn.expand_interlaced_row
729 fn expand_last_interlaced_row(
730 &self,
731 img: &mut [u8],
732 img_row_stride: usize,
733 row: &[u8],
734 bits_per_pixel: u8,
735 ) {
736 let Some(png::InterlaceInfo::Adam7(ref adam7info)) = self.last_interlace_info.as_ref()
737 else {
738 panic!("This function should only be called after decoding an interlaced row");
739 };
740 png::expand_interlaced_row(img, img_row_stride, row, adam7info, bits_per_pixel);
741 }
742
743 /// Decodes the next row directly into a caller-provided buffer - see
744 /// https://docs.rs/png/0.18.0-rc.3/png/struct.Reader.html#method.read_row
745 fn read_row(&mut self, output_buffer: &mut [u8]) -> ffi::DecodingResult {
746 match self.reader.read_row(output_buffer) {
747 Ok(Some(info)) => {
748 self.last_interlace_info = Some(info);
749 ffi::DecodingResult::Success
750 }
751 Ok(None) => ffi::DecodingResult::EndOfFrame,
752 Err(e) => ffi::DecodingResult::from(Some(&e)),
753 }
754 }
755 }
756
757 fn png_u32_into_f32(v: png::ScaledFloat) -> f32 {
758 // This uses `0.00001_f32 * (v.into_scaled() as f32)` instead of just
759 // `v.into_value()` for compatibility with the legacy implementation
760 // of `ReadColorProfile` in
761 // `.../blink/renderer/platform/image-decoders/png/png_image_decoder.cc`.
762 0.00001_f32 * (v.into_scaled() as f32)
763 }
764
765 /// This provides a public C++ API for decoding a PNG image.
766 fn new_reader(input: cxx::UniquePtr<ffi::SkStreamAdapter>) -> Box<ResultOfReader> {
767 Box::new(ResultOfReader(Reader::new(input)))
768 }
769
770 /// FFI-friendly wrapper around `Result<T, E>` (`cxx` can't handle arbitrary
771 /// generics, so we manually monomorphize here, but still expose a minimal,
772 /// somewhat tweaked API of the original type).
773 struct ResultOfWriter(Result<Writer, png::EncodingError>);
774
775 impl ResultOfWriter {
776 fn err(&self) -> ffi::EncodingResult {
777 self.0.as_ref().err().into()
778 }
779
780 fn unwrap(&mut self) -> Box<Writer> {
781 // Leaving `self` in a C++-friendly "moved-away" state.
782 let mut result = Err(png::EncodingError::LimitsExceeded);
783 std::mem::swap(&mut self.0, &mut result);
784
785 Box::new(result.unwrap())
786 }
787 }
788
789 /// FFI-friendly wrapper around `png::Writer` (`cxx` can't handle
790 /// arbitrary generics, so we manually monomorphize here, but still expose a
791 /// minimal, somewhat tweaked API of the original type).
792 struct Writer(png::Writer<cxx::UniquePtr<ffi::WriteTrait>>);
793
794 impl Writer {
795 fn new(
796 output: cxx::UniquePtr<ffi::WriteTrait>,
797 width: u32,
798 height: u32,
799 color: ffi::ColorType,
800 bits_per_component: u8,
801 compression: ffi::Compression,
802 icc_profile: &[u8],
803 ) -> Result<Self, png::EncodingError> {
804 let mut info = png::Info::with_size(width, height);
805 info.color_type = color.into();
806 info.bit_depth = match bits_per_component {
807 8 => png::BitDepth::Eight,
808 16 => png::BitDepth::Sixteen,
809
810 // `SkPngRustEncoderImpl` only encodes 8-bit or 16-bit images.
811 _ => unreachable!(),
812 };
813 if !icc_profile.is_empty() {
814 info.icc_profile = Some(Cow::Owned(icc_profile.to_owned()));
815 }
816 let mut encoder = png::Encoder::with_info(output, info)?;
817 compression.apply(&mut encoder);
818
819 let writer = encoder.write_header()?;
820 Ok(Self(writer))
821 }
822
823 /// FFI-friendly wrapper around `png::Writer::write_text_chunk`.
824 ///
825 /// `keyword` and `text` are treated as strings encoded as Latin-1 (i.e.
826 /// ISO-8859-1).
827 ///
828 /// `ffi::EncodingResult::Parameter` error will be returned if `keyword` or
829 /// `text` don't meet the requirements of the PNG spec. `text` may have
830 /// any length and contain any of the 191 Latin-1 characters (and/or the
831 /// linefeed character), but `keyword`'s length is restricted to at most
832 /// 79 characters and it can't contain a non-breaking space character.
833 ///
834 /// See also https://docs.rs/png/latest/png/struct.Writer.html#method.write_text_chunk
835 fn write_text_chunk(&mut self, keyword: &[u8], text: &[u8]) -> ffi::EncodingResult {
836 // https://www.w3.org/TR/png-3/#11tEXt says that "`text` is interpreted according to the
837 // Latin-1 character set [ISO_8859-1]. The text string may contain any Latin-1
838 // character."
839 let is_latin1_byte = |b| (0x20..=0x7E).contains(b) || (0xA0..=0xFF).contains(b);
840 let is_nbsp_byte = |&b: &u8| b == 0xA0;
841 let is_linefeed_byte = |&b: &u8| b == 10;
842 if !text
843 .iter()
844 .all(|b| is_latin1_byte(b) || is_linefeed_byte(b))
845 {
846 return ffi::EncodingResult::ParameterError;
847 }
848 fn latin1_bytes_into_string(bytes: &[u8]) -> String {
849 bytes.iter().map(|&b| b as char).collect()
850 }
851 let text = latin1_bytes_into_string(text);
852
853 // https://www.w3.org/TR/png-3/#11keywords says that "keywords shall contain only printable
854 // Latin-1 [ISO_8859-1] characters and spaces; that is, only code points 0x20-7E
855 // and 0xA1-FF are allowed."
856 if !keyword
857 .iter()
858 .all(|b| is_latin1_byte(b) && !is_nbsp_byte(b))
859 {
860 return ffi::EncodingResult::ParameterError;
861 }
862 let keyword = latin1_bytes_into_string(keyword);
863
864 let chunk = png::text_metadata::TEXtChunk { keyword, text };
865 let result = self.0.write_text_chunk(&chunk);
866 result.as_ref().err().into()
867 }
868 }
869
870 /// FFI-friendly wrapper around `png::Writer::into_stream_writer`.
871 ///
872 /// See also https://docs.rs/png/latest/png/struct.Writer.html#method.into_stream_writer
873 fn convert_writer_into_stream_writer(writer: Box<Writer>) -> Box<ResultOfStreamWriter> {
874 Box::new(ResultOfStreamWriter(
875 writer.0.into_stream_writer().map(StreamWriter),
876 ))
877 }
878
879 /// FFI-friendly wrapper around `Result<T, E>` (`cxx` can't handle arbitrary
880 /// generics, so we manually monomorphize here, but still expose a minimal,
881 /// somewhat tweaked API of the original type).
882 struct ResultOfStreamWriter(Result<StreamWriter, png::EncodingError>);
883
884 impl ResultOfStreamWriter {
885 fn err(&self) -> ffi::EncodingResult {
886 self.0.as_ref().err().into()
887 }
888
889 fn unwrap(&mut self) -> Box<StreamWriter> {
890 // Leaving `self` in a C++-friendly "moved-away" state.
891 let mut result = Err(png::EncodingError::LimitsExceeded);
892 std::mem::swap(&mut self.0, &mut result);
893
894 Box::new(result.unwrap())
895 }
896 }
897
898 /// FFI-friendly wrapper around `png::StreamWriter` (`cxx` can't handle
899 /// arbitrary generics, so we manually monomorphize here, but still expose a
900 /// minimal, somewhat tweaked API of the original type).
901 struct StreamWriter(png::StreamWriter<'static, cxx::UniquePtr<ffi::WriteTrait>>);
902
903 impl StreamWriter {
904 /// FFI-friendly wrapper around `Write::write` implementation of
905 /// `png::StreamWriter`.
906 ///
907 /// See also https://docs.rs/png/latest/png/struct.StreamWriter.html#method.write
908 pub fn write(&mut self, data: &[u8]) -> ffi::EncodingResult {
909 let io_result = self.0.write(data);
910 let encoding_result = io_result.map_err(|err| png::EncodingError::IoError(err));
911 encoding_result.as_ref().err().into()
912 }
913 }
914
915 /// This provides a public C++ API for encoding a PNG image.
916 ///
917 /// `icc_profile` set to an empty slice acts as null / `None`.
918 fn new_writer(
919 output: cxx::UniquePtr<ffi::WriteTrait>,
920 width: u32,
921 height: u32,
922 color: ffi::ColorType,
923 bits_per_component: u8,
924 compression: ffi::Compression,
925 icc_profile: &[u8],
926 ) -> Box<ResultOfWriter> {
927 Box::new(ResultOfWriter(Writer::new(
928 output,
929 width,
930 height,
931 color,
932 bits_per_component,
933 compression,
934 icc_profile,
935 )))
936 }
937
938 /// FFI-friendly wrapper around `png::StreamWriter::finish`.
939 ///
940 /// See also https://docs.rs/png/latest/png/struct.StreamWriter.html#method.finish
941 fn finish_encoding(stream_writer: Box<StreamWriter>) -> ffi::EncodingResult {
942 stream_writer.0.finish().as_ref().err().into()
943 }