initialize method

Future<void> initialize({
  1. SegmentationConfig config = const SegmentationConfig(),
})

Initializes the worker isolate and loads the segmentation model.

This spawns a background isolate, transfers the model bytes, and creates the TFLite interpreter inside the isolate.

config controls model selection, delegate selection, and other options.

Throws StateError if already initialized. Throws SegmentationException if model loading fails. On failure, any partially-spawned isolate is cleaned up before rethrowing.

Implementation

Future<void> initialize({
  SegmentationConfig config = const SegmentationConfig(),
}) async {
  if (isReady) {
    throw StateError('SegmentationWorker already initialized');
  }

  _model = config.model;
  final modelFile = segmentationModelFile(_model);

  final ByteData modelData = await rootBundle.load(
    'packages/face_detection_tflite/assets/models/$modelFile',
  );
  final Uint8List modelBytes = modelData.buffer.asUint8List();

  try {
    await initWorker(
      (sendPort) => Isolate.spawn(
        _isolateEntry,
        sendPort,
        debugName: 'SegmentationWorker',
      ),
      onResponse: (msg) => rpc.handleResponse(
        msg,
        errorWrapper: (e) =>
            SegmentationException(SegmentationError.inferenceFailed, e),
      ),
      timeout: const Duration(seconds: 10),
      timeoutMessage: 'Worker initialization timed out',
      markReady: false,
    );

    final Map result = await sendRequestUnchecked<Map>('init', {
      'modelBytes': TransferableTypedData.fromList([modelBytes]),
      'numThreads': config.performanceConfig.numThreads ?? 4,
      'mode': config.performanceConfig.mode.index,
      'modelIndex': config.model.index,
    });

    _inputWidth = result['inputWidth'] as int;
    _inputHeight = result['inputHeight'] as int;
    _outputWidth = result['outputWidth'] as int;
    _outputHeight = result['outputHeight'] as int;

    markInitialized();
  } catch (e) {
    await super.dispose();
    if (e is SegmentationException) rethrow;
    throw SegmentationException(
      SegmentationError.interpreterCreationFailed,
      'Failed to initialize SegmentationWorker: $e',
      e,
    );
  }
}