stopScreenCapture method

Future<void> stopScreenCapture()

Implementation

Future<void> stopScreenCapture() async {
  _isStreaming = false;
  _isInitializingStream = false;

  try {
    // 1. Detener tracks de stream inmediatamente
    if (_localStream != null) {
      for (final track in _localStream!.getTracks()) {
        try {
          await track.stop();
        } catch (_) {}
      }
    }

    // 2. Cerrar PeerConnection
    if (_peerConnection != null) {
      try {
        await _peerConnection!.close();
      } catch (_) {}
      _peerConnection = null;
    }

    // 3. Dispose de stream
    if (_localStream != null) {
      try {
        await _localStream!.dispose();
      } catch (_) {}
      _localStream = null;
    }

    // 4. Breve pausa para asegurar liberación de Surface en Flutter antes de detener servicio nativo
    await Future.delayed(const Duration(milliseconds: 200));

    // 5. Liberar MediaProjection y detener servicio nativo
    await NativeBridge.releaseMediaProjection();
    await NativeBridge.stopScreenCapture();

    _cancelInactivityTimer();
    log('✅ Screen capture detenido');
  } catch (e) {
    log('❌ Error al detener screen capture: $e');
    _localStream = null;
    _peerConnection = null;
    try {
      await NativeBridge.releaseMediaProjection();
      await NativeBridge.stopScreenCapture();
    } catch (_) {}
  } finally {
    _isStreaming = false;
    _isInitializingStream = false;
  }
}