startCapture method

  1. @override
Future<void> startCapture(
  1. void onFrame(
    1. MiniAVBuffer buffer,
    2. Object? userData
    ), {
  2. Object? userData,
})
override

Start screen capture. onFrame is called for each frame received.

Implementation

@override
Future<void> startCapture(
  void Function(MiniAVBuffer buffer, Object? userData) onFrame, {
  Object? userData,
}) async {
  _ensureNotDestroyed();

  await stopCapture(); // Ensure any previous capture is stopped

  void ffiCallback(
    ffi.Pointer<bindings.MiniAVBuffer> bufferPtr,
    ffi.Pointer<ffi.Void> cbUserData,
  ) {
    // Check if context was destroyed during callback
    if (_isDestroyed) {
      return; // Silently ignore if destroyed
    }

    // Important: Check if bufferPtr is not null before dereferencing
    if (bufferPtr == ffi.nullptr) {
      print("FFI Callback received null buffer pointer");
      return;
    }

    final platformBuffer = MiniAVBufferFFI.fromPointer(bufferPtr);
    try {
      onFrame(platformBuffer, userData);
    } catch (e, s) {
      print('Error in screen capture user callback: $e\n$s');
    }
  }

  _callbackHandle =
      ffi.NativeCallable<bindings.MiniAVBufferCallbackFunction>.listener(
        ffiCallback,
      );

  final result = bindings.MiniAV_Screen_StartCapture(
    _context!,
    _callbackHandle!.nativeFunction,
    ffi.nullptr,
  );

  if (result != bindings.MiniAVResultCode.MINIAV_SUCCESS) {
    await _cleanupCallback();
    throw Exception('Failed to start screen capture: ${result.name}');
  }
}