Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -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
Expand Down
146 changes: 121 additions & 25 deletions lib/src/blurhash.dart
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,21 @@ Future<Uint8List> 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);

Expand Down Expand Up @@ -118,7 +133,7 @@ Future<Uint8List> optimizedBlurHashDecode({
}
}

return Future.value(pixels);
return pixels;
}

// Create this once as a static variable
Expand Down Expand Up @@ -161,6 +176,19 @@ Future<Uint8List> 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);

Expand Down Expand Up @@ -214,7 +242,7 @@ Future<Uint8List> blurHashDecode({
}
}

return Future.value(pixels);
return pixels;
}

Future<ui.Image> blurHashDecodeImage({
Expand All @@ -224,38 +252,106 @@ Future<ui.Image> blurHashDecodeImage({
double punch = 1.0,
BlurHashOptimizationMode optimizationMode = BlurHashOptimizationMode.standard,
}) async {
_validateBlurHash(blurHash);

final completer = Completer<ui.Image>();
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.Image>();
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<ui.Image> _createBmp(Uint8List pixels, int width, int height) async {
int size = (width * height * 4) + 122;
final bmp = Uint8List(size);
Expand Down
26 changes: 24 additions & 2 deletions lib/src/blurhash_image.dart
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import 'dart:async';
import 'dart:ui' as ui;

import 'package:flutter/foundation.dart';
import 'package:flutter/painting.dart';
Expand Down Expand Up @@ -33,8 +34,29 @@ class BlurHashImage extends ImageProvider<BlurHashImage> {

@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<ImageInfo> _loadAsync(BlurHashImage key) async {
assert(key == this);
Expand Down
49 changes: 37 additions & 12 deletions lib/src/blurhash_widget.dart
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,10 @@ class BlurHash extends StatefulWidget {

class BlurHashState extends State<BlurHash> {
late Future<ui.Image> _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;

Expand Down Expand Up @@ -107,12 +111,26 @@ class BlurHashState extends State<BlurHash> {
}

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());
}
Expand Down Expand Up @@ -156,12 +174,19 @@ class BlurHashState extends State<BlurHash> {
);

/// Decode the blurhash then display the resulting Image
Widget buildBlurHashBackground() => FutureBuilder<ui.Image>(
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<ui.Image>(
future: _image,
builder: (ctx, snap) => snap.hasData
? Image(image: UiImage(snap.data!), fit: widget.imageFit)
: Container(color: widget.color),
);
}
}

// Inner display details & controls
Expand Down
5 changes: 3 additions & 2 deletions pubspec.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
73 changes: 73 additions & 0 deletions test/blurhash_sync_test.dart
Original file line number Diff line number Diff line change
@@ -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<ImageInfo> _firstImage(ImageStream stream) {
final completer = Completer<ImageInfo>();
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;
}