summaryrefslogtreecommitdiff
path: root/lib/services/common/decoding.dart
blob: 67ee61eb8e5b292821e9fcadaf2252b0208a62be (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
import 'dart:async';
import 'dart:ui' as ui;

import 'package:flutter/foundation.dart';
import 'package:flutter/painting.dart';
import 'package:flutter/services.dart';

class InteropDecoding {
  // bytes are expected to be in a basic format decodable by Flutter
  static Future<ui.Codec?> encodedBytesToCodec(Uint8List? bytes, ImageDecoderCallback? decode) async {
    if (bytes == null || decode == null) return null;

    const trailerLength = 1; // decoded/encoded format byte
    final byteCount = bytes.lengthInBytes;
    if (byteCount < trailerLength) return null;

    final trailerOffset = byteCount - trailerLength;

    // trim custom trailer
    // a view does not reallocate memory and uses the underlying buffer
    final imageBytes = Uint8List.sublistView(bytes, 0, trailerOffset);

    final buffer = await ui.ImmutableBuffer.fromUint8List(imageBytes);
    return await decode(buffer);
  }

  // bytes are expected to be in ARGB_8888
  // with a custom trailer from the platform side
  static Future<ui.ImageDescriptor?> rawBytesToDescriptor(Uint8List? bytes) async {
    if (bytes == null) return null;

    const trailerLength = 4 * 2 + 1; // 2 integers + decoded/encoded format byte
    final byteCount = bytes.lengthInBytes;
    if (byteCount < trailerLength) return null;

    final trailerOffset = byteCount - trailerLength;

    // fetch trailer
    final trailer = ByteData.sublistView(bytes, trailerOffset);
    final bitmapWidth = trailer.getUint32(0);
    final bitmapHeight = trailer.getUint32(4);

    // trim custom trailer
    // a view does not reallocate memory and uses the underlying buffer
    final imageBytes = Uint8List.sublistView(bytes, 0, trailerOffset);

    final buffer = await ui.ImmutableBuffer.fromUint8List(imageBytes);
    return ui.ImageDescriptor.raw(
      buffer,
      width: bitmapWidth,
      height: bitmapHeight,
      pixelFormat: ui.PixelFormat.rgba8888,
    );
  }
}