From a7481bd5d538e1c253f4b3d40d4abee9eb305d14 Mon Sep 17 00:00:00 2001
From: Harry Terkelsen <1961493+harryterkelsen@users.noreply.github.com>
Date: Thu, 8 Aug 2024 14:47:22 -0700
Subject: [PATCH] [canvaskit] Detect animated WebP images
(flutter/engine#54418)
Reads the WebP header to determine if the WebP image is animated or not. If it's not animated, we can use `
` tag decoding for less jank.
The WebP half of https://github.com/flutter/flutter/issues/151911
[C++, Objective-C, Java style guides]: https://github.com/flutter/engine/blob/main/CONTRIBUTING.md#style
---
.../lib/src/engine/image_format_detector.dart | 93 ++++++++++++++++++-
.../engine/image_format_detector_test.dart | 79 ++++++++++++++++
2 files changed, 168 insertions(+), 4 deletions(-)
create mode 100644 engine/src/flutter/lib/web_ui/test/engine/image_format_detector_test.dart
diff --git a/engine/src/flutter/lib/web_ui/lib/src/engine/image_format_detector.dart b/engine/src/flutter/lib/web_ui/lib/src/engine/image_format_detector.dart
index f6a4f89dd0..50af121539 100644
--- a/engine/src/flutter/lib/web_ui/lib/src/engine/image_format_detector.dart
+++ b/engine/src/flutter/lib/web_ui/lib/src/engine/image_format_detector.dart
@@ -34,6 +34,12 @@ ImageType? detectImageType(Uint8List data) {
}
}
+ // If we detect a WebP image, check if it is animated.
+ if (format.imageType == ImageType.webp) {
+ if (_WebpHeaderReader(data.buffer.asByteData()).isAnimated()) {
+ return ImageType.animatedWebp;
+ }
+ }
return format.imageType;
}
@@ -61,9 +67,11 @@ enum ImageType {
// animated. We should detect if they are actually animated by reading the
// image headers, https://github.com/flutter/flutter/issues/151911.
png(ImageFileType.png, isAnimated: false),
- gif(ImageFileType.gif, isAnimated: true),
+ gif(ImageFileType.gif, isAnimated: false),
+ animatedGif(ImageFileType.gif, isAnimated: true),
jpeg(ImageFileType.jpeg, isAnimated: false),
- webp(ImageFileType.webp, isAnimated: true),
+ webp(ImageFileType.webp, isAnimated: false),
+ animatedWebp(ImageFileType.webp, isAnimated: true),
bmp(ImageFileType.bmp, isAnimated: false),
avif(ImageFileType.avif, isAnimated: false);
@@ -84,11 +92,11 @@ enum ImageFileSignature {
),
gif87a(
[0x47, 0x49, 0x46, 0x38, 0x37, 0x61],
- ImageType.gif,
+ ImageType.animatedGif,
),
gif89a(
[0x47, 0x49, 0x46, 0x38, 0x39, 0x61],
- ImageType.gif,
+ ImageType.animatedGif,
),
jpeg(
[0xFF, 0xD8, 0xFF],
@@ -173,3 +181,80 @@ bool isAvif(Uint8List data) {
}
return false;
}
+
+/// Reads the header of a WebP file to determine if it is animated or not.
+///
+/// See https://developers.google.com/speed/webp/docs/riff_container
+class _WebpHeaderReader {
+ _WebpHeaderReader(this.bytes);
+
+ final ByteData bytes;
+
+ /// The current position we are reading from in bytes.
+ int _position = 0;
+
+ /// Returns [true] if this WebP is animated.
+ bool isAnimated() {
+ final bool isWebP = _readWebpHeader();
+ if (!isWebP) {
+ return false;
+ }
+ // If this is an animated WebP, then it must have a 'VP8X' chunk header
+ // with the 'animation' bit set. See: https://developers.google.com/speed/webp/docs/riff_container#extended_file_format
+ final bool isVP8X = _readChunkHeader('VP8X');
+ if (!isVP8X) {
+ return false;
+ }
+
+ // If this is a VP8X style WebP, then the next byte will have a bit which
+ // indicates whether it is animated or not.
+ final int headerByte = _readUint8();
+ const int animatedMask = 1 << 1;
+ return headerByte & animatedMask != 0;
+ }
+
+ /// Reads a RIFF chunk header. Returns [false] if the header FourCC isn't
+ /// [expectedHeader].
+ bool _readChunkHeader(String expectedHeader) {
+ final String chunkFourCC = _readFourCC();
+ // Read chunk size.
+ _readUint32();
+ return chunkFourCC == expectedHeader;
+ }
+
+ /// Reads the WebP header. Returns [false] if this is not a valid WebP header.
+ bool _readWebpHeader() {
+ final String riffBytes = _readFourCC();
+
+ // Read file size byte.
+ _readUint32();
+
+ final String webpBytes = _readFourCC();
+ return riffBytes == 'RIFF' && webpBytes == 'WEBP';
+ }
+
+ int _readUint32() {
+ final int result = bytes.getUint32(_position, Endian.little);
+ _position += 4;
+ return result;
+ }
+
+ int _readUint8() {
+ final int result = bytes.getUint8(_position);
+ _position += 1;
+ return result;
+ }
+
+ /// A four-character code is a uint32 created by concatenating four ASCII
+ /// characters in little-endian order.
+ String _readFourCC() {
+ final List chars = [
+ bytes.getUint8(_position),
+ bytes.getUint8(_position + 1),
+ bytes.getUint8(_position + 2),
+ bytes.getUint8(_position + 3),
+ ];
+ _position += 4;
+ return String.fromCharCodes(chars);
+ }
+}
diff --git a/engine/src/flutter/lib/web_ui/test/engine/image_format_detector_test.dart b/engine/src/flutter/lib/web_ui/test/engine/image_format_detector_test.dart
new file mode 100644
index 0000000000..64a7213fc7
--- /dev/null
+++ b/engine/src/flutter/lib/web_ui/test/engine/image_format_detector_test.dart
@@ -0,0 +1,79 @@
+// Copyright 2013 The Flutter Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+import 'dart:typed_data';
+
+import 'package:test/bootstrap/browser.dart';
+import 'package:test/test.dart';
+import 'package:ui/src/engine.dart';
+
+import '../common/test_initialization.dart';
+
+void main() {
+ internalBootstrapBrowserTest(() => testMain);
+}
+
+List? testFiles;
+
+Future testMain() async {
+ setUpUnitTests();
+
+ Future> createTestFiles() async {
+ final HttpFetchResponse listingResponse = await httpFetch('/test_images/');
+ final List testFiles =
+ (await listingResponse.json() as List).cast();
+
+ // Sanity-check the test file list. If suddenly test files are moved or
+ // deleted, and the test server returns an empty list, or is missing some
+ // important test files, we want to know.
+ assert(testFiles.isNotEmpty);
+ assert(testFiles.any((String testFile) => testFile.endsWith('.jpg')));
+ assert(testFiles.any((String testFile) => testFile.endsWith('.png')));
+ assert(testFiles.any((String testFile) => testFile.endsWith('.gif')));
+ assert(testFiles.any((String testFile) => testFile.endsWith('.webp')));
+ assert(testFiles.any((String testFile) => testFile.endsWith('.bmp')));
+
+ return testFiles;
+ }
+
+ testFiles = await createTestFiles();
+
+ for (final String testFile in testFiles!) {
+ test('can detect image type of $testFile', () async {
+ final HttpFetchResponse response =
+ await httpFetch('/test_images/$testFile');
+
+ if (!response.hasPayload) {
+ throw Exception('Unable to fetch() image test file "$testFile"');
+ }
+
+ final Uint8List responseBytes = await response.asUint8List();
+
+ // WebP files which are known to be animated.
+ const List animatedWebpFiles = [
+ 'blendBG.webp',
+ 'required.webp',
+ 'stoplight_h.webp',
+ 'stoplight.webp',
+ ];
+
+ final String testFileExtension =
+ testFile.substring(testFile.lastIndexOf('.') + 1);
+ final ImageType? expectedImageType = switch (testFileExtension) {
+ 'jpg' => ImageType.jpeg,
+ 'jpeg' => ImageType.jpeg,
+ 'gif' => ImageType.animatedGif,
+ 'webp' => animatedWebpFiles.contains(testFile)
+ ? ImageType.animatedWebp
+ : ImageType.webp,
+ 'avif' => ImageType.avif,
+ 'bmp' => ImageType.bmp,
+ 'png' => ImageType.png,
+ _ => null,
+ };
+
+ expect(detectImageType(responseBytes), expectedImageType);
+ });
+ }
+}