JingleRtpConnection.java

   1package eu.siacs.conversations.xmpp.jingle;
   2
   3import android.os.SystemClock;
   4import android.util.Log;
   5
   6import com.google.common.base.Optional;
   7import com.google.common.base.Preconditions;
   8import com.google.common.base.Strings;
   9import com.google.common.base.Throwables;
  10import com.google.common.collect.Collections2;
  11import com.google.common.collect.ImmutableList;
  12import com.google.common.collect.ImmutableMap;
  13import com.google.common.collect.Sets;
  14import com.google.common.primitives.Ints;
  15import com.google.common.util.concurrent.ListenableFuture;
  16
  17import org.webrtc.EglBase;
  18import org.webrtc.IceCandidate;
  19import org.webrtc.PeerConnection;
  20import org.webrtc.VideoTrack;
  21
  22import java.util.ArrayDeque;
  23import java.util.Arrays;
  24import java.util.Collection;
  25import java.util.Collections;
  26import java.util.List;
  27import java.util.Map;
  28import java.util.Set;
  29import java.util.concurrent.ScheduledFuture;
  30import java.util.concurrent.TimeUnit;
  31
  32import eu.siacs.conversations.Config;
  33import eu.siacs.conversations.crypto.axolotl.AxolotlService;
  34import eu.siacs.conversations.crypto.axolotl.CryptoFailedException;
  35import eu.siacs.conversations.entities.Account;
  36import eu.siacs.conversations.entities.Conversation;
  37import eu.siacs.conversations.entities.Conversational;
  38import eu.siacs.conversations.entities.Message;
  39import eu.siacs.conversations.entities.RtpSessionStatus;
  40import eu.siacs.conversations.services.AppRTCAudioManager;
  41import eu.siacs.conversations.utils.IP;
  42import eu.siacs.conversations.xml.Element;
  43import eu.siacs.conversations.xml.Namespace;
  44import eu.siacs.conversations.xmpp.Jid;
  45import eu.siacs.conversations.xmpp.jingle.stanzas.Group;
  46import eu.siacs.conversations.xmpp.jingle.stanzas.IceUdpTransportInfo;
  47import eu.siacs.conversations.xmpp.jingle.stanzas.JinglePacket;
  48import eu.siacs.conversations.xmpp.jingle.stanzas.Proceed;
  49import eu.siacs.conversations.xmpp.jingle.stanzas.Propose;
  50import eu.siacs.conversations.xmpp.jingle.stanzas.Reason;
  51import eu.siacs.conversations.xmpp.jingle.stanzas.RtpDescription;
  52import eu.siacs.conversations.xmpp.stanzas.IqPacket;
  53import eu.siacs.conversations.xmpp.stanzas.MessagePacket;
  54
  55public class JingleRtpConnection extends AbstractJingleConnection implements WebRTCWrapper.EventCallback {
  56
  57    public static final List<State> STATES_SHOWING_ONGOING_CALL = Arrays.asList(
  58            State.PROCEED,
  59            State.SESSION_INITIALIZED_PRE_APPROVED,
  60            State.SESSION_ACCEPTED
  61    );
  62    private static final long BUSY_TIME_OUT = 30;
  63    private static final List<State> TERMINATED = Arrays.asList(
  64            State.ACCEPTED,
  65            State.REJECTED,
  66            State.REJECTED_RACED,
  67            State.RETRACTED,
  68            State.RETRACTED_RACED,
  69            State.TERMINATED_SUCCESS,
  70            State.TERMINATED_DECLINED_OR_BUSY,
  71            State.TERMINATED_CONNECTIVITY_ERROR,
  72            State.TERMINATED_CANCEL_OR_TIMEOUT,
  73            State.TERMINATED_APPLICATION_FAILURE
  74    );
  75
  76    private static final Map<State, Collection<State>> VALID_TRANSITIONS;
  77
  78    static {
  79        final ImmutableMap.Builder<State, Collection<State>> transitionBuilder = new ImmutableMap.Builder<>();
  80        transitionBuilder.put(State.NULL, ImmutableList.of(
  81                State.PROPOSED,
  82                State.SESSION_INITIALIZED,
  83                State.TERMINATED_APPLICATION_FAILURE
  84        ));
  85        transitionBuilder.put(State.PROPOSED, ImmutableList.of(
  86                State.ACCEPTED,
  87                State.PROCEED,
  88                State.REJECTED,
  89                State.RETRACTED,
  90                State.TERMINATED_APPLICATION_FAILURE,
  91                State.TERMINATED_CONNECTIVITY_ERROR //only used when the xmpp connection rebinds
  92        ));
  93        transitionBuilder.put(State.PROCEED, ImmutableList.of(
  94                State.REJECTED_RACED,
  95                State.RETRACTED_RACED,
  96                State.SESSION_INITIALIZED_PRE_APPROVED,
  97                State.TERMINATED_SUCCESS,
  98                State.TERMINATED_APPLICATION_FAILURE,
  99                State.TERMINATED_CONNECTIVITY_ERROR //at this state used for error bounces of the proceed message
 100        ));
 101        transitionBuilder.put(State.SESSION_INITIALIZED, ImmutableList.of(
 102                State.SESSION_ACCEPTED,
 103                State.TERMINATED_SUCCESS,
 104                State.TERMINATED_DECLINED_OR_BUSY,
 105                State.TERMINATED_CONNECTIVITY_ERROR,  //at this state used for IQ errors and IQ timeouts
 106                State.TERMINATED_CANCEL_OR_TIMEOUT,
 107                State.TERMINATED_APPLICATION_FAILURE
 108        ));
 109        transitionBuilder.put(State.SESSION_INITIALIZED_PRE_APPROVED, ImmutableList.of(
 110                State.SESSION_ACCEPTED,
 111                State.TERMINATED_SUCCESS,
 112                State.TERMINATED_DECLINED_OR_BUSY,
 113                State.TERMINATED_CONNECTIVITY_ERROR,  //at this state used for IQ errors and IQ timeouts
 114                State.TERMINATED_CANCEL_OR_TIMEOUT,
 115                State.TERMINATED_APPLICATION_FAILURE
 116        ));
 117        transitionBuilder.put(State.SESSION_ACCEPTED, ImmutableList.of(
 118                State.TERMINATED_SUCCESS,
 119                State.TERMINATED_DECLINED_OR_BUSY,
 120                State.TERMINATED_CONNECTIVITY_ERROR,
 121                State.TERMINATED_CANCEL_OR_TIMEOUT,
 122                State.TERMINATED_APPLICATION_FAILURE
 123        ));
 124        VALID_TRANSITIONS = transitionBuilder.build();
 125    }
 126
 127    private final WebRTCWrapper webRTCWrapper = new WebRTCWrapper(this);
 128    private final ArrayDeque<Set<Map.Entry<String, RtpContentMap.DescriptionTransport>>> pendingIceCandidates = new ArrayDeque<>();
 129    private final OmemoVerification omemoVerification = new OmemoVerification();
 130    private final Message message;
 131    private State state = State.NULL;
 132    private StateTransitionException stateTransitionException;
 133    private Set<Media> proposedMedia;
 134    private RtpContentMap initiatorRtpContentMap;
 135    private RtpContentMap responderRtpContentMap;
 136    private long rtpConnectionStarted = 0; //time of 'connected'
 137    private long rtpConnectionEnded = 0;
 138    private ScheduledFuture<?> ringingTimeoutFuture;
 139
 140    JingleRtpConnection(JingleConnectionManager jingleConnectionManager, Id id, Jid initiator) {
 141        super(jingleConnectionManager, id, initiator);
 142        final Conversation conversation = jingleConnectionManager.getXmppConnectionService().findOrCreateConversation(
 143                id.account,
 144                id.with.asBareJid(),
 145                false,
 146                false
 147        );
 148        this.message = new Message(
 149                conversation,
 150                isInitiator() ? Message.STATUS_SEND : Message.STATUS_RECEIVED,
 151                Message.TYPE_RTP_SESSION,
 152                id.sessionId
 153        );
 154    }
 155
 156    private static State reasonToState(Reason reason) {
 157        switch (reason) {
 158            case SUCCESS:
 159                return State.TERMINATED_SUCCESS;
 160            case DECLINE:
 161            case BUSY:
 162                return State.TERMINATED_DECLINED_OR_BUSY;
 163            case CANCEL:
 164            case TIMEOUT:
 165                return State.TERMINATED_CANCEL_OR_TIMEOUT;
 166            case FAILED_APPLICATION:
 167            case SECURITY_ERROR:
 168            case UNSUPPORTED_TRANSPORTS:
 169            case UNSUPPORTED_APPLICATIONS:
 170                return State.TERMINATED_APPLICATION_FAILURE;
 171            default:
 172                return State.TERMINATED_CONNECTIVITY_ERROR;
 173        }
 174    }
 175
 176    @Override
 177    synchronized void deliverPacket(final JinglePacket jinglePacket) {
 178        Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": packet delivered to JingleRtpConnection");
 179        switch (jinglePacket.getAction()) {
 180            case SESSION_INITIATE:
 181                receiveSessionInitiate(jinglePacket);
 182                break;
 183            case TRANSPORT_INFO:
 184                receiveTransportInfo(jinglePacket);
 185                break;
 186            case SESSION_ACCEPT:
 187                receiveSessionAccept(jinglePacket);
 188                break;
 189            case SESSION_TERMINATE:
 190                receiveSessionTerminate(jinglePacket);
 191                break;
 192            default:
 193                respondOk(jinglePacket);
 194                Log.d(Config.LOGTAG, String.format("%s: received unhandled jingle action %s", id.account.getJid().asBareJid(), jinglePacket.getAction()));
 195                break;
 196        }
 197    }
 198
 199    @Override
 200    synchronized void notifyRebound() {
 201        if (isTerminated()) {
 202            return;
 203        }
 204        webRTCWrapper.close();
 205        if (!isInitiator() && isInState(State.PROPOSED, State.SESSION_INITIALIZED)) {
 206            xmppConnectionService.getNotificationService().cancelIncomingCallNotification();
 207        }
 208        if (isInState(State.SESSION_INITIALIZED, State.SESSION_INITIALIZED_PRE_APPROVED, State.SESSION_ACCEPTED)) {
 209            //we might have already changed resources (full jid) at this point; so this might not even reach the other party
 210            sendSessionTerminate(Reason.CONNECTIVITY_ERROR);
 211        } else {
 212            transitionOrThrow(State.TERMINATED_CONNECTIVITY_ERROR);
 213            finish();
 214        }
 215    }
 216
 217    private void receiveSessionTerminate(final JinglePacket jinglePacket) {
 218        respondOk(jinglePacket);
 219        final JinglePacket.ReasonWrapper wrapper = jinglePacket.getReason();
 220        final State previous = this.state;
 221        Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": received session terminate reason=" + wrapper.reason + "(" + Strings.nullToEmpty(wrapper.text) + ") while in state " + previous);
 222        if (TERMINATED.contains(previous)) {
 223            Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": ignoring session terminate because already in " + previous);
 224            return;
 225        }
 226        webRTCWrapper.close();
 227        final State target = reasonToState(wrapper.reason);
 228        transitionOrThrow(target);
 229        writeLogMessage(target);
 230        if (previous == State.PROPOSED || previous == State.SESSION_INITIALIZED) {
 231            xmppConnectionService.getNotificationService().cancelIncomingCallNotification();
 232        }
 233        finish();
 234    }
 235
 236    private void receiveTransportInfo(final JinglePacket jinglePacket) {
 237        if (isInState(State.SESSION_INITIALIZED, State.SESSION_INITIALIZED_PRE_APPROVED, State.SESSION_ACCEPTED)) {
 238            respondOk(jinglePacket);
 239            final RtpContentMap contentMap;
 240            try {
 241                contentMap = RtpContentMap.of(jinglePacket);
 242            } catch (IllegalArgumentException | NullPointerException e) {
 243                Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": improperly formatted contents; ignoring", e);
 244                return;
 245            }
 246            final Set<Map.Entry<String, RtpContentMap.DescriptionTransport>> candidates = contentMap.contents.entrySet();
 247            if (this.state == State.SESSION_ACCEPTED) {
 248                try {
 249                    processCandidates(candidates);
 250                } catch (final WebRTCWrapper.PeerConnectionNotInitialized e) {
 251                    Log.w(Config.LOGTAG, id.account.getJid().asBareJid() + ": PeerConnection was not initialized when processing transport info. this usually indicates a race condition that can be ignored");
 252                }
 253            } else {
 254                pendingIceCandidates.push(candidates);
 255            }
 256        } else {
 257            if (isTerminated()) {
 258                respondOk(jinglePacket);
 259                Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": ignoring out-of-order transport info; we where already terminated");
 260            } else {
 261                Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": received transport info while in state=" + this.state);
 262                terminateWithOutOfOrder(jinglePacket);
 263            }
 264        }
 265    }
 266
 267    private void processCandidates(final Set<Map.Entry<String, RtpContentMap.DescriptionTransport>> contents) {
 268        final RtpContentMap rtpContentMap = isInitiator() ? this.responderRtpContentMap : this.initiatorRtpContentMap;
 269        final Group originalGroup = rtpContentMap.group;
 270        final List<String> identificationTags = originalGroup == null ? rtpContentMap.getNames() : originalGroup.getIdentificationTags();
 271        if (identificationTags.size() == 0) {
 272            Log.w(Config.LOGTAG, id.account.getJid().asBareJid() + ": no identification tags found in initial offer. we won't be able to calculate mLineIndices");
 273        }
 274        processCandidates(identificationTags, contents);
 275    }
 276
 277    private void processCandidates(final List<String> indices, final Set<Map.Entry<String, RtpContentMap.DescriptionTransport>> contents) {
 278        for (final Map.Entry<String, RtpContentMap.DescriptionTransport> content : contents) {
 279            final String ufrag = content.getValue().transport.getAttribute("ufrag");
 280            for (final IceUdpTransportInfo.Candidate candidate : content.getValue().transport.getCandidates()) {
 281                final String sdp;
 282                try {
 283                    sdp = candidate.toSdpAttribute(ufrag);
 284                } catch (IllegalArgumentException e) {
 285                    Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": ignoring invalid ICE candidate " + e.getMessage());
 286                    continue;
 287                }
 288                final String sdpMid = content.getKey();
 289                final int mLineIndex = indices.indexOf(sdpMid);
 290                final IceCandidate iceCandidate = new IceCandidate(sdpMid, mLineIndex, sdp);
 291                Log.d(Config.LOGTAG, "received candidate: " + iceCandidate);
 292                this.webRTCWrapper.addIceCandidate(iceCandidate);
 293            }
 294        }
 295    }
 296
 297    private RtpContentMap receiveRtpContentMap(final JinglePacket jinglePacket, final boolean expectVerification) {
 298        final RtpContentMap receivedContentMap = RtpContentMap.of(jinglePacket);
 299        if (receivedContentMap instanceof OmemoVerifiedRtpContentMap) {
 300            final AxolotlService.OmemoVerifiedPayload<RtpContentMap> omemoVerifiedPayload;
 301            try {
 302                omemoVerifiedPayload = id.account.getAxolotlService().decrypt((OmemoVerifiedRtpContentMap) receivedContentMap, id.with);
 303            } catch (final CryptoFailedException e) {
 304                throw new SecurityException("Unable to verify DTLS Fingerprint with OMEMO", e);
 305            }
 306            this.omemoVerification.setOrEnsureEqual(omemoVerifiedPayload);
 307            Log.d(Config.LOGTAG,id.account.getJid().asBareJid()+": received verifiable DTLS fingerprint via "+this.omemoVerification);
 308            return omemoVerifiedPayload.getPayload();
 309        } else if (expectVerification) {
 310            throw new SecurityException("DTLS fingerprint was unexpectedly not verifiable");
 311        } else {
 312            return receivedContentMap;
 313        }
 314    }
 315
 316    private void receiveSessionInitiate(final JinglePacket jinglePacket) {
 317        if (isInitiator()) {
 318            Log.d(Config.LOGTAG, String.format("%s: received session-initiate even though we were initiating", id.account.getJid().asBareJid()));
 319            terminateWithOutOfOrder(jinglePacket);
 320            return;
 321        }
 322        final RtpContentMap contentMap;
 323        try {
 324            contentMap = receiveRtpContentMap(jinglePacket, false);
 325            contentMap.requireContentDescriptions();
 326            contentMap.requireDTLSFingerprint();
 327        } catch (final RuntimeException e) {
 328            Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": improperly formatted contents", Throwables.getRootCause(e));
 329            respondOk(jinglePacket);
 330            sendSessionTerminate(Reason.of(e), e.getMessage());
 331            return;
 332        }
 333        Log.d(Config.LOGTAG, "processing session-init with " + contentMap.contents.size() + " contents");
 334        final State target;
 335        if (this.state == State.PROCEED) {
 336            Preconditions.checkState(
 337                    proposedMedia != null && proposedMedia.size() > 0,
 338                    "proposed media must be set when processing pre-approved session-initiate"
 339            );
 340            if (!this.proposedMedia.equals(contentMap.getMedia())) {
 341                sendSessionTerminate(Reason.SECURITY_ERROR, String.format(
 342                        "Your session proposal (Jingle Message Initiation) included media %s but your session-initiate was %s",
 343                        this.proposedMedia,
 344                        contentMap.getMedia()
 345                ));
 346                return;
 347            }
 348            target = State.SESSION_INITIALIZED_PRE_APPROVED;
 349        } else {
 350            target = State.SESSION_INITIALIZED;
 351        }
 352        if (transition(target, () -> this.initiatorRtpContentMap = contentMap)) {
 353            respondOk(jinglePacket);
 354            //TODO Do not push empty set
 355            pendingIceCandidates.push(contentMap.contents.entrySet());
 356            if (target == State.SESSION_INITIALIZED_PRE_APPROVED) {
 357                Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": automatically accepting session-initiate");
 358                sendSessionAccept();
 359            } else {
 360                Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": received not pre-approved session-initiate. start ringing");
 361                startRinging();
 362            }
 363        } else {
 364            Log.d(Config.LOGTAG, String.format("%s: received session-initiate while in state %s", id.account.getJid().asBareJid(), state));
 365            terminateWithOutOfOrder(jinglePacket);
 366        }
 367    }
 368
 369    private void receiveSessionAccept(final JinglePacket jinglePacket) {
 370        if (!isInitiator()) {
 371            Log.d(Config.LOGTAG, String.format("%s: received session-accept even though we were responding", id.account.getJid().asBareJid()));
 372            terminateWithOutOfOrder(jinglePacket);
 373            return;
 374        }
 375        final RtpContentMap contentMap;
 376        try {
 377            contentMap = receiveRtpContentMap(jinglePacket, this.omemoVerification.hasFingerprint());
 378            contentMap.requireContentDescriptions();
 379            contentMap.requireDTLSFingerprint();
 380        } catch (final RuntimeException e) {
 381            respondOk(jinglePacket);
 382            Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": improperly formatted contents in session-accept", e);
 383            webRTCWrapper.close();
 384            sendSessionTerminate(Reason.of(e), e.getMessage());
 385            return;
 386        }
 387        final Set<Media> initiatorMedia = this.initiatorRtpContentMap.getMedia();
 388        if (!initiatorMedia.equals(contentMap.getMedia())) {
 389            sendSessionTerminate(Reason.SECURITY_ERROR, String.format(
 390                    "Your session-included included media %s but our session-initiate was %s",
 391                    this.proposedMedia,
 392                    contentMap.getMedia()
 393            ));
 394            return;
 395        }
 396        Log.d(Config.LOGTAG, "processing session-accept with " + contentMap.contents.size() + " contents");
 397        if (transition(State.SESSION_ACCEPTED)) {
 398            respondOk(jinglePacket);
 399            receiveSessionAccept(contentMap);
 400        } else {
 401            Log.d(Config.LOGTAG, String.format("%s: received session-accept while in state %s", id.account.getJid().asBareJid(), state));
 402            respondOk(jinglePacket);
 403        }
 404    }
 405
 406    private void receiveSessionAccept(final RtpContentMap contentMap) {
 407        this.responderRtpContentMap = contentMap;
 408        final SessionDescription sessionDescription;
 409        try {
 410            sessionDescription = SessionDescription.of(contentMap);
 411        } catch (final IllegalArgumentException | NullPointerException e) {
 412            Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": unable convert offer from session-accept to SDP", e);
 413            webRTCWrapper.close();
 414            sendSessionTerminate(Reason.FAILED_APPLICATION, e.getMessage());
 415            return;
 416        }
 417        final org.webrtc.SessionDescription answer = new org.webrtc.SessionDescription(
 418                org.webrtc.SessionDescription.Type.ANSWER,
 419                sessionDescription.toString()
 420        );
 421        try {
 422            this.webRTCWrapper.setRemoteDescription(answer).get();
 423        } catch (final Exception e) {
 424            Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": unable to set remote description after receiving session-accept", Throwables.getRootCause(e));
 425            webRTCWrapper.close();
 426            sendSessionTerminate(Reason.FAILED_APPLICATION);
 427            return;
 428        }
 429        final List<String> identificationTags = contentMap.group == null ? contentMap.getNames() : contentMap.group.getIdentificationTags();
 430        processCandidates(identificationTags, contentMap.contents.entrySet());
 431    }
 432
 433    private void sendSessionAccept() {
 434        final RtpContentMap rtpContentMap = this.initiatorRtpContentMap;
 435        if (rtpContentMap == null) {
 436            throw new IllegalStateException("initiator RTP Content Map has not been set");
 437        }
 438        final SessionDescription offer;
 439        try {
 440            offer = SessionDescription.of(rtpContentMap);
 441        } catch (final IllegalArgumentException | NullPointerException e) {
 442            Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": unable convert offer from session-initiate to SDP", e);
 443            webRTCWrapper.close();
 444            sendSessionTerminate(Reason.FAILED_APPLICATION, e.getMessage());
 445            return;
 446        }
 447        sendSessionAccept(rtpContentMap.getMedia(), offer);
 448    }
 449
 450    private void sendSessionAccept(final Set<Media> media, final SessionDescription offer) {
 451        discoverIceServers(iceServers -> sendSessionAccept(media, offer, iceServers));
 452    }
 453
 454    private synchronized void sendSessionAccept(final Set<Media> media, final SessionDescription offer, final List<PeerConnection.IceServer> iceServers) {
 455        if (isTerminated()) {
 456            Log.w(Config.LOGTAG, id.account.getJid().asBareJid() + ": ICE servers got discovered when session was already terminated. nothing to do.");
 457            return;
 458        }
 459        try {
 460            setupWebRTC(media, iceServers);
 461        } catch (final WebRTCWrapper.InitializationException e) {
 462            Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": unable to initialize WebRTC");
 463            webRTCWrapper.close();
 464            sendSessionTerminate(Reason.FAILED_APPLICATION);
 465            return;
 466        }
 467        final org.webrtc.SessionDescription sdp = new org.webrtc.SessionDescription(
 468                org.webrtc.SessionDescription.Type.OFFER,
 469                offer.toString()
 470        );
 471        try {
 472            this.webRTCWrapper.setRemoteDescription(sdp).get();
 473            addIceCandidatesFromBlackLog();
 474            org.webrtc.SessionDescription webRTCSessionDescription = this.webRTCWrapper.createAnswer().get();
 475            final SessionDescription sessionDescription = SessionDescription.parse(webRTCSessionDescription.description);
 476            final RtpContentMap respondingRtpContentMap = RtpContentMap.of(sessionDescription);
 477            sendSessionAccept(respondingRtpContentMap);
 478            this.webRTCWrapper.setLocalDescription(webRTCSessionDescription).get();
 479        } catch (final Exception e) {
 480            Log.d(Config.LOGTAG, "unable to send session accept", Throwables.getRootCause(e));
 481            webRTCWrapper.close();
 482            sendSessionTerminate(Reason.FAILED_APPLICATION);
 483        }
 484    }
 485
 486    private void addIceCandidatesFromBlackLog() {
 487        while (!this.pendingIceCandidates.isEmpty()) {
 488            processCandidates(this.pendingIceCandidates.poll());
 489            Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": added candidates from back log");
 490        }
 491    }
 492
 493    private void sendSessionAccept(final RtpContentMap rtpContentMap) {
 494        this.responderRtpContentMap = rtpContentMap;
 495        this.transitionOrThrow(State.SESSION_ACCEPTED);
 496        final RtpContentMap outgoingContentMap;
 497        if (this.omemoVerification.hasDeviceId()) {
 498            final AxolotlService.OmemoVerifiedPayload<OmemoVerifiedRtpContentMap> verifiedPayload;
 499            try {
 500                verifiedPayload = id.account.getAxolotlService().encrypt(rtpContentMap, id.with, omemoVerification.getDeviceId());
 501                outgoingContentMap = verifiedPayload.getPayload();
 502                this.omemoVerification.setOrEnsureEqual(verifiedPayload);
 503            } catch (final Exception e) {
 504                throw new SecurityException("Unable to verify DTLS Fingerprint with OMEMO", e);
 505            }
 506        } else {
 507            outgoingContentMap = rtpContentMap;
 508        }
 509        final JinglePacket sessionAccept = outgoingContentMap.toJinglePacket(JinglePacket.Action.SESSION_ACCEPT, id.sessionId);
 510        send(sessionAccept);
 511    }
 512
 513    synchronized void deliveryMessage(final Jid from, final Element message, final String serverMessageId, final long timestamp) {
 514        Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": delivered message to JingleRtpConnection " + message);
 515        switch (message.getName()) {
 516            case "propose":
 517                receivePropose(from, Propose.upgrade(message), serverMessageId, timestamp);
 518                break;
 519            case "proceed":
 520                receiveProceed(from, Proceed.upgrade(message), serverMessageId, timestamp);
 521                break;
 522            case "retract":
 523                receiveRetract(from, serverMessageId, timestamp);
 524                break;
 525            case "reject":
 526                receiveReject(from, serverMessageId, timestamp);
 527                break;
 528            case "accept":
 529                receiveAccept(from, serverMessageId, timestamp);
 530                break;
 531            default:
 532                break;
 533        }
 534    }
 535
 536    void deliverFailedProceed() {
 537        Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": receive message error for proceed message");
 538        if (transition(State.TERMINATED_CONNECTIVITY_ERROR)) {
 539            webRTCWrapper.close();
 540            Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": transitioned into connectivity error");
 541            this.finish();
 542        }
 543    }
 544
 545    private void receiveAccept(final Jid from, final String serverMsgId, final long timestamp) {
 546        final boolean originatedFromMyself = from.asBareJid().equals(id.account.getJid().asBareJid());
 547        if (originatedFromMyself) {
 548            if (transition(State.ACCEPTED)) {
 549                if (serverMsgId != null) {
 550                    this.message.setServerMsgId(serverMsgId);
 551                }
 552                this.message.setTime(timestamp);
 553                this.message.setCarbon(true); //indicate that call was accepted on other device
 554                this.writeLogMessageSuccess(0);
 555                this.xmppConnectionService.getNotificationService().cancelIncomingCallNotification();
 556                this.finish();
 557            } else {
 558                Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": unable to transition to accept because already in state=" + this.state);
 559            }
 560        } else {
 561            Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": ignoring 'accept' from " + from);
 562        }
 563    }
 564
 565    private void receiveReject(final Jid from, final String serverMsgId, final long timestamp) {
 566        final boolean originatedFromMyself = from.asBareJid().equals(id.account.getJid().asBareJid());
 567        //reject from another one of my clients
 568        if (originatedFromMyself) {
 569            receiveRejectFromMyself(serverMsgId, timestamp);
 570        } else if (isInitiator()) {
 571            if (from.equals(id.with)) {
 572                receiveRejectFromResponder();
 573            } else {
 574                Log.d(Config.LOGTAG, id.account.getJid() + ": ignoring reject from " + from + " for session with " + id.with);
 575            }
 576        } else {
 577            Log.d(Config.LOGTAG, id.account.getJid() + ": ignoring reject from " + from + " for session with " + id.with);
 578        }
 579    }
 580
 581    private void receiveRejectFromMyself(String serverMsgId, long timestamp) {
 582        if (transition(State.REJECTED)) {
 583            this.xmppConnectionService.getNotificationService().cancelIncomingCallNotification();
 584            this.finish();
 585            if (serverMsgId != null) {
 586                this.message.setServerMsgId(serverMsgId);
 587            }
 588            this.message.setTime(timestamp);
 589            this.message.setCarbon(true); //indicate that call was rejected on other device
 590            writeLogMessageMissed();
 591        } else {
 592            Log.d(Config.LOGTAG, "not able to transition into REJECTED because already in " + this.state);
 593        }
 594    }
 595
 596    private void receiveRejectFromResponder() {
 597        if (isInState(State.PROCEED)) {
 598            Log.d(Config.LOGTAG, id.account.getJid() + ": received reject while still in proceed. callee reconsidered");
 599            closeTransitionLogFinish(State.REJECTED_RACED);
 600            return;
 601        }
 602        if (isInState(State.SESSION_INITIALIZED_PRE_APPROVED)) {
 603            Log.d(Config.LOGTAG, id.account.getJid() + ": received reject while in SESSION_INITIATED_PRE_APPROVED. callee reconsidered before receiving session-init");
 604            closeTransitionLogFinish(State.TERMINATED_DECLINED_OR_BUSY);
 605            return;
 606        }
 607        Log.d(Config.LOGTAG, id.account.getJid() + ": ignoring reject from responder because already in state " + this.state);
 608    }
 609
 610    private void receivePropose(final Jid from, final Propose propose, final String serverMsgId, final long timestamp) {
 611        final boolean originatedFromMyself = from.asBareJid().equals(id.account.getJid().asBareJid());
 612        if (originatedFromMyself) {
 613            Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": saw proposal from myself. ignoring");
 614        } else if (transition(State.PROPOSED, () -> {
 615            final Collection<RtpDescription> descriptions = Collections2.transform(
 616                    Collections2.filter(propose.getDescriptions(), d -> d instanceof RtpDescription),
 617                    input -> (RtpDescription) input
 618            );
 619            final Collection<Media> media = Collections2.transform(descriptions, RtpDescription::getMedia);
 620            Preconditions.checkState(!media.contains(Media.UNKNOWN), "RTP descriptions contain unknown media");
 621            Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": received session proposal from " + from + " for " + media);
 622            this.proposedMedia = Sets.newHashSet(media);
 623        })) {
 624            if (serverMsgId != null) {
 625                this.message.setServerMsgId(serverMsgId);
 626            }
 627            this.message.setTime(timestamp);
 628            startRinging();
 629        } else {
 630            Log.d(Config.LOGTAG, id.account.getJid() + ": ignoring session proposal because already in " + state);
 631        }
 632    }
 633
 634    private void startRinging() {
 635        Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": received call from " + id.with + ". start ringing");
 636        ringingTimeoutFuture = jingleConnectionManager.schedule(this::ringingTimeout, BUSY_TIME_OUT, TimeUnit.SECONDS);
 637        xmppConnectionService.getNotificationService().startRinging(id, getMedia());
 638    }
 639
 640    private synchronized void ringingTimeout() {
 641        Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": timeout reached for ringing");
 642        switch (this.state) {
 643            case PROPOSED:
 644                message.markUnread();
 645                rejectCallFromProposed();
 646                break;
 647            case SESSION_INITIALIZED:
 648                message.markUnread();
 649                rejectCallFromSessionInitiate();
 650                break;
 651        }
 652    }
 653
 654    private void cancelRingingTimeout() {
 655        final ScheduledFuture<?> future = this.ringingTimeoutFuture;
 656        if (future != null && !future.isCancelled()) {
 657            future.cancel(false);
 658        }
 659    }
 660
 661    private void receiveProceed(final Jid from, final Proceed proceed, final String serverMsgId, final long timestamp) {
 662        final Set<Media> media = Preconditions.checkNotNull(this.proposedMedia, "Proposed media has to be set before handling proceed");
 663        Preconditions.checkState(media.size() > 0, "Proposed media should not be empty");
 664        if (from.equals(id.with)) {
 665            if (isInitiator()) {
 666                if (transition(State.PROCEED)) {
 667                    if (serverMsgId != null) {
 668                        this.message.setServerMsgId(serverMsgId);
 669                    }
 670                    this.message.setTime(timestamp);
 671                    this.omemoVerification.setDeviceId(proceed.getDeviceId());
 672                    this.sendSessionInitiate(media, State.SESSION_INITIALIZED_PRE_APPROVED);
 673                } else {
 674                    Log.d(Config.LOGTAG, String.format("%s: ignoring proceed because already in %s", id.account.getJid().asBareJid(), this.state));
 675                }
 676            } else {
 677                Log.d(Config.LOGTAG, String.format("%s: ignoring proceed because we were not initializing", id.account.getJid().asBareJid()));
 678            }
 679        } else if (from.asBareJid().equals(id.account.getJid().asBareJid())) {
 680            if (transition(State.ACCEPTED)) {
 681                Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": moved session with " + id.with + " into state accepted after received carbon copied procced");
 682                this.xmppConnectionService.getNotificationService().cancelIncomingCallNotification();
 683                this.finish();
 684            }
 685        } else {
 686            Log.d(Config.LOGTAG, String.format("%s: ignoring proceed from %s. was expected from %s", id.account.getJid().asBareJid(), from, id.with));
 687        }
 688    }
 689
 690    private void receiveRetract(final Jid from, final String serverMsgId, final long timestamp) {
 691        if (from.equals(id.with)) {
 692            final State target = this.state == State.PROCEED ? State.RETRACTED_RACED : State.RETRACTED;
 693            if (transition(target)) {
 694                xmppConnectionService.getNotificationService().cancelIncomingCallNotification();
 695                Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": session with " + id.with + " has been retracted (serverMsgId=" + serverMsgId + ")");
 696                if (serverMsgId != null) {
 697                    this.message.setServerMsgId(serverMsgId);
 698                }
 699                this.message.setTime(timestamp);
 700                if (target == State.RETRACTED) {
 701                    this.message.markUnread();
 702                }
 703                writeLogMessageMissed();
 704                finish();
 705            } else {
 706                Log.d(Config.LOGTAG, "ignoring retract because already in " + this.state);
 707            }
 708        } else {
 709            //TODO parse retract from self
 710            Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": received retract from " + from + ". expected retract from" + id.with + ". ignoring");
 711        }
 712    }
 713
 714    public void sendSessionInitiate() {
 715        sendSessionInitiate(this.proposedMedia, State.SESSION_INITIALIZED);
 716    }
 717
 718    private void sendSessionInitiate(final Set<Media> media, final State targetState) {
 719        Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": prepare session-initiate");
 720        discoverIceServers(iceServers -> sendSessionInitiate(media, targetState, iceServers));
 721    }
 722
 723    private synchronized void sendSessionInitiate(final Set<Media> media, final State targetState, final List<PeerConnection.IceServer> iceServers) {
 724        if (isTerminated()) {
 725            Log.w(Config.LOGTAG, id.account.getJid().asBareJid() + ": ICE servers got discovered when session was already terminated. nothing to do.");
 726            return;
 727        }
 728        try {
 729            setupWebRTC(media, iceServers);
 730        } catch (final WebRTCWrapper.InitializationException e) {
 731            Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": unable to initialize WebRTC");
 732            webRTCWrapper.close();
 733            sendJingleMessage("retract", id.with.asBareJid());
 734            transitionOrThrow(State.TERMINATED_APPLICATION_FAILURE);
 735            this.finish();
 736            return;
 737        }
 738        try {
 739            org.webrtc.SessionDescription webRTCSessionDescription = this.webRTCWrapper.createOffer().get();
 740            final SessionDescription sessionDescription = SessionDescription.parse(webRTCSessionDescription.description);
 741            final RtpContentMap rtpContentMap = RtpContentMap.of(sessionDescription);
 742            sendSessionInitiate(rtpContentMap, targetState);
 743            this.webRTCWrapper.setLocalDescription(webRTCSessionDescription).get();
 744        } catch (final Exception e) {
 745            Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": unable to sendSessionInitiate", Throwables.getRootCause(e));
 746            webRTCWrapper.close();
 747            if (isInState(targetState)) {
 748                sendSessionTerminate(Reason.FAILED_APPLICATION);
 749            } else {
 750                sendJingleMessage("retract", id.with.asBareJid());
 751                transitionOrThrow(State.TERMINATED_APPLICATION_FAILURE);
 752                this.finish();
 753            }
 754        }
 755    }
 756
 757    private void sendSessionInitiate(final RtpContentMap rtpContentMap, final State targetState) {
 758        this.initiatorRtpContentMap = rtpContentMap;
 759        this.transitionOrThrow(targetState);
 760        //TODO do on background thread?
 761        final RtpContentMap outgoingContentMap = encryptSessionInitiate(rtpContentMap);
 762        final JinglePacket sessionInitiate = outgoingContentMap.toJinglePacket(JinglePacket.Action.SESSION_INITIATE, id.sessionId);
 763        send(sessionInitiate);
 764    }
 765
 766    private RtpContentMap encryptSessionInitiate(final RtpContentMap rtpContentMap) {
 767        if (this.omemoVerification.hasDeviceId()) {
 768            final AxolotlService.OmemoVerifiedPayload<OmemoVerifiedRtpContentMap> verifiedPayload;
 769            try {
 770                verifiedPayload = id.account.getAxolotlService().encrypt(rtpContentMap, id.with, omemoVerification.getDeviceId());
 771            } catch (final CryptoFailedException e) {
 772                Log.w(Config.LOGTAG,id.account.getJid().asBareJid()+": unable to use OMEMO DTLS verification on outgoing session initiate. falling back", e);
 773                return rtpContentMap;
 774            }
 775            this.omemoVerification.setSessionFingerprint(verifiedPayload.getFingerprint());
 776            return verifiedPayload.getPayload();
 777        } else {
 778            return rtpContentMap;
 779        }
 780    }
 781
 782    private void sendSessionTerminate(final Reason reason) {
 783        sendSessionTerminate(reason, null);
 784    }
 785
 786    private void sendSessionTerminate(final Reason reason, final String text) {
 787        final State previous = this.state;
 788        final State target = reasonToState(reason);
 789        transitionOrThrow(target);
 790        if (previous != State.NULL) {
 791            writeLogMessage(target);
 792        }
 793        final JinglePacket jinglePacket = new JinglePacket(JinglePacket.Action.SESSION_TERMINATE, id.sessionId);
 794        jinglePacket.setReason(reason, text);
 795        Log.d(Config.LOGTAG, jinglePacket.toString());
 796        send(jinglePacket);
 797        finish();
 798    }
 799
 800    private void sendTransportInfo(final String contentName, IceUdpTransportInfo.Candidate candidate) {
 801        final RtpContentMap transportInfo;
 802        try {
 803            final RtpContentMap rtpContentMap = isInitiator() ? this.initiatorRtpContentMap : this.responderRtpContentMap;
 804            transportInfo = rtpContentMap.transportInfo(contentName, candidate);
 805        } catch (final Exception e) {
 806            Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": unable to prepare transport-info from candidate for content=" + contentName);
 807            return;
 808        }
 809        final JinglePacket jinglePacket = transportInfo.toJinglePacket(JinglePacket.Action.TRANSPORT_INFO, id.sessionId);
 810        send(jinglePacket);
 811    }
 812
 813    private void send(final JinglePacket jinglePacket) {
 814        jinglePacket.setTo(id.with);
 815        xmppConnectionService.sendIqPacket(id.account, jinglePacket, this::handleIqResponse);
 816    }
 817
 818    private synchronized void handleIqResponse(final Account account, final IqPacket response) {
 819        if (response.getType() == IqPacket.TYPE.ERROR) {
 820            final String errorCondition = response.getErrorCondition();
 821            Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": received IQ-error from " + response.getFrom() + " in RTP session. " + errorCondition);
 822            if (isTerminated()) {
 823                Log.i(Config.LOGTAG, id.account.getJid().asBareJid() + ": ignoring error because session was already terminated");
 824                return;
 825            }
 826            this.webRTCWrapper.close();
 827            final State target;
 828            if (Arrays.asList(
 829                    "service-unavailable",
 830                    "recipient-unavailable",
 831                    "remote-server-not-found",
 832                    "remote-server-timeout"
 833            ).contains(errorCondition)) {
 834                target = State.TERMINATED_CONNECTIVITY_ERROR;
 835            } else {
 836                target = State.TERMINATED_APPLICATION_FAILURE;
 837            }
 838            transitionOrThrow(target);
 839            this.finish();
 840        } else if (response.getType() == IqPacket.TYPE.TIMEOUT) {
 841            Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": received IQ timeout in RTP session with " + id.with + ". terminating with connectivity error");
 842            if (isTerminated()) {
 843                Log.i(Config.LOGTAG, id.account.getJid().asBareJid() + ": ignoring error because session was already terminated");
 844                return;
 845            }
 846            this.webRTCWrapper.close();
 847            transitionOrThrow(State.TERMINATED_CONNECTIVITY_ERROR);
 848            this.finish();
 849        }
 850    }
 851
 852    private void terminateWithOutOfOrder(final JinglePacket jinglePacket) {
 853        Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": terminating session with out-of-order");
 854        this.webRTCWrapper.close();
 855        transitionOrThrow(State.TERMINATED_APPLICATION_FAILURE);
 856        respondWithOutOfOrder(jinglePacket);
 857        this.finish();
 858    }
 859
 860    private void respondWithOutOfOrder(final JinglePacket jinglePacket) {
 861        jingleConnectionManager.respondWithJingleError(id.account, jinglePacket, "out-of-order", "unexpected-request", "wait");
 862    }
 863
 864    private void respondOk(final JinglePacket jinglePacket) {
 865        xmppConnectionService.sendIqPacket(id.account, jinglePacket.generateResponse(IqPacket.TYPE.RESULT), null);
 866    }
 867
 868    public void throwStateTransitionException() {
 869        final StateTransitionException exception = this.stateTransitionException;
 870        if (exception != null) {
 871            throw new IllegalStateException(String.format("Transition to %s did not call finish", exception.state), exception);
 872        }
 873    }
 874
 875    public RtpEndUserState getEndUserState() {
 876        switch (this.state) {
 877            case NULL:
 878            case PROPOSED:
 879            case SESSION_INITIALIZED:
 880                if (isInitiator()) {
 881                    return RtpEndUserState.RINGING;
 882                } else {
 883                    return RtpEndUserState.INCOMING_CALL;
 884                }
 885            case PROCEED:
 886                if (isInitiator()) {
 887                    return RtpEndUserState.RINGING;
 888                } else {
 889                    return RtpEndUserState.ACCEPTING_CALL;
 890                }
 891            case SESSION_INITIALIZED_PRE_APPROVED:
 892                if (isInitiator()) {
 893                    return RtpEndUserState.RINGING;
 894                } else {
 895                    return RtpEndUserState.CONNECTING;
 896                }
 897            case SESSION_ACCEPTED:
 898                final PeerConnection.PeerConnectionState state;
 899                try {
 900                    state = webRTCWrapper.getState();
 901                } catch (final WebRTCWrapper.PeerConnectionNotInitialized e) {
 902                    //We usually close the WebRTCWrapper *before* transitioning so we might still
 903                    //be in SESSION_ACCEPTED even though the peerConnection has been torn down
 904                    return RtpEndUserState.ENDING_CALL;
 905                }
 906                if (state == PeerConnection.PeerConnectionState.CONNECTED) {
 907                    return RtpEndUserState.CONNECTED;
 908                } else if (state == PeerConnection.PeerConnectionState.NEW || state == PeerConnection.PeerConnectionState.CONNECTING) {
 909                    return RtpEndUserState.CONNECTING;
 910                } else if (state == PeerConnection.PeerConnectionState.CLOSED) {
 911                    return RtpEndUserState.ENDING_CALL;
 912                } else {
 913                    return rtpConnectionStarted == 0 ? RtpEndUserState.CONNECTIVITY_ERROR : RtpEndUserState.CONNECTIVITY_LOST_ERROR;
 914                }
 915            case REJECTED:
 916            case REJECTED_RACED:
 917            case TERMINATED_DECLINED_OR_BUSY:
 918                if (isInitiator()) {
 919                    return RtpEndUserState.DECLINED_OR_BUSY;
 920                } else {
 921                    return RtpEndUserState.ENDED;
 922                }
 923            case TERMINATED_SUCCESS:
 924            case ACCEPTED:
 925            case RETRACTED:
 926            case TERMINATED_CANCEL_OR_TIMEOUT:
 927                return RtpEndUserState.ENDED;
 928            case RETRACTED_RACED:
 929                if (isInitiator()) {
 930                    return RtpEndUserState.ENDED;
 931                } else {
 932                    return RtpEndUserState.RETRACTED;
 933                }
 934            case TERMINATED_CONNECTIVITY_ERROR:
 935                return rtpConnectionStarted == 0 ? RtpEndUserState.CONNECTIVITY_ERROR : RtpEndUserState.CONNECTIVITY_LOST_ERROR;
 936            case TERMINATED_APPLICATION_FAILURE:
 937                return RtpEndUserState.APPLICATION_ERROR;
 938        }
 939        throw new IllegalStateException(String.format("%s has no equivalent EndUserState", this.state));
 940    }
 941
 942    public Set<Media> getMedia() {
 943        final State current = getState();
 944        if (current == State.NULL) {
 945            if (isInitiator()) {
 946                return Preconditions.checkNotNull(
 947                        this.proposedMedia,
 948                        "RTP connection has not been initialized properly"
 949                );
 950            }
 951            throw new IllegalStateException("RTP connection has not been initialized yet");
 952        }
 953        if (Arrays.asList(State.PROPOSED, State.PROCEED).contains(current)) {
 954            return Preconditions.checkNotNull(
 955                    this.proposedMedia,
 956                    "RTP connection has not been initialized properly"
 957            );
 958        }
 959        final RtpContentMap initiatorContentMap = initiatorRtpContentMap;
 960        if (initiatorContentMap != null) {
 961            return initiatorContentMap.getMedia();
 962        } else if (isTerminated()) {
 963            return Collections.emptySet(); //we might fail before we ever got a chance to set media
 964        } else {
 965            return Preconditions.checkNotNull(this.proposedMedia, "RTP connection has not been initialized properly");
 966        }
 967    }
 968
 969
 970    public synchronized void acceptCall() {
 971        switch (this.state) {
 972            case PROPOSED:
 973                cancelRingingTimeout();
 974                acceptCallFromProposed();
 975                break;
 976            case SESSION_INITIALIZED:
 977                cancelRingingTimeout();
 978                acceptCallFromSessionInitialized();
 979                break;
 980            case ACCEPTED:
 981                Log.w(Config.LOGTAG, id.account.getJid().asBareJid() + ": the call has already been accepted  with another client. UI was just lagging behind");
 982                break;
 983            case PROCEED:
 984            case SESSION_ACCEPTED:
 985                Log.w(Config.LOGTAG, id.account.getJid().asBareJid() + ": the call has already been accepted. user probably double tapped the UI");
 986                break;
 987            default:
 988                throw new IllegalStateException("Can not accept call from " + this.state);
 989        }
 990    }
 991
 992
 993    public void notifyPhoneCall() {
 994        Log.d(Config.LOGTAG, "a phone call has just been started. killing jingle rtp connections");
 995        if (Arrays.asList(State.PROPOSED, State.SESSION_INITIALIZED).contains(this.state)) {
 996            rejectCall();
 997        } else {
 998            endCall();
 999        }
1000    }
1001
1002    public synchronized void rejectCall() {
1003        if (isTerminated()) {
1004            Log.w(Config.LOGTAG, id.account.getJid().asBareJid() + ": received rejectCall() when session has already been terminated. nothing to do");
1005            return;
1006        }
1007        switch (this.state) {
1008            case PROPOSED:
1009                rejectCallFromProposed();
1010                break;
1011            case SESSION_INITIALIZED:
1012                rejectCallFromSessionInitiate();
1013                break;
1014            default:
1015                throw new IllegalStateException("Can not reject call from " + this.state);
1016        }
1017    }
1018
1019    public synchronized void endCall() {
1020        if (isTerminated()) {
1021            Log.w(Config.LOGTAG, id.account.getJid().asBareJid() + ": received endCall() when session has already been terminated. nothing to do");
1022            return;
1023        }
1024        if (isInState(State.PROPOSED) && !isInitiator()) {
1025            rejectCallFromProposed();
1026            return;
1027        }
1028        if (isInState(State.PROCEED)) {
1029            if (isInitiator()) {
1030                retractFromProceed();
1031            } else {
1032                rejectCallFromProceed();
1033            }
1034            return;
1035        }
1036        if (isInitiator() && isInState(State.SESSION_INITIALIZED, State.SESSION_INITIALIZED_PRE_APPROVED)) {
1037            this.webRTCWrapper.close();
1038            sendSessionTerminate(Reason.CANCEL);
1039            return;
1040        }
1041        if (isInState(State.SESSION_INITIALIZED)) {
1042            rejectCallFromSessionInitiate();
1043            return;
1044        }
1045        if (isInState(State.SESSION_INITIALIZED_PRE_APPROVED, State.SESSION_ACCEPTED)) {
1046            this.webRTCWrapper.close();
1047            sendSessionTerminate(Reason.SUCCESS);
1048            return;
1049        }
1050        if (isInState(State.TERMINATED_APPLICATION_FAILURE, State.TERMINATED_CONNECTIVITY_ERROR, State.TERMINATED_DECLINED_OR_BUSY)) {
1051            Log.d(Config.LOGTAG, "ignoring request to end call because already in state " + this.state);
1052            return;
1053        }
1054        throw new IllegalStateException("called 'endCall' while in state " + this.state + ". isInitiator=" + isInitiator());
1055    }
1056
1057    private void retractFromProceed() {
1058        Log.d(Config.LOGTAG, "retract from proceed");
1059        this.sendJingleMessage("retract");
1060        closeTransitionLogFinish(State.RETRACTED_RACED);
1061    }
1062
1063    private void closeTransitionLogFinish(final State state) {
1064        this.webRTCWrapper.close();
1065        transitionOrThrow(state);
1066        writeLogMessage(state);
1067        finish();
1068    }
1069
1070    private void setupWebRTC(final Set<Media> media, final List<PeerConnection.IceServer> iceServers) throws WebRTCWrapper.InitializationException {
1071        this.jingleConnectionManager.ensureConnectionIsRegistered(this);
1072        final AppRTCAudioManager.SpeakerPhonePreference speakerPhonePreference;
1073        if (media.contains(Media.VIDEO)) {
1074            speakerPhonePreference = AppRTCAudioManager.SpeakerPhonePreference.SPEAKER;
1075        } else {
1076            speakerPhonePreference = AppRTCAudioManager.SpeakerPhonePreference.EARPIECE;
1077        }
1078        this.webRTCWrapper.setup(this.xmppConnectionService, speakerPhonePreference);
1079        this.webRTCWrapper.initializePeerConnection(media, iceServers);
1080    }
1081
1082    private void acceptCallFromProposed() {
1083        transitionOrThrow(State.PROCEED);
1084        xmppConnectionService.getNotificationService().cancelIncomingCallNotification();
1085        this.sendJingleMessage("accept", id.account.getJid().asBareJid());
1086        this.sendJingleMessage("proceed");
1087    }
1088
1089    private void rejectCallFromProposed() {
1090        transitionOrThrow(State.REJECTED);
1091        writeLogMessageMissed();
1092        xmppConnectionService.getNotificationService().cancelIncomingCallNotification();
1093        this.sendJingleMessage("reject");
1094        finish();
1095    }
1096
1097    private void rejectCallFromProceed() {
1098        this.sendJingleMessage("reject");
1099        closeTransitionLogFinish(State.REJECTED_RACED);
1100    }
1101
1102    private void rejectCallFromSessionInitiate() {
1103        webRTCWrapper.close();
1104        sendSessionTerminate(Reason.DECLINE);
1105        xmppConnectionService.getNotificationService().cancelIncomingCallNotification();
1106    }
1107
1108    private void sendJingleMessage(final String action) {
1109        sendJingleMessage(action, id.with);
1110    }
1111
1112    private void sendJingleMessage(final String action, final Jid to) {
1113        final MessagePacket messagePacket = new MessagePacket();
1114        messagePacket.setType(MessagePacket.TYPE_CHAT); //we want to carbon copy those
1115        messagePacket.setTo(to);
1116        final Element intent = messagePacket.addChild(action, Namespace.JINGLE_MESSAGE).setAttribute("id", id.sessionId);
1117        if ("proceed".equals(action)) {
1118            messagePacket.setId(JINGLE_MESSAGE_PROCEED_ID_PREFIX + id.sessionId);
1119
1120            //TODO only do this if OMEMO is enable so we have an easy way to opt out
1121            final int deviceId = id.account.getAxolotlService().getOwnDeviceId();
1122            final Element device = intent.addChild("device", Namespace.OMEMO_DTLS_SRTP_VERIFICATION);
1123            device.setAttribute("id", deviceId);
1124        }
1125        messagePacket.addChild("store", "urn:xmpp:hints");
1126        xmppConnectionService.sendMessagePacket(id.account, messagePacket);
1127    }
1128
1129    private void acceptCallFromSessionInitialized() {
1130        xmppConnectionService.getNotificationService().cancelIncomingCallNotification();
1131        sendSessionAccept();
1132    }
1133
1134    private synchronized boolean isInState(State... state) {
1135        return Arrays.asList(state).contains(this.state);
1136    }
1137
1138    private boolean transition(final State target) {
1139        return transition(target, null);
1140    }
1141
1142    private synchronized boolean transition(final State target, final Runnable runnable) {
1143        final Collection<State> validTransitions = VALID_TRANSITIONS.get(this.state);
1144        if (validTransitions != null && validTransitions.contains(target)) {
1145            this.state = target;
1146            this.stateTransitionException = new StateTransitionException(target);
1147            if (runnable != null) {
1148                runnable.run();
1149            }
1150            Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": transitioned into " + target);
1151            updateEndUserState();
1152            updateOngoingCallNotification();
1153            return true;
1154        } else {
1155            return false;
1156        }
1157    }
1158
1159    void transitionOrThrow(final State target) {
1160        if (!transition(target)) {
1161            throw new IllegalStateException(String.format("Unable to transition from %s to %s", this.state, target));
1162        }
1163    }
1164
1165    @Override
1166    public void onIceCandidate(final IceCandidate iceCandidate) {
1167        final IceUdpTransportInfo.Candidate candidate = IceUdpTransportInfo.Candidate.fromSdpAttribute(iceCandidate.sdp);
1168        Log.d(Config.LOGTAG, "sending candidate: " + iceCandidate.toString());
1169        sendTransportInfo(iceCandidate.sdpMid, candidate);
1170    }
1171
1172    @Override
1173    public void onConnectionChange(final PeerConnection.PeerConnectionState newState) {
1174        Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": PeerConnectionState changed to " + newState);
1175        if (newState == PeerConnection.PeerConnectionState.CONNECTED && this.rtpConnectionStarted == 0) {
1176            this.rtpConnectionStarted = SystemClock.elapsedRealtime();
1177        }
1178        if (newState == PeerConnection.PeerConnectionState.CLOSED && this.rtpConnectionEnded == 0) {
1179            this.rtpConnectionEnded = SystemClock.elapsedRealtime();
1180        }
1181        //TODO 'DISCONNECTED' might be an opportunity to renew the offer and send a transport-replace
1182        //TODO exact syntax is yet to be determined but transport-replace sounds like the most reasonable
1183        //as there is no content-replace
1184        if (Arrays.asList(PeerConnection.PeerConnectionState.FAILED, PeerConnection.PeerConnectionState.DISCONNECTED).contains(newState)) {
1185            if (isTerminated()) {
1186                Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": not sending session-terminate after connectivity error because session is already in state " + this.state);
1187                return;
1188            }
1189            new Thread(this::closeWebRTCSessionAfterFailedConnection).start();
1190        } else {
1191            updateEndUserState();
1192        }
1193    }
1194
1195    private void closeWebRTCSessionAfterFailedConnection() {
1196        this.webRTCWrapper.close();
1197        synchronized (this) {
1198            if (isTerminated()) {
1199                Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": no need to send session-terminate after failed connection. Other party already did");
1200                return;
1201            }
1202            sendSessionTerminate(Reason.CONNECTIVITY_ERROR);
1203        }
1204    }
1205
1206    public long getRtpConnectionStarted() {
1207        return this.rtpConnectionStarted;
1208    }
1209
1210    public long getRtpConnectionEnded() {
1211        return this.rtpConnectionEnded;
1212    }
1213
1214    public AppRTCAudioManager getAudioManager() {
1215        return webRTCWrapper.getAudioManager();
1216    }
1217
1218    public boolean isMicrophoneEnabled() {
1219        return webRTCWrapper.isMicrophoneEnabled();
1220    }
1221
1222    public boolean setMicrophoneEnabled(final boolean enabled) {
1223        return webRTCWrapper.setMicrophoneEnabled(enabled);
1224    }
1225
1226    public boolean isVideoEnabled() {
1227        return webRTCWrapper.isVideoEnabled();
1228    }
1229
1230    public void setVideoEnabled(final boolean enabled) {
1231        webRTCWrapper.setVideoEnabled(enabled);
1232    }
1233
1234    public boolean isCameraSwitchable() {
1235        return webRTCWrapper.isCameraSwitchable();
1236    }
1237
1238    public boolean isFrontCamera() {
1239        return webRTCWrapper.isFrontCamera();
1240    }
1241
1242    public ListenableFuture<Boolean> switchCamera() {
1243        return webRTCWrapper.switchCamera();
1244    }
1245
1246    @Override
1247    public void onAudioDeviceChanged(AppRTCAudioManager.AudioDevice selectedAudioDevice, Set<AppRTCAudioManager.AudioDevice> availableAudioDevices) {
1248        xmppConnectionService.notifyJingleRtpConnectionUpdate(selectedAudioDevice, availableAudioDevices);
1249    }
1250
1251    private void updateEndUserState() {
1252        final RtpEndUserState endUserState = getEndUserState();
1253        jingleConnectionManager.toneManager.transition(isInitiator(), endUserState, getMedia());
1254        xmppConnectionService.notifyJingleRtpConnectionUpdate(id.account, id.with, id.sessionId, endUserState);
1255    }
1256
1257    private void updateOngoingCallNotification() {
1258        if (STATES_SHOWING_ONGOING_CALL.contains(this.state)) {
1259            xmppConnectionService.setOngoingCall(id, getMedia());
1260        } else {
1261            xmppConnectionService.removeOngoingCall();
1262        }
1263    }
1264
1265    private void discoverIceServers(final OnIceServersDiscovered onIceServersDiscovered) {
1266        if (id.account.getXmppConnection().getFeatures().externalServiceDiscovery()) {
1267            final IqPacket request = new IqPacket(IqPacket.TYPE.GET);
1268            request.setTo(id.account.getDomain());
1269            request.addChild("services", Namespace.EXTERNAL_SERVICE_DISCOVERY);
1270            xmppConnectionService.sendIqPacket(id.account, request, (account, response) -> {
1271                ImmutableList.Builder<PeerConnection.IceServer> listBuilder = new ImmutableList.Builder<>();
1272                if (response.getType() == IqPacket.TYPE.RESULT) {
1273                    final Element services = response.findChild("services", Namespace.EXTERNAL_SERVICE_DISCOVERY);
1274                    final List<Element> children = services == null ? Collections.emptyList() : services.getChildren();
1275                    for (final Element child : children) {
1276                        if ("service".equals(child.getName())) {
1277                            final String type = child.getAttribute("type");
1278                            final String host = child.getAttribute("host");
1279                            final String sport = child.getAttribute("port");
1280                            final Integer port = sport == null ? null : Ints.tryParse(sport);
1281                            final String transport = child.getAttribute("transport");
1282                            final String username = child.getAttribute("username");
1283                            final String password = child.getAttribute("password");
1284                            if (Strings.isNullOrEmpty(host) || port == null) {
1285                                continue;
1286                            }
1287                            if (port < 0 || port > 65535) {
1288                                continue;
1289                            }
1290                            if (Arrays.asList("stun", "stuns", "turn", "turns").contains(type) && Arrays.asList("udp", "tcp").contains(transport)) {
1291                                if (Arrays.asList("stuns", "turns").contains(type) && "udp".equals(transport)) {
1292                                    Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": skipping invalid combination of udp/tls in external services");
1293                                    continue;
1294                                }
1295                                final PeerConnection.IceServer.Builder iceServerBuilder = PeerConnection.IceServer
1296                                        .builder(String.format("%s:%s:%s?transport=%s", type, IP.wrapIPv6(host), port, transport));
1297                                iceServerBuilder.setTlsCertPolicy(PeerConnection.TlsCertPolicy.TLS_CERT_POLICY_INSECURE_NO_CHECK);
1298                                if (username != null && password != null) {
1299                                    iceServerBuilder.setUsername(username);
1300                                    iceServerBuilder.setPassword(password);
1301                                } else if (Arrays.asList("turn", "turns").contains(type)) {
1302                                    //The WebRTC spec requires throwing an InvalidAccessError when username (from libwebrtc source coder)
1303                                    //https://chromium.googlesource.com/external/webrtc/+/master/pc/ice_server_parsing.cc
1304                                    Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": skipping " + type + "/" + transport + " without username and password");
1305                                    continue;
1306                                }
1307                                final PeerConnection.IceServer iceServer = iceServerBuilder.createIceServer();
1308                                Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": discovered ICE Server: " + iceServer);
1309                                listBuilder.add(iceServer);
1310                            }
1311                        }
1312                    }
1313                }
1314                final List<PeerConnection.IceServer> iceServers = listBuilder.build();
1315                if (iceServers.size() == 0) {
1316                    Log.w(Config.LOGTAG, id.account.getJid().asBareJid() + ": no ICE server found " + response);
1317                }
1318                onIceServersDiscovered.onIceServersDiscovered(iceServers);
1319            });
1320        } else {
1321            Log.w(Config.LOGTAG, id.account.getJid().asBareJid() + ": has no external service discovery");
1322            onIceServersDiscovered.onIceServersDiscovered(Collections.emptyList());
1323        }
1324    }
1325
1326    private void finish() {
1327        if (isTerminated()) {
1328            this.cancelRingingTimeout();
1329            this.webRTCWrapper.verifyClosed();
1330            this.jingleConnectionManager.setTerminalSessionState(id, getEndUserState(), getMedia());
1331            this.jingleConnectionManager.finishConnectionOrThrow(this);
1332        } else {
1333            throw new IllegalStateException(String.format("Unable to call finish from %s", this.state));
1334        }
1335    }
1336
1337    private void writeLogMessage(final State state) {
1338        final long started = this.rtpConnectionStarted;
1339        long duration = started <= 0 ? 0 : SystemClock.elapsedRealtime() - started;
1340        if (state == State.TERMINATED_SUCCESS || (state == State.TERMINATED_CONNECTIVITY_ERROR && duration > 0)) {
1341            writeLogMessageSuccess(duration);
1342        } else {
1343            writeLogMessageMissed();
1344        }
1345    }
1346
1347    private void writeLogMessageSuccess(final long duration) {
1348        this.message.setBody(new RtpSessionStatus(true, duration).toString());
1349        this.writeMessage();
1350    }
1351
1352    private void writeLogMessageMissed() {
1353        this.message.setBody(new RtpSessionStatus(false, 0).toString());
1354        this.writeMessage();
1355    }
1356
1357    private void writeMessage() {
1358        final Conversational conversational = message.getConversation();
1359        if (conversational instanceof Conversation) {
1360            ((Conversation) conversational).add(this.message);
1361            xmppConnectionService.createMessageAsync(message);
1362            xmppConnectionService.updateConversationUi();
1363        } else {
1364            throw new IllegalStateException("Somehow the conversation in a message was a stub");
1365        }
1366    }
1367
1368    public State getState() {
1369        return this.state;
1370    }
1371
1372    boolean isTerminated() {
1373        return TERMINATED.contains(this.state);
1374    }
1375
1376    public Optional<VideoTrack> getLocalVideoTrack() {
1377        return webRTCWrapper.getLocalVideoTrack();
1378    }
1379
1380    public Optional<VideoTrack> getRemoteVideoTrack() {
1381        return webRTCWrapper.getRemoteVideoTrack();
1382    }
1383
1384
1385    public EglBase.Context getEglBaseContext() {
1386        return webRTCWrapper.getEglBaseContext();
1387    }
1388
1389    void setProposedMedia(final Set<Media> media) {
1390        this.proposedMedia = media;
1391    }
1392
1393    public void fireStateUpdate() {
1394        final RtpEndUserState endUserState = getEndUserState();
1395        xmppConnectionService.notifyJingleRtpConnectionUpdate(id.account, id.with, id.sessionId, endUserState);
1396    }
1397
1398    private interface OnIceServersDiscovered {
1399        void onIceServersDiscovered(List<PeerConnection.IceServer> iceServers);
1400    }
1401
1402    private static class StateTransitionException extends Exception {
1403        private final State state;
1404
1405        private StateTransitionException(final State state) {
1406            this.state = state;
1407        }
1408    }
1409}