setScreensharingEnabled method

Future<bool> setScreensharingEnabled(
  1. bool enabled,
  2. String desktopCapturerSourceId
)

Implementation

Future<bool> setScreensharingEnabled(
  bool enabled,
  String desktopCapturerSourceId,
) async {
  if (enabled == isScreensharing()) {
    return enabled;
  }

  if (enabled) {
    try {
      Logs().v('Asking for screensharing permissions...');
      final stream = await _getDisplayMedia();
      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, '');
        };
      }
      Logs().v(
          'Screensharing permissions granted. Setting screensharing enabled on all calls');
      localDesktopCapturerSourceId = desktopCapturerSourceId;
      localScreenshareStream = WrappedMediaStream(
        renderer: voip.delegate.createRenderer(),
        stream: stream,
        userId: client.userID!,
        room: room,
        client: client,
        purpose: SDPStreamMetadataPurpose.Screenshare,
        audioMuted: stream.getAudioTracks().isEmpty,
        videoMuted: stream.getVideoTracks().isEmpty,
        isWeb: voip.delegate.isWeb,
        isGroupCall: true,
      );

      addScreenshareStream(localScreenshareStream!);
      await localScreenshareStream!.initialize();

      onGroupCallEvent.add(GroupCallEvent.LocalScreenshareStateChanged);
      for (final call in calls) {
        await call.addLocalStream(
            await localScreenshareStream!.stream!.clone(),
            localScreenshareStream!.purpose);
      }

      await sendMemberStateEvent();

      return true;
    } catch (e, s) {
      Logs().e('Enabling screensharing error', e, s);
      lastError = GroupCallError(GroupCallErrorCode.NoUserMedia,
          'Failed to get screen-sharing stream: ', e);
      onGroupCallEvent.add(GroupCallEvent.Error);
      return false;
    }
  } else {
    for (final call in calls) {
      await call.removeLocalStream(call.localScreenSharingStream!);
    }

    await stopMediaStream(localScreenshareStream?.stream);
    await removeScreenshareStream(localScreenshareStream!);
    localScreenshareStream = null;
    localDesktopCapturerSourceId = null;
    await sendMemberStateEvent();
    onGroupCallEvent.add(GroupCallEvent.LocalMuteStateChanged);
    return false;
  }
}