setScreensharingEnabled method

Future<bool> setScreensharingEnabled(
  1. bool enabled
)

Implementation

Future<bool> setScreensharingEnabled(bool enabled) async {
  // Skip if there is nothing to do
  if (enabled && localScreenSharingStream != null) {
    Logs().w(
        'There is already a screensharing stream - there is nothing to do!');
    return true;
  } else if (!enabled && localScreenSharingStream == null) {
    Logs().w(
        'There already isn\'t a screensharing stream - there is nothing to do!');
    return false;
  }

  Logs().d('Set screensharing enabled? $enabled');

  if (enabled) {
    try {
      final stream = await _getDisplayMedia();
      if (stream == null) {
        return false;
      }
      for (final track in stream.getTracks()) {
        // screen sharing should only have 1 video track anyway, so this only
        // fires once
        track.onEnded = () async {
          await setScreensharingEnabled(false);
        };
      }

      await addLocalStream(stream, SDPStreamMetadataPurpose.Screenshare);
      return true;
    } catch (err) {
      fireCallEvent(CallEvent.kError);
      lastError = CallError(CallErrorCode.NoUserMedia,
          'Failed to get screen-sharing stream: ', err);
      return false;
    }
  } else {
    try {
      for (final sender in screensharingSenders) {
        await pc!.removeTrack(sender);
      }
      for (final track in localScreenSharingStream!.stream!.getTracks()) {
        await track.stop();
      }
      localScreenSharingStream!.stopped = true;
      await _removeStream(localScreenSharingStream!.stream!);
      fireCallEvent(CallEvent.kFeedsChanged);
      return false;
    } catch (e, s) {
      Logs().e('[VOIP] stopping screen sharing track failed', e, s);
      return false;
    }
  }
}