LCOV - code coverage report
Current view: top level - lib/src/voip - call_session.dart (source / functions) Coverage Total Hit
Test: merged.info Lines: 44.2 % 833 368
Test Date: 2025-01-14 13:39:53 Functions: - 0 0

            Line data    Source code
       1              : /*
       2              :  *   Famedly Matrix SDK
       3              :  *   Copyright (C) 2021 Famedly GmbH
       4              :  *
       5              :  *   This program is free software: you can redistribute it and/or modify
       6              :  *   it under the terms of the GNU Affero General Public License as
       7              :  *   published by the Free Software Foundation, either version 3 of the
       8              :  *   License, or (at your option) any later version.
       9              :  *
      10              :  *   This program is distributed in the hope that it will be useful,
      11              :  *   but WITHOUT ANY WARRANTY; without even the implied warranty of
      12              :  *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
      13              :  *   GNU Affero General Public License for more details.
      14              :  *
      15              :  *   You should have received a copy of the GNU Affero General Public License
      16              :  *   along with this program.  If not, see <https://www.gnu.org/licenses/>.
      17              :  */
      18              : 
      19              : import 'dart:async';
      20              : import 'dart:core';
      21              : import 'dart:math';
      22              : 
      23              : import 'package:collection/collection.dart';
      24              : import 'package:webrtc_interface/webrtc_interface.dart';
      25              : 
      26              : import 'package:matrix/matrix.dart';
      27              : import 'package:matrix/src/utils/cached_stream_controller.dart';
      28              : import 'package:matrix/src/voip/models/call_options.dart';
      29              : import 'package:matrix/src/voip/models/voip_id.dart';
      30              : import 'package:matrix/src/voip/utils/stream_helper.dart';
      31              : import 'package:matrix/src/voip/utils/user_media_constraints.dart';
      32              : 
      33              : /// Parses incoming matrix events to the apropriate webrtc layer underneath using
      34              : /// a `WebRTCDelegate`. This class is also responsible for sending any outgoing
      35              : /// matrix events if required (f.ex m.call.answer).
      36              : ///
      37              : /// Handles p2p calls as well individual mesh group call peer connections.
      38              : class CallSession {
      39            2 :   CallSession(this.opts);
      40              :   CallOptions opts;
      41            6 :   CallType get type => opts.type;
      42            6 :   Room get room => opts.room;
      43            6 :   VoIP get voip => opts.voip;
      44            6 :   String? get groupCallId => opts.groupCallId;
      45            6 :   String get callId => opts.callId;
      46            6 :   String get localPartyId => opts.localPartyId;
      47              : 
      48            6 :   CallDirection get direction => opts.dir;
      49              : 
      50            4 :   CallState get state => _state;
      51              :   CallState _state = CallState.kFledgling;
      52              : 
      53            0 :   bool get isOutgoing => direction == CallDirection.kOutgoing;
      54              : 
      55            0 :   bool get isRinging => state == CallState.kRinging;
      56              : 
      57              :   RTCPeerConnection? pc;
      58              : 
      59              :   final _remoteCandidates = <RTCIceCandidate>[];
      60              :   final _localCandidates = <RTCIceCandidate>[];
      61              : 
      62            0 :   AssertedIdentity? get remoteAssertedIdentity => _remoteAssertedIdentity;
      63              :   AssertedIdentity? _remoteAssertedIdentity;
      64              : 
      65            6 :   bool get callHasEnded => state == CallState.kEnded;
      66              : 
      67              :   bool _iceGatheringFinished = false;
      68              : 
      69              :   bool _inviteOrAnswerSent = false;
      70              : 
      71            0 :   bool get localHold => _localHold;
      72              :   bool _localHold = false;
      73              : 
      74            0 :   bool get remoteOnHold => _remoteOnHold;
      75              :   bool _remoteOnHold = false;
      76              : 
      77              :   bool _answeredByUs = false;
      78              : 
      79              :   bool _speakerOn = false;
      80              : 
      81              :   bool _makingOffer = false;
      82              : 
      83              :   bool _ignoreOffer = false;
      84              : 
      85            0 :   bool get answeredByUs => _answeredByUs;
      86              : 
      87            8 :   Client get client => opts.room.client;
      88              : 
      89              :   /// The local participant in the call, with id userId + deviceId
      90            6 :   CallParticipant? get localParticipant => voip.localParticipant;
      91              : 
      92              :   /// The ID of the user being called. If omitted, any user in the room can answer.
      93              :   String? remoteUserId;
      94              : 
      95            0 :   User? get remoteUser => remoteUserId != null
      96            0 :       ? room.unsafeGetUserFromMemoryOrFallback(remoteUserId!)
      97              :       : null;
      98              : 
      99              :   /// The ID of the device being called. If omitted, any device for the remoteUserId in the room can answer.
     100              :   String? remoteDeviceId;
     101              :   String? remoteSessionId; // same
     102              :   String? remotePartyId; // random string
     103              : 
     104              :   CallErrorCode? hangupReason;
     105              :   CallSession? _successor;
     106              :   int _toDeviceSeq = 0;
     107              :   int _candidateSendTries = 0;
     108            4 :   bool get isGroupCall => groupCallId != null;
     109              :   bool _missedCall = true;
     110              : 
     111              :   final CachedStreamController<CallSession> onCallStreamsChanged =
     112              :       CachedStreamController();
     113              : 
     114              :   final CachedStreamController<CallSession> onCallReplaced =
     115              :       CachedStreamController();
     116              : 
     117              :   final CachedStreamController<CallSession> onCallHangupNotifierForGroupCalls =
     118              :       CachedStreamController();
     119              : 
     120              :   final CachedStreamController<CallState> onCallStateChanged =
     121              :       CachedStreamController();
     122              : 
     123              :   final CachedStreamController<CallStateChange> onCallEventChanged =
     124              :       CachedStreamController();
     125              : 
     126              :   final CachedStreamController<WrappedMediaStream> onStreamAdd =
     127              :       CachedStreamController();
     128              : 
     129              :   final CachedStreamController<WrappedMediaStream> onStreamRemoved =
     130              :       CachedStreamController();
     131              : 
     132              :   SDPStreamMetadata? _remoteSDPStreamMetadata;
     133              :   final List<RTCRtpSender> _usermediaSenders = [];
     134              :   final List<RTCRtpSender> _screensharingSenders = [];
     135              :   final List<WrappedMediaStream> _streams = <WrappedMediaStream>[];
     136              : 
     137            2 :   List<WrappedMediaStream> get getLocalStreams =>
     138           10 :       _streams.where((element) => element.isLocal()).toList();
     139            0 :   List<WrappedMediaStream> get getRemoteStreams =>
     140            0 :       _streams.where((element) => !element.isLocal()).toList();
     141              : 
     142            0 :   bool get isLocalVideoMuted => localUserMediaStream?.isVideoMuted() ?? false;
     143              : 
     144            0 :   bool get isMicrophoneMuted => localUserMediaStream?.isAudioMuted() ?? false;
     145              : 
     146            0 :   bool get screensharingEnabled => localScreenSharingStream != null;
     147              : 
     148            2 :   WrappedMediaStream? get localUserMediaStream {
     149            4 :     final stream = getLocalStreams.where(
     150            6 :       (element) => element.purpose == SDPStreamMetadataPurpose.Usermedia,
     151              :     );
     152            2 :     if (stream.isNotEmpty) {
     153            2 :       return stream.first;
     154              :     }
     155              :     return null;
     156              :   }
     157              : 
     158            2 :   WrappedMediaStream? get localScreenSharingStream {
     159            4 :     final stream = getLocalStreams.where(
     160            6 :       (element) => element.purpose == SDPStreamMetadataPurpose.Screenshare,
     161              :     );
     162            2 :     if (stream.isNotEmpty) {
     163            0 :       return stream.first;
     164              :     }
     165              :     return null;
     166              :   }
     167              : 
     168            0 :   WrappedMediaStream? get remoteUserMediaStream {
     169            0 :     final stream = getRemoteStreams.where(
     170            0 :       (element) => element.purpose == SDPStreamMetadataPurpose.Usermedia,
     171              :     );
     172            0 :     if (stream.isNotEmpty) {
     173            0 :       return stream.first;
     174              :     }
     175              :     return null;
     176              :   }
     177              : 
     178            0 :   WrappedMediaStream? get remoteScreenSharingStream {
     179            0 :     final stream = getRemoteStreams.where(
     180            0 :       (element) => element.purpose == SDPStreamMetadataPurpose.Screenshare,
     181              :     );
     182            0 :     if (stream.isNotEmpty) {
     183            0 :       return stream.first;
     184              :     }
     185              :     return null;
     186              :   }
     187              : 
     188              :   /// returns whether a 1:1 call sender has video tracks
     189            0 :   Future<bool> hasVideoToSend() async {
     190            0 :     final transceivers = await pc!.getTransceivers();
     191            0 :     final localUserMediaVideoTrack = localUserMediaStream?.stream
     192            0 :         ?.getTracks()
     193            0 :         .singleWhereOrNull((track) => track.kind == 'video');
     194              : 
     195              :     // check if we have a video track locally and have transceivers setup correctly.
     196              :     return localUserMediaVideoTrack != null &&
     197            0 :         transceivers.singleWhereOrNull(
     198            0 :               (transceiver) =>
     199            0 :                   transceiver.sender.track?.id == localUserMediaVideoTrack.id,
     200              :             ) !=
     201              :             null;
     202              :   }
     203              : 
     204              :   Timer? _inviteTimer;
     205              :   Timer? _ringingTimer;
     206              : 
     207              :   // outgoing call
     208            2 :   Future<void> initOutboundCall(CallType type) async {
     209            2 :     await _preparePeerConnection();
     210            2 :     setCallState(CallState.kCreateOffer);
     211            2 :     final stream = await _getUserMedia(type);
     212              :     if (stream != null) {
     213            2 :       await addLocalStream(stream, SDPStreamMetadataPurpose.Usermedia);
     214              :     }
     215              :   }
     216              : 
     217              :   // incoming call
     218            2 :   Future<void> initWithInvite(
     219              :     CallType type,
     220              :     RTCSessionDescription offer,
     221              :     SDPStreamMetadata? metadata,
     222              :     int lifetime,
     223              :     bool isGroupCall,
     224              :   ) async {
     225              :     if (!isGroupCall) {
     226              :       // glare fixes
     227           10 :       final prevCallId = voip.incomingCallRoomId[room.id];
     228              :       if (prevCallId != null) {
     229              :         // This is probably an outbound call, but we already have a incoming invite, so let's terminate it.
     230              :         final prevCall =
     231           12 :             voip.calls[VoipId(roomId: room.id, callId: prevCallId)];
     232              :         if (prevCall != null) {
     233            2 :           if (prevCall._inviteOrAnswerSent) {
     234            4 :             Logs().d('[glare] invite or answer sent, lex compare now');
     235            8 :             if (callId.compareTo(prevCall.callId) > 0) {
     236            4 :               Logs().d(
     237            6 :                 '[glare] new call $callId needs to be canceled because the older one ${prevCall.callId} has a smaller lex',
     238              :               );
     239            2 :               await hangup(reason: CallErrorCode.unknownError);
     240            4 :               voip.currentCID =
     241            8 :                   VoipId(roomId: room.id, callId: prevCall.callId);
     242              :             } else {
     243            0 :               Logs().d(
     244            0 :                 '[glare] nice, lex of newer call $callId is smaller auto accept this here',
     245              :               );
     246              : 
     247              :               /// These fixes do not work all the time because sometimes the code
     248              :               /// is at an unrecoverable stage (invite already sent when we were
     249              :               /// checking if we want to send a invite), so commented out answering
     250              :               /// automatically to prevent unknown cases
     251              :               // await answer();
     252              :               // return;
     253              :             }
     254              :           } else {
     255            4 :             Logs().d(
     256            4 :               '[glare] ${prevCall.callId} was still preparing prev call, nvm now cancel it',
     257              :             );
     258            2 :             await prevCall.hangup(reason: CallErrorCode.unknownError);
     259              :           }
     260              :         }
     261              :       }
     262              :     }
     263              : 
     264            2 :     await _preparePeerConnection();
     265              :     if (metadata != null) {
     266            0 :       _updateRemoteSDPStreamMetadata(metadata);
     267              :     }
     268            4 :     await pc!.setRemoteDescription(offer);
     269              : 
     270              :     /// only add local stream if it is not a group call.
     271              :     if (!isGroupCall) {
     272            2 :       final stream = await _getUserMedia(type);
     273              :       if (stream != null) {
     274            2 :         await addLocalStream(stream, SDPStreamMetadataPurpose.Usermedia);
     275              :       } else {
     276              :         // we don't have a localstream, call probably crashed
     277              :         // for sanity
     278            0 :         if (state == CallState.kEnded) {
     279              :           return;
     280              :         }
     281              :       }
     282              :     }
     283              : 
     284            2 :     setCallState(CallState.kRinging);
     285              : 
     286            4 :     _ringingTimer = Timer(CallTimeouts.callInviteLifetime, () {
     287            0 :       if (state == CallState.kRinging) {
     288            0 :         Logs().v('[VOIP] Call invite has expired. Hanging up.');
     289              : 
     290            0 :         fireCallEvent(CallStateChange.kHangup);
     291            0 :         hangup(reason: CallErrorCode.inviteTimeout);
     292              :       }
     293            0 :       _ringingTimer?.cancel();
     294            0 :       _ringingTimer = null;
     295              :     });
     296              :   }
     297              : 
     298            0 :   Future<void> answerWithStreams(List<WrappedMediaStream> callFeeds) async {
     299            0 :     if (_inviteOrAnswerSent) return;
     300            0 :     Logs().d('answering call $callId');
     301            0 :     await gotCallFeedsForAnswer(callFeeds);
     302              :   }
     303              : 
     304            0 :   Future<void> replacedBy(CallSession newCall) async {
     305            0 :     if (state == CallState.kWaitLocalMedia) {
     306            0 :       Logs().v('Telling new call to wait for local media');
     307            0 :     } else if (state == CallState.kCreateOffer ||
     308            0 :         state == CallState.kInviteSent) {
     309            0 :       Logs().v('Handing local stream to new call');
     310            0 :       await newCall.gotCallFeedsForAnswer(getLocalStreams);
     311              :     }
     312            0 :     _successor = newCall;
     313            0 :     onCallReplaced.add(newCall);
     314              :     // ignore: unawaited_futures
     315            0 :     hangup(reason: CallErrorCode.replaced);
     316              :   }
     317              : 
     318            0 :   Future<void> sendAnswer(RTCSessionDescription answer) async {
     319            0 :     final callCapabilities = CallCapabilities()
     320            0 :       ..dtmf = false
     321            0 :       ..transferee = false;
     322              : 
     323            0 :     final metadata = SDPStreamMetadata({
     324            0 :       localUserMediaStream!.stream!.id: SDPStreamPurpose(
     325              :         purpose: SDPStreamMetadataPurpose.Usermedia,
     326            0 :         audio_muted: localUserMediaStream!.stream!.getAudioTracks().isEmpty,
     327            0 :         video_muted: localUserMediaStream!.stream!.getVideoTracks().isEmpty,
     328              :       ),
     329              :     });
     330              : 
     331            0 :     final res = await sendAnswerCall(
     332            0 :       room,
     333            0 :       callId,
     334            0 :       answer.sdp!,
     335            0 :       localPartyId,
     336            0 :       type: answer.type!,
     337              :       capabilities: callCapabilities,
     338              :       metadata: metadata,
     339              :     );
     340            0 :     Logs().v('[VOIP] answer res => $res');
     341              :   }
     342              : 
     343            0 :   Future<void> gotCallFeedsForAnswer(List<WrappedMediaStream> callFeeds) async {
     344            0 :     if (state == CallState.kEnded) return;
     345              : 
     346            0 :     for (final element in callFeeds) {
     347            0 :       await addLocalStream(await element.stream!.clone(), element.purpose);
     348              :     }
     349              : 
     350            0 :     await answer();
     351              :   }
     352              : 
     353            0 :   Future<void> placeCallWithStreams(
     354              :     List<WrappedMediaStream> callFeeds, {
     355              :     bool requestScreenSharing = false,
     356              :   }) async {
     357              :     // create the peer connection now so it can be gathering candidates while we get user
     358              :     // media (assuming a candidate pool size is configured)
     359            0 :     await _preparePeerConnection();
     360            0 :     await gotCallFeedsForInvite(
     361              :       callFeeds,
     362              :       requestScreenSharing: requestScreenSharing,
     363              :     );
     364              :   }
     365              : 
     366            0 :   Future<void> gotCallFeedsForInvite(
     367              :     List<WrappedMediaStream> callFeeds, {
     368              :     bool requestScreenSharing = false,
     369              :   }) async {
     370            0 :     if (_successor != null) {
     371            0 :       await _successor!.gotCallFeedsForAnswer(callFeeds);
     372              :       return;
     373              :     }
     374            0 :     if (state == CallState.kEnded) {
     375            0 :       await cleanUp();
     376              :       return;
     377              :     }
     378              : 
     379            0 :     for (final element in callFeeds) {
     380            0 :       await addLocalStream(await element.stream!.clone(), element.purpose);
     381              :     }
     382              : 
     383              :     if (requestScreenSharing) {
     384            0 :       await pc!.addTransceiver(
     385              :         kind: RTCRtpMediaType.RTCRtpMediaTypeVideo,
     386            0 :         init: RTCRtpTransceiverInit(direction: TransceiverDirection.RecvOnly),
     387              :       );
     388              :     }
     389              : 
     390            0 :     setCallState(CallState.kCreateOffer);
     391              : 
     392            0 :     Logs().d('gotUserMediaForInvite');
     393              :     // Now we wait for the negotiationneeded event
     394              :   }
     395              : 
     396            0 :   Future<void> onAnswerReceived(
     397              :     RTCSessionDescription answer,
     398              :     SDPStreamMetadata? metadata,
     399              :   ) async {
     400              :     if (metadata != null) {
     401            0 :       _updateRemoteSDPStreamMetadata(metadata);
     402              :     }
     403              : 
     404            0 :     if (direction == CallDirection.kOutgoing) {
     405            0 :       setCallState(CallState.kConnecting);
     406            0 :       await pc!.setRemoteDescription(answer);
     407            0 :       for (final candidate in _remoteCandidates) {
     408            0 :         await pc!.addCandidate(candidate);
     409              :       }
     410              :     }
     411            0 :     if (remotePartyId != null) {
     412              :       /// Send select_answer event.
     413            0 :       await sendSelectCallAnswer(
     414            0 :         opts.room,
     415            0 :         callId,
     416            0 :         localPartyId,
     417            0 :         remotePartyId!,
     418              :       );
     419              :     }
     420              :   }
     421              : 
     422            0 :   Future<void> onNegotiateReceived(
     423              :     SDPStreamMetadata? metadata,
     424              :     RTCSessionDescription description,
     425              :   ) async {
     426            0 :     final polite = direction == CallDirection.kIncoming;
     427              : 
     428              :     // Here we follow the perfect negotiation logic from
     429              :     // https://developer.mozilla.org/en-US/docs/Web/API/WebRTC_API/Perfect_negotiation
     430            0 :     final offerCollision = ((description.type == 'offer') &&
     431            0 :         (_makingOffer ||
     432            0 :             pc!.signalingState != RTCSignalingState.RTCSignalingStateStable));
     433              : 
     434            0 :     _ignoreOffer = !polite && offerCollision;
     435            0 :     if (_ignoreOffer) {
     436            0 :       Logs().i('Ignoring colliding negotiate event because we\'re impolite');
     437              :       return;
     438              :     }
     439              : 
     440            0 :     final prevLocalOnHold = await isLocalOnHold();
     441              : 
     442              :     if (metadata != null) {
     443            0 :       _updateRemoteSDPStreamMetadata(metadata);
     444              :     }
     445              : 
     446              :     try {
     447            0 :       await pc!.setRemoteDescription(description);
     448              :       RTCSessionDescription? answer;
     449            0 :       if (description.type == 'offer') {
     450              :         try {
     451            0 :           answer = await pc!.createAnswer({});
     452              :         } catch (e) {
     453            0 :           await terminate(CallParty.kLocal, CallErrorCode.createAnswer, true);
     454              :           rethrow;
     455              :         }
     456              : 
     457            0 :         await sendCallNegotiate(
     458            0 :           room,
     459            0 :           callId,
     460            0 :           CallTimeouts.defaultCallEventLifetime.inMilliseconds,
     461            0 :           localPartyId,
     462            0 :           answer.sdp!,
     463            0 :           type: answer.type!,
     464              :         );
     465            0 :         await pc!.setLocalDescription(answer);
     466              :       }
     467              :     } catch (e, s) {
     468            0 :       Logs().e('[VOIP] onNegotiateReceived => ', e, s);
     469            0 :       await _getLocalOfferFailed(e);
     470              :       return;
     471              :     }
     472              : 
     473            0 :     final newLocalOnHold = await isLocalOnHold();
     474            0 :     if (prevLocalOnHold != newLocalOnHold) {
     475            0 :       _localHold = newLocalOnHold;
     476            0 :       fireCallEvent(CallStateChange.kLocalHoldUnhold);
     477              :     }
     478              :   }
     479              : 
     480            0 :   Future<void> updateMediaDeviceForCall() async {
     481            0 :     await updateMediaDevice(
     482            0 :       voip.delegate,
     483              :       MediaKind.audio,
     484            0 :       _usermediaSenders,
     485              :     );
     486            0 :     await updateMediaDevice(
     487            0 :       voip.delegate,
     488              :       MediaKind.video,
     489            0 :       _usermediaSenders,
     490              :     );
     491              :   }
     492              : 
     493            0 :   void _updateRemoteSDPStreamMetadata(SDPStreamMetadata metadata) {
     494            0 :     _remoteSDPStreamMetadata = metadata;
     495            0 :     _remoteSDPStreamMetadata?.sdpStreamMetadatas
     496            0 :         .forEach((streamId, sdpStreamMetadata) {
     497            0 :       Logs().i(
     498            0 :         'Stream purpose update: \nid = "$streamId", \npurpose = "${sdpStreamMetadata.purpose}",  \naudio_muted = ${sdpStreamMetadata.audio_muted}, \nvideo_muted = ${sdpStreamMetadata.video_muted}',
     499              :       );
     500              :     });
     501            0 :     for (final wpstream in getRemoteStreams) {
     502            0 :       final streamId = wpstream.stream!.id;
     503            0 :       final purpose = metadata.sdpStreamMetadatas[streamId];
     504              :       if (purpose != null) {
     505              :         wpstream
     506            0 :             .setAudioMuted(metadata.sdpStreamMetadatas[streamId]!.audio_muted);
     507              :         wpstream
     508            0 :             .setVideoMuted(metadata.sdpStreamMetadatas[streamId]!.video_muted);
     509            0 :         wpstream.purpose = metadata.sdpStreamMetadatas[streamId]!.purpose;
     510              :       } else {
     511            0 :         Logs().i('Not found purpose for remote stream $streamId, remove it?');
     512            0 :         wpstream.stopped = true;
     513            0 :         fireCallEvent(CallStateChange.kFeedsChanged);
     514              :       }
     515              :     }
     516              :   }
     517              : 
     518            0 :   Future<void> onSDPStreamMetadataReceived(SDPStreamMetadata metadata) async {
     519            0 :     _updateRemoteSDPStreamMetadata(metadata);
     520            0 :     fireCallEvent(CallStateChange.kFeedsChanged);
     521              :   }
     522              : 
     523            2 :   Future<void> onCandidatesReceived(List<dynamic> candidates) async {
     524            4 :     for (final json in candidates) {
     525            2 :       final candidate = RTCIceCandidate(
     526            2 :         json['candidate'],
     527            2 :         json['sdpMid'] ?? '',
     528            4 :         json['sdpMLineIndex']?.round() ?? 0,
     529              :       );
     530              : 
     531            2 :       if (!candidate.isValid) {
     532            0 :         Logs().w(
     533            0 :           '[VOIP] onCandidatesReceived => skip invalid candidate ${candidate.toMap()}',
     534              :         );
     535              :         continue;
     536              :       }
     537              : 
     538            4 :       if (direction == CallDirection.kOutgoing &&
     539            0 :           pc != null &&
     540            0 :           await pc!.getRemoteDescription() == null) {
     541            0 :         _remoteCandidates.add(candidate);
     542              :         continue;
     543              :       }
     544              : 
     545            4 :       if (pc != null && _inviteOrAnswerSent) {
     546              :         try {
     547            0 :           await pc!.addCandidate(candidate);
     548              :         } catch (e, s) {
     549            0 :           Logs().e('[VOIP] onCandidatesReceived => ', e, s);
     550              :         }
     551              :       } else {
     552            4 :         _remoteCandidates.add(candidate);
     553              :       }
     554              :     }
     555              :   }
     556              : 
     557            0 :   void onAssertedIdentityReceived(AssertedIdentity identity) {
     558            0 :     _remoteAssertedIdentity = identity;
     559            0 :     fireCallEvent(CallStateChange.kAssertedIdentityChanged);
     560              :   }
     561              : 
     562            0 :   Future<bool> setScreensharingEnabled(bool enabled) async {
     563              :     // Skip if there is nothing to do
     564            0 :     if (enabled && localScreenSharingStream != null) {
     565            0 :       Logs().w(
     566              :         'There is already a screensharing stream - there is nothing to do!',
     567              :       );
     568              :       return true;
     569            0 :     } else if (!enabled && localScreenSharingStream == null) {
     570            0 :       Logs().w(
     571              :         'There already isn\'t a screensharing stream - there is nothing to do!',
     572              :       );
     573              :       return false;
     574              :     }
     575              : 
     576            0 :     Logs().d('Set screensharing enabled? $enabled');
     577              : 
     578              :     if (enabled) {
     579              :       try {
     580            0 :         final stream = await _getDisplayMedia();
     581              :         if (stream == null) {
     582              :           return false;
     583              :         }
     584            0 :         for (final track in stream.getTracks()) {
     585              :           // screen sharing should only have 1 video track anyway, so this only
     586              :           // fires once
     587            0 :           track.onEnded = () async {
     588            0 :             await setScreensharingEnabled(false);
     589              :           };
     590              :         }
     591              : 
     592            0 :         await addLocalStream(stream, SDPStreamMetadataPurpose.Screenshare);
     593              :         return true;
     594              :       } catch (err) {
     595            0 :         fireCallEvent(CallStateChange.kError);
     596              :         return false;
     597              :       }
     598              :     } else {
     599              :       try {
     600            0 :         for (final sender in _screensharingSenders) {
     601            0 :           await pc!.removeTrack(sender);
     602              :         }
     603            0 :         for (final track in localScreenSharingStream!.stream!.getTracks()) {
     604            0 :           await track.stop();
     605              :         }
     606            0 :         localScreenSharingStream!.stopped = true;
     607            0 :         await _removeStream(localScreenSharingStream!.stream!);
     608            0 :         fireCallEvent(CallStateChange.kFeedsChanged);
     609              :         return false;
     610              :       } catch (e, s) {
     611            0 :         Logs().e('[VOIP] stopping screen sharing track failed', e, s);
     612              :         return false;
     613              :       }
     614              :     }
     615              :   }
     616              : 
     617            2 :   Future<void> addLocalStream(
     618              :     MediaStream stream,
     619              :     String purpose, {
     620              :     bool addToPeerConnection = true,
     621              :   }) async {
     622              :     final existingStream =
     623            4 :         getLocalStreams.where((element) => element.purpose == purpose);
     624            2 :     if (existingStream.isNotEmpty) {
     625            0 :       existingStream.first.setNewStream(stream);
     626              :     } else {
     627            2 :       final newStream = WrappedMediaStream(
     628            2 :         participant: localParticipant!,
     629            4 :         room: opts.room,
     630              :         stream: stream,
     631              :         purpose: purpose,
     632            2 :         client: client,
     633            4 :         audioMuted: stream.getAudioTracks().isEmpty,
     634            4 :         videoMuted: stream.getVideoTracks().isEmpty,
     635            2 :         isGroupCall: groupCallId != null,
     636            2 :         pc: pc,
     637            2 :         voip: voip,
     638              :       );
     639            4 :       _streams.add(newStream);
     640            4 :       onStreamAdd.add(newStream);
     641              :     }
     642              : 
     643              :     if (addToPeerConnection) {
     644            2 :       if (purpose == SDPStreamMetadataPurpose.Screenshare) {
     645            0 :         _screensharingSenders.clear();
     646            0 :         for (final track in stream.getTracks()) {
     647            0 :           _screensharingSenders.add(await pc!.addTrack(track, stream));
     648              :         }
     649            2 :       } else if (purpose == SDPStreamMetadataPurpose.Usermedia) {
     650            4 :         _usermediaSenders.clear();
     651            2 :         for (final track in stream.getTracks()) {
     652            0 :           _usermediaSenders.add(await pc!.addTrack(track, stream));
     653              :         }
     654              :       }
     655              :     }
     656              : 
     657            2 :     if (purpose == SDPStreamMetadataPurpose.Usermedia) {
     658            6 :       _speakerOn = type == CallType.kVideo;
     659           10 :       if (!voip.delegate.isWeb && stream.getAudioTracks().isNotEmpty) {
     660            0 :         final audioTrack = stream.getAudioTracks()[0];
     661            0 :         audioTrack.enableSpeakerphone(_speakerOn);
     662              :       }
     663              :     }
     664              : 
     665            2 :     fireCallEvent(CallStateChange.kFeedsChanged);
     666              :   }
     667              : 
     668            0 :   Future<void> _addRemoteStream(MediaStream stream) async {
     669              :     //final userId = remoteUser.id;
     670            0 :     final metadata = _remoteSDPStreamMetadata?.sdpStreamMetadatas[stream.id];
     671              :     if (metadata == null) {
     672            0 :       Logs().i(
     673            0 :         'Ignoring stream with id ${stream.id} because we didn\'t get any metadata about it',
     674              :       );
     675              :       return;
     676              :     }
     677              : 
     678            0 :     final purpose = metadata.purpose;
     679            0 :     final audioMuted = metadata.audio_muted;
     680            0 :     final videoMuted = metadata.video_muted;
     681              : 
     682              :     // Try to find a feed with the same purpose as the new stream,
     683              :     // if we find it replace the old stream with the new one
     684              :     final existingStream =
     685            0 :         getRemoteStreams.where((element) => element.purpose == purpose);
     686            0 :     if (existingStream.isNotEmpty) {
     687            0 :       existingStream.first.setNewStream(stream);
     688              :     } else {
     689            0 :       final newStream = WrappedMediaStream(
     690            0 :         participant: CallParticipant(
     691            0 :           voip,
     692            0 :           userId: remoteUserId!,
     693            0 :           deviceId: remoteDeviceId,
     694              :         ),
     695            0 :         room: opts.room,
     696              :         stream: stream,
     697              :         purpose: purpose,
     698            0 :         client: client,
     699              :         audioMuted: audioMuted,
     700              :         videoMuted: videoMuted,
     701            0 :         isGroupCall: groupCallId != null,
     702            0 :         pc: pc,
     703            0 :         voip: voip,
     704              :       );
     705            0 :       _streams.add(newStream);
     706            0 :       onStreamAdd.add(newStream);
     707              :     }
     708            0 :     fireCallEvent(CallStateChange.kFeedsChanged);
     709            0 :     Logs().i('Pushed remote stream (id="${stream.id}", purpose=$purpose)');
     710              :   }
     711              : 
     712            0 :   Future<void> deleteAllStreams() async {
     713            0 :     for (final stream in _streams) {
     714            0 :       if (stream.isLocal() || groupCallId == null) {
     715            0 :         await stream.dispose();
     716              :       }
     717              :     }
     718            0 :     _streams.clear();
     719            0 :     fireCallEvent(CallStateChange.kFeedsChanged);
     720              :   }
     721              : 
     722            0 :   Future<void> deleteFeedByStream(MediaStream stream) async {
     723              :     final index =
     724            0 :         _streams.indexWhere((element) => element.stream!.id == stream.id);
     725            0 :     if (index == -1) {
     726            0 :       Logs().w('Didn\'t find the feed with stream id ${stream.id} to delete');
     727              :       return;
     728              :     }
     729            0 :     final wstream = _streams.elementAt(index);
     730            0 :     onStreamRemoved.add(wstream);
     731            0 :     await deleteStream(wstream);
     732              :   }
     733              : 
     734            0 :   Future<void> deleteStream(WrappedMediaStream stream) async {
     735            0 :     await stream.dispose();
     736            0 :     _streams.removeAt(_streams.indexOf(stream));
     737            0 :     fireCallEvent(CallStateChange.kFeedsChanged);
     738              :   }
     739              : 
     740            0 :   Future<void> removeLocalStream(WrappedMediaStream callFeed) async {
     741            0 :     final senderArray = callFeed.purpose == SDPStreamMetadataPurpose.Usermedia
     742            0 :         ? _usermediaSenders
     743            0 :         : _screensharingSenders;
     744              : 
     745            0 :     for (final element in senderArray) {
     746            0 :       await pc!.removeTrack(element);
     747              :     }
     748              : 
     749            0 :     if (callFeed.purpose == SDPStreamMetadataPurpose.Screenshare) {
     750            0 :       await stopMediaStream(callFeed.stream);
     751              :     }
     752              : 
     753              :     // Empty the array
     754            0 :     senderArray.removeRange(0, senderArray.length);
     755            0 :     onStreamRemoved.add(callFeed);
     756            0 :     await deleteStream(callFeed);
     757              :   }
     758              : 
     759            2 :   void setCallState(CallState newState) {
     760            2 :     _state = newState;
     761            4 :     onCallStateChanged.add(newState);
     762            2 :     fireCallEvent(CallStateChange.kState);
     763              :   }
     764              : 
     765            0 :   Future<void> setLocalVideoMuted(bool muted) async {
     766              :     if (!muted) {
     767            0 :       final videoToSend = await hasVideoToSend();
     768              :       if (!videoToSend) {
     769            0 :         if (_remoteSDPStreamMetadata == null) return;
     770            0 :         await insertVideoTrackToAudioOnlyStream();
     771              :       }
     772              :     }
     773            0 :     localUserMediaStream?.setVideoMuted(muted);
     774            0 :     await updateMuteStatus();
     775              :   }
     776              : 
     777              :   // used for upgrading 1:1 calls
     778            0 :   Future<void> insertVideoTrackToAudioOnlyStream() async {
     779            0 :     if (localUserMediaStream != null && localUserMediaStream!.stream != null) {
     780            0 :       final stream = await _getUserMedia(CallType.kVideo);
     781              :       if (stream != null) {
     782            0 :         Logs().d('[VOIP] running replaceTracks() on stream: ${stream.id}');
     783            0 :         _setTracksEnabled(stream.getVideoTracks(), true);
     784              :         // replace local tracks
     785            0 :         for (final track in localUserMediaStream!.stream!.getTracks()) {
     786              :           try {
     787            0 :             await localUserMediaStream!.stream!.removeTrack(track);
     788            0 :             await track.stop();
     789              :           } catch (e) {
     790            0 :             Logs().w('failed to stop track');
     791              :           }
     792              :         }
     793            0 :         final streamTracks = stream.getTracks();
     794            0 :         for (final newTrack in streamTracks) {
     795            0 :           await localUserMediaStream!.stream!.addTrack(newTrack);
     796              :         }
     797              : 
     798              :         // remove any screen sharing or remote transceivers, these don't need
     799              :         // to be replaced anyway.
     800            0 :         final transceivers = await pc!.getTransceivers();
     801            0 :         transceivers.removeWhere(
     802            0 :           (transceiver) =>
     803            0 :               transceiver.sender.track == null ||
     804            0 :               (localScreenSharingStream != null &&
     805            0 :                   localScreenSharingStream!.stream != null &&
     806            0 :                   localScreenSharingStream!.stream!
     807            0 :                       .getTracks()
     808            0 :                       .map((e) => e.id)
     809            0 :                       .contains(transceiver.sender.track?.id)),
     810              :         );
     811              : 
     812              :         // in an ideal case the following should happen
     813              :         // - audio track gets replaced
     814              :         // - new video track gets added
     815            0 :         for (final newTrack in streamTracks) {
     816            0 :           final transceiver = transceivers.singleWhereOrNull(
     817            0 :             (transceiver) => transceiver.sender.track!.kind == newTrack.kind,
     818              :           );
     819              :           if (transceiver != null) {
     820            0 :             Logs().d(
     821            0 :               '[VOIP] replacing ${transceiver.sender.track} in transceiver',
     822              :             );
     823            0 :             final oldSender = transceiver.sender;
     824            0 :             await oldSender.replaceTrack(newTrack);
     825            0 :             await transceiver.setDirection(
     826            0 :               await transceiver.getDirection() ==
     827              :                       TransceiverDirection.Inactive // upgrade, send now
     828              :                   ? TransceiverDirection.SendOnly
     829              :                   : TransceiverDirection.SendRecv,
     830              :             );
     831              :           } else {
     832              :             // adding transceiver
     833            0 :             Logs().d('[VOIP] adding track $newTrack to pc');
     834            0 :             await pc!.addTrack(newTrack, localUserMediaStream!.stream!);
     835              :           }
     836              :         }
     837              :         // for renderer to be able to show new video track
     838            0 :         localUserMediaStream?.onStreamChanged
     839            0 :             .add(localUserMediaStream!.stream!);
     840              :       }
     841              :     }
     842              :   }
     843              : 
     844            0 :   Future<void> setMicrophoneMuted(bool muted) async {
     845            0 :     localUserMediaStream?.setAudioMuted(muted);
     846            0 :     await updateMuteStatus();
     847              :   }
     848              : 
     849            0 :   Future<void> setRemoteOnHold(bool onHold) async {
     850            0 :     if (remoteOnHold == onHold) return;
     851            0 :     _remoteOnHold = onHold;
     852            0 :     final transceivers = await pc!.getTransceivers();
     853            0 :     for (final transceiver in transceivers) {
     854            0 :       await transceiver.setDirection(
     855              :         onHold ? TransceiverDirection.SendOnly : TransceiverDirection.SendRecv,
     856              :       );
     857              :     }
     858            0 :     await updateMuteStatus();
     859            0 :     fireCallEvent(CallStateChange.kRemoteHoldUnhold);
     860              :   }
     861              : 
     862            0 :   Future<bool> isLocalOnHold() async {
     863            0 :     if (state != CallState.kConnected) return false;
     864              :     var callOnHold = true;
     865              :     // We consider a call to be on hold only if *all* the tracks are on hold
     866              :     // (is this the right thing to do?)
     867            0 :     final transceivers = await pc!.getTransceivers();
     868            0 :     for (final transceiver in transceivers) {
     869            0 :       final currentDirection = await transceiver.getCurrentDirection();
     870            0 :       final trackOnHold = (currentDirection == TransceiverDirection.Inactive ||
     871            0 :           currentDirection == TransceiverDirection.RecvOnly);
     872              :       if (!trackOnHold) {
     873              :         callOnHold = false;
     874              :       }
     875              :     }
     876              :     return callOnHold;
     877              :   }
     878              : 
     879            2 :   Future<void> answer({String? txid}) async {
     880            2 :     if (_inviteOrAnswerSent) {
     881              :       return;
     882              :     }
     883              :     // stop play ringtone
     884            6 :     await voip.delegate.stopRingtone();
     885              : 
     886            4 :     if (direction == CallDirection.kIncoming) {
     887            2 :       setCallState(CallState.kCreateAnswer);
     888              : 
     889            6 :       final answer = await pc!.createAnswer({});
     890            4 :       for (final candidate in _remoteCandidates) {
     891            4 :         await pc!.addCandidate(candidate);
     892              :       }
     893              : 
     894            2 :       final callCapabilities = CallCapabilities()
     895            2 :         ..dtmf = false
     896            2 :         ..transferee = false;
     897              : 
     898            4 :       final metadata = SDPStreamMetadata({
     899            2 :         if (localUserMediaStream != null)
     900           10 :           localUserMediaStream!.stream!.id: SDPStreamPurpose(
     901              :             purpose: SDPStreamMetadataPurpose.Usermedia,
     902            4 :             audio_muted: localUserMediaStream!.audioMuted,
     903            4 :             video_muted: localUserMediaStream!.videoMuted,
     904              :           ),
     905            2 :         if (localScreenSharingStream != null)
     906            0 :           localScreenSharingStream!.stream!.id: SDPStreamPurpose(
     907              :             purpose: SDPStreamMetadataPurpose.Screenshare,
     908            0 :             audio_muted: localScreenSharingStream!.audioMuted,
     909            0 :             video_muted: localScreenSharingStream!.videoMuted,
     910              :           ),
     911              :       });
     912              : 
     913            4 :       await pc!.setLocalDescription(answer);
     914            2 :       setCallState(CallState.kConnecting);
     915              : 
     916              :       // Allow a short time for initial candidates to be gathered
     917            4 :       await Future.delayed(Duration(milliseconds: 200));
     918              : 
     919            2 :       final res = await sendAnswerCall(
     920            2 :         room,
     921            2 :         callId,
     922            2 :         answer.sdp!,
     923            2 :         localPartyId,
     924            2 :         type: answer.type!,
     925              :         capabilities: callCapabilities,
     926              :         metadata: metadata,
     927              :         txid: txid,
     928              :       );
     929            6 :       Logs().v('[VOIP] answer res => $res');
     930              : 
     931            2 :       _inviteOrAnswerSent = true;
     932            2 :       _answeredByUs = true;
     933              :     }
     934              :   }
     935              : 
     936              :   /// Reject a call
     937              :   /// This used to be done by calling hangup, but is a separate method and protocol
     938              :   /// event as of MSC2746.
     939            2 :   Future<void> reject({CallErrorCode? reason, bool shouldEmit = true}) async {
     940            4 :     if (state != CallState.kRinging && state != CallState.kFledgling) {
     941            0 :       Logs().e(
     942            0 :         '[VOIP] Call must be in \'ringing|fledgling\' state to reject! (current state was: ${state.toString()}) Calling hangup instead',
     943              :       );
     944            0 :       await hangup(reason: CallErrorCode.userHangup, shouldEmit: shouldEmit);
     945              :       return;
     946              :     }
     947            8 :     Logs().d('[VOIP] Rejecting call: $callId');
     948            2 :     setCallState(CallState.kEnding);
     949            2 :     await terminate(CallParty.kLocal, CallErrorCode.userHangup, shouldEmit);
     950              :     if (shouldEmit) {
     951            8 :       await sendCallReject(room, callId, localPartyId);
     952              :     }
     953              :   }
     954              : 
     955            2 :   Future<void> hangup({
     956              :     required CallErrorCode reason,
     957              :     bool shouldEmit = true,
     958              :   }) async {
     959            2 :     setCallState(CallState.kEnding);
     960            2 :     await terminate(CallParty.kLocal, reason, shouldEmit);
     961              :     try {
     962              :       final res =
     963            8 :           await sendHangupCall(room, callId, localPartyId, 'userHangup');
     964            6 :       Logs().v('[VOIP] hangup res => $res');
     965              :     } catch (e) {
     966            0 :       Logs().v('[VOIP] hangup error => ${e.toString()}');
     967              :     }
     968              :   }
     969              : 
     970            0 :   Future<void> sendDTMF(String tones) async {
     971            0 :     final senders = await pc!.getSenders();
     972            0 :     for (final sender in senders) {
     973            0 :       if (sender.track != null && sender.track!.kind == 'audio') {
     974            0 :         await sender.dtmfSender.insertDTMF(tones);
     975              :         return;
     976              :       } else {
     977            0 :         Logs().w('[VOIP] Unable to find a track to send DTMF on');
     978              :       }
     979              :     }
     980              :   }
     981              : 
     982            2 :   Future<void> terminate(
     983              :     CallParty party,
     984              :     CallErrorCode reason,
     985              :     bool shouldEmit,
     986              :   ) async {
     987            4 :     if (state == CallState.kConnected) {
     988            0 :       await hangup(
     989              :         reason: CallErrorCode.userHangup,
     990              :         shouldEmit: true,
     991              :       );
     992              :       return;
     993              :     }
     994              : 
     995            4 :     Logs().d('[VOIP] terminating call');
     996            4 :     _inviteTimer?.cancel();
     997            2 :     _inviteTimer = null;
     998              : 
     999            4 :     _ringingTimer?.cancel();
    1000            2 :     _ringingTimer = null;
    1001              : 
    1002              :     try {
    1003            6 :       await voip.delegate.stopRingtone();
    1004              :     } catch (e) {
    1005              :       // maybe rigntone never started (group calls) or has been stopped already
    1006            0 :       Logs().d('stopping ringtone failed ', e);
    1007              :     }
    1008              : 
    1009            2 :     hangupReason = reason;
    1010              : 
    1011              :     // don't see any reason to wrap this with shouldEmit atm,
    1012              :     // looks like a local state change only
    1013            2 :     setCallState(CallState.kEnded);
    1014              : 
    1015            2 :     if (!isGroupCall) {
    1016              :       // when a call crash and this call is already terminated the currentCId is null.
    1017              :       // So don't return bc the hangup or reject will not proceed anymore.
    1018            4 :       if (voip.currentCID != null &&
    1019           14 :           voip.currentCID != VoipId(roomId: room.id, callId: callId)) {
    1020              :         return;
    1021              :       }
    1022            4 :       voip.currentCID = null;
    1023           12 :       voip.incomingCallRoomId.removeWhere((key, value) => value == callId);
    1024              :     }
    1025              : 
    1026           14 :     voip.calls.removeWhere((key, value) => key.callId == callId);
    1027              : 
    1028            2 :     await cleanUp();
    1029              :     if (shouldEmit) {
    1030            4 :       onCallHangupNotifierForGroupCalls.add(this);
    1031            6 :       await voip.delegate.handleCallEnded(this);
    1032            2 :       fireCallEvent(CallStateChange.kHangup);
    1033            2 :       if ((party == CallParty.kRemote &&
    1034            2 :           _missedCall &&
    1035            2 :           reason != CallErrorCode.answeredElsewhere)) {
    1036            0 :         await voip.delegate.handleMissedCall(this);
    1037              :       }
    1038              :     }
    1039              :   }
    1040              : 
    1041            0 :   Future<void> onRejectReceived(CallErrorCode? reason) async {
    1042            0 :     Logs().v('[VOIP] Reject received for call ID $callId');
    1043              :     // No need to check party_id for reject because if we'd received either
    1044              :     // an answer or reject, we wouldn't be in state InviteSent
    1045            0 :     final shouldTerminate = (state == CallState.kFledgling &&
    1046            0 :             direction == CallDirection.kIncoming) ||
    1047            0 :         CallState.kInviteSent == state ||
    1048            0 :         CallState.kRinging == state;
    1049              : 
    1050              :     if (shouldTerminate) {
    1051            0 :       await terminate(
    1052              :         CallParty.kRemote,
    1053              :         reason ?? CallErrorCode.userHangup,
    1054              :         true,
    1055              :       );
    1056              :     } else {
    1057            0 :       Logs().e('[VOIP] Call is in state: ${state.toString()}: ignoring reject');
    1058              :     }
    1059              :   }
    1060              : 
    1061            2 :   Future<void> _gotLocalOffer(RTCSessionDescription offer) async {
    1062            2 :     if (callHasEnded) {
    1063            0 :       Logs().d(
    1064            0 :         'Ignoring newly created offer on call ID ${opts.callId} because the call has ended',
    1065              :       );
    1066              :       return;
    1067              :     }
    1068              : 
    1069              :     try {
    1070            4 :       await pc!.setLocalDescription(offer);
    1071              :     } catch (err) {
    1072            0 :       Logs().d('Error setting local description! ${err.toString()}');
    1073            0 :       await terminate(
    1074              :         CallParty.kLocal,
    1075              :         CallErrorCode.setLocalDescription,
    1076              :         true,
    1077              :       );
    1078              :       return;
    1079              :     }
    1080              : 
    1081            6 :     if (pc!.iceGatheringState ==
    1082              :         RTCIceGatheringState.RTCIceGatheringStateGathering) {
    1083              :       // Allow a short time for initial candidates to be gathered
    1084            0 :       await Future.delayed(CallTimeouts.iceGatheringDelay);
    1085              :     }
    1086              : 
    1087            2 :     if (callHasEnded) return;
    1088              : 
    1089            2 :     final callCapabilities = CallCapabilities()
    1090            2 :       ..dtmf = false
    1091            2 :       ..transferee = false;
    1092            2 :     final metadata = _getLocalSDPStreamMetadata();
    1093            4 :     if (state == CallState.kCreateOffer) {
    1094            2 :       await sendInviteToCall(
    1095            2 :         room,
    1096            2 :         callId,
    1097            2 :         CallTimeouts.callInviteLifetime.inMilliseconds,
    1098            2 :         localPartyId,
    1099            2 :         offer.sdp!,
    1100              :         capabilities: callCapabilities,
    1101              :         metadata: metadata,
    1102              :       );
    1103              :       // just incase we ended the call but already sent the invite
    1104              :       // raraley happens during glares
    1105            4 :       if (state == CallState.kEnded) {
    1106            0 :         await hangup(reason: CallErrorCode.replaced);
    1107              :         return;
    1108              :       }
    1109            2 :       _inviteOrAnswerSent = true;
    1110              : 
    1111            2 :       if (!isGroupCall) {
    1112            4 :         Logs().d('[glare] set callid because new invite sent');
    1113           12 :         voip.incomingCallRoomId[room.id] = callId;
    1114              :       }
    1115              : 
    1116            2 :       setCallState(CallState.kInviteSent);
    1117              : 
    1118            4 :       _inviteTimer = Timer(CallTimeouts.callInviteLifetime, () {
    1119            0 :         if (state == CallState.kInviteSent) {
    1120            0 :           hangup(reason: CallErrorCode.inviteTimeout);
    1121              :         }
    1122            0 :         _inviteTimer?.cancel();
    1123            0 :         _inviteTimer = null;
    1124              :       });
    1125              :     } else {
    1126            0 :       await sendCallNegotiate(
    1127            0 :         room,
    1128            0 :         callId,
    1129            0 :         CallTimeouts.defaultCallEventLifetime.inMilliseconds,
    1130            0 :         localPartyId,
    1131            0 :         offer.sdp!,
    1132            0 :         type: offer.type!,
    1133              :         capabilities: callCapabilities,
    1134              :         metadata: metadata,
    1135              :       );
    1136              :     }
    1137              :   }
    1138              : 
    1139            2 :   Future<void> onNegotiationNeeded() async {
    1140            4 :     Logs().d('Negotiation is needed!');
    1141            2 :     _makingOffer = true;
    1142              :     try {
    1143              :       // The first addTrack(audio track) on iOS will trigger
    1144              :       // onNegotiationNeeded, which causes creatOffer to only include
    1145              :       // audio m-line, add delay and wait for video track to be added,
    1146              :       // then createOffer can get audio/video m-line correctly.
    1147            2 :       await Future.delayed(CallTimeouts.delayBeforeOffer);
    1148            6 :       final offer = await pc!.createOffer({});
    1149            2 :       await _gotLocalOffer(offer);
    1150              :     } catch (e) {
    1151            0 :       await _getLocalOfferFailed(e);
    1152              :       return;
    1153              :     } finally {
    1154            2 :       _makingOffer = false;
    1155              :     }
    1156              :   }
    1157              : 
    1158            2 :   Future<void> _preparePeerConnection() async {
    1159              :     int iceRestartedCount = 0;
    1160              : 
    1161              :     try {
    1162            4 :       pc = await _createPeerConnection();
    1163            6 :       pc!.onRenegotiationNeeded = onNegotiationNeeded;
    1164              : 
    1165            4 :       pc!.onIceCandidate = (RTCIceCandidate candidate) async {
    1166            0 :         if (callHasEnded) return;
    1167            0 :         _localCandidates.add(candidate);
    1168              : 
    1169            0 :         if (state == CallState.kRinging || !_inviteOrAnswerSent) return;
    1170              : 
    1171              :         // MSC2746 recommends these values (can be quite long when calling because the
    1172              :         // callee will need a while to answer the call)
    1173            0 :         final delay = direction == CallDirection.kIncoming ? 500 : 2000;
    1174            0 :         if (_candidateSendTries == 0) {
    1175            0 :           Timer(Duration(milliseconds: delay), () {
    1176            0 :             _sendCandidateQueue();
    1177              :           });
    1178              :         }
    1179              :       };
    1180              : 
    1181            6 :       pc!.onIceGatheringState = (RTCIceGatheringState state) async {
    1182            8 :         Logs().v('[VOIP] IceGatheringState => ${state.toString()}');
    1183            2 :         if (state == RTCIceGatheringState.RTCIceGatheringStateGathering) {
    1184            0 :           Timer(Duration(seconds: 3), () async {
    1185            0 :             if (!_iceGatheringFinished) {
    1186            0 :               _iceGatheringFinished = true;
    1187            0 :               await _sendCandidateQueue();
    1188              :             }
    1189              :           });
    1190              :         }
    1191            2 :         if (state == RTCIceGatheringState.RTCIceGatheringStateComplete) {
    1192            2 :           if (!_iceGatheringFinished) {
    1193            2 :             _iceGatheringFinished = true;
    1194            2 :             await _sendCandidateQueue();
    1195              :           }
    1196              :         }
    1197              :       };
    1198            6 :       pc!.onIceConnectionState = (RTCIceConnectionState state) async {
    1199            8 :         Logs().v('[VOIP] RTCIceConnectionState => ${state.toString()}');
    1200            2 :         if (state == RTCIceConnectionState.RTCIceConnectionStateConnected) {
    1201            4 :           _localCandidates.clear();
    1202            4 :           _remoteCandidates.clear();
    1203              :           iceRestartedCount = 0;
    1204            2 :           setCallState(CallState.kConnected);
    1205              :           // fix any state/race issues we had with sdp packets and cloned streams
    1206            2 :           await updateMuteStatus();
    1207            2 :           _missedCall = false;
    1208              :         } else if ({
    1209            2 :           RTCIceConnectionState.RTCIceConnectionStateFailed,
    1210            2 :           RTCIceConnectionState.RTCIceConnectionStateDisconnected,
    1211            2 :         }.contains(state)) {
    1212            0 :           if (iceRestartedCount < 3) {
    1213            0 :             await restartIce();
    1214            0 :             iceRestartedCount++;
    1215              :           } else {
    1216            0 :             await hangup(reason: CallErrorCode.iceFailed);
    1217              :           }
    1218              :         }
    1219              :       };
    1220              :     } catch (e) {
    1221            0 :       Logs().v('[VOIP] prepareMediaStream error => ${e.toString()}');
    1222              :     }
    1223              :   }
    1224              : 
    1225            0 :   Future<void> onAnsweredElsewhere() async {
    1226            0 :     Logs().d('Call ID $callId answered elsewhere');
    1227            0 :     await terminate(CallParty.kRemote, CallErrorCode.answeredElsewhere, true);
    1228              :   }
    1229              : 
    1230            2 :   Future<void> cleanUp() async {
    1231              :     try {
    1232            4 :       for (final stream in _streams) {
    1233            2 :         await stream.dispose();
    1234              :       }
    1235            4 :       _streams.clear();
    1236              :     } catch (e, s) {
    1237            0 :       Logs().e('[VOIP] cleaning up streams failed', e, s);
    1238              :     }
    1239              : 
    1240              :     try {
    1241            2 :       if (pc != null) {
    1242            4 :         await pc!.close();
    1243            4 :         await pc!.dispose();
    1244              :       }
    1245              :     } catch (e, s) {
    1246            0 :       Logs().e('[VOIP] removing pc failed', e, s);
    1247              :     }
    1248              :   }
    1249              : 
    1250            2 :   Future<void> updateMuteStatus() async {
    1251            2 :     final micShouldBeMuted = (localUserMediaStream != null &&
    1252            0 :             localUserMediaStream!.isAudioMuted()) ||
    1253            2 :         _remoteOnHold;
    1254            2 :     final vidShouldBeMuted = (localUserMediaStream != null &&
    1255            0 :             localUserMediaStream!.isVideoMuted()) ||
    1256            2 :         _remoteOnHold;
    1257              : 
    1258            2 :     _setTracksEnabled(
    1259            4 :       localUserMediaStream?.stream?.getAudioTracks() ?? [],
    1260              :       !micShouldBeMuted,
    1261              :     );
    1262            2 :     _setTracksEnabled(
    1263            4 :       localUserMediaStream?.stream?.getVideoTracks() ?? [],
    1264              :       !vidShouldBeMuted,
    1265              :     );
    1266              : 
    1267            2 :     await sendSDPStreamMetadataChanged(
    1268            2 :       room,
    1269            2 :       callId,
    1270            2 :       localPartyId,
    1271            2 :       _getLocalSDPStreamMetadata(),
    1272              :     );
    1273              :   }
    1274              : 
    1275            2 :   void _setTracksEnabled(List<MediaStreamTrack> tracks, bool enabled) {
    1276            2 :     for (final track in tracks) {
    1277            0 :       track.enabled = enabled;
    1278              :     }
    1279              :   }
    1280              : 
    1281            2 :   SDPStreamMetadata _getLocalSDPStreamMetadata() {
    1282            2 :     final sdpStreamMetadatas = <String, SDPStreamPurpose>{};
    1283            4 :     for (final wpstream in getLocalStreams) {
    1284            2 :       if (wpstream.stream != null) {
    1285            8 :         sdpStreamMetadatas[wpstream.stream!.id] = SDPStreamPurpose(
    1286            2 :           purpose: wpstream.purpose,
    1287            2 :           audio_muted: wpstream.audioMuted,
    1288            2 :           video_muted: wpstream.videoMuted,
    1289              :         );
    1290              :       }
    1291              :     }
    1292            2 :     final metadata = SDPStreamMetadata(sdpStreamMetadatas);
    1293           10 :     Logs().v('Got local SDPStreamMetadata ${metadata.toJson().toString()}');
    1294              :     return metadata;
    1295              :   }
    1296              : 
    1297            0 :   Future<void> restartIce() async {
    1298            0 :     Logs().v('[VOIP] iceRestart.');
    1299              :     // Needs restart ice on session.pc and renegotiation.
    1300            0 :     _iceGatheringFinished = false;
    1301            0 :     _localCandidates.clear();
    1302            0 :     await pc!.restartIce();
    1303              :   }
    1304              : 
    1305            2 :   Future<MediaStream?> _getUserMedia(CallType type) async {
    1306            2 :     final mediaConstraints = {
    1307              :       'audio': UserMediaConstraints.micMediaConstraints,
    1308            2 :       'video': type == CallType.kVideo
    1309              :           ? UserMediaConstraints.camMediaConstraints
    1310              :           : false,
    1311              :     };
    1312              :     try {
    1313            8 :       return await voip.delegate.mediaDevices.getUserMedia(mediaConstraints);
    1314              :     } catch (e) {
    1315            0 :       await _getUserMediaFailed(e);
    1316              :       rethrow;
    1317              :     }
    1318              :   }
    1319              : 
    1320            0 :   Future<MediaStream?> _getDisplayMedia() async {
    1321              :     try {
    1322            0 :       return await voip.delegate.mediaDevices
    1323            0 :           .getDisplayMedia(UserMediaConstraints.screenMediaConstraints);
    1324              :     } catch (e) {
    1325            0 :       await _getUserMediaFailed(e);
    1326              :     }
    1327              :     return null;
    1328              :   }
    1329              : 
    1330            2 :   Future<RTCPeerConnection> _createPeerConnection() async {
    1331            2 :     final configuration = <String, dynamic>{
    1332            4 :       'iceServers': opts.iceServers,
    1333              :       'sdpSemantics': 'unified-plan',
    1334              :     };
    1335            6 :     final pc = await voip.delegate.createPeerConnection(configuration);
    1336            2 :     pc.onTrack = (RTCTrackEvent event) async {
    1337            0 :       for (final stream in event.streams) {
    1338            0 :         await _addRemoteStream(stream);
    1339            0 :         for (final track in stream.getTracks()) {
    1340            0 :           track.onEnded = () async {
    1341            0 :             if (stream.getTracks().isEmpty) {
    1342            0 :               Logs().d('[VOIP] detected a empty stream, removing it');
    1343            0 :               await _removeStream(stream);
    1344              :             }
    1345              :           };
    1346              :         }
    1347              :       }
    1348              :     };
    1349              :     return pc;
    1350              :   }
    1351              : 
    1352            0 :   Future<void> createDataChannel(
    1353              :     String label,
    1354              :     RTCDataChannelInit dataChannelDict,
    1355              :   ) async {
    1356            0 :     await pc?.createDataChannel(label, dataChannelDict);
    1357              :   }
    1358              : 
    1359            0 :   Future<void> tryRemoveStopedStreams() async {
    1360            0 :     final removedStreams = <String, WrappedMediaStream>{};
    1361            0 :     for (final stream in _streams) {
    1362            0 :       if (stream.stopped) {
    1363            0 :         removedStreams[stream.stream!.id] = stream;
    1364              :       }
    1365              :     }
    1366            0 :     _streams
    1367            0 :         .removeWhere((stream) => removedStreams.containsKey(stream.stream!.id));
    1368            0 :     for (final element in removedStreams.entries) {
    1369            0 :       await _removeStream(element.value.stream!);
    1370              :     }
    1371              :   }
    1372              : 
    1373            0 :   Future<void> _removeStream(MediaStream stream) async {
    1374            0 :     Logs().v('Removing feed with stream id ${stream.id}');
    1375              : 
    1376            0 :     final it = _streams.where((element) => element.stream!.id == stream.id);
    1377            0 :     if (it.isEmpty) {
    1378            0 :       Logs().v('Didn\'t find the feed with stream id ${stream.id} to delete');
    1379              :       return;
    1380              :     }
    1381            0 :     final wpstream = it.first;
    1382            0 :     _streams.removeWhere((element) => element.stream!.id == stream.id);
    1383            0 :     onStreamRemoved.add(wpstream);
    1384            0 :     fireCallEvent(CallStateChange.kFeedsChanged);
    1385            0 :     await wpstream.dispose();
    1386              :   }
    1387              : 
    1388            2 :   Future<void> _sendCandidateQueue() async {
    1389            2 :     if (callHasEnded) return;
    1390              :     /*
    1391              :     Currently, trickle-ice is not supported, so it will take a
    1392              :     long time to wait to collect all the canidates, set the
    1393              :     timeout for collection canidates to speed up the connection.
    1394              :     */
    1395            2 :     final candidatesQueue = _localCandidates;
    1396              :     try {
    1397            2 :       if (candidatesQueue.isNotEmpty) {
    1398            0 :         final candidates = <Map<String, dynamic>>[];
    1399            0 :         for (final element in candidatesQueue) {
    1400            0 :           candidates.add(element.toMap());
    1401              :         }
    1402            0 :         _localCandidates.clear();
    1403            0 :         final res = await sendCallCandidates(
    1404            0 :           opts.room,
    1405            0 :           callId,
    1406            0 :           localPartyId,
    1407              :           candidates,
    1408              :         );
    1409            0 :         Logs().v('[VOIP] sendCallCandidates res => $res');
    1410              :       }
    1411              :     } catch (e) {
    1412            0 :       Logs().v('[VOIP] sendCallCandidates e => ${e.toString()}');
    1413            0 :       _candidateSendTries++;
    1414            0 :       _localCandidates.clear();
    1415            0 :       _localCandidates.addAll(candidatesQueue);
    1416              : 
    1417            0 :       if (_candidateSendTries > 5) {
    1418            0 :         Logs().d(
    1419            0 :           'Failed to send candidates on attempt $_candidateSendTries Giving up on this call.',
    1420              :         );
    1421            0 :         await hangup(reason: CallErrorCode.iceTimeout);
    1422              :         return;
    1423              :       }
    1424              : 
    1425            0 :       final delay = 500 * pow(2, _candidateSendTries);
    1426            0 :       Timer(Duration(milliseconds: delay as int), () {
    1427            0 :         _sendCandidateQueue();
    1428              :       });
    1429              :     }
    1430              :   }
    1431              : 
    1432            2 :   void fireCallEvent(CallStateChange event) {
    1433            4 :     onCallEventChanged.add(event);
    1434            8 :     Logs().i('CallStateChange: ${event.toString()}');
    1435              :     switch (event) {
    1436            2 :       case CallStateChange.kFeedsChanged:
    1437            4 :         onCallStreamsChanged.add(this);
    1438              :         break;
    1439            2 :       case CallStateChange.kState:
    1440           10 :         Logs().i('CallState: ${state.toString()}');
    1441              :         break;
    1442            2 :       case CallStateChange.kError:
    1443              :         break;
    1444            2 :       case CallStateChange.kHangup:
    1445              :         break;
    1446            0 :       case CallStateChange.kReplaced:
    1447              :         break;
    1448            0 :       case CallStateChange.kLocalHoldUnhold:
    1449              :         break;
    1450            0 :       case CallStateChange.kRemoteHoldUnhold:
    1451              :         break;
    1452            0 :       case CallStateChange.kAssertedIdentityChanged:
    1453              :         break;
    1454              :     }
    1455              :   }
    1456              : 
    1457            0 :   Future<void> _getLocalOfferFailed(dynamic err) async {
    1458            0 :     Logs().e('Failed to get local offer ${err.toString()}');
    1459            0 :     fireCallEvent(CallStateChange.kError);
    1460              : 
    1461            0 :     await terminate(CallParty.kLocal, CallErrorCode.localOfferFailed, true);
    1462              :   }
    1463              : 
    1464            0 :   Future<void> _getUserMediaFailed(dynamic err) async {
    1465            0 :     Logs().w('Failed to get user media - ending call ${err.toString()}');
    1466            0 :     fireCallEvent(CallStateChange.kError);
    1467            0 :     await terminate(CallParty.kLocal, CallErrorCode.userMediaFailed, true);
    1468              :   }
    1469              : 
    1470            2 :   Future<void> onSelectAnswerReceived(String? selectedPartyId) async {
    1471            4 :     if (direction != CallDirection.kIncoming) {
    1472            0 :       Logs().w('Got select_answer for an outbound call: ignoring');
    1473              :       return;
    1474              :     }
    1475              :     if (selectedPartyId == null) {
    1476            0 :       Logs().w(
    1477              :         'Got nonsensical select_answer with null/undefined selected_party_id: ignoring',
    1478              :       );
    1479              :       return;
    1480              :     }
    1481              : 
    1482            4 :     if (selectedPartyId != localPartyId) {
    1483            4 :       Logs().w(
    1484            4 :         'Got select_answer for party ID $selectedPartyId: we are party ID $localPartyId.',
    1485              :       );
    1486              :       // The other party has picked somebody else's answer
    1487            2 :       await terminate(CallParty.kRemote, CallErrorCode.answeredElsewhere, true);
    1488              :     }
    1489              :   }
    1490              : 
    1491              :   /// This is sent by the caller when they wish to establish a call.
    1492              :   /// [callId] is a unique identifier for the call.
    1493              :   /// [version] is the version of the VoIP specification this message adheres to. This specification is version 1.
    1494              :   /// [lifetime] is the time in milliseconds that the invite is valid for. Once the invite age exceeds this value,
    1495              :   /// clients should discard it. They should also no longer show the call as awaiting an answer in the UI.
    1496              :   /// [type] The type of session description. Must be 'offer'.
    1497              :   /// [sdp] The SDP text of the session description.
    1498              :   /// [invitee] The user ID of the person who is being invited. Invites without an invitee field are defined to be
    1499              :   /// intended for any member of the room other than the sender of the event.
    1500              :   /// [party_id] The party ID for call, Can be set to client.deviceId.
    1501            2 :   Future<String?> sendInviteToCall(
    1502              :     Room room,
    1503              :     String callId,
    1504              :     int lifetime,
    1505              :     String party_id,
    1506              :     String sdp, {
    1507              :     String type = 'offer',
    1508              :     String version = voipProtoVersion,
    1509              :     String? txid,
    1510              :     CallCapabilities? capabilities,
    1511              :     SDPStreamMetadata? metadata,
    1512              :   }) async {
    1513            2 :     final content = {
    1514            2 :       'call_id': callId,
    1515            2 :       'party_id': party_id,
    1516            2 :       if (groupCallId != null) 'conf_id': groupCallId!,
    1517            2 :       'version': version,
    1518            2 :       'lifetime': lifetime,
    1519            4 :       'offer': {'sdp': sdp, 'type': type},
    1520            2 :       if (remoteUserId != null)
    1521            2 :         'invitee':
    1522            2 :             remoteUserId!, // TODO: rename this to invitee_user_id? breaks spec though
    1523            2 :       if (remoteDeviceId != null) 'invitee_device_id': remoteDeviceId!,
    1524            2 :       if (remoteDeviceId != null)
    1525            0 :         'device_id': client
    1526            0 :             .deviceID!, // Having a remoteDeviceId means you are doing to-device events, so you want to send your deviceId too
    1527            4 :       if (capabilities != null) 'capabilities': capabilities.toJson(),
    1528            4 :       if (metadata != null) sdpStreamMetadataKey: metadata.toJson(),
    1529              :     };
    1530            2 :     return await _sendContent(
    1531              :       room,
    1532            2 :       isGroupCall ? EventTypes.GroupCallMemberInvite : EventTypes.CallInvite,
    1533              :       content,
    1534              :       txid: txid,
    1535              :     );
    1536              :   }
    1537              : 
    1538              :   /// The calling party sends the party_id of the first selected answer.
    1539              :   ///
    1540              :   /// Usually after receiving the first answer sdp in the client.onCallAnswer event,
    1541              :   /// save the `party_id`, and then send `CallSelectAnswer` to others peers that the call has been picked up.
    1542              :   ///
    1543              :   /// [callId] is a unique identifier for the call.
    1544              :   /// [version] is the version of the VoIP specification this message adheres to. This specification is version 1.
    1545              :   /// [party_id] The party ID for call, Can be set to client.deviceId.
    1546              :   /// [selected_party_id] The party ID for the selected answer.
    1547            2 :   Future<String?> sendSelectCallAnswer(
    1548              :     Room room,
    1549              :     String callId,
    1550              :     String party_id,
    1551              :     String selected_party_id, {
    1552              :     String version = voipProtoVersion,
    1553              :     String? txid,
    1554              :   }) async {
    1555            2 :     final content = {
    1556            2 :       'call_id': callId,
    1557            2 :       'party_id': party_id,
    1558            2 :       if (groupCallId != null) 'conf_id': groupCallId!,
    1559            2 :       'version': version,
    1560            2 :       'selected_party_id': selected_party_id,
    1561              :     };
    1562              : 
    1563            2 :     return await _sendContent(
    1564              :       room,
    1565            2 :       isGroupCall
    1566              :           ? EventTypes.GroupCallMemberSelectAnswer
    1567              :           : EventTypes.CallSelectAnswer,
    1568              :       content,
    1569              :       txid: txid,
    1570              :     );
    1571              :   }
    1572              : 
    1573              :   /// Reject a call
    1574              :   /// [callId] is a unique identifier for the call.
    1575              :   /// [version] is the version of the VoIP specification this message adheres to. This specification is version 1.
    1576              :   /// [party_id] The party ID for call, Can be set to client.deviceId.
    1577            2 :   Future<String?> sendCallReject(
    1578              :     Room room,
    1579              :     String callId,
    1580              :     String party_id, {
    1581              :     String version = voipProtoVersion,
    1582              :     String? txid,
    1583              :   }) async {
    1584            2 :     final content = {
    1585            2 :       'call_id': callId,
    1586            2 :       'party_id': party_id,
    1587            2 :       if (groupCallId != null) 'conf_id': groupCallId!,
    1588            2 :       'version': version,
    1589              :     };
    1590              : 
    1591            2 :     return await _sendContent(
    1592              :       room,
    1593            2 :       isGroupCall ? EventTypes.GroupCallMemberReject : EventTypes.CallReject,
    1594              :       content,
    1595              :       txid: txid,
    1596              :     );
    1597              :   }
    1598              : 
    1599              :   /// When local audio/video tracks are added/deleted or hold/unhold,
    1600              :   /// need to createOffer and renegotiation.
    1601              :   /// [callId] is a unique identifier for the call.
    1602              :   /// [version] is the version of the VoIP specification this message adheres to. This specification is version 1.
    1603              :   /// [party_id] The party ID for call, Can be set to client.deviceId.
    1604            2 :   Future<String?> sendCallNegotiate(
    1605              :     Room room,
    1606              :     String callId,
    1607              :     int lifetime,
    1608              :     String party_id,
    1609              :     String sdp, {
    1610              :     String type = 'offer',
    1611              :     String version = voipProtoVersion,
    1612              :     String? txid,
    1613              :     CallCapabilities? capabilities,
    1614              :     SDPStreamMetadata? metadata,
    1615              :   }) async {
    1616            2 :     final content = {
    1617            2 :       'call_id': callId,
    1618            2 :       'party_id': party_id,
    1619            2 :       if (groupCallId != null) 'conf_id': groupCallId!,
    1620            2 :       'version': version,
    1621            2 :       'lifetime': lifetime,
    1622            4 :       'description': {'sdp': sdp, 'type': type},
    1623            0 :       if (capabilities != null) 'capabilities': capabilities.toJson(),
    1624            0 :       if (metadata != null) sdpStreamMetadataKey: metadata.toJson(),
    1625              :     };
    1626            2 :     return await _sendContent(
    1627              :       room,
    1628            2 :       isGroupCall
    1629              :           ? EventTypes.GroupCallMemberNegotiate
    1630              :           : EventTypes.CallNegotiate,
    1631              :       content,
    1632              :       txid: txid,
    1633              :     );
    1634              :   }
    1635              : 
    1636              :   /// This is sent by callers after sending an invite and by the callee after answering.
    1637              :   /// Its purpose is to give the other party additional ICE candidates to try using to communicate.
    1638              :   ///
    1639              :   /// [callId] The ID of the call this event relates to.
    1640              :   ///
    1641              :   /// [version] The version of the VoIP specification this messages adheres to. This specification is version 1.
    1642              :   ///
    1643              :   /// [party_id] The party ID for call, Can be set to client.deviceId.
    1644              :   ///
    1645              :   /// [candidates] Array of objects describing the candidates. Example:
    1646              :   ///
    1647              :   /// ```
    1648              :   /// [
    1649              :   ///       {
    1650              :   ///           "candidate": "candidate:863018703 1 udp 2122260223 10.9.64.156 43670 typ host generation 0",
    1651              :   ///           "sdpMLineIndex": 0,
    1652              :   ///           "sdpMid": "audio"
    1653              :   ///       }
    1654              :   ///   ],
    1655              :   /// ```
    1656            2 :   Future<String?> sendCallCandidates(
    1657              :     Room room,
    1658              :     String callId,
    1659              :     String party_id,
    1660              :     List<Map<String, dynamic>> candidates, {
    1661              :     String version = voipProtoVersion,
    1662              :     String? txid,
    1663              :   }) async {
    1664            2 :     final content = {
    1665            2 :       'call_id': callId,
    1666            2 :       'party_id': party_id,
    1667            2 :       if (groupCallId != null) 'conf_id': groupCallId!,
    1668            2 :       'version': version,
    1669            2 :       'candidates': candidates,
    1670              :     };
    1671            2 :     return await _sendContent(
    1672              :       room,
    1673            2 :       isGroupCall
    1674              :           ? EventTypes.GroupCallMemberCandidates
    1675              :           : EventTypes.CallCandidates,
    1676              :       content,
    1677              :       txid: txid,
    1678              :     );
    1679              :   }
    1680              : 
    1681              :   /// This event is sent by the callee when they wish to answer the call.
    1682              :   /// [callId] is a unique identifier for the call.
    1683              :   /// [version] is the version of the VoIP specification this message adheres to. This specification is version 1.
    1684              :   /// [type] The type of session description. Must be 'answer'.
    1685              :   /// [sdp] The SDP text of the session description.
    1686              :   /// [party_id] The party ID for call, Can be set to client.deviceId.
    1687            2 :   Future<String?> sendAnswerCall(
    1688              :     Room room,
    1689              :     String callId,
    1690              :     String sdp,
    1691              :     String party_id, {
    1692              :     String type = 'answer',
    1693              :     String version = voipProtoVersion,
    1694              :     String? txid,
    1695              :     CallCapabilities? capabilities,
    1696              :     SDPStreamMetadata? metadata,
    1697              :   }) async {
    1698            2 :     final content = {
    1699            2 :       'call_id': callId,
    1700            2 :       'party_id': party_id,
    1701            2 :       if (groupCallId != null) 'conf_id': groupCallId!,
    1702            2 :       'version': version,
    1703            4 :       'answer': {'sdp': sdp, 'type': type},
    1704            4 :       if (capabilities != null) 'capabilities': capabilities.toJson(),
    1705            4 :       if (metadata != null) sdpStreamMetadataKey: metadata.toJson(),
    1706              :     };
    1707            2 :     return await _sendContent(
    1708              :       room,
    1709            2 :       isGroupCall ? EventTypes.GroupCallMemberAnswer : EventTypes.CallAnswer,
    1710              :       content,
    1711              :       txid: txid,
    1712              :     );
    1713              :   }
    1714              : 
    1715              :   /// This event is sent by the callee when they wish to answer the call.
    1716              :   /// [callId] The ID of the call this event relates to.
    1717              :   /// [version] is the version of the VoIP specification this message adheres to. This specification is version 1.
    1718              :   /// [party_id] The party ID for call, Can be set to client.deviceId.
    1719            2 :   Future<String?> sendHangupCall(
    1720              :     Room room,
    1721              :     String callId,
    1722              :     String party_id,
    1723              :     String? hangupCause, {
    1724              :     String version = voipProtoVersion,
    1725              :     String? txid,
    1726              :   }) async {
    1727            2 :     final content = {
    1728            2 :       'call_id': callId,
    1729            2 :       'party_id': party_id,
    1730            2 :       if (groupCallId != null) 'conf_id': groupCallId!,
    1731            2 :       'version': version,
    1732            2 :       if (hangupCause != null) 'reason': hangupCause,
    1733              :     };
    1734            2 :     return await _sendContent(
    1735              :       room,
    1736            2 :       isGroupCall ? EventTypes.GroupCallMemberHangup : EventTypes.CallHangup,
    1737              :       content,
    1738              :       txid: txid,
    1739              :     );
    1740              :   }
    1741              : 
    1742              :   /// Send SdpStreamMetadata Changed event.
    1743              :   ///
    1744              :   /// This MSC also adds a new call event m.call.sdp_stream_metadata_changed,
    1745              :   /// which has the common VoIP fields as specified in
    1746              :   /// MSC2746 (version, call_id, party_id) and a sdp_stream_metadata object which
    1747              :   /// is the same thing as sdp_stream_metadata in m.call.negotiate, m.call.invite
    1748              :   /// and m.call.answer. The client sends this event the when sdp_stream_metadata
    1749              :   /// has changed but no negotiation is required
    1750              :   ///  (e.g. the user mutes their camera/microphone).
    1751              :   ///
    1752              :   /// [callId] The ID of the call this event relates to.
    1753              :   /// [version] is the version of the VoIP specification this message adheres to. This specification is version 1.
    1754              :   /// [party_id] The party ID for call, Can be set to client.deviceId.
    1755              :   /// [metadata] The sdp_stream_metadata object.
    1756            2 :   Future<String?> sendSDPStreamMetadataChanged(
    1757              :     Room room,
    1758              :     String callId,
    1759              :     String party_id,
    1760              :     SDPStreamMetadata metadata, {
    1761              :     String version = voipProtoVersion,
    1762              :     String? txid,
    1763              :   }) async {
    1764            2 :     final content = {
    1765            2 :       'call_id': callId,
    1766            2 :       'party_id': party_id,
    1767            2 :       if (groupCallId != null) 'conf_id': groupCallId!,
    1768            2 :       'version': version,
    1769            4 :       sdpStreamMetadataKey: metadata.toJson(),
    1770              :     };
    1771            2 :     return await _sendContent(
    1772              :       room,
    1773            2 :       isGroupCall
    1774              :           ? EventTypes.GroupCallMemberSDPStreamMetadataChanged
    1775              :           : EventTypes.CallSDPStreamMetadataChanged,
    1776              :       content,
    1777              :       txid: txid,
    1778              :     );
    1779              :   }
    1780              : 
    1781              :   /// CallReplacesEvent for Transfered calls
    1782              :   ///
    1783              :   /// [callId] The ID of the call this event relates to.
    1784              :   /// [version] is the version of the VoIP specification this message adheres to. This specification is version 1.
    1785              :   /// [party_id] The party ID for call, Can be set to client.deviceId.
    1786              :   /// [callReplaces] transfer info
    1787            2 :   Future<String?> sendCallReplaces(
    1788              :     Room room,
    1789              :     String callId,
    1790              :     String party_id,
    1791              :     CallReplaces callReplaces, {
    1792              :     String version = voipProtoVersion,
    1793              :     String? txid,
    1794              :   }) async {
    1795            2 :     final content = {
    1796            2 :       'call_id': callId,
    1797            2 :       'party_id': party_id,
    1798            2 :       if (groupCallId != null) 'conf_id': groupCallId!,
    1799            2 :       'version': version,
    1800            2 :       ...callReplaces.toJson(),
    1801              :     };
    1802            2 :     return await _sendContent(
    1803              :       room,
    1804            2 :       isGroupCall
    1805              :           ? EventTypes.GroupCallMemberReplaces
    1806              :           : EventTypes.CallReplaces,
    1807              :       content,
    1808              :       txid: txid,
    1809              :     );
    1810              :   }
    1811              : 
    1812              :   /// send AssertedIdentity event
    1813              :   ///
    1814              :   /// [callId] The ID of the call this event relates to.
    1815              :   /// [version] is the version of the VoIP specification this message adheres to. This specification is version 1.
    1816              :   /// [party_id] The party ID for call, Can be set to client.deviceId.
    1817              :   /// [assertedIdentity] the asserted identity
    1818            2 :   Future<String?> sendAssertedIdentity(
    1819              :     Room room,
    1820              :     String callId,
    1821              :     String party_id,
    1822              :     AssertedIdentity assertedIdentity, {
    1823              :     String version = voipProtoVersion,
    1824              :     String? txid,
    1825              :   }) async {
    1826            2 :     final content = {
    1827            2 :       'call_id': callId,
    1828            2 :       'party_id': party_id,
    1829            2 :       if (groupCallId != null) 'conf_id': groupCallId!,
    1830            2 :       'version': version,
    1831            4 :       'asserted_identity': assertedIdentity.toJson(),
    1832              :     };
    1833            2 :     return await _sendContent(
    1834              :       room,
    1835            2 :       isGroupCall
    1836              :           ? EventTypes.GroupCallMemberAssertedIdentity
    1837              :           : EventTypes.CallAssertedIdentity,
    1838              :       content,
    1839              :       txid: txid,
    1840              :     );
    1841              :   }
    1842              : 
    1843            2 :   Future<String?> _sendContent(
    1844              :     Room room,
    1845              :     String type,
    1846              :     Map<String, Object> content, {
    1847              :     String? txid,
    1848              :   }) async {
    1849            6 :     Logs().d('[VOIP] sending content type $type, with conf: $content');
    1850            0 :     txid ??= VoIP.customTxid ?? client.generateUniqueTransactionId();
    1851            2 :     final mustEncrypt = room.encrypted && client.encryptionEnabled;
    1852              : 
    1853              :     // opponentDeviceId is only set for a few events during group calls,
    1854              :     // therefore only group calls use to-device messages for call events
    1855            2 :     if (isGroupCall && remoteDeviceId != null) {
    1856            0 :       final toDeviceSeq = _toDeviceSeq++;
    1857            0 :       final Map<String, Object> data = {
    1858              :         ...content,
    1859            0 :         'seq': toDeviceSeq,
    1860            0 :         if (remoteSessionId != null) 'dest_session_id': remoteSessionId!,
    1861            0 :         'sender_session_id': voip.currentSessionId,
    1862            0 :         'room_id': room.id,
    1863              :       };
    1864              : 
    1865              :       if (mustEncrypt) {
    1866            0 :         await client.userDeviceKeysLoading;
    1867            0 :         if (client.userDeviceKeys[remoteUserId]?.deviceKeys[remoteDeviceId] !=
    1868              :             null) {
    1869            0 :           await client.sendToDeviceEncrypted(
    1870            0 :             [
    1871            0 :               client.userDeviceKeys[remoteUserId]!.deviceKeys[remoteDeviceId]!,
    1872              :             ],
    1873              :             type,
    1874              :             data,
    1875              :           );
    1876              :         } else {
    1877            0 :           Logs().w(
    1878            0 :             '[VOIP] _sendCallContent missing device keys for $remoteUserId',
    1879              :           );
    1880              :         }
    1881              :       } else {
    1882            0 :         await client.sendToDevice(
    1883              :           type,
    1884              :           txid,
    1885            0 :           {
    1886            0 :             remoteUserId!: {remoteDeviceId!: data},
    1887              :           },
    1888              :         );
    1889              :       }
    1890              :       return '';
    1891              :     } else {
    1892              :       final sendMessageContent = mustEncrypt
    1893            0 :           ? await client.encryption!
    1894            0 :               .encryptGroupMessagePayload(room.id, content, type: type)
    1895              :           : content;
    1896            4 :       return await client.sendMessage(
    1897            2 :         room.id,
    1898            2 :         sendMessageContent.containsKey('ciphertext')
    1899              :             ? EventTypes.Encrypted
    1900              :             : type,
    1901              :         txid,
    1902              :         sendMessageContent,
    1903              :       );
    1904              :     }
    1905              :   }
    1906              : }
        

Generated by: LCOV version 2.0-1