JingleRtpConnection.java

   1package eu.siacs.conversations.xmpp.jingle;
   2
   3import android.content.Intent;
   4import android.telecom.TelecomManager;
   5import android.telecom.VideoProfile;
   6import android.util.Log;
   7
   8import androidx.annotation.NonNull;
   9import androidx.annotation.Nullable;
  10
  11import com.google.common.base.Joiner;
  12import com.google.common.base.Optional;
  13import com.google.common.base.Preconditions;
  14import com.google.common.base.Stopwatch;
  15import com.google.common.base.Strings;
  16import com.google.common.base.Throwables;
  17import com.google.common.collect.Collections2;
  18import com.google.common.collect.ImmutableMultimap;
  19import com.google.common.collect.ImmutableSet;
  20import com.google.common.collect.Iterables;
  21import com.google.common.collect.Maps;
  22import com.google.common.collect.Sets;
  23import com.google.common.util.concurrent.FutureCallback;
  24import com.google.common.util.concurrent.Futures;
  25import com.google.common.util.concurrent.ListenableFuture;
  26import com.google.common.util.concurrent.MoreExecutors;
  27
  28import eu.siacs.conversations.BuildConfig;
  29import eu.siacs.conversations.Config;
  30import eu.siacs.conversations.crypto.axolotl.AxolotlService;
  31import eu.siacs.conversations.crypto.axolotl.CryptoFailedException;
  32import eu.siacs.conversations.crypto.axolotl.FingerprintStatus;
  33import eu.siacs.conversations.entities.Account;
  34import eu.siacs.conversations.entities.Conversation;
  35import eu.siacs.conversations.entities.Conversational;
  36import eu.siacs.conversations.entities.Message;
  37import eu.siacs.conversations.entities.RtpSessionStatus;
  38import eu.siacs.conversations.services.CallIntegration;
  39import eu.siacs.conversations.ui.RtpSessionActivity;
  40import eu.siacs.conversations.xml.Element;
  41import eu.siacs.conversations.xml.Namespace;
  42import eu.siacs.conversations.xmpp.Jid;
  43import eu.siacs.conversations.xmpp.jingle.stanzas.Content;
  44import eu.siacs.conversations.xmpp.jingle.stanzas.Group;
  45import eu.siacs.conversations.xmpp.jingle.stanzas.IceUdpTransportInfo;
  46import eu.siacs.conversations.xmpp.jingle.stanzas.Proceed;
  47import eu.siacs.conversations.xmpp.jingle.stanzas.Propose;
  48import eu.siacs.conversations.xmpp.jingle.stanzas.Reason;
  49import eu.siacs.conversations.xmpp.jingle.stanzas.RtpDescription;
  50
  51import im.conversations.android.xmpp.model.jingle.Jingle;
  52import im.conversations.android.xmpp.model.stanza.Iq;
  53
  54import org.webrtc.EglBase;
  55import org.webrtc.IceCandidate;
  56import org.webrtc.PeerConnection;
  57import org.webrtc.VideoTrack;
  58
  59import java.util.Arrays;
  60import java.util.Collection;
  61import java.util.Collections;
  62import java.util.LinkedList;
  63import java.util.List;
  64import java.util.Map;
  65import java.util.Queue;
  66import java.util.Set;
  67import java.util.concurrent.ExecutionException;
  68import java.util.concurrent.ScheduledFuture;
  69import java.util.concurrent.TimeUnit;
  70
  71public class JingleRtpConnection extends AbstractJingleConnection
  72        implements WebRTCWrapper.EventCallback, CallIntegration.Callback, OngoingRtpSession {
  73
  74    // TODO consider adding State.SESSION_INITIALIZED to ongoing call states for direct init mode
  75    public static final List<State> STATES_SHOWING_ONGOING_CALL =
  76            Arrays.asList(
  77                    State.PROPOSED,
  78                    State.PROCEED,
  79                    State.SESSION_INITIALIZED_PRE_APPROVED,
  80                    State.SESSION_ACCEPTED);
  81    private static final long BUSY_TIME_OUT = 30;
  82
  83    private final WebRTCWrapper webRTCWrapper = new WebRTCWrapper(this);
  84    private final Queue<
  85                    Map.Entry<String, DescriptionTransport<RtpDescription, IceUdpTransportInfo>>>
  86            pendingIceCandidates = new LinkedList<>();
  87    private final OmemoVerification omemoVerification = new OmemoVerification();
  88    private final CallIntegration callIntegration;
  89    private final Message message;
  90
  91    private Set<Media> proposedMedia;
  92    private RtpContentMap initiatorRtpContentMap;
  93    private RtpContentMap responderRtpContentMap;
  94    private RtpContentMap incomingContentAdd;
  95    private RtpContentMap outgoingContentAdd;
  96    private IceUdpTransportInfo.Setup peerDtlsSetup;
  97    private final Stopwatch sessionDuration = Stopwatch.createUnstarted();
  98    private final Queue<PeerConnection.PeerConnectionState> stateHistory = new LinkedList<>();
  99    private ScheduledFuture<?> ringingTimeoutFuture;
 100
 101    JingleRtpConnection(
 102            final JingleConnectionManager jingleConnectionManager,
 103            final Id id,
 104            final Jid initiator) {
 105        this(
 106                jingleConnectionManager,
 107                id,
 108                initiator,
 109                new CallIntegration(
 110                        jingleConnectionManager
 111                                .getXmppConnectionService()
 112                                .getApplicationContext()));
 113        this.callIntegration.setAddress(
 114                CallIntegration.address(id.with.asBareJid()), TelecomManager.PRESENTATION_ALLOWED);
 115        final var contact = id.getContact();
 116        this.callIntegration.setCallerDisplayName(
 117                contact.getDisplayName(), TelecomManager.PRESENTATION_ALLOWED);
 118        this.callIntegration.setInitialized();
 119    }
 120
 121    JingleRtpConnection(
 122            final JingleConnectionManager jingleConnectionManager,
 123            final Id id,
 124            final Jid initiator,
 125            final CallIntegration callIntegration) {
 126        super(jingleConnectionManager, id, initiator);
 127        final Conversation conversation =
 128                jingleConnectionManager
 129                        .getXmppConnectionService()
 130                        .findOrCreateConversation(id.account, id.with.asBareJid(), false, false);
 131        this.message =
 132                new Message(
 133                        conversation,
 134                        isInitiator() ? Message.STATUS_SEND : Message.STATUS_RECEIVED,
 135                        Message.TYPE_RTP_SESSION,
 136                        id.sessionId);
 137        this.callIntegration = callIntegration;
 138        this.callIntegration.setCallback(this);
 139    }
 140
 141    @Override
 142    synchronized void deliverPacket(final Iq iq) {
 143        final var jingle = iq.getExtension(Jingle.class);
 144        switch (jingle.getAction()) {
 145            case SESSION_INITIATE -> receiveSessionInitiate(iq, jingle);
 146            case TRANSPORT_INFO -> receiveTransportInfo(iq, jingle);
 147            case SESSION_ACCEPT -> receiveSessionAccept(iq, jingle);
 148            case SESSION_TERMINATE -> receiveSessionTerminate(iq);
 149            case CONTENT_ADD -> receiveContentAdd(iq, jingle);
 150            case CONTENT_ACCEPT -> receiveContentAccept(iq);
 151            case CONTENT_REJECT -> receiveContentReject(iq, jingle);
 152            case CONTENT_REMOVE -> receiveContentRemove(iq, jingle);
 153            case CONTENT_MODIFY -> receiveContentModify(iq, jingle);
 154            default -> {
 155                respondOk(iq);
 156                Log.d(
 157                        Config.LOGTAG,
 158                        String.format(
 159                                "%s: received unhandled jingle action %s",
 160                                id.account.getJid().asBareJid(), jingle.getAction()));
 161            }
 162        }
 163    }
 164
 165    @Override
 166    synchronized void notifyRebound() {
 167        if (isTerminated()) {
 168            return;
 169        }
 170        webRTCWrapper.close();
 171        if (isResponder() && isInState(State.PROPOSED, State.SESSION_INITIALIZED)) {
 172            xmppConnectionService.getNotificationService().cancelIncomingCallNotification();
 173        }
 174        if (isInState(
 175                State.SESSION_INITIALIZED,
 176                State.SESSION_INITIALIZED_PRE_APPROVED,
 177                State.SESSION_ACCEPTED)) {
 178            // we might have already changed resources (full jid) at this point; so this might not
 179            // even reach the other party
 180            sendSessionTerminate(Reason.CONNECTIVITY_ERROR);
 181        } else {
 182            transitionOrThrow(State.TERMINATED_CONNECTIVITY_ERROR);
 183            finish();
 184        }
 185    }
 186
 187    private void receiveSessionTerminate(final Iq jinglePacket) {
 188        respondOk(jinglePacket);
 189        final var jingle = jinglePacket.getExtension(Jingle.class);
 190        final Jingle.ReasonWrapper wrapper = jingle.getReason();
 191        final State previous = this.state;
 192        Log.d(
 193                Config.LOGTAG,
 194                id.account.getJid().asBareJid()
 195                        + ": received session terminate reason="
 196                        + wrapper.reason
 197                        + "("
 198                        + Strings.nullToEmpty(wrapper.text)
 199                        + ") while in state "
 200                        + previous);
 201        if (TERMINATED.contains(previous)) {
 202            Log.d(
 203                    Config.LOGTAG,
 204                    id.account.getJid().asBareJid()
 205                            + ": ignoring session terminate because already in "
 206                            + previous);
 207            return;
 208        }
 209        webRTCWrapper.close();
 210        final State target = reasonToState(wrapper.reason);
 211        transitionOrThrow(target);
 212        writeLogMessage(target);
 213        if (previous == State.PROPOSED || previous == State.SESSION_INITIALIZED) {
 214            xmppConnectionService.getNotificationService().cancelIncomingCallNotification();
 215        }
 216        finish();
 217    }
 218
 219    private void receiveTransportInfo(final Iq jinglePacket, final Jingle jingle) {
 220        // Due to the asynchronicity of processing session-init we might move from NULL|PROCEED to
 221        // INITIALIZED only after transport-info has been received
 222        if (isInState(
 223                State.NULL,
 224                State.PROCEED,
 225                State.SESSION_INITIALIZED,
 226                State.SESSION_INITIALIZED_PRE_APPROVED,
 227                State.SESSION_ACCEPTED)) {
 228            final RtpContentMap contentMap;
 229            try {
 230                contentMap = RtpContentMap.of(jingle);
 231            } catch (final IllegalArgumentException | NullPointerException e) {
 232                Log.d(
 233                        Config.LOGTAG,
 234                        id.account.getJid().asBareJid()
 235                                + ": improperly formatted contents; ignoring",
 236                        e);
 237                respondOk(jinglePacket);
 238                return;
 239            }
 240            receiveTransportInfo(jinglePacket, contentMap);
 241        } else {
 242            if (isTerminated()) {
 243                respondOk(jinglePacket);
 244                Log.d(
 245                        Config.LOGTAG,
 246                        id.account.getJid().asBareJid()
 247                                + ": ignoring out-of-order transport info; we where already terminated");
 248            } else {
 249                Log.d(
 250                        Config.LOGTAG,
 251                        id.account.getJid().asBareJid()
 252                                + ": received transport info while in state="
 253                                + this.state);
 254                terminateWithOutOfOrder(jinglePacket);
 255            }
 256        }
 257    }
 258
 259    private void receiveTransportInfo(final Iq jinglePacket, final RtpContentMap contentMap) {
 260        final Set<Map.Entry<String, DescriptionTransport<RtpDescription, IceUdpTransportInfo>>>
 261                candidates = contentMap.contents.entrySet();
 262        final RtpContentMap remote = getRemoteContentMap();
 263        final Set<String> remoteContentIds =
 264                remote == null ? Collections.emptySet() : remote.contents.keySet();
 265        if (Collections.disjoint(remoteContentIds, contentMap.contents.keySet())) {
 266            Log.d(
 267                    Config.LOGTAG,
 268                    "received transport-info for unknown contents "
 269                            + contentMap.contents.keySet()
 270                            + " (known: "
 271                            + remoteContentIds
 272                            + ")");
 273            respondOk(jinglePacket);
 274            pendingIceCandidates.addAll(candidates);
 275            return;
 276        }
 277        if (this.state != State.SESSION_ACCEPTED) {
 278            Log.d(Config.LOGTAG, "received transport-info prematurely. adding to backlog");
 279            respondOk(jinglePacket);
 280            pendingIceCandidates.addAll(candidates);
 281            return;
 282        }
 283        // zero candidates + modified credentials are an ICE restart offer
 284        if (checkForIceRestart(jinglePacket, contentMap)) {
 285            return;
 286        }
 287        respondOk(jinglePacket);
 288        try {
 289            processCandidates(candidates);
 290        } catch (final WebRTCWrapper.PeerConnectionNotInitialized e) {
 291            Log.w(
 292                    Config.LOGTAG,
 293                    id.account.getJid().asBareJid()
 294                            + ": PeerConnection was not initialized when processing transport info. this usually indicates a race condition that can be ignored");
 295        }
 296    }
 297
 298    private void receiveContentAdd(final Iq iq, final Jingle jingle) {
 299        final RtpContentMap modification;
 300        try {
 301            modification = RtpContentMap.of(jingle);
 302            modification.requireContentDescriptions();
 303        } catch (final RuntimeException e) {
 304            Log.d(
 305                    Config.LOGTAG,
 306                    id.getAccount().getJid().asBareJid() + ": improperly formatted contents",
 307                    Throwables.getRootCause(e));
 308            respondOk(iq);
 309            webRTCWrapper.close();
 310            sendSessionTerminate(Reason.of(e), e.getMessage());
 311            return;
 312        }
 313        if (isInState(State.SESSION_ACCEPTED)) {
 314            final boolean hasFullTransportInfo = modification.hasFullTransportInfo();
 315            final ListenableFuture<RtpContentMap> future =
 316                    receiveRtpContentMap(
 317                            modification,
 318                            this.omemoVerification.hasFingerprint() && hasFullTransportInfo);
 319            Futures.addCallback(
 320                    future,
 321                    new FutureCallback<>() {
 322                        @Override
 323                        public void onSuccess(final RtpContentMap rtpContentMap) {
 324                            receiveContentAdd(iq, rtpContentMap);
 325                        }
 326
 327                        @Override
 328                        public void onFailure(@NonNull Throwable throwable) {
 329                            respondOk(iq);
 330                            final Throwable rootCause = Throwables.getRootCause(throwable);
 331                            Log.d(
 332                                    Config.LOGTAG,
 333                                    id.account.getJid().asBareJid()
 334                                            + ": improperly formatted contents in content-add",
 335                                    throwable);
 336                            webRTCWrapper.close();
 337                            sendSessionTerminate(
 338                                    Reason.ofThrowable(rootCause), rootCause.getMessage());
 339                        }
 340                    },
 341                    MoreExecutors.directExecutor());
 342        } else {
 343            terminateWithOutOfOrder(iq);
 344        }
 345    }
 346
 347    private void receiveContentAdd(final Iq jinglePacket, final RtpContentMap modification) {
 348        final RtpContentMap remote = getRemoteContentMap();
 349        if (!Collections.disjoint(modification.getNames(), remote.getNames())) {
 350            respondOk(jinglePacket);
 351            this.webRTCWrapper.close();
 352            sendSessionTerminate(
 353                    Reason.FAILED_APPLICATION,
 354                    String.format(
 355                            "contents with names %s already exists",
 356                            Joiner.on(", ").join(modification.getNames())));
 357            return;
 358        }
 359        final ContentAddition contentAddition =
 360                ContentAddition.of(ContentAddition.Direction.INCOMING, modification);
 361
 362        final RtpContentMap outgoing = this.outgoingContentAdd;
 363        final Set<ContentAddition.Summary> outgoingContentAddSummary =
 364                outgoing == null ? Collections.emptySet() : ContentAddition.summary(outgoing);
 365
 366        if (outgoingContentAddSummary.equals(contentAddition.summary)) {
 367            if (isInitiator()) {
 368                Log.d(
 369                        Config.LOGTAG,
 370                        id.getAccount().getJid().asBareJid()
 371                                + ": respond with tie break to matching content-add offer");
 372                respondWithTieBreak(jinglePacket);
 373            } else {
 374                Log.d(
 375                        Config.LOGTAG,
 376                        id.getAccount().getJid().asBareJid()
 377                                + ": automatically accept matching content-add offer");
 378                acceptContentAdd(contentAddition.summary, modification);
 379            }
 380            return;
 381        }
 382
 383        // once we can display multiple video tracks we can be more loose with this condition
 384        // theoretically it should also be fine to automatically accept audio only contents
 385        if (Media.audioOnly(remote.getMedia()) && Media.videoOnly(contentAddition.media())) {
 386            Log.d(
 387                    Config.LOGTAG,
 388                    id.getAccount().getJid().asBareJid() + ": received " + contentAddition);
 389            this.incomingContentAdd = modification;
 390            respondOk(jinglePacket);
 391            updateEndUserState();
 392        } else {
 393            respondOk(jinglePacket);
 394            // TODO do we want to add a reason?
 395            rejectContentAdd(modification);
 396        }
 397    }
 398
 399    private void receiveContentAccept(final Iq jinglePacket) {
 400        final var jingle = jinglePacket.getExtension(Jingle.class);
 401        final RtpContentMap receivedContentAccept;
 402        try {
 403            receivedContentAccept = RtpContentMap.of(jingle);
 404            receivedContentAccept.requireContentDescriptions();
 405        } catch (final RuntimeException e) {
 406            Log.d(
 407                    Config.LOGTAG,
 408                    id.getAccount().getJid().asBareJid() + ": improperly formatted contents",
 409                    Throwables.getRootCause(e));
 410            respondOk(jinglePacket);
 411            webRTCWrapper.close();
 412            sendSessionTerminate(Reason.of(e), e.getMessage());
 413            return;
 414        }
 415
 416        final RtpContentMap outgoingContentAdd = this.outgoingContentAdd;
 417        if (outgoingContentAdd == null) {
 418            Log.d(Config.LOGTAG, "received content-accept when we had no outgoing content add");
 419            terminateWithOutOfOrder(jinglePacket);
 420            return;
 421        }
 422        final Set<ContentAddition.Summary> ourSummary = ContentAddition.summary(outgoingContentAdd);
 423        if (ourSummary.equals(ContentAddition.summary(receivedContentAccept))) {
 424            this.outgoingContentAdd = null;
 425            respondOk(jinglePacket);
 426            final boolean hasFullTransportInfo = receivedContentAccept.hasFullTransportInfo();
 427            final ListenableFuture<RtpContentMap> future =
 428                    receiveRtpContentMap(
 429                            receivedContentAccept,
 430                            this.omemoVerification.hasFingerprint() && hasFullTransportInfo);
 431            Futures.addCallback(
 432                    future,
 433                    new FutureCallback<>() {
 434                        @Override
 435                        public void onSuccess(final RtpContentMap result) {
 436                            receiveContentAccept(result);
 437                        }
 438
 439                        @Override
 440                        public void onFailure(@NonNull final Throwable throwable) {
 441                            webRTCWrapper.close();
 442                            sendSessionTerminate(
 443                                    Reason.ofThrowable(throwable), throwable.getMessage());
 444                        }
 445                    },
 446                    MoreExecutors.directExecutor());
 447        } else {
 448            Log.d(Config.LOGTAG, "received content-accept did not match our outgoing content-add");
 449            terminateWithOutOfOrder(jinglePacket);
 450        }
 451    }
 452
 453    private void receiveContentAccept(final RtpContentMap receivedContentAccept) {
 454        final IceUdpTransportInfo.Setup peerDtlsSetup = getPeerDtlsSetup();
 455        final RtpContentMap modifiedContentMap =
 456                getRemoteContentMap().addContent(receivedContentAccept, peerDtlsSetup);
 457
 458        setRemoteContentMap(modifiedContentMap);
 459
 460        final SessionDescription answer = SessionDescription.of(modifiedContentMap, isResponder());
 461
 462        final org.webrtc.SessionDescription sdp =
 463                new org.webrtc.SessionDescription(
 464                        org.webrtc.SessionDescription.Type.ANSWER, answer.toString());
 465
 466        try {
 467            this.webRTCWrapper.setRemoteDescription(sdp).get();
 468        } catch (final Exception e) {
 469            final Throwable cause = Throwables.getRootCause(e);
 470            Log.d(
 471                    Config.LOGTAG,
 472                    id.getAccount().getJid().asBareJid()
 473                            + ": unable to set remote description after receiving content-accept",
 474                    cause);
 475            webRTCWrapper.close();
 476            sendSessionTerminate(Reason.FAILED_APPLICATION, cause.getMessage());
 477            return;
 478        }
 479        Log.d(
 480                Config.LOGTAG,
 481                id.getAccount().getJid().asBareJid()
 482                        + ": remote has accepted content-add "
 483                        + ContentAddition.summary(receivedContentAccept));
 484        processCandidates(receivedContentAccept.contents.entrySet());
 485        updateEndUserState();
 486    }
 487
 488    private void receiveContentModify(final Iq jinglePacket, final Jingle jingle) {
 489        if (this.state != State.SESSION_ACCEPTED) {
 490            terminateWithOutOfOrder(jinglePacket);
 491            return;
 492        }
 493        final Map<String, Content.Senders> modification =
 494                Maps.transformEntries(
 495                        jingle.getJingleContents(), (key, value) -> value.getSenders());
 496        final boolean isInitiator = isInitiator();
 497        final RtpContentMap currentOutgoing = this.outgoingContentAdd;
 498        final RtpContentMap remoteContentMap = this.getRemoteContentMap();
 499        final Set<String> currentOutgoingMediaIds =
 500                currentOutgoing == null
 501                        ? Collections.emptySet()
 502                        : currentOutgoing.contents.keySet();
 503        Log.d(Config.LOGTAG, "receiveContentModification(" + modification + ")");
 504        if (currentOutgoing != null && currentOutgoingMediaIds.containsAll(modification.keySet())) {
 505            respondOk(jinglePacket);
 506            final RtpContentMap modifiedContentMap;
 507            try {
 508                modifiedContentMap =
 509                        currentOutgoing.modifiedSendersChecked(isInitiator, modification);
 510            } catch (final IllegalArgumentException e) {
 511                webRTCWrapper.close();
 512                sendSessionTerminate(Reason.FAILED_APPLICATION, e.getMessage());
 513                return;
 514            }
 515            this.outgoingContentAdd = modifiedContentMap;
 516            Log.d(
 517                    Config.LOGTAG,
 518                    id.account.getJid().asBareJid()
 519                            + ": processed content-modification for pending content-add");
 520        } else if (remoteContentMap != null
 521                && remoteContentMap.contents.keySet().containsAll(modification.keySet())) {
 522            respondOk(jinglePacket);
 523            final RtpContentMap modifiedRemoteContentMap;
 524            try {
 525                modifiedRemoteContentMap =
 526                        remoteContentMap.modifiedSendersChecked(isInitiator, modification);
 527            } catch (final IllegalArgumentException e) {
 528                webRTCWrapper.close();
 529                sendSessionTerminate(Reason.FAILED_APPLICATION, e.getMessage());
 530                return;
 531            }
 532            final SessionDescription offer;
 533            try {
 534                offer = SessionDescription.of(modifiedRemoteContentMap, isResponder());
 535            } catch (final IllegalArgumentException | NullPointerException e) {
 536                Log.d(
 537                        Config.LOGTAG,
 538                        id.getAccount().getJid().asBareJid()
 539                                + ": unable convert offer from content-modify to SDP",
 540                        e);
 541                webRTCWrapper.close();
 542                sendSessionTerminate(Reason.FAILED_APPLICATION, e.getMessage());
 543                return;
 544            }
 545            Log.d(
 546                    Config.LOGTAG,
 547                    id.account.getJid().asBareJid() + ": auto accepting content-modification");
 548            this.autoAcceptContentModify(modifiedRemoteContentMap, offer);
 549        } else {
 550            Log.d(Config.LOGTAG, "received unsupported content modification " + modification);
 551            respondWithItemNotFound(jinglePacket);
 552        }
 553    }
 554
 555    private void autoAcceptContentModify(
 556            final RtpContentMap modifiedRemoteContentMap, final SessionDescription offer) {
 557        this.setRemoteContentMap(modifiedRemoteContentMap);
 558        final org.webrtc.SessionDescription sdp =
 559                new org.webrtc.SessionDescription(
 560                        org.webrtc.SessionDescription.Type.OFFER, offer.toString());
 561        try {
 562            this.webRTCWrapper.setRemoteDescription(sdp).get();
 563            // auto accept is only done when we already have tracks
 564            final SessionDescription answer = setLocalSessionDescription();
 565            final RtpContentMap rtpContentMap = RtpContentMap.of(answer, isInitiator());
 566            modifyLocalContentMap(rtpContentMap);
 567            // we do not need to send an answer but do we have to resend the candidates currently in
 568            // SDP?
 569            // resendCandidatesFromSdp(answer);
 570            webRTCWrapper.setIsReadyToReceiveIceCandidates(true);
 571        } catch (final Exception e) {
 572            Log.d(Config.LOGTAG, "unable to accept content add", Throwables.getRootCause(e));
 573            webRTCWrapper.close();
 574            sendSessionTerminate(Reason.FAILED_APPLICATION);
 575        }
 576    }
 577
 578    private static ImmutableMultimap<String, IceUdpTransportInfo.Candidate> parseCandidates(
 579            final SessionDescription answer) {
 580        final ImmutableMultimap.Builder<String, IceUdpTransportInfo.Candidate> candidateBuilder =
 581                new ImmutableMultimap.Builder<>();
 582        for (final SessionDescription.Media media : answer.media) {
 583            final String mid = Iterables.getFirst(media.attributes.get("mid"), null);
 584            if (Strings.isNullOrEmpty(mid)) {
 585                continue;
 586            }
 587            for (final String sdpCandidate : media.attributes.get("candidate")) {
 588                final IceUdpTransportInfo.Candidate candidate =
 589                        IceUdpTransportInfo.Candidate.fromSdpAttributeValue(sdpCandidate, null);
 590                if (candidate != null) {
 591                    candidateBuilder.put(mid, candidate);
 592                }
 593            }
 594        }
 595        return candidateBuilder.build();
 596    }
 597
 598    private void receiveContentReject(final Iq jinglePacket, final Jingle jingle) {
 599        final RtpContentMap receivedContentReject;
 600        try {
 601            receivedContentReject = RtpContentMap.of(jingle);
 602        } catch (final RuntimeException e) {
 603            Log.d(
 604                    Config.LOGTAG,
 605                    id.getAccount().getJid().asBareJid() + ": improperly formatted contents",
 606                    Throwables.getRootCause(e));
 607            respondOk(jinglePacket);
 608            this.webRTCWrapper.close();
 609            sendSessionTerminate(Reason.of(e), e.getMessage());
 610            return;
 611        }
 612
 613        final RtpContentMap outgoingContentAdd = this.outgoingContentAdd;
 614        if (outgoingContentAdd == null) {
 615            Log.d(Config.LOGTAG, "received content-reject when we had no outgoing content add");
 616            terminateWithOutOfOrder(jinglePacket);
 617            return;
 618        }
 619        final Set<ContentAddition.Summary> ourSummary = ContentAddition.summary(outgoingContentAdd);
 620        if (ourSummary.equals(ContentAddition.summary(receivedContentReject))) {
 621            this.outgoingContentAdd = null;
 622            respondOk(jinglePacket);
 623            Log.d(Config.LOGTAG, jinglePacket.toString());
 624            receiveContentReject(ourSummary);
 625        } else {
 626            Log.d(Config.LOGTAG, "received content-reject did not match our outgoing content-add");
 627            terminateWithOutOfOrder(jinglePacket);
 628        }
 629    }
 630
 631    private void receiveContentReject(final Set<ContentAddition.Summary> summary) {
 632        try {
 633            this.webRTCWrapper.removeTrack(Media.VIDEO);
 634            final RtpContentMap localContentMap = customRollback();
 635            modifyLocalContentMap(localContentMap);
 636        } catch (final Exception e) {
 637            final Throwable cause = Throwables.getRootCause(e);
 638            Log.d(
 639                    Config.LOGTAG,
 640                    id.getAccount().getJid().asBareJid()
 641                            + ": unable to rollback local description after receiving content-reject",
 642                    cause);
 643            webRTCWrapper.close();
 644            sendSessionTerminate(Reason.FAILED_APPLICATION, cause.getMessage());
 645            return;
 646        }
 647        Log.d(
 648                Config.LOGTAG,
 649                id.getAccount().getJid().asBareJid()
 650                        + ": remote has rejected our content-add "
 651                        + summary);
 652    }
 653
 654    private void receiveContentRemove(final Iq jinglePacket, final Jingle jingle) {
 655        final RtpContentMap receivedContentRemove;
 656        try {
 657            receivedContentRemove = RtpContentMap.of(jingle);
 658            receivedContentRemove.requireContentDescriptions();
 659        } catch (final RuntimeException e) {
 660            Log.d(
 661                    Config.LOGTAG,
 662                    id.getAccount().getJid().asBareJid() + ": improperly formatted contents",
 663                    Throwables.getRootCause(e));
 664            respondOk(jinglePacket);
 665            this.webRTCWrapper.close();
 666            sendSessionTerminate(Reason.of(e), e.getMessage());
 667            return;
 668        }
 669        respondOk(jinglePacket);
 670        receiveContentRemove(receivedContentRemove);
 671    }
 672
 673    private void receiveContentRemove(final RtpContentMap receivedContentRemove) {
 674        final RtpContentMap incomingContentAdd = this.incomingContentAdd;
 675        final Set<ContentAddition.Summary> contentAddSummary =
 676                incomingContentAdd == null
 677                        ? Collections.emptySet()
 678                        : ContentAddition.summary(incomingContentAdd);
 679        final Set<ContentAddition.Summary> removeSummary =
 680                ContentAddition.summary(receivedContentRemove);
 681        if (contentAddSummary.equals(removeSummary)) {
 682            this.incomingContentAdd = null;
 683            updateEndUserState();
 684        } else {
 685            webRTCWrapper.close();
 686            sendSessionTerminate(
 687                    Reason.FAILED_APPLICATION,
 688                    String.format(
 689                            "%s only supports %s as a means to retract a not yet accepted %s",
 690                            BuildConfig.APP_NAME,
 691                            Jingle.Action.CONTENT_REMOVE,
 692                            Jingle.Action.CONTENT_ADD));
 693        }
 694    }
 695
 696    public synchronized void retractContentAdd() {
 697        final RtpContentMap outgoingContentAdd = this.outgoingContentAdd;
 698        if (outgoingContentAdd == null) {
 699            throw new IllegalStateException("Not outgoing content add");
 700        }
 701        try {
 702            webRTCWrapper.removeTrack(Media.VIDEO);
 703            final RtpContentMap localContentMap = customRollback();
 704            modifyLocalContentMap(localContentMap);
 705        } catch (final Exception e) {
 706            final Throwable cause = Throwables.getRootCause(e);
 707            Log.d(
 708                    Config.LOGTAG,
 709                    id.getAccount().getJid().asBareJid()
 710                            + ": unable to rollback local description after trying to retract content-add",
 711                    cause);
 712            webRTCWrapper.close();
 713            sendSessionTerminate(Reason.FAILED_APPLICATION, cause.getMessage());
 714            return;
 715        }
 716        this.outgoingContentAdd = null;
 717        final Iq retract =
 718                outgoingContentAdd
 719                        .toStub()
 720                        .toJinglePacket(Jingle.Action.CONTENT_REMOVE, id.sessionId);
 721        this.send(retract);
 722        Log.d(
 723                Config.LOGTAG,
 724                id.getAccount().getJid()
 725                        + ": retract content-add "
 726                        + ContentAddition.summary(outgoingContentAdd));
 727    }
 728
 729    private RtpContentMap customRollback() throws ExecutionException, InterruptedException {
 730        final SessionDescription sdp = setLocalSessionDescription();
 731        final RtpContentMap localRtpContentMap = RtpContentMap.of(sdp, isInitiator());
 732        final SessionDescription answer = generateFakeResponse(localRtpContentMap);
 733        this.webRTCWrapper
 734                .setRemoteDescription(
 735                        new org.webrtc.SessionDescription(
 736                                org.webrtc.SessionDescription.Type.ANSWER, answer.toString()))
 737                .get();
 738        return localRtpContentMap;
 739    }
 740
 741    private SessionDescription generateFakeResponse(final RtpContentMap localContentMap) {
 742        final RtpContentMap currentRemote = getRemoteContentMap();
 743        final RtpContentMap.Diff diff = currentRemote.diff(localContentMap);
 744        if (diff.isEmpty()) {
 745            throw new IllegalStateException(
 746                    "Unexpected rollback condition. No difference between local and remote");
 747        }
 748        final RtpContentMap patch = localContentMap.toContentModification(diff.added);
 749        if (ImmutableSet.of(Content.Senders.NONE).equals(patch.getSenders())) {
 750            final RtpContentMap nextRemote =
 751                    currentRemote.addContent(
 752                            patch.modifiedSenders(Content.Senders.NONE), getPeerDtlsSetup());
 753            return SessionDescription.of(nextRemote, isResponder());
 754        }
 755        throw new IllegalStateException(
 756                "Unexpected rollback condition. Senders were not uniformly none");
 757    }
 758
 759    public synchronized void acceptContentAdd(
 760            @NonNull final Set<ContentAddition.Summary> contentAddition) {
 761        final RtpContentMap incomingContentAdd = this.incomingContentAdd;
 762        if (incomingContentAdd == null) {
 763            throw new IllegalStateException("No incoming content add");
 764        }
 765
 766        if (contentAddition.equals(ContentAddition.summary(incomingContentAdd))) {
 767            this.incomingContentAdd = null;
 768            final Set<Content.Senders> senders = incomingContentAdd.getSenders();
 769            Log.d(Config.LOGTAG, "senders of incoming content-add: " + senders);
 770            if (senders.equals(Content.Senders.receiveOnly(isInitiator()))) {
 771                Log.d(
 772                        Config.LOGTAG,
 773                        "content addition is receive only. we want to upgrade to 'both'");
 774                final RtpContentMap modifiedSenders =
 775                        incomingContentAdd.modifiedSenders(Content.Senders.BOTH);
 776                final Iq proposedContentModification =
 777                        modifiedSenders
 778                                .toStub()
 779                                .toJinglePacket(Jingle.Action.CONTENT_MODIFY, id.sessionId);
 780                proposedContentModification.setTo(id.with);
 781                xmppConnectionService.sendIqPacket(
 782                        id.account,
 783                        proposedContentModification,
 784                        (response) -> {
 785                            if (response.getType() == Iq.Type.RESULT) {
 786                                Log.d(
 787                                        Config.LOGTAG,
 788                                        id.account.getJid().asBareJid()
 789                                                + ": remote has accepted our upgrade to senders=both");
 790                                acceptContentAdd(
 791                                        ContentAddition.summary(modifiedSenders), modifiedSenders);
 792                            } else {
 793                                Log.d(
 794                                        Config.LOGTAG,
 795                                        id.account.getJid().asBareJid()
 796                                                + ": remote has rejected our upgrade to senders=both");
 797                                acceptContentAdd(contentAddition, incomingContentAdd);
 798                            }
 799                        });
 800            } else {
 801                acceptContentAdd(contentAddition, incomingContentAdd);
 802            }
 803        } else {
 804            throw new IllegalStateException(
 805                    "Accepted content add does not match pending content-add");
 806        }
 807    }
 808
 809    private void acceptContentAdd(
 810            @NonNull final Set<ContentAddition.Summary> contentAddition,
 811            final RtpContentMap incomingContentAdd) {
 812        final IceUdpTransportInfo.Setup setup = getPeerDtlsSetup();
 813        final RtpContentMap modifiedContentMap =
 814                getRemoteContentMap().addContent(incomingContentAdd, setup);
 815        this.setRemoteContentMap(modifiedContentMap);
 816
 817        final SessionDescription offer;
 818        try {
 819            offer = SessionDescription.of(modifiedContentMap, isResponder());
 820        } catch (final IllegalArgumentException | NullPointerException e) {
 821            Log.d(
 822                    Config.LOGTAG,
 823                    id.getAccount().getJid().asBareJid()
 824                            + ": unable convert offer from content-add to SDP",
 825                    e);
 826            webRTCWrapper.close();
 827            sendSessionTerminate(Reason.FAILED_APPLICATION, e.getMessage());
 828            return;
 829        }
 830        this.incomingContentAdd = null;
 831        acceptContentAdd(contentAddition, offer);
 832    }
 833
 834    private void acceptContentAdd(
 835            final Set<ContentAddition.Summary> contentAddition, final SessionDescription offer) {
 836        final org.webrtc.SessionDescription sdp =
 837                new org.webrtc.SessionDescription(
 838                        org.webrtc.SessionDescription.Type.OFFER, offer.toString());
 839        try {
 840            this.webRTCWrapper.setRemoteDescription(sdp).get();
 841
 842            // TODO add tracks for 'media' where contentAddition.senders matches
 843
 844            // TODO if senders.sending(isInitiator())
 845
 846            this.webRTCWrapper.addTrack(Media.VIDEO);
 847
 848            // TODO add additional transceivers for recv only cases
 849
 850            final SessionDescription answer = setLocalSessionDescription();
 851            final RtpContentMap rtpContentMap = RtpContentMap.of(answer, isInitiator());
 852
 853            final RtpContentMap contentAcceptMap =
 854                    rtpContentMap.toContentModification(
 855                            Collections2.transform(contentAddition, ca -> ca.name));
 856
 857            Log.d(
 858                    Config.LOGTAG,
 859                    id.getAccount().getJid().asBareJid()
 860                            + ": sending content-accept "
 861                            + ContentAddition.summary(contentAcceptMap));
 862
 863            addIceCandidatesFromBlackLog();
 864
 865            modifyLocalContentMap(rtpContentMap);
 866            final ListenableFuture<RtpContentMap> future =
 867                    prepareOutgoingContentMap(contentAcceptMap);
 868            Futures.addCallback(
 869                    future,
 870                    new FutureCallback<>() {
 871                        @Override
 872                        public void onSuccess(final RtpContentMap rtpContentMap) {
 873                            sendContentAccept(rtpContentMap);
 874                            webRTCWrapper.setIsReadyToReceiveIceCandidates(true);
 875                        }
 876
 877                        @Override
 878                        public void onFailure(@NonNull final Throwable throwable) {
 879                            failureToPerformAction(Jingle.Action.CONTENT_ACCEPT, throwable);
 880                        }
 881                    },
 882                    MoreExecutors.directExecutor());
 883        } catch (final Exception e) {
 884            Log.d(Config.LOGTAG, "unable to accept content add", Throwables.getRootCause(e));
 885            webRTCWrapper.close();
 886            sendSessionTerminate(Reason.FAILED_APPLICATION);
 887        }
 888    }
 889
 890    private void sendContentAccept(final RtpContentMap contentAcceptMap) {
 891        final Iq iq = contentAcceptMap.toJinglePacket(Jingle.Action.CONTENT_ACCEPT, id.sessionId);
 892        send(iq);
 893    }
 894
 895    public synchronized void rejectContentAdd() {
 896        final RtpContentMap incomingContentAdd = this.incomingContentAdd;
 897        if (incomingContentAdd == null) {
 898            throw new IllegalStateException("No incoming content add");
 899        }
 900        this.incomingContentAdd = null;
 901        updateEndUserState();
 902        rejectContentAdd(incomingContentAdd);
 903    }
 904
 905    private void rejectContentAdd(final RtpContentMap contentMap) {
 906        final Iq iq =
 907                contentMap.toStub().toJinglePacket(Jingle.Action.CONTENT_REJECT, id.sessionId);
 908        Log.d(
 909                Config.LOGTAG,
 910                id.getAccount().getJid().asBareJid()
 911                        + ": rejecting content "
 912                        + ContentAddition.summary(contentMap));
 913        send(iq);
 914    }
 915
 916    private boolean checkForIceRestart(final Iq jinglePacket, final RtpContentMap rtpContentMap) {
 917        final RtpContentMap existing = getRemoteContentMap();
 918        final Set<IceUdpTransportInfo.Credentials> existingCredentials;
 919        final IceUdpTransportInfo.Credentials newCredentials;
 920        try {
 921            existingCredentials = existing.getCredentials();
 922            newCredentials = rtpContentMap.getDistinctCredentials();
 923        } catch (final IllegalStateException e) {
 924            Log.d(Config.LOGTAG, "unable to gather credentials for comparison", e);
 925            return false;
 926        }
 927        if (existingCredentials.contains(newCredentials)) {
 928            return false;
 929        }
 930        // TODO an alternative approach is to check if we already got an iq result to our
 931        // ICE-restart
 932        // and if that's the case we are seeing an answer.
 933        // This might be more spec compliant but also more error prone potentially
 934        final boolean isSignalStateStable =
 935                this.webRTCWrapper.getSignalingState() == PeerConnection.SignalingState.STABLE;
 936        // TODO a stable signal state can be another indicator that we have an offer to restart ICE
 937        final boolean isOffer = rtpContentMap.emptyCandidates();
 938        final RtpContentMap restartContentMap;
 939        try {
 940            if (isOffer) {
 941                Log.d(Config.LOGTAG, "received offer to restart ICE " + newCredentials);
 942                restartContentMap =
 943                        existing.modifiedCredentials(
 944                                newCredentials, IceUdpTransportInfo.Setup.ACTPASS);
 945            } else {
 946                final IceUdpTransportInfo.Setup setup = getPeerDtlsSetup();
 947                Log.d(
 948                        Config.LOGTAG,
 949                        "received confirmation of ICE restart"
 950                                + newCredentials
 951                                + " peer_setup="
 952                                + setup);
 953                // DTLS setup attribute needs to be rewritten to reflect current peer state
 954                // https://groups.google.com/g/discuss-webrtc/c/DfpIMwvUfeM
 955                restartContentMap = existing.modifiedCredentials(newCredentials, setup);
 956            }
 957            if (applyIceRestart(jinglePacket, restartContentMap, isOffer)) {
 958                return isOffer;
 959            } else {
 960                Log.d(Config.LOGTAG, "ignoring ICE restart. sending tie-break");
 961                respondWithTieBreak(jinglePacket);
 962                return true;
 963            }
 964        } catch (final Exception exception) {
 965            respondOk(jinglePacket);
 966            final Throwable rootCause = Throwables.getRootCause(exception);
 967            if (rootCause instanceof WebRTCWrapper.PeerConnectionNotInitialized) {
 968                // If this happens a termination is already in progress
 969                Log.d(Config.LOGTAG, "ignoring PeerConnectionNotInitialized on ICE restart");
 970                return true;
 971            }
 972            Log.d(Config.LOGTAG, "failure to apply ICE restart", rootCause);
 973            webRTCWrapper.close();
 974            sendSessionTerminate(Reason.ofThrowable(rootCause), rootCause.getMessage());
 975            return true;
 976        }
 977    }
 978
 979    private IceUdpTransportInfo.Setup getPeerDtlsSetup() {
 980        final IceUdpTransportInfo.Setup peerSetup = this.peerDtlsSetup;
 981        if (peerSetup == null || peerSetup == IceUdpTransportInfo.Setup.ACTPASS) {
 982            throw new IllegalStateException("Invalid peer setup");
 983        }
 984        return peerSetup;
 985    }
 986
 987    private void storePeerDtlsSetup(final IceUdpTransportInfo.Setup setup) {
 988        if (setup == null || setup == IceUdpTransportInfo.Setup.ACTPASS) {
 989            throw new IllegalArgumentException("Trying to store invalid peer dtls setup");
 990        }
 991        this.peerDtlsSetup = setup;
 992    }
 993
 994    private boolean applyIceRestart(
 995            final Iq jinglePacket, final RtpContentMap restartContentMap, final boolean isOffer)
 996            throws ExecutionException, InterruptedException {
 997        final SessionDescription sessionDescription =
 998                SessionDescription.of(restartContentMap, isResponder());
 999        final org.webrtc.SessionDescription.Type type =
1000                isOffer
1001                        ? org.webrtc.SessionDescription.Type.OFFER
1002                        : org.webrtc.SessionDescription.Type.ANSWER;
1003        org.webrtc.SessionDescription sdp =
1004                new org.webrtc.SessionDescription(type, sessionDescription.toString());
1005        if (isOffer && webRTCWrapper.getSignalingState() != PeerConnection.SignalingState.STABLE) {
1006            if (isInitiator()) {
1007                // We ignore the offer and respond with tie-break. This will clause the responder
1008                // not to apply the content map
1009                return false;
1010            }
1011        }
1012        webRTCWrapper.setRemoteDescription(sdp).get();
1013        setRemoteContentMap(restartContentMap);
1014        if (isOffer) {
1015            final SessionDescription localSessionDescription = setLocalSessionDescription();
1016            setLocalContentMap(RtpContentMap.of(localSessionDescription, isInitiator()));
1017            // We need to respond OK before sending any candidates
1018            respondOk(jinglePacket);
1019            webRTCWrapper.setIsReadyToReceiveIceCandidates(true);
1020        } else {
1021            storePeerDtlsSetup(restartContentMap.getDtlsSetup());
1022        }
1023        return true;
1024    }
1025
1026    private void processCandidates(
1027            final Set<Map.Entry<String, DescriptionTransport<RtpDescription, IceUdpTransportInfo>>>
1028                    contents) {
1029        for (final Map.Entry<String, DescriptionTransport<RtpDescription, IceUdpTransportInfo>>
1030                content : contents) {
1031            processCandidate(content);
1032        }
1033    }
1034
1035    private void processCandidate(
1036            final Map.Entry<String, DescriptionTransport<RtpDescription, IceUdpTransportInfo>>
1037                    content) {
1038        final RtpContentMap rtpContentMap = getRemoteContentMap();
1039        final List<String> indices = toIdentificationTags(rtpContentMap);
1040        final String sdpMid = content.getKey(); // aka content name
1041        final IceUdpTransportInfo transport = content.getValue().transport;
1042        final IceUdpTransportInfo.Credentials credentials = transport.getCredentials();
1043
1044        // TODO check that credentials remained the same
1045
1046        for (final IceUdpTransportInfo.Candidate candidate : transport.getCandidates()) {
1047            final String sdp;
1048            try {
1049                sdp = candidate.toSdpAttribute(credentials.ufrag);
1050            } catch (final IllegalArgumentException e) {
1051                Log.d(
1052                        Config.LOGTAG,
1053                        id.account.getJid().asBareJid()
1054                                + ": ignoring invalid ICE candidate "
1055                                + e.getMessage());
1056                continue;
1057            }
1058            final int mLineIndex = indices.indexOf(sdpMid);
1059            if (mLineIndex < 0) {
1060                Log.w(
1061                        Config.LOGTAG,
1062                        "mLineIndex not found for " + sdpMid + ". available indices " + indices);
1063            }
1064            final IceCandidate iceCandidate = new IceCandidate(sdpMid, mLineIndex, sdp);
1065            Log.d(Config.LOGTAG, "received candidate: " + iceCandidate);
1066            this.webRTCWrapper.addIceCandidate(iceCandidate);
1067        }
1068    }
1069
1070    private RtpContentMap getRemoteContentMap() {
1071        return isInitiator() ? this.responderRtpContentMap : this.initiatorRtpContentMap;
1072    }
1073
1074    private RtpContentMap getLocalContentMap() {
1075        return isInitiator() ? this.initiatorRtpContentMap : this.responderRtpContentMap;
1076    }
1077
1078    private List<String> toIdentificationTags(final RtpContentMap rtpContentMap) {
1079        final Group originalGroup = rtpContentMap.group;
1080        final List<String> identificationTags =
1081                originalGroup == null
1082                        ? rtpContentMap.getNames()
1083                        : originalGroup.getIdentificationTags();
1084        if (identificationTags.size() == 0) {
1085            Log.w(
1086                    Config.LOGTAG,
1087                    id.account.getJid().asBareJid()
1088                            + ": no identification tags found in initial offer. we won't be able to calculate mLineIndices");
1089        }
1090        return identificationTags;
1091    }
1092
1093    private ListenableFuture<RtpContentMap> receiveRtpContentMap(
1094            final Jingle jinglePacket, final boolean expectVerification) {
1095        try {
1096            return receiveRtpContentMap(RtpContentMap.of(jinglePacket), expectVerification);
1097        } catch (final Exception e) {
1098            return Futures.immediateFailedFuture(e);
1099        }
1100    }
1101
1102    private ListenableFuture<RtpContentMap> receiveRtpContentMap(
1103            final RtpContentMap receivedContentMap, final boolean expectVerification) {
1104        Log.d(
1105                Config.LOGTAG,
1106                "receiveRtpContentMap("
1107                        + receivedContentMap.getClass().getSimpleName()
1108                        + ",expectVerification="
1109                        + expectVerification
1110                        + ")");
1111        if (receivedContentMap instanceof OmemoVerifiedRtpContentMap) {
1112            final ListenableFuture<AxolotlService.OmemoVerifiedPayload<RtpContentMap>> future =
1113                    id.account
1114                            .getAxolotlService()
1115                            .decrypt((OmemoVerifiedRtpContentMap) receivedContentMap, id.with);
1116            return Futures.transform(
1117                    future,
1118                    omemoVerifiedPayload -> {
1119                        // TODO test if an exception here triggers a correct abort
1120                        omemoVerification.setOrEnsureEqual(omemoVerifiedPayload);
1121                        Log.d(
1122                                Config.LOGTAG,
1123                                id.account.getJid().asBareJid()
1124                                        + ": received verifiable DTLS fingerprint via "
1125                                        + omemoVerification);
1126                        return omemoVerifiedPayload.getPayload();
1127                    },
1128                    MoreExecutors.directExecutor());
1129        } else if (Config.REQUIRE_RTP_VERIFICATION || expectVerification) {
1130            return Futures.immediateFailedFuture(
1131                    new SecurityException("DTLS fingerprint was unexpectedly not verifiable"));
1132        } else {
1133            return Futures.immediateFuture(receivedContentMap);
1134        }
1135    }
1136
1137    private void receiveSessionInitiate(final Iq jinglePacket, final Jingle jingle) {
1138        if (isInitiator()) {
1139            receiveOutOfOrderAction(jinglePacket, Jingle.Action.SESSION_INITIATE);
1140            return;
1141        }
1142        final ListenableFuture<RtpContentMap> future = receiveRtpContentMap(jingle, false);
1143        Futures.addCallback(
1144                future,
1145                new FutureCallback<>() {
1146                    @Override
1147                    public void onSuccess(@Nullable RtpContentMap rtpContentMap) {
1148                        receiveSessionInitiate(jinglePacket, rtpContentMap);
1149                    }
1150
1151                    @Override
1152                    public void onFailure(@NonNull final Throwable throwable) {
1153                        respondOk(jinglePacket);
1154                        sendSessionTerminate(Reason.ofThrowable(throwable), throwable.getMessage());
1155                    }
1156                },
1157                MoreExecutors.directExecutor());
1158    }
1159
1160    private void receiveSessionInitiate(final Iq jinglePacket, final RtpContentMap contentMap) {
1161        try {
1162            contentMap.requireContentDescriptions();
1163            contentMap.requireDTLSFingerprint(true);
1164        } catch (final RuntimeException e) {
1165            Log.d(
1166                    Config.LOGTAG,
1167                    id.account.getJid().asBareJid() + ": improperly formatted contents",
1168                    Throwables.getRootCause(e));
1169            respondOk(jinglePacket);
1170            sendSessionTerminate(Reason.of(e), e.getMessage());
1171            return;
1172        }
1173        Log.d(
1174                Config.LOGTAG,
1175                "processing session-init with " + contentMap.contents.size() + " contents");
1176        final State target;
1177        if (this.state == State.PROCEED) {
1178            Preconditions.checkState(
1179                    proposedMedia != null && proposedMedia.size() > 0,
1180                    "proposed media must be set when processing pre-approved session-initiate");
1181            if (!this.proposedMedia.equals(contentMap.getMedia())) {
1182                sendSessionTerminate(
1183                        Reason.SECURITY_ERROR,
1184                        String.format(
1185                                "Your session proposal (Jingle Message Initiation) included media %s but your session-initiate was %s",
1186                                this.proposedMedia, contentMap.getMedia()));
1187                return;
1188            }
1189            target = State.SESSION_INITIALIZED_PRE_APPROVED;
1190        } else {
1191            target = State.SESSION_INITIALIZED;
1192            setProposedMedia(contentMap.getMedia());
1193        }
1194        if (transition(target, () -> this.initiatorRtpContentMap = contentMap)) {
1195            respondOk(jinglePacket);
1196            pendingIceCandidates.addAll(contentMap.contents.entrySet());
1197            if (target == State.SESSION_INITIALIZED_PRE_APPROVED) {
1198                Log.d(
1199                        Config.LOGTAG,
1200                        id.account.getJid().asBareJid()
1201                                + ": automatically accepting session-initiate");
1202                sendSessionAccept();
1203            } else {
1204                Log.d(
1205                        Config.LOGTAG,
1206                        id.account.getJid().asBareJid()
1207                                + ": received not pre-approved session-initiate. start ringing");
1208                startRinging();
1209            }
1210        } else {
1211            Log.d(
1212                    Config.LOGTAG,
1213                    String.format(
1214                            "%s: received session-initiate while in state %s",
1215                            id.account.getJid().asBareJid(), state));
1216            terminateWithOutOfOrder(jinglePacket);
1217        }
1218    }
1219
1220    private void receiveSessionAccept(final Iq jinglePacket, final Jingle jingle) {
1221        if (isResponder()) {
1222            receiveOutOfOrderAction(jinglePacket, Jingle.Action.SESSION_ACCEPT);
1223            return;
1224        }
1225        final ListenableFuture<RtpContentMap> future =
1226                receiveRtpContentMap(jingle, this.omemoVerification.hasFingerprint());
1227        Futures.addCallback(
1228                future,
1229                new FutureCallback<>() {
1230                    @Override
1231                    public void onSuccess(@Nullable RtpContentMap rtpContentMap) {
1232                        receiveSessionAccept(jinglePacket, rtpContentMap);
1233                    }
1234
1235                    @Override
1236                    public void onFailure(@NonNull final Throwable throwable) {
1237                        respondOk(jinglePacket);
1238                        Log.d(
1239                                Config.LOGTAG,
1240                                id.account.getJid().asBareJid()
1241                                        + ": improperly formatted contents in session-accept",
1242                                throwable);
1243                        webRTCWrapper.close();
1244                        sendSessionTerminate(Reason.ofThrowable(throwable), throwable.getMessage());
1245                    }
1246                },
1247                MoreExecutors.directExecutor());
1248    }
1249
1250    private void receiveSessionAccept(final Iq jinglePacket, final RtpContentMap contentMap) {
1251        try {
1252            contentMap.requireContentDescriptions();
1253            contentMap.requireDTLSFingerprint();
1254        } catch (final RuntimeException e) {
1255            respondOk(jinglePacket);
1256            Log.d(
1257                    Config.LOGTAG,
1258                    id.account.getJid().asBareJid()
1259                            + ": improperly formatted contents in session-accept",
1260                    e);
1261            webRTCWrapper.close();
1262            sendSessionTerminate(Reason.of(e), e.getMessage());
1263            return;
1264        }
1265        final Set<Media> initiatorMedia = this.initiatorRtpContentMap.getMedia();
1266        if (!initiatorMedia.equals(contentMap.getMedia())) {
1267            sendSessionTerminate(
1268                    Reason.SECURITY_ERROR,
1269                    String.format(
1270                            "Your session-included included media %s but our session-initiate was %s",
1271                            this.proposedMedia, contentMap.getMedia()));
1272            return;
1273        }
1274        Log.d(
1275                Config.LOGTAG,
1276                "processing session-accept with " + contentMap.contents.size() + " contents");
1277        if (transition(State.SESSION_ACCEPTED)) {
1278            respondOk(jinglePacket);
1279            receiveSessionAccept(contentMap);
1280        } else {
1281            Log.d(
1282                    Config.LOGTAG,
1283                    String.format(
1284                            "%s: received session-accept while in state %s",
1285                            id.account.getJid().asBareJid(), state));
1286            respondOk(jinglePacket);
1287        }
1288    }
1289
1290    private void receiveSessionAccept(final RtpContentMap contentMap) {
1291        this.responderRtpContentMap = contentMap;
1292        this.storePeerDtlsSetup(contentMap.getDtlsSetup());
1293        final SessionDescription sessionDescription;
1294        try {
1295            sessionDescription = SessionDescription.of(contentMap, false);
1296        } catch (final IllegalArgumentException | NullPointerException e) {
1297            Log.d(
1298                    Config.LOGTAG,
1299                    id.account.getJid().asBareJid()
1300                            + ": unable convert offer from session-accept to SDP",
1301                    e);
1302            webRTCWrapper.close();
1303            sendSessionTerminate(Reason.FAILED_APPLICATION, e.getMessage());
1304            return;
1305        }
1306        final org.webrtc.SessionDescription answer =
1307                new org.webrtc.SessionDescription(
1308                        org.webrtc.SessionDescription.Type.ANSWER, sessionDescription.toString());
1309        try {
1310            this.webRTCWrapper.setRemoteDescription(answer).get();
1311        } catch (final Exception e) {
1312            Log.d(
1313                    Config.LOGTAG,
1314                    id.account.getJid().asBareJid()
1315                            + ": unable to set remote description after receiving session-accept",
1316                    Throwables.getRootCause(e));
1317            webRTCWrapper.close();
1318            sendSessionTerminate(
1319                    Reason.FAILED_APPLICATION, Throwables.getRootCause(e).getMessage());
1320            return;
1321        }
1322        processCandidates(contentMap.contents.entrySet());
1323    }
1324
1325    private void sendSessionAccept() {
1326        final RtpContentMap rtpContentMap = this.initiatorRtpContentMap;
1327        if (rtpContentMap == null) {
1328            throw new IllegalStateException("initiator RTP Content Map has not been set");
1329        }
1330        final SessionDescription offer;
1331        try {
1332            offer = SessionDescription.of(rtpContentMap, true);
1333        } catch (final IllegalArgumentException | NullPointerException e) {
1334            Log.d(
1335                    Config.LOGTAG,
1336                    id.account.getJid().asBareJid()
1337                            + ": unable convert offer from session-initiate to SDP",
1338                    e);
1339            webRTCWrapper.close();
1340            sendSessionTerminate(Reason.FAILED_APPLICATION, e.getMessage());
1341            return;
1342        }
1343        sendSessionAccept(rtpContentMap.getMedia(), offer);
1344    }
1345
1346    private void sendSessionAccept(final Set<Media> media, final SessionDescription offer) {
1347        discoverIceServers(iceServers -> sendSessionAccept(media, offer, iceServers));
1348    }
1349
1350    private synchronized void sendSessionAccept(
1351            final Set<Media> media,
1352            final SessionDescription offer,
1353            final List<PeerConnection.IceServer> iceServers) {
1354        if (isTerminated()) {
1355            Log.w(
1356                    Config.LOGTAG,
1357                    id.account.getJid().asBareJid()
1358                            + ": ICE servers got discovered when session was already terminated. nothing to do.");
1359            return;
1360        }
1361        final boolean includeCandidates = remoteHasSdpOfferAnswer();
1362        try {
1363            setupWebRTC(media, iceServers, !includeCandidates);
1364        } catch (final WebRTCWrapper.InitializationException e) {
1365            Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": unable to initialize WebRTC");
1366            webRTCWrapper.close();
1367            sendSessionTerminate(Reason.FAILED_APPLICATION, e.getMessage());
1368            return;
1369        }
1370        final org.webrtc.SessionDescription sdp =
1371                new org.webrtc.SessionDescription(
1372                        org.webrtc.SessionDescription.Type.OFFER, offer.toString());
1373        try {
1374            this.webRTCWrapper.setRemoteDescription(sdp).get();
1375            addIceCandidatesFromBlackLog();
1376            org.webrtc.SessionDescription webRTCSessionDescription =
1377                    this.webRTCWrapper.setLocalDescription(includeCandidates).get();
1378            prepareSessionAccept(webRTCSessionDescription, includeCandidates);
1379        } catch (final Exception e) {
1380            failureToAcceptSession(e);
1381        }
1382    }
1383
1384    private void failureToAcceptSession(final Throwable throwable) {
1385        if (isTerminated()) {
1386            return;
1387        }
1388        final Throwable rootCause = Throwables.getRootCause(throwable);
1389        Log.d(Config.LOGTAG, "unable to send session accept", rootCause);
1390        webRTCWrapper.close();
1391        sendSessionTerminate(Reason.ofThrowable(rootCause), rootCause.getMessage());
1392    }
1393
1394    private void failureToPerformAction(final Jingle.Action action, final Throwable throwable) {
1395        if (isTerminated()) {
1396            return;
1397        }
1398        final Throwable rootCause = Throwables.getRootCause(throwable);
1399        Log.d(Config.LOGTAG, "unable to send " + action, rootCause);
1400        webRTCWrapper.close();
1401        sendSessionTerminate(Reason.ofThrowable(rootCause), rootCause.getMessage());
1402    }
1403
1404    private void addIceCandidatesFromBlackLog() {
1405        Map.Entry<String, DescriptionTransport<RtpDescription, IceUdpTransportInfo>> foo;
1406        while ((foo = this.pendingIceCandidates.poll()) != null) {
1407            processCandidate(foo);
1408            Log.d(
1409                    Config.LOGTAG,
1410                    id.account.getJid().asBareJid() + ": added candidate from back log");
1411        }
1412    }
1413
1414    private void prepareSessionAccept(
1415            final org.webrtc.SessionDescription webRTCSessionDescription,
1416            final boolean includeCandidates) {
1417        final SessionDescription sessionDescription =
1418                SessionDescription.parse(webRTCSessionDescription.description);
1419        final RtpContentMap respondingRtpContentMap = RtpContentMap.of(sessionDescription, false);
1420        final ImmutableMultimap<String, IceUdpTransportInfo.Candidate> candidates;
1421        if (includeCandidates) {
1422            candidates = parseCandidates(sessionDescription);
1423        } else {
1424            candidates = ImmutableMultimap.of();
1425        }
1426        this.responderRtpContentMap = respondingRtpContentMap;
1427        storePeerDtlsSetup(respondingRtpContentMap.getDtlsSetup().flip());
1428        final ListenableFuture<RtpContentMap> outgoingContentMapFuture =
1429                prepareOutgoingContentMap(respondingRtpContentMap);
1430        Futures.addCallback(
1431                outgoingContentMapFuture,
1432                new FutureCallback<>() {
1433                    @Override
1434                    public void onSuccess(final RtpContentMap outgoingContentMap) {
1435                        if (includeCandidates) {
1436                            Log.d(
1437                                    Config.LOGTAG,
1438                                    "including "
1439                                            + candidates.size()
1440                                            + " candidates in session accept");
1441                            sendSessionAccept(outgoingContentMap.withCandidates(candidates));
1442                        } else {
1443                            sendSessionAccept(outgoingContentMap);
1444                        }
1445                        webRTCWrapper.setIsReadyToReceiveIceCandidates(true);
1446                    }
1447
1448                    @Override
1449                    public void onFailure(@NonNull Throwable throwable) {
1450                        failureToAcceptSession(throwable);
1451                    }
1452                },
1453                MoreExecutors.directExecutor());
1454    }
1455
1456    private void sendSessionAccept(final RtpContentMap rtpContentMap) {
1457        if (isTerminated()) {
1458            Log.w(
1459                    Config.LOGTAG,
1460                    id.account.getJid().asBareJid()
1461                            + ": preparing session accept was too slow. already terminated. nothing to do.");
1462            return;
1463        }
1464        transitionOrThrow(State.SESSION_ACCEPTED);
1465        final Iq sessionAccept =
1466                rtpContentMap.toJinglePacket(Jingle.Action.SESSION_ACCEPT, id.sessionId);
1467        send(sessionAccept);
1468    }
1469
1470    private ListenableFuture<RtpContentMap> prepareOutgoingContentMap(
1471            final RtpContentMap rtpContentMap) {
1472        if (this.omemoVerification.hasDeviceId()) {
1473            ListenableFuture<AxolotlService.OmemoVerifiedPayload<OmemoVerifiedRtpContentMap>>
1474                    verifiedPayloadFuture =
1475                            id.account
1476                                    .getAxolotlService()
1477                                    .encrypt(
1478                                            rtpContentMap,
1479                                            id.with,
1480                                            omemoVerification.getDeviceId());
1481            return Futures.transform(
1482                    verifiedPayloadFuture,
1483                    verifiedPayload -> {
1484                        omemoVerification.setOrEnsureEqual(verifiedPayload);
1485                        return verifiedPayload.getPayload();
1486                    },
1487                    MoreExecutors.directExecutor());
1488        } else {
1489            return Futures.immediateFuture(rtpContentMap);
1490        }
1491    }
1492
1493    synchronized void deliveryMessage(
1494            final Jid from,
1495            final Element message,
1496            final String serverMessageId,
1497            final long timestamp) {
1498        Log.d(
1499                Config.LOGTAG,
1500                id.account.getJid().asBareJid()
1501                        + ": delivered message to JingleRtpConnection "
1502                        + message);
1503        switch (message.getName()) {
1504            case "propose" -> receivePropose(
1505                    from, Propose.upgrade(message), serverMessageId, timestamp);
1506            case "proceed" -> receiveProceed(
1507                    from, Proceed.upgrade(message), serverMessageId, timestamp);
1508            case "retract" -> receiveRetract(from, serverMessageId, timestamp);
1509            case "reject" -> receiveReject(from, serverMessageId, timestamp);
1510            case "accept" -> receiveAccept(from, serverMessageId, timestamp);
1511        }
1512    }
1513
1514    void deliverFailedProceed(final String message) {
1515        Log.d(
1516                Config.LOGTAG,
1517                id.account.getJid().asBareJid()
1518                        + ": receive message error for proceed message ("
1519                        + Strings.nullToEmpty(message)
1520                        + ")");
1521        if (transition(State.TERMINATED_CONNECTIVITY_ERROR)) {
1522            webRTCWrapper.close();
1523            Log.d(
1524                    Config.LOGTAG,
1525                    id.account.getJid().asBareJid() + ": transitioned into connectivity error");
1526            this.finish();
1527        }
1528    }
1529
1530    private void receiveAccept(final Jid from, final String serverMsgId, final long timestamp) {
1531        final boolean originatedFromMyself =
1532                from.asBareJid().equals(id.account.getJid().asBareJid());
1533        if (originatedFromMyself) {
1534            if (transition(State.ACCEPTED)) {
1535                acceptedOnOtherDevice(serverMsgId, timestamp);
1536            } else {
1537                Log.d(
1538                        Config.LOGTAG,
1539                        id.account.getJid().asBareJid()
1540                                + ": unable to transition to accept because already in state="
1541                                + this.state);
1542                Log.d(Config.LOGTAG, id.account.getJid() + ": received accept from " + from);
1543            }
1544        } else {
1545            Log.d(
1546                    Config.LOGTAG,
1547                    id.account.getJid().asBareJid() + ": ignoring 'accept' from " + from);
1548        }
1549    }
1550
1551    private void acceptedOnOtherDevice(final String serverMsgId, final long timestamp) {
1552        if (serverMsgId != null) {
1553            this.message.setServerMsgId(serverMsgId);
1554        }
1555        this.message.setTime(timestamp);
1556        this.message.setCarbon(true); // indicate that call was accepted on other device
1557        this.writeLogMessageSuccess(0);
1558        this.xmppConnectionService.getNotificationService().cancelIncomingCallNotification();
1559        this.finish();
1560    }
1561
1562    private void receiveReject(final Jid from, final String serverMsgId, final long timestamp) {
1563        final boolean originatedFromMyself =
1564                from.asBareJid().equals(id.account.getJid().asBareJid());
1565        // reject from another one of my clients
1566        if (originatedFromMyself) {
1567            receiveRejectFromMyself(serverMsgId, timestamp);
1568        } else if (isInitiator()) {
1569            if (from.equals(id.with)) {
1570                receiveRejectFromResponder();
1571            } else {
1572                Log.d(
1573                        Config.LOGTAG,
1574                        id.account.getJid()
1575                                + ": ignoring reject from "
1576                                + from
1577                                + " for session with "
1578                                + id.with);
1579            }
1580        } else {
1581            Log.d(
1582                    Config.LOGTAG,
1583                    id.account.getJid()
1584                            + ": ignoring reject from "
1585                            + from
1586                            + " for session with "
1587                            + id.with);
1588        }
1589    }
1590
1591    private void receiveRejectFromMyself(String serverMsgId, long timestamp) {
1592        if (transition(State.REJECTED)) {
1593            this.xmppConnectionService.getNotificationService().cancelIncomingCallNotification();
1594            this.finish();
1595            if (serverMsgId != null) {
1596                this.message.setServerMsgId(serverMsgId);
1597            }
1598            this.message.setTime(timestamp);
1599            this.message.setCarbon(true); // indicate that call was rejected on other device
1600            writeLogMessageMissed();
1601        } else {
1602            Log.d(
1603                    Config.LOGTAG,
1604                    "not able to transition into REJECTED because already in " + this.state);
1605        }
1606    }
1607
1608    private void receiveRejectFromResponder() {
1609        if (isInState(State.PROCEED)) {
1610            Log.d(
1611                    Config.LOGTAG,
1612                    id.account.getJid()
1613                            + ": received reject while still in proceed. callee reconsidered");
1614            closeTransitionLogFinish(State.REJECTED_RACED);
1615            return;
1616        }
1617        if (isInState(State.SESSION_INITIALIZED_PRE_APPROVED)) {
1618            Log.d(
1619                    Config.LOGTAG,
1620                    id.account.getJid()
1621                            + ": received reject while in SESSION_INITIATED_PRE_APPROVED. callee reconsidered before receiving session-init");
1622            closeTransitionLogFinish(State.TERMINATED_DECLINED_OR_BUSY);
1623            return;
1624        }
1625        Log.d(
1626                Config.LOGTAG,
1627                id.account.getJid()
1628                        + ": ignoring reject from responder because already in state "
1629                        + this.state);
1630    }
1631
1632    private void receivePropose(
1633            final Jid from, final Propose propose, final String serverMsgId, final long timestamp) {
1634        final boolean originatedFromMyself =
1635                from.asBareJid().equals(id.account.getJid().asBareJid());
1636        if (originatedFromMyself) {
1637            Log.d(
1638                    Config.LOGTAG,
1639                    id.account.getJid().asBareJid() + ": saw proposal from myself. ignoring");
1640        } else if (transition(
1641                State.PROPOSED,
1642                () -> {
1643                    final Collection<RtpDescription> descriptions =
1644                            Collections2.transform(
1645                                    Collections2.filter(
1646                                            propose.getDescriptions(),
1647                                            d -> d instanceof RtpDescription),
1648                                    input -> (RtpDescription) input);
1649                    final Collection<Media> media =
1650                            Collections2.transform(descriptions, RtpDescription::getMedia);
1651                    Preconditions.checkState(
1652                            !media.contains(Media.UNKNOWN),
1653                            "RTP descriptions contain unknown media");
1654                    Log.d(
1655                            Config.LOGTAG,
1656                            id.account.getJid().asBareJid()
1657                                    + ": received session proposal from "
1658                                    + from
1659                                    + " for "
1660                                    + media);
1661                    this.setProposedMedia(Sets.newHashSet(media));
1662                })) {
1663            if (serverMsgId != null) {
1664                this.message.setServerMsgId(serverMsgId);
1665            }
1666            this.message.setTime(timestamp);
1667            startRinging();
1668            // in environments where we always use discovery timeouts we always want to respond with
1669            // 'ringing'
1670            if (Config.JINGLE_MESSAGE_INIT_STRICT_DEVICE_TIMEOUT
1671                    || id.getContact().showInContactList()) {
1672                sendJingleMessage("ringing");
1673            }
1674        } else {
1675            Log.d(
1676                    Config.LOGTAG,
1677                    id.account.getJid()
1678                            + ": ignoring session proposal because already in "
1679                            + state);
1680        }
1681    }
1682
1683    private void startRinging() {
1684        this.callIntegration.setRinging();
1685        Log.d(
1686                Config.LOGTAG,
1687                id.account.getJid().asBareJid()
1688                        + ": received call from "
1689                        + id.with
1690                        + ". start ringing");
1691        ringingTimeoutFuture =
1692                jingleConnectionManager.schedule(
1693                        this::ringingTimeout, BUSY_TIME_OUT, TimeUnit.SECONDS);
1694        if (CallIntegration.selfManaged(xmppConnectionService)) {
1695            return;
1696        }
1697        xmppConnectionService.getNotificationService().startRinging(id, getMedia());
1698    }
1699
1700    private synchronized void ringingTimeout() {
1701        Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": timeout reached for ringing");
1702        switch (this.state) {
1703            case PROPOSED -> {
1704                message.markUnread();
1705                rejectCallFromProposed();
1706            }
1707            case SESSION_INITIALIZED -> {
1708                message.markUnread();
1709                rejectCallFromSessionInitiate();
1710            }
1711        }
1712        xmppConnectionService.getNotificationService().pushMissedCallNow(message);
1713    }
1714
1715    private void cancelRingingTimeout() {
1716        final ScheduledFuture<?> future = this.ringingTimeoutFuture;
1717        if (future != null && !future.isCancelled()) {
1718            future.cancel(false);
1719        }
1720    }
1721
1722    private void receiveProceed(
1723            final Jid from, final Proceed proceed, final String serverMsgId, final long timestamp) {
1724        final Set<Media> media =
1725                Preconditions.checkNotNull(
1726                        this.proposedMedia, "Proposed media has to be set before handling proceed");
1727        Preconditions.checkState(media.size() > 0, "Proposed media should not be empty");
1728        if (from.equals(id.with)) {
1729            if (isInitiator()) {
1730                if (transition(State.PROCEED)) {
1731                    if (serverMsgId != null) {
1732                        this.message.setServerMsgId(serverMsgId);
1733                    }
1734                    this.message.setTime(timestamp);
1735                    final Integer remoteDeviceId = proceed.getDeviceId();
1736                    if (isOmemoEnabled()) {
1737                        this.omemoVerification.setDeviceId(remoteDeviceId);
1738                    } else {
1739                        if (remoteDeviceId != null) {
1740                            Log.d(
1741                                    Config.LOGTAG,
1742                                    id.account.getJid().asBareJid()
1743                                            + ": remote party signaled support for OMEMO verification but we have OMEMO disabled");
1744                        }
1745                        this.omemoVerification.setDeviceId(null);
1746                    }
1747                    this.sendSessionInitiate(media, State.SESSION_INITIALIZED_PRE_APPROVED);
1748                } else {
1749                    Log.d(
1750                            Config.LOGTAG,
1751                            String.format(
1752                                    "%s: ignoring proceed because already in %s",
1753                                    id.account.getJid().asBareJid(), this.state));
1754                }
1755            } else {
1756                Log.d(
1757                        Config.LOGTAG,
1758                        String.format(
1759                                "%s: ignoring proceed because we were not initializing",
1760                                id.account.getJid().asBareJid()));
1761            }
1762        } else if (from.asBareJid().equals(id.account.getJid().asBareJid())) {
1763            if (transition(State.ACCEPTED)) {
1764                Log.d(
1765                        Config.LOGTAG,
1766                        id.account.getJid().asBareJid()
1767                                + ": moved session with "
1768                                + id.with
1769                                + " into state accepted after received carbon copied proceed");
1770                acceptedOnOtherDevice(serverMsgId, timestamp);
1771            }
1772        } else {
1773            Log.d(
1774                    Config.LOGTAG,
1775                    String.format(
1776                            "%s: ignoring proceed from %s. was expected from %s",
1777                            id.account.getJid().asBareJid(), from, id.with));
1778        }
1779    }
1780
1781    private void receiveRetract(final Jid from, final String serverMsgId, final long timestamp) {
1782        if (from.equals(id.with)) {
1783            final State target =
1784                    this.state == State.PROCEED ? State.RETRACTED_RACED : State.RETRACTED;
1785            if (transition(target)) {
1786                xmppConnectionService.getNotificationService().cancelIncomingCallNotification();
1787                xmppConnectionService.getNotificationService().pushMissedCallNow(message);
1788                Log.d(
1789                        Config.LOGTAG,
1790                        id.account.getJid().asBareJid()
1791                                + ": session with "
1792                                + id.with
1793                                + " has been retracted (serverMsgId="
1794                                + serverMsgId
1795                                + ")");
1796                if (serverMsgId != null) {
1797                    this.message.setServerMsgId(serverMsgId);
1798                }
1799                this.message.setTime(timestamp);
1800                if (target == State.RETRACTED) {
1801                    this.message.markUnread();
1802                }
1803                writeLogMessageMissed();
1804                finish();
1805            } else {
1806                Log.d(Config.LOGTAG, "ignoring retract because already in " + this.state);
1807            }
1808        } else {
1809            // TODO parse retract from self
1810            Log.d(
1811                    Config.LOGTAG,
1812                    id.account.getJid().asBareJid()
1813                            + ": received retract from "
1814                            + from
1815                            + ". expected retract from"
1816                            + id.with
1817                            + ". ignoring");
1818        }
1819    }
1820
1821    public void sendSessionInitiate() {
1822        sendSessionInitiate(this.proposedMedia, State.SESSION_INITIALIZED);
1823    }
1824
1825    private void sendSessionInitiate(final Set<Media> media, final State targetState) {
1826        Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": prepare session-initiate");
1827        discoverIceServers(iceServers -> sendSessionInitiate(media, targetState, iceServers));
1828    }
1829
1830    private synchronized void sendSessionInitiate(
1831            final Set<Media> media,
1832            final State targetState,
1833            final List<PeerConnection.IceServer> iceServers) {
1834        if (isTerminated()) {
1835            Log.w(
1836                    Config.LOGTAG,
1837                    id.account.getJid().asBareJid()
1838                            + ": ICE servers got discovered when session was already terminated. nothing to do.");
1839            return;
1840        }
1841        final boolean includeCandidates = remoteHasSdpOfferAnswer();
1842        try {
1843            setupWebRTC(media, iceServers, !includeCandidates);
1844        } catch (final WebRTCWrapper.InitializationException e) {
1845            Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": unable to initialize WebRTC");
1846            webRTCWrapper.close();
1847            sendRetract(Reason.ofThrowable(e));
1848            return;
1849        }
1850        try {
1851            org.webrtc.SessionDescription webRTCSessionDescription =
1852                    this.webRTCWrapper.setLocalDescription(includeCandidates).get();
1853            prepareSessionInitiate(webRTCSessionDescription, includeCandidates, targetState);
1854        } catch (final Exception e) {
1855            // TODO sending the error text is worthwhile as well. Especially for FailureToSet
1856            // exceptions
1857            failureToInitiateSession(e, targetState);
1858        }
1859    }
1860
1861    private void failureToInitiateSession(final Throwable throwable, final State targetState) {
1862        if (isTerminated()) {
1863            return;
1864        }
1865        Log.d(
1866                Config.LOGTAG,
1867                id.account.getJid().asBareJid() + ": unable to sendSessionInitiate",
1868                Throwables.getRootCause(throwable));
1869        webRTCWrapper.close();
1870        final Reason reason = Reason.ofThrowable(throwable);
1871        if (isInState(targetState)) {
1872            sendSessionTerminate(reason, throwable.getMessage());
1873        } else {
1874            sendRetract(reason);
1875        }
1876    }
1877
1878    private void sendRetract(final Reason reason) {
1879        // TODO embed reason into retract
1880        sendJingleMessage("retract", id.with.asBareJid());
1881        transitionOrThrow(reasonToState(reason));
1882        this.finish();
1883    }
1884
1885    private void prepareSessionInitiate(
1886            final org.webrtc.SessionDescription webRTCSessionDescription,
1887            final boolean includeCandidates,
1888            final State targetState) {
1889        final SessionDescription sessionDescription =
1890                SessionDescription.parse(webRTCSessionDescription.description);
1891        final RtpContentMap rtpContentMap = RtpContentMap.of(sessionDescription, true);
1892        final ImmutableMultimap<String, IceUdpTransportInfo.Candidate> candidates;
1893        if (includeCandidates) {
1894            candidates = parseCandidates(sessionDescription);
1895        } else {
1896            candidates = ImmutableMultimap.of();
1897        }
1898        this.initiatorRtpContentMap = rtpContentMap;
1899        final ListenableFuture<RtpContentMap> outgoingContentMapFuture =
1900                encryptSessionInitiate(rtpContentMap);
1901        Futures.addCallback(
1902                outgoingContentMapFuture,
1903                new FutureCallback<>() {
1904                    @Override
1905                    public void onSuccess(final RtpContentMap outgoingContentMap) {
1906                        if (includeCandidates) {
1907                            Log.d(
1908                                    Config.LOGTAG,
1909                                    "including "
1910                                            + candidates.size()
1911                                            + " candidates in session initiate");
1912                            sendSessionInitiate(
1913                                    outgoingContentMap.withCandidates(candidates), targetState);
1914                        } else {
1915                            sendSessionInitiate(outgoingContentMap, targetState);
1916                        }
1917                        webRTCWrapper.setIsReadyToReceiveIceCandidates(true);
1918                    }
1919
1920                    @Override
1921                    public void onFailure(@NonNull final Throwable throwable) {
1922                        failureToInitiateSession(throwable, targetState);
1923                    }
1924                },
1925                MoreExecutors.directExecutor());
1926    }
1927
1928    private void sendSessionInitiate(final RtpContentMap rtpContentMap, final State targetState) {
1929        if (isTerminated()) {
1930            Log.w(
1931                    Config.LOGTAG,
1932                    id.account.getJid().asBareJid()
1933                            + ": preparing session was too slow. already terminated. nothing to do.");
1934            return;
1935        }
1936        this.transitionOrThrow(targetState);
1937        final Iq sessionInitiate =
1938                rtpContentMap.toJinglePacket(Jingle.Action.SESSION_INITIATE, id.sessionId);
1939        send(sessionInitiate);
1940    }
1941
1942    private ListenableFuture<RtpContentMap> encryptSessionInitiate(
1943            final RtpContentMap rtpContentMap) {
1944        if (this.omemoVerification.hasDeviceId()) {
1945            final ListenableFuture<AxolotlService.OmemoVerifiedPayload<OmemoVerifiedRtpContentMap>>
1946                    verifiedPayloadFuture =
1947                            id.account
1948                                    .getAxolotlService()
1949                                    .encrypt(
1950                                            rtpContentMap,
1951                                            id.with,
1952                                            omemoVerification.getDeviceId());
1953            final ListenableFuture<RtpContentMap> future =
1954                    Futures.transform(
1955                            verifiedPayloadFuture,
1956                            verifiedPayload -> {
1957                                omemoVerification.setSessionFingerprint(
1958                                        verifiedPayload.getFingerprint());
1959                                return verifiedPayload.getPayload();
1960                            },
1961                            MoreExecutors.directExecutor());
1962            if (Config.REQUIRE_RTP_VERIFICATION) {
1963                return future;
1964            }
1965            return Futures.catching(
1966                    future,
1967                    CryptoFailedException.class,
1968                    e -> {
1969                        Log.w(
1970                                Config.LOGTAG,
1971                                id.account.getJid().asBareJid()
1972                                        + ": unable to use OMEMO DTLS verification on outgoing session initiate. falling back",
1973                                e);
1974                        return rtpContentMap;
1975                    },
1976                    MoreExecutors.directExecutor());
1977        } else {
1978            return Futures.immediateFuture(rtpContentMap);
1979        }
1980    }
1981
1982    protected void sendSessionTerminate(final Reason reason) {
1983        sendSessionTerminate(reason, null);
1984    }
1985
1986    protected void sendSessionTerminate(final Reason reason, final String text) {
1987        sendSessionTerminate(reason, text, this::writeLogMessage);
1988        sendJingleMessageFinish(reason);
1989    }
1990
1991    private void sendTransportInfo(
1992            final String contentName, IceUdpTransportInfo.Candidate candidate) {
1993        final RtpContentMap transportInfo;
1994        try {
1995            final RtpContentMap rtpContentMap =
1996                    isInitiator() ? this.initiatorRtpContentMap : this.responderRtpContentMap;
1997            transportInfo = rtpContentMap.transportInfo(contentName, candidate);
1998        } catch (final Exception e) {
1999            Log.d(
2000                    Config.LOGTAG,
2001                    id.account.getJid().asBareJid()
2002                            + ": unable to prepare transport-info from candidate for content="
2003                            + contentName);
2004            return;
2005        }
2006        final Iq iq = transportInfo.toJinglePacket(Jingle.Action.TRANSPORT_INFO, id.sessionId);
2007        send(iq);
2008    }
2009
2010    public RtpEndUserState getEndUserState() {
2011        switch (this.state) {
2012            case NULL, PROPOSED, SESSION_INITIALIZED -> {
2013                if (isInitiator()) {
2014                    return RtpEndUserState.RINGING;
2015                } else {
2016                    return RtpEndUserState.INCOMING_CALL;
2017                }
2018            }
2019            case PROCEED -> {
2020                if (isInitiator()) {
2021                    return RtpEndUserState.RINGING;
2022                } else {
2023                    return RtpEndUserState.ACCEPTING_CALL;
2024                }
2025            }
2026            case SESSION_INITIALIZED_PRE_APPROVED -> {
2027                if (isInitiator()) {
2028                    return RtpEndUserState.RINGING;
2029                } else {
2030                    return RtpEndUserState.CONNECTING;
2031                }
2032            }
2033            case SESSION_ACCEPTED -> {
2034                final ContentAddition ca = getPendingContentAddition();
2035                if (ca != null && ca.direction == ContentAddition.Direction.INCOMING) {
2036                    return RtpEndUserState.INCOMING_CONTENT_ADD;
2037                }
2038                return getPeerConnectionStateAsEndUserState();
2039            }
2040            case REJECTED, REJECTED_RACED, TERMINATED_DECLINED_OR_BUSY -> {
2041                if (isInitiator()) {
2042                    return RtpEndUserState.DECLINED_OR_BUSY;
2043                } else {
2044                    return RtpEndUserState.ENDED;
2045                }
2046            }
2047            case TERMINATED_SUCCESS, ACCEPTED, RETRACTED, TERMINATED_CANCEL_OR_TIMEOUT -> {
2048                return RtpEndUserState.ENDED;
2049            }
2050            case RETRACTED_RACED -> {
2051                if (isInitiator()) {
2052                    return RtpEndUserState.ENDED;
2053                } else {
2054                    return RtpEndUserState.RETRACTED;
2055                }
2056            }
2057            case TERMINATED_CONNECTIVITY_ERROR -> {
2058                return zeroDuration()
2059                        ? RtpEndUserState.CONNECTIVITY_ERROR
2060                        : RtpEndUserState.CONNECTIVITY_LOST_ERROR;
2061            }
2062            case TERMINATED_APPLICATION_FAILURE -> {
2063                return RtpEndUserState.APPLICATION_ERROR;
2064            }
2065            case TERMINATED_SECURITY_ERROR -> {
2066                return RtpEndUserState.SECURITY_ERROR;
2067            }
2068        }
2069        throw new IllegalStateException(
2070                String.format("%s has no equivalent EndUserState", this.state));
2071    }
2072
2073    private RtpEndUserState getPeerConnectionStateAsEndUserState() {
2074        final PeerConnection.PeerConnectionState state;
2075        try {
2076            state = webRTCWrapper.getState();
2077        } catch (final WebRTCWrapper.PeerConnectionNotInitialized e) {
2078            // We usually close the WebRTCWrapper *before* transitioning so we might still
2079            // be in SESSION_ACCEPTED even though the peerConnection has been torn down
2080            return RtpEndUserState.ENDING_CALL;
2081        }
2082        return switch (state) {
2083            case CONNECTED -> RtpEndUserState.CONNECTED;
2084            case NEW, CONNECTING -> RtpEndUserState.CONNECTING;
2085            case CLOSED -> RtpEndUserState.ENDING_CALL;
2086            default -> zeroDuration()
2087                    ? RtpEndUserState.CONNECTIVITY_ERROR
2088                    : RtpEndUserState.RECONNECTING;
2089        };
2090    }
2091
2092    private boolean isPeerConnectionConnected() {
2093        try {
2094            return webRTCWrapper.getState() == PeerConnection.PeerConnectionState.CONNECTED;
2095        } catch (final WebRTCWrapper.PeerConnectionNotInitialized e) {
2096            return false;
2097        }
2098    }
2099
2100    private void updateCallIntegrationState() {
2101        switch (this.state) {
2102            case NULL, PROPOSED, SESSION_INITIALIZED -> {
2103                if (isInitiator()) {
2104                    this.callIntegration.setDialing();
2105                } else {
2106                    this.callIntegration.setRinging();
2107                }
2108            }
2109            case PROCEED, SESSION_INITIALIZED_PRE_APPROVED -> {
2110                if (isInitiator()) {
2111                    this.callIntegration.setDialing();
2112                } else {
2113                    this.callIntegration.setInitialized();
2114                }
2115            }
2116            case SESSION_ACCEPTED -> {
2117                if (isPeerConnectionConnected()) {
2118                    this.callIntegration.setActive();
2119                } else {
2120                    this.callIntegration.setInitialized();
2121                }
2122            }
2123            case REJECTED, REJECTED_RACED, TERMINATED_DECLINED_OR_BUSY -> {
2124                if (isInitiator()) {
2125                    this.callIntegration.busy();
2126                } else {
2127                    this.callIntegration.rejected();
2128                }
2129            }
2130            case TERMINATED_SUCCESS -> this.callIntegration.success();
2131            case ACCEPTED -> this.callIntegration.accepted();
2132            case RETRACTED, RETRACTED_RACED, TERMINATED_CANCEL_OR_TIMEOUT -> this.callIntegration
2133                    .retracted();
2134            case TERMINATED_CONNECTIVITY_ERROR,
2135                    TERMINATED_APPLICATION_FAILURE,
2136                    TERMINATED_SECURITY_ERROR -> this.callIntegration.error();
2137            default -> throw new IllegalStateException(
2138                    String.format("%s is not handled", this.state));
2139        }
2140    }
2141
2142    public ContentAddition getPendingContentAddition() {
2143        final RtpContentMap in = this.incomingContentAdd;
2144        final RtpContentMap out = this.outgoingContentAdd;
2145        if (out != null) {
2146            return ContentAddition.of(ContentAddition.Direction.OUTGOING, out);
2147        } else if (in != null) {
2148            return ContentAddition.of(ContentAddition.Direction.INCOMING, in);
2149        } else {
2150            return null;
2151        }
2152    }
2153
2154    public Set<Media> getMedia() {
2155        final State current = getState();
2156        if (current == State.NULL) {
2157            if (isInitiator()) {
2158                return Preconditions.checkNotNull(
2159                        this.proposedMedia, "RTP connection has not been initialized properly");
2160            }
2161            throw new IllegalStateException("RTP connection has not been initialized yet");
2162        }
2163        if (Arrays.asList(State.PROPOSED, State.PROCEED).contains(current)) {
2164            return Preconditions.checkNotNull(
2165                    this.proposedMedia, "RTP connection has not been initialized properly");
2166        }
2167        final RtpContentMap localContentMap = getLocalContentMap();
2168        final RtpContentMap initiatorContentMap = initiatorRtpContentMap;
2169        if (localContentMap != null) {
2170            return localContentMap.getMedia();
2171        } else if (initiatorContentMap != null) {
2172            return initiatorContentMap.getMedia();
2173        } else if (isTerminated()) {
2174            return Collections.emptySet(); // we might fail before we ever got a chance to set media
2175        } else {
2176            return Preconditions.checkNotNull(
2177                    this.proposedMedia, "RTP connection has not been initialized properly");
2178        }
2179    }
2180
2181    public boolean isVerified() {
2182        final String fingerprint = this.omemoVerification.getFingerprint();
2183        if (fingerprint == null) {
2184            return false;
2185        }
2186        final FingerprintStatus status =
2187                id.account.getAxolotlService().getFingerprintTrust(fingerprint);
2188        return status != null && status.isVerified();
2189    }
2190
2191    public boolean addMedia(final Media media) {
2192        final Set<Media> currentMedia = getMedia();
2193        if (currentMedia.contains(media)) {
2194            throw new IllegalStateException(String.format("%s has already been proposed", media));
2195        }
2196        // TODO add state protection - can only add while ACCEPTED or so
2197        Log.d(Config.LOGTAG, "adding media: " + media);
2198        return webRTCWrapper.addTrack(media);
2199    }
2200
2201    public synchronized void acceptCall() {
2202        switch (this.state) {
2203            case PROPOSED -> {
2204                cancelRingingTimeout();
2205                acceptCallFromProposed();
2206            }
2207            case SESSION_INITIALIZED -> {
2208                cancelRingingTimeout();
2209                acceptCallFromSessionInitialized();
2210            }
2211            case ACCEPTED -> Log.w(
2212                    Config.LOGTAG,
2213                    id.account.getJid().asBareJid()
2214                            + ": the call has already been accepted  with another client. UI was just lagging behind");
2215            case PROCEED, SESSION_ACCEPTED -> Log.w(
2216                    Config.LOGTAG,
2217                    id.account.getJid().asBareJid()
2218                            + ": the call has already been accepted. user probably double tapped the UI");
2219            default -> throw new IllegalStateException("Can not accept call from " + this.state);
2220        }
2221    }
2222
2223    public synchronized void rejectCall() {
2224        if (isTerminated()) {
2225            Log.w(
2226                    Config.LOGTAG,
2227                    id.account.getJid().asBareJid()
2228                            + ": received rejectCall() when session has already been terminated. nothing to do");
2229            return;
2230        }
2231        switch (this.state) {
2232            case PROPOSED -> rejectCallFromProposed();
2233            case SESSION_INITIALIZED -> rejectCallFromSessionInitiate();
2234            default -> throw new IllegalStateException("Can not reject call from " + this.state);
2235        }
2236    }
2237
2238    public synchronized void integrationFailure() {
2239        final var state = getState();
2240        if (state == State.PROPOSED) {
2241            Log.e(
2242                    Config.LOGTAG,
2243                    id.account.getJid().asBareJid()
2244                            + ": failed call integration in state proposed");
2245            rejectCallFromProposed();
2246        } else if (state == State.SESSION_INITIALIZED) {
2247            Log.e(Config.LOGTAG, id.account.getJid().asBareJid() + ": failed call integration");
2248            this.webRTCWrapper.close();
2249            sendSessionTerminate(Reason.FAILED_APPLICATION, "CallIntegration failed");
2250        } else {
2251            throw new IllegalStateException(
2252                    String.format("Can not fail integration in state %s", state));
2253        }
2254    }
2255
2256    public synchronized void endCall() {
2257        if (isTerminated()) {
2258            Log.w(
2259                    Config.LOGTAG,
2260                    id.account.getJid().asBareJid()
2261                            + ": received endCall() when session has already been terminated. nothing to do");
2262            return;
2263        }
2264        if (isInState(State.PROPOSED) && isResponder()) {
2265            rejectCallFromProposed();
2266            return;
2267        }
2268        if (isInState(State.PROCEED)) {
2269            if (isInitiator()) {
2270                retractFromProceed();
2271            } else {
2272                rejectCallFromProceed();
2273            }
2274            return;
2275        }
2276        if (isInitiator()
2277                && isInState(State.SESSION_INITIALIZED, State.SESSION_INITIALIZED_PRE_APPROVED)) {
2278            this.webRTCWrapper.close();
2279            sendSessionTerminate(Reason.CANCEL);
2280            return;
2281        }
2282        if (isInState(State.SESSION_INITIALIZED)) {
2283            rejectCallFromSessionInitiate();
2284            return;
2285        }
2286        if (isInState(State.SESSION_INITIALIZED_PRE_APPROVED, State.SESSION_ACCEPTED)) {
2287            this.webRTCWrapper.close();
2288            sendSessionTerminate(Reason.SUCCESS);
2289            return;
2290        }
2291        if (isInState(
2292                State.TERMINATED_APPLICATION_FAILURE,
2293                State.TERMINATED_CONNECTIVITY_ERROR,
2294                State.TERMINATED_DECLINED_OR_BUSY)) {
2295            Log.d(
2296                    Config.LOGTAG,
2297                    "ignoring request to end call because already in state " + this.state);
2298            return;
2299        }
2300        throw new IllegalStateException(
2301                "called 'endCall' while in state " + this.state + ". isInitiator=" + isInitiator());
2302    }
2303
2304    private void retractFromProceed() {
2305        Log.d(Config.LOGTAG, "retract from proceed");
2306        this.sendJingleMessage("retract");
2307        closeTransitionLogFinish(State.RETRACTED_RACED);
2308    }
2309
2310    private void closeTransitionLogFinish(final State state) {
2311        this.webRTCWrapper.close();
2312        transitionOrThrow(state);
2313        writeLogMessage(state);
2314        finish();
2315    }
2316
2317    private void setupWebRTC(
2318            final Set<Media> media,
2319            final List<PeerConnection.IceServer> iceServers,
2320            final boolean trickle)
2321            throws WebRTCWrapper.InitializationException {
2322        this.jingleConnectionManager.ensureConnectionIsRegistered(this);
2323        this.webRTCWrapper.setup(this.xmppConnectionService);
2324        this.webRTCWrapper.initializePeerConnection(media, iceServers, trickle);
2325        // this.webRTCWrapper.setMicrophoneEnabledOrThrow(callIntegration.isMicrophoneEnabled());
2326        this.webRTCWrapper.setMicrophoneEnabledOrThrow(true);
2327    }
2328
2329    private void acceptCallFromProposed() {
2330        transitionOrThrow(State.PROCEED);
2331        xmppConnectionService.getNotificationService().cancelIncomingCallNotification();
2332        this.callIntegration.startAudioRouting();
2333        this.sendJingleMessage("accept", id.account.getJid().asBareJid());
2334        this.sendJingleMessage("proceed");
2335    }
2336
2337    private void rejectCallFromProposed() {
2338        transitionOrThrow(State.REJECTED);
2339        writeLogMessageMissed();
2340        xmppConnectionService.getNotificationService().cancelIncomingCallNotification();
2341        this.sendJingleMessage("reject");
2342        finish();
2343    }
2344
2345    private void rejectCallFromProceed() {
2346        this.sendJingleMessage("reject");
2347        closeTransitionLogFinish(State.REJECTED_RACED);
2348    }
2349
2350    private void rejectCallFromSessionInitiate() {
2351        webRTCWrapper.close();
2352        sendSessionTerminate(Reason.DECLINE);
2353        xmppConnectionService.getNotificationService().cancelIncomingCallNotification();
2354    }
2355
2356    private void sendJingleMessage(final String action) {
2357        sendJingleMessage(action, id.with);
2358    }
2359
2360    private void sendJingleMessage(final String action, final Jid to) {
2361        final var messagePacket = new im.conversations.android.xmpp.model.stanza.Message();
2362        messagePacket.setType(
2363                im.conversations.android.xmpp.model.stanza.Message.Type
2364                        .CHAT); // we want to carbon copy those
2365        messagePacket.setTo(to);
2366        final Element intent =
2367                messagePacket
2368                        .addChild(action, Namespace.JINGLE_MESSAGE)
2369                        .setAttribute("id", id.sessionId);
2370        if ("proceed".equals(action)) {
2371            messagePacket.setId(JINGLE_MESSAGE_PROCEED_ID_PREFIX + id.sessionId);
2372            if (isOmemoEnabled()) {
2373                final int deviceId = id.account.getAxolotlService().getOwnDeviceId();
2374                final Element device =
2375                        intent.addChild("device", Namespace.OMEMO_DTLS_SRTP_VERIFICATION);
2376                device.setAttribute("id", deviceId);
2377            }
2378        }
2379        messagePacket.addChild("store", "urn:xmpp:hints");
2380        xmppConnectionService.sendMessagePacket(id.account, messagePacket);
2381    }
2382
2383    private void sendJingleMessageFinish(final Reason reason) {
2384        final var account = id.getAccount();
2385        final var messagePacket =
2386                xmppConnectionService
2387                        .getMessageGenerator()
2388                        .sessionFinish(id.with, id.sessionId, reason);
2389        xmppConnectionService.sendMessagePacket(account, messagePacket);
2390    }
2391
2392    private boolean isOmemoEnabled() {
2393        final Conversational conversational = message.getConversation();
2394        if (conversational instanceof Conversation) {
2395            return ((Conversation) conversational).getNextEncryption()
2396                    == Message.ENCRYPTION_AXOLOTL;
2397        }
2398        return false;
2399    }
2400
2401    private void acceptCallFromSessionInitialized() {
2402        xmppConnectionService.getNotificationService().cancelIncomingCallNotification();
2403        this.callIntegration.startAudioRouting();
2404        sendSessionAccept();
2405    }
2406
2407    @Override
2408    protected synchronized boolean transition(final State target, final Runnable runnable) {
2409        if (super.transition(target, runnable)) {
2410            updateEndUserState();
2411            updateOngoingCallNotification();
2412            return true;
2413        } else {
2414            return false;
2415        }
2416    }
2417
2418    @Override
2419    public void onIceCandidate(final IceCandidate iceCandidate) {
2420        final RtpContentMap rtpContentMap =
2421                isInitiator() ? this.initiatorRtpContentMap : this.responderRtpContentMap;
2422        final IceUdpTransportInfo.Credentials credentials;
2423        try {
2424            credentials = rtpContentMap.getCredentials(iceCandidate.sdpMid);
2425        } catch (final IllegalArgumentException e) {
2426            Log.d(Config.LOGTAG, "ignoring (not sending) candidate: " + iceCandidate, e);
2427            return;
2428        }
2429        final String uFrag = credentials.ufrag;
2430        final IceUdpTransportInfo.Candidate candidate =
2431                IceUdpTransportInfo.Candidate.fromSdpAttribute(iceCandidate.sdp, uFrag);
2432        if (candidate == null) {
2433            Log.d(Config.LOGTAG, "ignoring (not sending) candidate: " + iceCandidate);
2434            return;
2435        }
2436        Log.d(Config.LOGTAG, "sending candidate: " + iceCandidate);
2437        sendTransportInfo(iceCandidate.sdpMid, candidate);
2438    }
2439
2440    @Override
2441    public void onConnectionChange(final PeerConnection.PeerConnectionState newState) {
2442        Log.d(
2443                Config.LOGTAG,
2444                id.account.getJid().asBareJid() + ": PeerConnectionState changed to " + newState);
2445        this.stateHistory.add(newState);
2446        if (newState == PeerConnection.PeerConnectionState.CONNECTED) {
2447            this.sessionDuration.start();
2448            updateOngoingCallNotification();
2449        } else if (this.sessionDuration.isRunning()) {
2450            this.sessionDuration.stop();
2451            updateOngoingCallNotification();
2452        }
2453
2454        final boolean neverConnected =
2455                !this.stateHistory.contains(PeerConnection.PeerConnectionState.CONNECTED);
2456
2457        if (newState == PeerConnection.PeerConnectionState.FAILED) {
2458            if (neverConnected) {
2459                if (isTerminated()) {
2460                    Log.d(
2461                            Config.LOGTAG,
2462                            id.account.getJid().asBareJid()
2463                                    + ": not sending session-terminate after connectivity error because session is already in state "
2464                                    + this.state);
2465                    return;
2466                }
2467                webRTCWrapper.execute(this::closeWebRTCSessionAfterFailedConnection);
2468                return;
2469            } else {
2470                this.restartIce();
2471            }
2472        }
2473        updateEndUserState();
2474    }
2475
2476    private void restartIce() {
2477        this.stateHistory.clear();
2478        this.webRTCWrapper.restartIceAsync();
2479    }
2480
2481    @Override
2482    public void onRenegotiationNeeded() {
2483        this.webRTCWrapper.execute(this::renegotiate);
2484    }
2485
2486    private synchronized void renegotiate() {
2487        final SessionDescription sessionDescription;
2488        try {
2489            sessionDescription = setLocalSessionDescription();
2490        } catch (final Exception e) {
2491            final Throwable cause = Throwables.getRootCause(e);
2492            webRTCWrapper.close();
2493            if (isTerminated()) {
2494                Log.d(
2495                        Config.LOGTAG,
2496                        "failed to renegotiate. session was already terminated",
2497                        cause);
2498                return;
2499            }
2500            Log.d(Config.LOGTAG, "failed to renegotiate. sending session-terminate", cause);
2501            sendSessionTerminate(Reason.FAILED_APPLICATION, cause.getMessage());
2502            return;
2503        }
2504        final RtpContentMap rtpContentMap = RtpContentMap.of(sessionDescription, isInitiator());
2505        final RtpContentMap currentContentMap = getLocalContentMap();
2506        final boolean iceRestart = currentContentMap.iceRestart(rtpContentMap);
2507        final RtpContentMap.Diff diff = currentContentMap.diff(rtpContentMap);
2508
2509        Log.d(
2510                Config.LOGTAG,
2511                id.getAccount().getJid().asBareJid()
2512                        + ": renegotiate. iceRestart="
2513                        + iceRestart
2514                        + " content id diff="
2515                        + diff);
2516
2517        if (diff.hasModifications() && iceRestart) {
2518            webRTCWrapper.close();
2519            sendSessionTerminate(
2520                    Reason.FAILED_APPLICATION,
2521                    "WebRTC unexpectedly tried to modify content and transport at once");
2522            return;
2523        }
2524
2525        if (iceRestart) {
2526            initiateIceRestart(rtpContentMap);
2527            return;
2528        } else if (diff.isEmpty()) {
2529            Log.d(
2530                    Config.LOGTAG,
2531                    "renegotiation. nothing to do. SignalingState="
2532                            + this.webRTCWrapper.getSignalingState());
2533        }
2534
2535        if (diff.added.isEmpty()) {
2536            return;
2537        }
2538        modifyLocalContentMap(rtpContentMap);
2539        sendContentAdd(rtpContentMap, diff.added);
2540    }
2541
2542    private void initiateIceRestart(final RtpContentMap rtpContentMap) {
2543        final RtpContentMap transportInfo = rtpContentMap.transportInfo();
2544        final Iq iq = transportInfo.toJinglePacket(Jingle.Action.TRANSPORT_INFO, id.sessionId);
2545        Log.d(Config.LOGTAG, "initiating ice restart: " + iq);
2546        iq.setTo(id.with);
2547        xmppConnectionService.sendIqPacket(
2548                id.account,
2549                iq,
2550                (response) -> {
2551                    if (response.getType() == Iq.Type.RESULT) {
2552                        Log.d(Config.LOGTAG, "received success to our ice restart");
2553                        setLocalContentMap(rtpContentMap);
2554                        webRTCWrapper.setIsReadyToReceiveIceCandidates(true);
2555                        return;
2556                    }
2557                    if (response.getType() == Iq.Type.ERROR) {
2558                        if (isTieBreak(response)) {
2559                            Log.d(Config.LOGTAG, "received tie-break as result of ice restart");
2560                            return;
2561                        }
2562                        handleIqErrorResponse(response);
2563                    }
2564                    if (response.getType() == Iq.Type.TIMEOUT) {
2565                        handleIqTimeoutResponse(response);
2566                    }
2567                });
2568    }
2569
2570    private boolean isTieBreak(final Iq response) {
2571        final Element error = response.findChild("error");
2572        return error != null && error.hasChild("tie-break", Namespace.JINGLE_ERRORS);
2573    }
2574
2575    private void sendContentAdd(final RtpContentMap rtpContentMap, final Collection<String> added) {
2576        final RtpContentMap contentAdd = rtpContentMap.toContentModification(added);
2577        this.outgoingContentAdd = contentAdd;
2578        final ListenableFuture<RtpContentMap> outgoingContentMapFuture =
2579                prepareOutgoingContentMap(contentAdd);
2580        Futures.addCallback(
2581                outgoingContentMapFuture,
2582                new FutureCallback<>() {
2583                    @Override
2584                    public void onSuccess(final RtpContentMap outgoingContentMap) {
2585                        sendContentAdd(outgoingContentMap);
2586                        webRTCWrapper.setIsReadyToReceiveIceCandidates(true);
2587                    }
2588
2589                    @Override
2590                    public void onFailure(@NonNull Throwable throwable) {
2591                        failureToPerformAction(Jingle.Action.CONTENT_ADD, throwable);
2592                    }
2593                },
2594                MoreExecutors.directExecutor());
2595    }
2596
2597    private void sendContentAdd(final RtpContentMap contentAdd) {
2598
2599        final Iq iq = contentAdd.toJinglePacket(Jingle.Action.CONTENT_ADD, id.sessionId);
2600        iq.setTo(id.with);
2601        xmppConnectionService.sendIqPacket(
2602                id.account,
2603                iq,
2604                (response) -> {
2605                    if (response.getType() == Iq.Type.RESULT) {
2606                        Log.d(
2607                                Config.LOGTAG,
2608                                id.getAccount().getJid().asBareJid()
2609                                        + ": received ACK to our content-add");
2610                        return;
2611                    }
2612                    if (response.getType() == Iq.Type.ERROR) {
2613                        if (isTieBreak(response)) {
2614                            this.outgoingContentAdd = null;
2615                            Log.d(Config.LOGTAG, "received tie-break as result of our content-add");
2616                            return;
2617                        }
2618                        handleIqErrorResponse(response);
2619                    }
2620                    if (response.getType() == Iq.Type.TIMEOUT) {
2621                        handleIqTimeoutResponse(response);
2622                    }
2623                });
2624    }
2625
2626    private void setLocalContentMap(final RtpContentMap rtpContentMap) {
2627        if (isInitiator()) {
2628            this.initiatorRtpContentMap = rtpContentMap;
2629        } else {
2630            this.responderRtpContentMap = rtpContentMap;
2631        }
2632    }
2633
2634    private void setRemoteContentMap(final RtpContentMap rtpContentMap) {
2635        if (isInitiator()) {
2636            this.responderRtpContentMap = rtpContentMap;
2637        } else {
2638            this.initiatorRtpContentMap = rtpContentMap;
2639        }
2640    }
2641
2642    // this method is to be used for content map modifications that modify media
2643    private void modifyLocalContentMap(final RtpContentMap rtpContentMap) {
2644        final RtpContentMap activeContents = rtpContentMap.activeContents();
2645        setLocalContentMap(activeContents);
2646        this.callIntegration.setAudioDeviceWhenAvailable(
2647                CallIntegration.initialAudioDevice(activeContents.getMedia()));
2648        updateEndUserState();
2649    }
2650
2651    private SessionDescription setLocalSessionDescription()
2652            throws ExecutionException, InterruptedException {
2653        final org.webrtc.SessionDescription sessionDescription =
2654                this.webRTCWrapper.setLocalDescription(false).get();
2655        return SessionDescription.parse(sessionDescription.description);
2656    }
2657
2658    private void closeWebRTCSessionAfterFailedConnection() {
2659        this.webRTCWrapper.close();
2660        synchronized (this) {
2661            if (isTerminated()) {
2662                Log.d(
2663                        Config.LOGTAG,
2664                        id.account.getJid().asBareJid()
2665                                + ": no need to send session-terminate after failed connection. Other party already did");
2666                return;
2667            }
2668            sendSessionTerminate(Reason.CONNECTIVITY_ERROR);
2669        }
2670    }
2671
2672    public boolean zeroDuration() {
2673        return this.sessionDuration.elapsed(TimeUnit.NANOSECONDS) <= 0;
2674    }
2675
2676    public long getCallDuration() {
2677        return this.sessionDuration.elapsed(TimeUnit.MILLISECONDS);
2678    }
2679
2680    @Override
2681    public CallIntegration getCallIntegration() {
2682        return this.callIntegration;
2683    }
2684
2685    public boolean isMicrophoneEnabled() {
2686        return webRTCWrapper.isMicrophoneEnabled();
2687    }
2688
2689    public boolean setMicrophoneEnabled(final boolean enabled) {
2690        return webRTCWrapper.setMicrophoneEnabledOrThrow(enabled);
2691    }
2692
2693    public boolean isVideoEnabled() {
2694        return webRTCWrapper.isVideoEnabled();
2695    }
2696
2697    public void setVideoEnabled(final boolean enabled) {
2698        webRTCWrapper.setVideoEnabled(enabled);
2699    }
2700
2701    public boolean isCameraSwitchable() {
2702        return webRTCWrapper.isCameraSwitchable();
2703    }
2704
2705    public boolean isFrontCamera() {
2706        return webRTCWrapper.isFrontCamera();
2707    }
2708
2709    public ListenableFuture<Boolean> switchCamera() {
2710        return webRTCWrapper.switchCamera();
2711    }
2712
2713    @Override
2714    public synchronized void onCallIntegrationShowIncomingCallUi() {
2715        if (isTerminated()) {
2716            // there might be race conditions with the call integration service invoking this
2717            // callback when the rtp session has already ended.
2718            Log.w(
2719                    Config.LOGTAG,
2720                    "CallIntegration requested incoming call UI but session was already terminated");
2721            return;
2722        }
2723        // TODO apparently this can be called too early as well?
2724        xmppConnectionService.getNotificationService().startRinging(id, getMedia());
2725    }
2726
2727    @Override
2728    public void onCallIntegrationDisconnect() {
2729        Log.d(Config.LOGTAG, "a phone call has just been started. killing jingle rtp connections");
2730        if (Arrays.asList(State.PROPOSED, State.SESSION_INITIALIZED).contains(this.state)) {
2731            rejectCall();
2732        } else {
2733            endCall();
2734        }
2735    }
2736
2737    @Override
2738    public void onCallIntegrationReject() {
2739        Log.d(Config.LOGTAG, "rejecting call from system notification / call integration");
2740        try {
2741            rejectCall();
2742        } catch (final IllegalStateException e) {
2743            Log.w(Config.LOGTAG, "race condition on rejecting call from notification", e);
2744        }
2745    }
2746
2747    @Override
2748    public void onCallIntegrationAnswer() {
2749        // we need to start the UI to a) show it and b) be able to ask for permissions
2750        final Intent intent = new Intent(xmppConnectionService, RtpSessionActivity.class);
2751        intent.setAction(RtpSessionActivity.ACTION_ACCEPT_CALL);
2752        intent.putExtra(RtpSessionActivity.EXTRA_ACCOUNT, id.account.getJid().toEscapedString());
2753        intent.putExtra(RtpSessionActivity.EXTRA_WITH, id.with.toEscapedString());
2754        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2755        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
2756        intent.putExtra(RtpSessionActivity.EXTRA_SESSION_ID, id.sessionId);
2757        Log.d(Config.LOGTAG, "start activity to accept call from call integration");
2758        xmppConnectionService.startActivity(intent);
2759    }
2760
2761    @Override
2762    public void onCallIntegrationSilence() {
2763        xmppConnectionService.getNotificationService().stopSoundAndVibration();
2764    }
2765
2766    @Override
2767    public void onCallIntegrationMicrophoneEnabled(final boolean enabled) {
2768        // this is called every time we switch audio devices. Thus it would re-enable a microphone
2769        // that was previous disabled by the user. A proper implementation would probably be to
2770        // track user choice and enable the microphone with a userEnabled() &&
2771        // callIntegration.isMicrophoneEnabled() condition
2772        Log.d(Config.LOGTAG, "ignoring onCallIntegrationMicrophoneEnabled(" + enabled + ")");
2773        // this.webRTCWrapper.setMicrophoneEnabled(enabled);
2774    }
2775
2776    @Override
2777    public void onAudioDeviceChanged(
2778            final CallIntegration.AudioDevice selectedAudioDevice,
2779            final Set<CallIntegration.AudioDevice> availableAudioDevices) {
2780        Log.d(
2781                Config.LOGTAG,
2782                "onAudioDeviceChanged(" + selectedAudioDevice + "," + availableAudioDevices + ")");
2783        xmppConnectionService.notifyJingleRtpConnectionUpdate(
2784                selectedAudioDevice, availableAudioDevices);
2785    }
2786
2787    private void updateEndUserState() {
2788        final RtpEndUserState endUserState = getEndUserState();
2789        this.updateCallIntegrationState();
2790        xmppConnectionService.notifyJingleRtpConnectionUpdate(
2791                id.account, id.with, id.sessionId, endUserState);
2792    }
2793
2794    private void updateOngoingCallNotification() {
2795        final State state = this.state;
2796        if (STATES_SHOWING_ONGOING_CALL.contains(state)) {
2797            if (Arrays.asList(State.PROPOSED, State.SESSION_INITIALIZED).contains(state)
2798                    && isResponder()) {
2799                Log.d(Config.LOGTAG, "do not set ongoing call during incoming call notification");
2800                xmppConnectionService.removeOngoingCall();
2801                return;
2802            }
2803            final boolean reconnecting;
2804            if (state == State.SESSION_ACCEPTED) {
2805                reconnecting =
2806                        getPeerConnectionStateAsEndUserState() == RtpEndUserState.RECONNECTING;
2807            } else {
2808                reconnecting = false;
2809            }
2810            xmppConnectionService.setOngoingCall(id, getMedia(), reconnecting);
2811        } else {
2812            xmppConnectionService.removeOngoingCall();
2813        }
2814    }
2815
2816    private void discoverIceServers(final OnIceServersDiscovered onIceServersDiscovered) {
2817        if (id.account.getXmppConnection().getFeatures().externalServiceDiscovery()) {
2818            final Iq request = new Iq(Iq.Type.GET);
2819            request.setTo(id.account.getDomain());
2820            request.addChild("services", Namespace.EXTERNAL_SERVICE_DISCOVERY);
2821            xmppConnectionService.sendIqPacket(
2822                    id.account,
2823                    request,
2824                    (response) -> {
2825                        final var iceServers = IceServers.parse(response);
2826                        if (iceServers.isEmpty()) {
2827                            Log.w(
2828                                    Config.LOGTAG,
2829                                    id.account.getJid().asBareJid()
2830                                            + ": no ICE server found "
2831                                            + response);
2832                        }
2833                        onIceServersDiscovered.onIceServersDiscovered(iceServers);
2834                    });
2835        } else {
2836            Log.w(
2837                    Config.LOGTAG,
2838                    id.account.getJid().asBareJid() + ": has no external service discovery");
2839            onIceServersDiscovered.onIceServersDiscovered(Collections.emptyList());
2840        }
2841    }
2842
2843    @Override
2844    protected void terminateTransport() {
2845        this.webRTCWrapper.close();
2846    }
2847
2848    @Override
2849    protected void finish() {
2850        if (isTerminated()) {
2851            this.cancelRingingTimeout();
2852            this.callIntegration.verifyDisconnected();
2853            this.webRTCWrapper.verifyClosed();
2854            this.jingleConnectionManager.setTerminalSessionState(id, getEndUserState(), getMedia());
2855            super.finish();
2856        } else {
2857            throw new IllegalStateException(
2858                    String.format("Unable to call finish from %s", this.state));
2859        }
2860    }
2861
2862    private void writeLogMessage(final State state) {
2863        final long duration = getCallDuration();
2864        if (state == State.TERMINATED_SUCCESS
2865                || (state == State.TERMINATED_CONNECTIVITY_ERROR && duration > 0)) {
2866            writeLogMessageSuccess(duration);
2867        } else {
2868            writeLogMessageMissed();
2869        }
2870    }
2871
2872    private void writeLogMessageSuccess(final long duration) {
2873        this.message.setBody(new RtpSessionStatus(true, duration).toString());
2874        this.writeMessage();
2875    }
2876
2877    private void writeLogMessageMissed() {
2878        this.message.setBody(new RtpSessionStatus(false, 0).toString());
2879        this.writeMessage();
2880    }
2881
2882    private void writeMessage() {
2883        final Conversational conversational = message.getConversation();
2884        if (conversational instanceof Conversation) {
2885            ((Conversation) conversational).add(this.message);
2886            xmppConnectionService.createMessageAsync(message);
2887            xmppConnectionService.updateConversationUi();
2888        } else {
2889            throw new IllegalStateException("Somehow the conversation in a message was a stub");
2890        }
2891    }
2892
2893    public Optional<VideoTrack> getLocalVideoTrack() {
2894        return webRTCWrapper.getLocalVideoTrack();
2895    }
2896
2897    public Optional<VideoTrack> getRemoteVideoTrack() {
2898        return webRTCWrapper.getRemoteVideoTrack();
2899    }
2900
2901    public EglBase.Context getEglBaseContext() {
2902        return webRTCWrapper.getEglBaseContext();
2903    }
2904
2905    void setProposedMedia(final Set<Media> media) {
2906        this.proposedMedia = media;
2907        this.callIntegration.setVideoState(
2908                Media.audioOnly(media)
2909                        ? VideoProfile.STATE_AUDIO_ONLY
2910                        : VideoProfile.STATE_BIDIRECTIONAL);
2911        this.callIntegration.setInitialAudioDevice(CallIntegration.initialAudioDevice(media));
2912    }
2913
2914    public void fireStateUpdate() {
2915        final RtpEndUserState endUserState = getEndUserState();
2916        xmppConnectionService.notifyJingleRtpConnectionUpdate(
2917                id.account, id.with, id.sessionId, endUserState);
2918    }
2919
2920    public boolean isSwitchToVideoAvailable() {
2921        final boolean prerequisite =
2922                Media.audioOnly(getMedia())
2923                        && Arrays.asList(RtpEndUserState.CONNECTED, RtpEndUserState.RECONNECTING)
2924                                .contains(getEndUserState());
2925        return prerequisite && remoteHasVideoFeature();
2926    }
2927
2928    private boolean remoteHasVideoFeature() {
2929        return remoteHasFeature(Namespace.JINGLE_FEATURE_VIDEO);
2930    }
2931
2932    private boolean remoteHasSdpOfferAnswer() {
2933        return remoteHasFeature(Namespace.SDP_OFFER_ANSWER);
2934    }
2935
2936    @Override
2937    public Account getAccount() {
2938        return id.account;
2939    }
2940
2941    @Override
2942    public Jid getWith() {
2943        return id.with;
2944    }
2945
2946    @Override
2947    public String getSessionId() {
2948        return id.sessionId;
2949    }
2950
2951    private interface OnIceServersDiscovered {
2952        void onIceServersDiscovered(List<PeerConnection.IceServer> iceServers);
2953    }
2954}