diff --git a/CHANGELOG.md b/CHANGELOG.md index 06651fb..5707d27 100755 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,11 @@ +# Unreleased + +- Decode blurhashes synchronously with `ui.decodeImageFromPixelsSync` when + available (Impeller), so `BlurHash` and `BlurHashImage` show the blurhash in + the first frame. Falls back to asynchronous decoding on the web and Skia. +- Add `blurHashDecodeImageSync` +- Flutter 3.41 as min required version + # 0.9.1 - Corrections diff --git a/lib/src/blurhash.dart b/lib/src/blurhash.dart index 0902a23..ac6e289 100644 --- a/lib/src/blurhash.dart +++ b/lib/src/blurhash.dart @@ -23,6 +23,21 @@ Future optimizedBlurHashDecode({ required int height, double punch = 1.0, BlurHashOptimizationMode optimizationMode = BlurHashOptimizationMode.standard, +}) => + Future.value(_optimizedBlurHashDecodeSync( + blurHash: blurHash, + width: width, + height: height, + punch: punch, + optimizationMode: optimizationMode, + )); + +Uint8List _optimizedBlurHashDecodeSync({ + required String blurHash, + required int width, + required int height, + required double punch, + required BlurHashOptimizationMode optimizationMode, }) { _validateBlurHash(blurHash); @@ -118,7 +133,7 @@ Future optimizedBlurHashDecode({ } } - return Future.value(pixels); + return pixels; } // Create this once as a static variable @@ -161,6 +176,19 @@ Future blurHashDecode({ required int width, required int height, double punch = 1.0, +}) => + Future.value(_blurHashDecodeSync( + blurHash: blurHash, + width: width, + height: height, + punch: punch, + )); + +Uint8List _blurHashDecodeSync({ + required String blurHash, + required int width, + required int height, + required double punch, }) { _validateBlurHash(blurHash); @@ -214,7 +242,7 @@ Future blurHashDecode({ } } - return Future.value(pixels); + return pixels; } Future blurHashDecodeImage({ @@ -224,38 +252,106 @@ Future blurHashDecodeImage({ double punch = 1.0, BlurHashOptimizationMode optimizationMode = BlurHashOptimizationMode.standard, }) async { - _validateBlurHash(blurHash); - - final completer = Completer(); + final pixels = _decodePixels( + blurHash: blurHash, + width: width, + height: height, + punch: punch, + optimizationMode: optimizationMode, + ); - final Uint8List pixels; - if (optimizationMode != BlurHashOptimizationMode.none) { - pixels = await optimizedBlurHashDecode( - blurHash: blurHash, - width: width, - height: height, - punch: punch, - optimizationMode: optimizationMode, - ); - } else { - pixels = await blurHashDecode( - blurHash: blurHash, - width: width, - height: height, - punch: punch, - ); + final image = _tryDecodeImageFromPixelsSync(pixels, width, height); + if (image != null) { + return image; } if (kIsWeb) { - completer.complete(_createBmp(pixels, width, height)); - } else { - ui.decodeImageFromPixels( - pixels, width, height, ui.PixelFormat.rgba8888, completer.complete); + return _createBmp(pixels, width, height); } + final completer = Completer(); + ui.decodeImageFromPixels( + pixels, width, height, ui.PixelFormat.rgba8888, completer.complete); return completer.future; } +/// Decodes [blurHash] into a [ui.Image] synchronously, using +/// [ui.decodeImageFromPixelsSync]. +/// +/// This allows the blurhash to be displayed in the very first frame, instead +/// of one or more frames later as with [blurHashDecodeImage]. +/// +/// Returns `null` if synchronous decoding is not supported on the current +/// platform, which is the case on the web and when Impeller is not enabled. +/// Callers should fall back to [blurHashDecodeImage] in that case. +/// +/// Throws if [blurHash] is invalid. +ui.Image? blurHashDecodeImageSync({ + required String blurHash, + required int width, + required int height, + double punch = 1.0, + BlurHashOptimizationMode optimizationMode = BlurHashOptimizationMode.standard, +}) { + _validateBlurHash(blurHash); + if (_syncDecodingUnsupported) { + return null; + } + + final pixels = _decodePixels( + blurHash: blurHash, + width: width, + height: height, + punch: punch, + optimizationMode: optimizationMode, + ); + return _tryDecodeImageFromPixelsSync(pixels, width, height); +} + +/// Set once [ui.decodeImageFromPixelsSync] turned out to be unavailable, so +/// that it is not attempted (and does not throw) over and over again. +bool _syncDecodingUnsupported = kIsWeb; + +ui.Image? _tryDecodeImageFromPixelsSync( + Uint8List pixels, int width, int height) { + // Invalid dimensions are left to the asynchronous path to report. + if (_syncDecodingUnsupported || width <= 0 || height <= 0) { + return null; + } + + try { + return ui.decodeImageFromPixelsSync( + pixels, width, height, ui.PixelFormat.rgba8888); + } catch (_) { + // Throws an UnimplementedError on the web and a String when Impeller is + // not enabled. + _syncDecodingUnsupported = true; + return null; + } +} + +Uint8List _decodePixels({ + required String blurHash, + required int width, + required int height, + required double punch, + required BlurHashOptimizationMode optimizationMode, +}) => + optimizationMode == BlurHashOptimizationMode.none + ? _blurHashDecodeSync( + blurHash: blurHash, + width: width, + height: height, + punch: punch, + ) + : _optimizedBlurHashDecodeSync( + blurHash: blurHash, + width: width, + height: height, + punch: punch, + optimizationMode: optimizationMode, + ); + Future _createBmp(Uint8List pixels, int width, int height) async { int size = (width * height * 4) + 122; final bmp = Uint8List(size); diff --git a/lib/src/blurhash_image.dart b/lib/src/blurhash_image.dart index 81a862b..a007f27 100644 --- a/lib/src/blurhash_image.dart +++ b/lib/src/blurhash_image.dart @@ -1,4 +1,5 @@ import 'dart:async'; +import 'dart:ui' as ui; import 'package:flutter/foundation.dart'; import 'package:flutter/painting.dart'; @@ -33,8 +34,29 @@ class BlurHashImage extends ImageProvider { @override ImageStreamCompleter loadImage( - BlurHashImage key, ImageDecoderCallback decode) => - OneFrameImageStreamCompleter(_loadAsync(key)); + BlurHashImage key, ImageDecoderCallback decode) { + final image = _loadSync(key); + if (image != null) { + return OneFrameImageStreamCompleter( + SynchronousFuture(ImageInfo(image: image, scale: key.scale))); + } + return OneFrameImageStreamCompleter(_loadAsync(key)); + } + + ui.Image? _loadSync(BlurHashImage key) { + assert(key == this); + + try { + return blurHashDecodeImageSync( + blurHash: blurHash, + width: decodingWidth, + height: decodingHeight, + ); + } catch (_) { + // Let _loadAsync report the error through the image stream. + return null; + } + } Future _loadAsync(BlurHashImage key) async { assert(key == this); diff --git a/lib/src/blurhash_widget.dart b/lib/src/blurhash_widget.dart index ee24cbd..90593b1 100644 --- a/lib/src/blurhash_widget.dart +++ b/lib/src/blurhash_widget.dart @@ -79,6 +79,10 @@ class BlurHash extends StatefulWidget { class BlurHashState extends State { late Future _image; + + /// Set when the blurhash could be decoded synchronously, so it can be + /// displayed without waiting for [_image] to complete. + ui.Image? _syncImage; late bool loaded; late bool loading; @@ -107,12 +111,26 @@ class BlurHashState extends State { } void _decodeImage() { - _image = blurHashDecodeImage( - blurHash: widget.hash, - width: widget.decodingWidth, - height: widget.decodingHeight, - optimizationMode: widget.optimizationMode, - ); + try { + _syncImage = blurHashDecodeImageSync( + blurHash: widget.hash, + width: widget.decodingWidth, + height: widget.decodingHeight, + optimizationMode: widget.optimizationMode, + ); + } catch (_) { + // Let blurHashDecodeImage report the error through the future. + _syncImage = null; + } + + _image = _syncImage != null + ? Future.value(_syncImage) + : blurHashDecodeImage( + blurHash: widget.hash, + width: widget.decodingWidth, + height: widget.decodingHeight, + optimizationMode: widget.optimizationMode, + ); _image.whenComplete(() => widget.onDecoded?.call()); } @@ -156,12 +174,19 @@ class BlurHashState extends State { ); /// Decode the blurhash then display the resulting Image - Widget buildBlurHashBackground() => FutureBuilder( - future: _image, - builder: (ctx, snap) => snap.hasData - ? Image(image: UiImage(snap.data!), fit: widget.imageFit) - : Container(color: widget.color), - ); + Widget buildBlurHashBackground() { + final syncImage = _syncImage; + if (syncImage != null) { + return Image(image: UiImage(syncImage), fit: widget.imageFit); + } + + return FutureBuilder( + future: _image, + builder: (ctx, snap) => snap.hasData + ? Image(image: UiImage(snap.data!), fit: widget.imageFit) + : Container(color: widget.color), + ); + } } // Inner display details & controls diff --git a/pubspec.yaml b/pubspec.yaml index 7de229b..8b958c2 100755 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -15,8 +15,9 @@ screenshots: path: screenshots/loaded.png environment: - # flutter: ">=3.16.0" - sdk: ">=3.0.0 <4.0.0" + # Required for ui.decodeImageFromPixelsSync + flutter: ">=3.41.0" + sdk: ">=3.11.0 <4.0.0" dependencies: flutter: diff --git a/test/blurhash_sync_test.dart b/test/blurhash_sync_test.dart new file mode 100644 index 0000000..1b52d25 --- /dev/null +++ b/test/blurhash_sync_test.dart @@ -0,0 +1,73 @@ +import 'dart:async'; + +import 'package:flutter/material.dart'; +import 'package:flutter_blurhash/flutter_blurhash.dart'; +import 'package:flutter_test/flutter_test.dart'; + +const _testHash = 'LGF5]+Yk^6#M@-5c,1J5@[or[Q6.'; + +void main() { + test('blurHashDecodeImageSync returns an image or null if unsupported', () { + final image = blurHashDecodeImageSync( + blurHash: _testHash, + width: 16, + height: 8, + ); + + if (image != null) { + expect(image.width, 16); + expect(image.height, 8); + image.dispose(); + } + }); + + test('blurHashDecodeImageSync throws on an invalid hash', () { + expect( + () => blurHashDecodeImageSync(blurHash: 'abc', width: 16, height: 16), + throwsException, + ); + }); + + testWidgets('BlurHash shows an image in the first frame if sync decoding ' + 'is supported', (tester) async { + final syncSupported = blurHashDecodeImageSync( + blurHash: _testHash, + width: 1, + height: 1, + ) != + null; + + await tester.pumpWidget( + const Directionality( + textDirection: TextDirection.ltr, + child: BlurHash(hash: _testHash), + ), + ); + + expect(find.byType(Image), syncSupported ? findsOneWidget : findsNothing); + }); + + testWidgets('BlurHashImage resolves', (tester) async { + await tester.runAsync(() async { + final stream = + const BlurHashImage(_testHash).resolve(ImageConfiguration.empty); + final info = await _firstImage(stream); + expect(info.image.width, 32); + expect(info.image.height, 32); + }); + }); +} + +Future _firstImage(ImageStream stream) { + final completer = Completer(); + late ImageStreamListener listener; + listener = ImageStreamListener((info, _) { + stream.removeListener(listener); + completer.complete(info); + }, onError: (error, stackTrace) { + stream.removeListener(listener); + completer.completeError(error, stackTrace); + }); + stream.addListener(listener); + return completer.future; +}