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        //TODO do on different thread
 498        if (this.omemoVerification.hasDeviceId()) {
 499            Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": encrypting session-accept");
 500            try {
 501                final AxolotlService.OmemoVerifiedPayload<OmemoVerifiedRtpContentMap> verifiedPayload = id.account.getAxolotlService().encrypt(rtpContentMap, id.with, omemoVerification.getDeviceId());
 502                outgoingContentMap = verifiedPayload.getPayload();
 503                this.omemoVerification.setOrEnsureEqual(verifiedPayload);
 504            } catch (final Exception e) {
 505                //TODO fail application if something goes wrong here
 506                Log.d(Config.LOGTAG, "unable to encrypt", e);
 507                return;
 508            }
 509        } else {
 510            outgoingContentMap = rtpContentMap;
 511        }
 512        final JinglePacket sessionAccept = outgoingContentMap.toJinglePacket(JinglePacket.Action.SESSION_ACCEPT, id.sessionId);
 513        send(sessionAccept);
 514    }
 515
 516    synchronized void deliveryMessage(final Jid from, final Element message, final String serverMessageId, final long timestamp) {
 517        Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": delivered message to JingleRtpConnection " + message);
 518        switch (message.getName()) {
 519            case "propose":
 520                receivePropose(from, Propose.upgrade(message), serverMessageId, timestamp);
 521                break;
 522            case "proceed":
 523                receiveProceed(from, Proceed.upgrade(message), serverMessageId, timestamp);
 524                break;
 525            case "retract":
 526                receiveRetract(from, serverMessageId, timestamp);
 527                break;
 528            case "reject":
 529                receiveReject(from, serverMessageId, timestamp);
 530                break;
 531            case "accept":
 532                receiveAccept(from, serverMessageId, timestamp);
 533                break;
 534            default:
 535                break;
 536        }
 537    }
 538
 539    void deliverFailedProceed() {
 540        Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": receive message error for proceed message");
 541        if (transition(State.TERMINATED_CONNECTIVITY_ERROR)) {
 542            webRTCWrapper.close();
 543            Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": transitioned into connectivity error");
 544            this.finish();
 545        }
 546    }
 547
 548    private void receiveAccept(final Jid from, final String serverMsgId, final long timestamp) {
 549        final boolean originatedFromMyself = from.asBareJid().equals(id.account.getJid().asBareJid());
 550        if (originatedFromMyself) {
 551            if (transition(State.ACCEPTED)) {
 552                if (serverMsgId != null) {
 553                    this.message.setServerMsgId(serverMsgId);
 554                }
 555                this.message.setTime(timestamp);
 556                this.message.setCarbon(true); //indicate that call was accepted on other device
 557                this.writeLogMessageSuccess(0);
 558                this.xmppConnectionService.getNotificationService().cancelIncomingCallNotification();
 559                this.finish();
 560            } else {
 561                Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": unable to transition to accept because already in state=" + this.state);
 562            }
 563        } else {
 564            Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": ignoring 'accept' from " + from);
 565        }
 566    }
 567
 568    private void receiveReject(final Jid from, final String serverMsgId, final long timestamp) {
 569        final boolean originatedFromMyself = from.asBareJid().equals(id.account.getJid().asBareJid());
 570        //reject from another one of my clients
 571        if (originatedFromMyself) {
 572            receiveRejectFromMyself(serverMsgId, timestamp);
 573        } else if (isInitiator()) {
 574            if (from.equals(id.with)) {
 575                receiveRejectFromResponder();
 576            } else {
 577                Log.d(Config.LOGTAG, id.account.getJid() + ": ignoring reject from " + from + " for session with " + id.with);
 578            }
 579        } else {
 580            Log.d(Config.LOGTAG, id.account.getJid() + ": ignoring reject from " + from + " for session with " + id.with);
 581        }
 582    }
 583
 584    private void receiveRejectFromMyself(String serverMsgId, long timestamp) {
 585        if (transition(State.REJECTED)) {
 586            this.xmppConnectionService.getNotificationService().cancelIncomingCallNotification();
 587            this.finish();
 588            if (serverMsgId != null) {
 589                this.message.setServerMsgId(serverMsgId);
 590            }
 591            this.message.setTime(timestamp);
 592            this.message.setCarbon(true); //indicate that call was rejected on other device
 593            writeLogMessageMissed();
 594        } else {
 595            Log.d(Config.LOGTAG, "not able to transition into REJECTED because already in " + this.state);
 596        }
 597    }
 598
 599    private void receiveRejectFromResponder() {
 600        if (isInState(State.PROCEED)) {
 601            Log.d(Config.LOGTAG, id.account.getJid() + ": received reject while still in proceed. callee reconsidered");
 602            closeTransitionLogFinish(State.REJECTED_RACED);
 603            return;
 604        }
 605        if (isInState(State.SESSION_INITIALIZED_PRE_APPROVED)) {
 606            Log.d(Config.LOGTAG, id.account.getJid() + ": received reject while in SESSION_INITIATED_PRE_APPROVED. callee reconsidered before receiving session-init");
 607            closeTransitionLogFinish(State.TERMINATED_DECLINED_OR_BUSY);
 608            return;
 609        }
 610        Log.d(Config.LOGTAG, id.account.getJid() + ": ignoring reject from responder because already in state " + this.state);
 611    }
 612
 613    private void receivePropose(final Jid from, final Propose propose, final String serverMsgId, final long timestamp) {
 614        final boolean originatedFromMyself = from.asBareJid().equals(id.account.getJid().asBareJid());
 615        if (originatedFromMyself) {
 616            Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": saw proposal from myself. ignoring");
 617        } else if (transition(State.PROPOSED, () -> {
 618            final Collection<RtpDescription> descriptions = Collections2.transform(
 619                    Collections2.filter(propose.getDescriptions(), d -> d instanceof RtpDescription),
 620                    input -> (RtpDescription) input
 621            );
 622            final Collection<Media> media = Collections2.transform(descriptions, RtpDescription::getMedia);
 623            Preconditions.checkState(!media.contains(Media.UNKNOWN), "RTP descriptions contain unknown media");
 624            Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": received session proposal from " + from + " for " + media);
 625            this.proposedMedia = Sets.newHashSet(media);
 626        })) {
 627            if (serverMsgId != null) {
 628                this.message.setServerMsgId(serverMsgId);
 629            }
 630            this.message.setTime(timestamp);
 631            startRinging();
 632        } else {
 633            Log.d(Config.LOGTAG, id.account.getJid() + ": ignoring session proposal because already in " + state);
 634        }
 635    }
 636
 637    private void startRinging() {
 638        Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": received call from " + id.with + ". start ringing");
 639        ringingTimeoutFuture = jingleConnectionManager.schedule(this::ringingTimeout, BUSY_TIME_OUT, TimeUnit.SECONDS);
 640        xmppConnectionService.getNotificationService().startRinging(id, getMedia());
 641    }
 642
 643    private synchronized void ringingTimeout() {
 644        Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": timeout reached for ringing");
 645        switch (this.state) {
 646            case PROPOSED:
 647                message.markUnread();
 648                rejectCallFromProposed();
 649                break;
 650            case SESSION_INITIALIZED:
 651                message.markUnread();
 652                rejectCallFromSessionInitiate();
 653                break;
 654        }
 655    }
 656
 657    private void cancelRingingTimeout() {
 658        final ScheduledFuture<?> future = this.ringingTimeoutFuture;
 659        if (future != null && !future.isCancelled()) {
 660            future.cancel(false);
 661        }
 662    }
 663
 664    private void receiveProceed(final Jid from, final Proceed proceed, final String serverMsgId, final long timestamp) {
 665        final Set<Media> media = Preconditions.checkNotNull(this.proposedMedia, "Proposed media has to be set before handling proceed");
 666        Preconditions.checkState(media.size() > 0, "Proposed media should not be empty");
 667        if (from.equals(id.with)) {
 668            if (isInitiator()) {
 669                if (transition(State.PROCEED)) {
 670                    if (serverMsgId != null) {
 671                        this.message.setServerMsgId(serverMsgId);
 672                    }
 673                    this.message.setTime(timestamp);
 674                    this.omemoVerification.setDeviceId(proceed.getDeviceId());
 675                    this.sendSessionInitiate(media, State.SESSION_INITIALIZED_PRE_APPROVED);
 676                } else {
 677                    Log.d(Config.LOGTAG, String.format("%s: ignoring proceed because already in %s", id.account.getJid().asBareJid(), this.state));
 678                }
 679            } else {
 680                Log.d(Config.LOGTAG, String.format("%s: ignoring proceed because we were not initializing", id.account.getJid().asBareJid()));
 681            }
 682        } else if (from.asBareJid().equals(id.account.getJid().asBareJid())) {
 683            if (transition(State.ACCEPTED)) {
 684                Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": moved session with " + id.with + " into state accepted after received carbon copied procced");
 685                this.xmppConnectionService.getNotificationService().cancelIncomingCallNotification();
 686                this.finish();
 687            }
 688        } else {
 689            Log.d(Config.LOGTAG, String.format("%s: ignoring proceed from %s. was expected from %s", id.account.getJid().asBareJid(), from, id.with));
 690        }
 691    }
 692
 693    private void receiveRetract(final Jid from, final String serverMsgId, final long timestamp) {
 694        if (from.equals(id.with)) {
 695            final State target = this.state == State.PROCEED ? State.RETRACTED_RACED : State.RETRACTED;
 696            if (transition(target)) {
 697                xmppConnectionService.getNotificationService().cancelIncomingCallNotification();
 698                Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": session with " + id.with + " has been retracted (serverMsgId=" + serverMsgId + ")");
 699                if (serverMsgId != null) {
 700                    this.message.setServerMsgId(serverMsgId);
 701                }
 702                this.message.setTime(timestamp);
 703                if (target == State.RETRACTED) {
 704                    this.message.markUnread();
 705                }
 706                writeLogMessageMissed();
 707                finish();
 708            } else {
 709                Log.d(Config.LOGTAG, "ignoring retract because already in " + this.state);
 710            }
 711        } else {
 712            //TODO parse retract from self
 713            Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": received retract from " + from + ". expected retract from" + id.with + ". ignoring");
 714        }
 715    }
 716
 717    public void sendSessionInitiate() {
 718        sendSessionInitiate(this.proposedMedia, State.SESSION_INITIALIZED);
 719    }
 720
 721    private void sendSessionInitiate(final Set<Media> media, final State targetState) {
 722        Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": prepare session-initiate");
 723        discoverIceServers(iceServers -> sendSessionInitiate(media, targetState, iceServers));
 724    }
 725
 726    private synchronized void sendSessionInitiate(final Set<Media> media, final State targetState, final List<PeerConnection.IceServer> iceServers) {
 727        if (isTerminated()) {
 728            Log.w(Config.LOGTAG, id.account.getJid().asBareJid() + ": ICE servers got discovered when session was already terminated. nothing to do.");
 729            return;
 730        }
 731        try {
 732            setupWebRTC(media, iceServers);
 733        } catch (final WebRTCWrapper.InitializationException e) {
 734            Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": unable to initialize WebRTC");
 735            webRTCWrapper.close();
 736            sendJingleMessage("retract", id.with.asBareJid());
 737            transitionOrThrow(State.TERMINATED_APPLICATION_FAILURE);
 738            this.finish();
 739            return;
 740        }
 741        try {
 742            org.webrtc.SessionDescription webRTCSessionDescription = this.webRTCWrapper.createOffer().get();
 743            final SessionDescription sessionDescription = SessionDescription.parse(webRTCSessionDescription.description);
 744            final RtpContentMap rtpContentMap = RtpContentMap.of(sessionDescription);
 745            sendSessionInitiate(rtpContentMap, targetState);
 746            this.webRTCWrapper.setLocalDescription(webRTCSessionDescription).get();
 747        } catch (final Exception e) {
 748            Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": unable to sendSessionInitiate", Throwables.getRootCause(e));
 749            webRTCWrapper.close();
 750            if (isInState(targetState)) {
 751                sendSessionTerminate(Reason.FAILED_APPLICATION);
 752            } else {
 753                sendJingleMessage("retract", id.with.asBareJid());
 754                transitionOrThrow(State.TERMINATED_APPLICATION_FAILURE);
 755                this.finish();
 756            }
 757        }
 758    }
 759
 760    private void sendSessionInitiate(final RtpContentMap rtpContentMap, final State targetState) {
 761        this.initiatorRtpContentMap = rtpContentMap;
 762        this.transitionOrThrow(targetState);
 763        //TODO do on background thread?
 764        final RtpContentMap outgoingContentMap = encryptSessionInitiate(rtpContentMap);
 765        final JinglePacket sessionInitiate = outgoingContentMap.toJinglePacket(JinglePacket.Action.SESSION_INITIATE, id.sessionId);
 766        send(sessionInitiate);
 767    }
 768
 769    private RtpContentMap encryptSessionInitiate(final RtpContentMap rtpContentMap) {
 770        if (this.omemoVerification.hasDeviceId()) {
 771            final AxolotlService.OmemoVerifiedPayload<OmemoVerifiedRtpContentMap> verifiedPayload;
 772            try {
 773                verifiedPayload = id.account.getAxolotlService().encrypt(rtpContentMap, id.with, omemoVerification.getDeviceId());
 774            } catch (final CryptoFailedException e) {
 775                Log.w(Config.LOGTAG,id.account.getJid().asBareJid()+": unable to use OMEMO DTLS verification on outgoing session initiate. falling back", e);
 776                return rtpContentMap;
 777            }
 778            this.omemoVerification.setSessionFingerprint(verifiedPayload.getFingerprint());
 779            return verifiedPayload.getPayload();
 780        } else {
 781            return rtpContentMap;
 782        }
 783    }
 784
 785    private void sendSessionTerminate(final Reason reason) {
 786        sendSessionTerminate(reason, null);
 787    }
 788
 789    private void sendSessionTerminate(final Reason reason, final String text) {
 790        final State previous = this.state;
 791        final State target = reasonToState(reason);
 792        transitionOrThrow(target);
 793        if (previous != State.NULL) {
 794            writeLogMessage(target);
 795        }
 796        final JinglePacket jinglePacket = new JinglePacket(JinglePacket.Action.SESSION_TERMINATE, id.sessionId);
 797        jinglePacket.setReason(reason, text);
 798        Log.d(Config.LOGTAG, jinglePacket.toString());
 799        send(jinglePacket);
 800        finish();
 801    }
 802
 803    private void sendTransportInfo(final String contentName, IceUdpTransportInfo.Candidate candidate) {
 804        final RtpContentMap transportInfo;
 805        try {
 806            final RtpContentMap rtpContentMap = isInitiator() ? this.initiatorRtpContentMap : this.responderRtpContentMap;
 807            transportInfo = rtpContentMap.transportInfo(contentName, candidate);
 808        } catch (final Exception e) {
 809            Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": unable to prepare transport-info from candidate for content=" + contentName);
 810            return;
 811        }
 812        final JinglePacket jinglePacket = transportInfo.toJinglePacket(JinglePacket.Action.TRANSPORT_INFO, id.sessionId);
 813        send(jinglePacket);
 814    }
 815
 816    private void send(final JinglePacket jinglePacket) {
 817        jinglePacket.setTo(id.with);
 818        xmppConnectionService.sendIqPacket(id.account, jinglePacket, this::handleIqResponse);
 819    }
 820
 821    private synchronized void handleIqResponse(final Account account, final IqPacket response) {
 822        if (response.getType() == IqPacket.TYPE.ERROR) {
 823            final String errorCondition = response.getErrorCondition();
 824            Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": received IQ-error from " + response.getFrom() + " in RTP session. " + errorCondition);
 825            if (isTerminated()) {
 826                Log.i(Config.LOGTAG, id.account.getJid().asBareJid() + ": ignoring error because session was already terminated");
 827                return;
 828            }
 829            this.webRTCWrapper.close();
 830            final State target;
 831            if (Arrays.asList(
 832                    "service-unavailable",
 833                    "recipient-unavailable",
 834                    "remote-server-not-found",
 835                    "remote-server-timeout"
 836            ).contains(errorCondition)) {
 837                target = State.TERMINATED_CONNECTIVITY_ERROR;
 838            } else {
 839                target = State.TERMINATED_APPLICATION_FAILURE;
 840            }
 841            transitionOrThrow(target);
 842            this.finish();
 843        } else if (response.getType() == IqPacket.TYPE.TIMEOUT) {
 844            Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": received IQ timeout in RTP session with " + id.with + ". terminating with connectivity error");
 845            if (isTerminated()) {
 846                Log.i(Config.LOGTAG, id.account.getJid().asBareJid() + ": ignoring error because session was already terminated");
 847                return;
 848            }
 849            this.webRTCWrapper.close();
 850            transitionOrThrow(State.TERMINATED_CONNECTIVITY_ERROR);
 851            this.finish();
 852        }
 853    }
 854
 855    private void terminateWithOutOfOrder(final JinglePacket jinglePacket) {
 856        Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": terminating session with out-of-order");
 857        this.webRTCWrapper.close();
 858        transitionOrThrow(State.TERMINATED_APPLICATION_FAILURE);
 859        respondWithOutOfOrder(jinglePacket);
 860        this.finish();
 861    }
 862
 863    private void respondWithOutOfOrder(final JinglePacket jinglePacket) {
 864        jingleConnectionManager.respondWithJingleError(id.account, jinglePacket, "out-of-order", "unexpected-request", "wait");
 865    }
 866
 867    private void respondOk(final JinglePacket jinglePacket) {
 868        xmppConnectionService.sendIqPacket(id.account, jinglePacket.generateResponse(IqPacket.TYPE.RESULT), null);
 869    }
 870
 871    public void throwStateTransitionException() {
 872        final StateTransitionException exception = this.stateTransitionException;
 873        if (exception != null) {
 874            throw new IllegalStateException(String.format("Transition to %s did not call finish", exception.state), exception);
 875        }
 876    }
 877
 878    public RtpEndUserState getEndUserState() {
 879        switch (this.state) {
 880            case NULL:
 881            case PROPOSED:
 882            case SESSION_INITIALIZED:
 883                if (isInitiator()) {
 884                    return RtpEndUserState.RINGING;
 885                } else {
 886                    return RtpEndUserState.INCOMING_CALL;
 887                }
 888            case PROCEED:
 889                if (isInitiator()) {
 890                    return RtpEndUserState.RINGING;
 891                } else {
 892                    return RtpEndUserState.ACCEPTING_CALL;
 893                }
 894            case SESSION_INITIALIZED_PRE_APPROVED:
 895                if (isInitiator()) {
 896                    return RtpEndUserState.RINGING;
 897                } else {
 898                    return RtpEndUserState.CONNECTING;
 899                }
 900            case SESSION_ACCEPTED:
 901                final PeerConnection.PeerConnectionState state;
 902                try {
 903                    state = webRTCWrapper.getState();
 904                } catch (final WebRTCWrapper.PeerConnectionNotInitialized e) {
 905                    //We usually close the WebRTCWrapper *before* transitioning so we might still
 906                    //be in SESSION_ACCEPTED even though the peerConnection has been torn down
 907                    return RtpEndUserState.ENDING_CALL;
 908                }
 909                if (state == PeerConnection.PeerConnectionState.CONNECTED) {
 910                    return RtpEndUserState.CONNECTED;
 911                } else if (state == PeerConnection.PeerConnectionState.NEW || state == PeerConnection.PeerConnectionState.CONNECTING) {
 912                    return RtpEndUserState.CONNECTING;
 913                } else if (state == PeerConnection.PeerConnectionState.CLOSED) {
 914                    return RtpEndUserState.ENDING_CALL;
 915                } else {
 916                    return rtpConnectionStarted == 0 ? RtpEndUserState.CONNECTIVITY_ERROR : RtpEndUserState.CONNECTIVITY_LOST_ERROR;
 917                }
 918            case REJECTED:
 919            case REJECTED_RACED:
 920            case TERMINATED_DECLINED_OR_BUSY:
 921                if (isInitiator()) {
 922                    return RtpEndUserState.DECLINED_OR_BUSY;
 923                } else {
 924                    return RtpEndUserState.ENDED;
 925                }
 926            case TERMINATED_SUCCESS:
 927            case ACCEPTED:
 928            case RETRACTED:
 929            case TERMINATED_CANCEL_OR_TIMEOUT:
 930                return RtpEndUserState.ENDED;
 931            case RETRACTED_RACED:
 932                if (isInitiator()) {
 933                    return RtpEndUserState.ENDED;
 934                } else {
 935                    return RtpEndUserState.RETRACTED;
 936                }
 937            case TERMINATED_CONNECTIVITY_ERROR:
 938                return rtpConnectionStarted == 0 ? RtpEndUserState.CONNECTIVITY_ERROR : RtpEndUserState.CONNECTIVITY_LOST_ERROR;
 939            case TERMINATED_APPLICATION_FAILURE:
 940                return RtpEndUserState.APPLICATION_ERROR;
 941        }
 942        throw new IllegalStateException(String.format("%s has no equivalent EndUserState", this.state));
 943    }
 944
 945    public Set<Media> getMedia() {
 946        final State current = getState();
 947        if (current == State.NULL) {
 948            if (isInitiator()) {
 949                return Preconditions.checkNotNull(
 950                        this.proposedMedia,
 951                        "RTP connection has not been initialized properly"
 952                );
 953            }
 954            throw new IllegalStateException("RTP connection has not been initialized yet");
 955        }
 956        if (Arrays.asList(State.PROPOSED, State.PROCEED).contains(current)) {
 957            return Preconditions.checkNotNull(
 958                    this.proposedMedia,
 959                    "RTP connection has not been initialized properly"
 960            );
 961        }
 962        final RtpContentMap initiatorContentMap = initiatorRtpContentMap;
 963        if (initiatorContentMap != null) {
 964            return initiatorContentMap.getMedia();
 965        } else if (isTerminated()) {
 966            return Collections.emptySet(); //we might fail before we ever got a chance to set media
 967        } else {
 968            return Preconditions.checkNotNull(this.proposedMedia, "RTP connection has not been initialized properly");
 969        }
 970    }
 971
 972
 973    public synchronized void acceptCall() {
 974        switch (this.state) {
 975            case PROPOSED:
 976                cancelRingingTimeout();
 977                acceptCallFromProposed();
 978                break;
 979            case SESSION_INITIALIZED:
 980                cancelRingingTimeout();
 981                acceptCallFromSessionInitialized();
 982                break;
 983            case ACCEPTED:
 984                Log.w(Config.LOGTAG, id.account.getJid().asBareJid() + ": the call has already been accepted  with another client. UI was just lagging behind");
 985                break;
 986            case PROCEED:
 987            case SESSION_ACCEPTED:
 988                Log.w(Config.LOGTAG, id.account.getJid().asBareJid() + ": the call has already been accepted. user probably double tapped the UI");
 989                break;
 990            default:
 991                throw new IllegalStateException("Can not accept call from " + this.state);
 992        }
 993    }
 994
 995
 996    public void notifyPhoneCall() {
 997        Log.d(Config.LOGTAG, "a phone call has just been started. killing jingle rtp connections");
 998        if (Arrays.asList(State.PROPOSED, State.SESSION_INITIALIZED).contains(this.state)) {
 999            rejectCall();
1000        } else {
1001            endCall();
1002        }
1003    }
1004
1005    public synchronized void rejectCall() {
1006        if (isTerminated()) {
1007            Log.w(Config.LOGTAG, id.account.getJid().asBareJid() + ": received rejectCall() when session has already been terminated. nothing to do");
1008            return;
1009        }
1010        switch (this.state) {
1011            case PROPOSED:
1012                rejectCallFromProposed();
1013                break;
1014            case SESSION_INITIALIZED:
1015                rejectCallFromSessionInitiate();
1016                break;
1017            default:
1018                throw new IllegalStateException("Can not reject call from " + this.state);
1019        }
1020    }
1021
1022    public synchronized void endCall() {
1023        if (isTerminated()) {
1024            Log.w(Config.LOGTAG, id.account.getJid().asBareJid() + ": received endCall() when session has already been terminated. nothing to do");
1025            return;
1026        }
1027        if (isInState(State.PROPOSED) && !isInitiator()) {
1028            rejectCallFromProposed();
1029            return;
1030        }
1031        if (isInState(State.PROCEED)) {
1032            if (isInitiator()) {
1033                retractFromProceed();
1034            } else {
1035                rejectCallFromProceed();
1036            }
1037            return;
1038        }
1039        if (isInitiator() && isInState(State.SESSION_INITIALIZED, State.SESSION_INITIALIZED_PRE_APPROVED)) {
1040            this.webRTCWrapper.close();
1041            sendSessionTerminate(Reason.CANCEL);
1042            return;
1043        }
1044        if (isInState(State.SESSION_INITIALIZED)) {
1045            rejectCallFromSessionInitiate();
1046            return;
1047        }
1048        if (isInState(State.SESSION_INITIALIZED_PRE_APPROVED, State.SESSION_ACCEPTED)) {
1049            this.webRTCWrapper.close();
1050            sendSessionTerminate(Reason.SUCCESS);
1051            return;
1052        }
1053        if (isInState(State.TERMINATED_APPLICATION_FAILURE, State.TERMINATED_CONNECTIVITY_ERROR, State.TERMINATED_DECLINED_OR_BUSY)) {
1054            Log.d(Config.LOGTAG, "ignoring request to end call because already in state " + this.state);
1055            return;
1056        }
1057        throw new IllegalStateException("called 'endCall' while in state " + this.state + ". isInitiator=" + isInitiator());
1058    }
1059
1060    private void retractFromProceed() {
1061        Log.d(Config.LOGTAG, "retract from proceed");
1062        this.sendJingleMessage("retract");
1063        closeTransitionLogFinish(State.RETRACTED_RACED);
1064    }
1065
1066    private void closeTransitionLogFinish(final State state) {
1067        this.webRTCWrapper.close();
1068        transitionOrThrow(state);
1069        writeLogMessage(state);
1070        finish();
1071    }
1072
1073    private void setupWebRTC(final Set<Media> media, final List<PeerConnection.IceServer> iceServers) throws WebRTCWrapper.InitializationException {
1074        this.jingleConnectionManager.ensureConnectionIsRegistered(this);
1075        final AppRTCAudioManager.SpeakerPhonePreference speakerPhonePreference;
1076        if (media.contains(Media.VIDEO)) {
1077            speakerPhonePreference = AppRTCAudioManager.SpeakerPhonePreference.SPEAKER;
1078        } else {
1079            speakerPhonePreference = AppRTCAudioManager.SpeakerPhonePreference.EARPIECE;
1080        }
1081        this.webRTCWrapper.setup(this.xmppConnectionService, speakerPhonePreference);
1082        this.webRTCWrapper.initializePeerConnection(media, iceServers);
1083    }
1084
1085    private void acceptCallFromProposed() {
1086        transitionOrThrow(State.PROCEED);
1087        xmppConnectionService.getNotificationService().cancelIncomingCallNotification();
1088        this.sendJingleMessage("accept", id.account.getJid().asBareJid());
1089        this.sendJingleMessage("proceed");
1090    }
1091
1092    private void rejectCallFromProposed() {
1093        transitionOrThrow(State.REJECTED);
1094        writeLogMessageMissed();
1095        xmppConnectionService.getNotificationService().cancelIncomingCallNotification();
1096        this.sendJingleMessage("reject");
1097        finish();
1098    }
1099
1100    private void rejectCallFromProceed() {
1101        this.sendJingleMessage("reject");
1102        closeTransitionLogFinish(State.REJECTED_RACED);
1103    }
1104
1105    private void rejectCallFromSessionInitiate() {
1106        webRTCWrapper.close();
1107        sendSessionTerminate(Reason.DECLINE);
1108        xmppConnectionService.getNotificationService().cancelIncomingCallNotification();
1109    }
1110
1111    private void sendJingleMessage(final String action) {
1112        sendJingleMessage(action, id.with);
1113    }
1114
1115    private void sendJingleMessage(final String action, final Jid to) {
1116        final MessagePacket messagePacket = new MessagePacket();
1117        messagePacket.setType(MessagePacket.TYPE_CHAT); //we want to carbon copy those
1118        messagePacket.setTo(to);
1119        final Element intent = messagePacket.addChild(action, Namespace.JINGLE_MESSAGE).setAttribute("id", id.sessionId);
1120        if ("proceed".equals(action)) {
1121            messagePacket.setId(JINGLE_MESSAGE_PROCEED_ID_PREFIX + id.sessionId);
1122
1123            //TODO only do this if OMEMO is enable so we have an easy way to opt out
1124            final int deviceId = id.account.getAxolotlService().getOwnDeviceId();
1125            final Element device = intent.addChild("device", Namespace.OMEMO_DTLS_SRTP_VERIFICATION);
1126            device.setAttribute("id", deviceId);
1127        }
1128        messagePacket.addChild("store", "urn:xmpp:hints");
1129        xmppConnectionService.sendMessagePacket(id.account, messagePacket);
1130    }
1131
1132    private void acceptCallFromSessionInitialized() {
1133        xmppConnectionService.getNotificationService().cancelIncomingCallNotification();
1134        sendSessionAccept();
1135    }
1136
1137    private synchronized boolean isInState(State... state) {
1138        return Arrays.asList(state).contains(this.state);
1139    }
1140
1141    private boolean transition(final State target) {
1142        return transition(target, null);
1143    }
1144
1145    private synchronized boolean transition(final State target, final Runnable runnable) {
1146        final Collection<State> validTransitions = VALID_TRANSITIONS.get(this.state);
1147        if (validTransitions != null && validTransitions.contains(target)) {
1148            this.state = target;
1149            this.stateTransitionException = new StateTransitionException(target);
1150            if (runnable != null) {
1151                runnable.run();
1152            }
1153            Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": transitioned into " + target);
1154            updateEndUserState();
1155            updateOngoingCallNotification();
1156            return true;
1157        } else {
1158            return false;
1159        }
1160    }
1161
1162    void transitionOrThrow(final State target) {
1163        if (!transition(target)) {
1164            throw new IllegalStateException(String.format("Unable to transition from %s to %s", this.state, target));
1165        }
1166    }
1167
1168    @Override
1169    public void onIceCandidate(final IceCandidate iceCandidate) {
1170        final IceUdpTransportInfo.Candidate candidate = IceUdpTransportInfo.Candidate.fromSdpAttribute(iceCandidate.sdp);
1171        Log.d(Config.LOGTAG, "sending candidate: " + iceCandidate.toString());
1172        sendTransportInfo(iceCandidate.sdpMid, candidate);
1173    }
1174
1175    @Override
1176    public void onConnectionChange(final PeerConnection.PeerConnectionState newState) {
1177        Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": PeerConnectionState changed to " + newState);
1178        if (newState == PeerConnection.PeerConnectionState.CONNECTED && this.rtpConnectionStarted == 0) {
1179            this.rtpConnectionStarted = SystemClock.elapsedRealtime();
1180        }
1181        if (newState == PeerConnection.PeerConnectionState.CLOSED && this.rtpConnectionEnded == 0) {
1182            this.rtpConnectionEnded = SystemClock.elapsedRealtime();
1183        }
1184        //TODO 'DISCONNECTED' might be an opportunity to renew the offer and send a transport-replace
1185        //TODO exact syntax is yet to be determined but transport-replace sounds like the most reasonable
1186        //as there is no content-replace
1187        if (Arrays.asList(PeerConnection.PeerConnectionState.FAILED, PeerConnection.PeerConnectionState.DISCONNECTED).contains(newState)) {
1188            if (isTerminated()) {
1189                Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": not sending session-terminate after connectivity error because session is already in state " + this.state);
1190                return;
1191            }
1192            new Thread(this::closeWebRTCSessionAfterFailedConnection).start();
1193        } else {
1194            updateEndUserState();
1195        }
1196    }
1197
1198    private void closeWebRTCSessionAfterFailedConnection() {
1199        this.webRTCWrapper.close();
1200        synchronized (this) {
1201            if (isTerminated()) {
1202                Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": no need to send session-terminate after failed connection. Other party already did");
1203                return;
1204            }
1205            sendSessionTerminate(Reason.CONNECTIVITY_ERROR);
1206        }
1207    }
1208
1209    public long getRtpConnectionStarted() {
1210        return this.rtpConnectionStarted;
1211    }
1212
1213    public long getRtpConnectionEnded() {
1214        return this.rtpConnectionEnded;
1215    }
1216
1217    public AppRTCAudioManager getAudioManager() {
1218        return webRTCWrapper.getAudioManager();
1219    }
1220
1221    public boolean isMicrophoneEnabled() {
1222        return webRTCWrapper.isMicrophoneEnabled();
1223    }
1224
1225    public boolean setMicrophoneEnabled(final boolean enabled) {
1226        return webRTCWrapper.setMicrophoneEnabled(enabled);
1227    }
1228
1229    public boolean isVideoEnabled() {
1230        return webRTCWrapper.isVideoEnabled();
1231    }
1232
1233    public void setVideoEnabled(final boolean enabled) {
1234        webRTCWrapper.setVideoEnabled(enabled);
1235    }
1236
1237    public boolean isCameraSwitchable() {
1238        return webRTCWrapper.isCameraSwitchable();
1239    }
1240
1241    public boolean isFrontCamera() {
1242        return webRTCWrapper.isFrontCamera();
1243    }
1244
1245    public ListenableFuture<Boolean> switchCamera() {
1246        return webRTCWrapper.switchCamera();
1247    }
1248
1249    @Override
1250    public void onAudioDeviceChanged(AppRTCAudioManager.AudioDevice selectedAudioDevice, Set<AppRTCAudioManager.AudioDevice> availableAudioDevices) {
1251        xmppConnectionService.notifyJingleRtpConnectionUpdate(selectedAudioDevice, availableAudioDevices);
1252    }
1253
1254    private void updateEndUserState() {
1255        final RtpEndUserState endUserState = getEndUserState();
1256        jingleConnectionManager.toneManager.transition(isInitiator(), endUserState, getMedia());
1257        xmppConnectionService.notifyJingleRtpConnectionUpdate(id.account, id.with, id.sessionId, endUserState);
1258    }
1259
1260    private void updateOngoingCallNotification() {
1261        if (STATES_SHOWING_ONGOING_CALL.contains(this.state)) {
1262            xmppConnectionService.setOngoingCall(id, getMedia());
1263        } else {
1264            xmppConnectionService.removeOngoingCall();
1265        }
1266    }
1267
1268    private void discoverIceServers(final OnIceServersDiscovered onIceServersDiscovered) {
1269        if (id.account.getXmppConnection().getFeatures().externalServiceDiscovery()) {
1270            final IqPacket request = new IqPacket(IqPacket.TYPE.GET);
1271            request.setTo(id.account.getDomain());
1272            request.addChild("services", Namespace.EXTERNAL_SERVICE_DISCOVERY);
1273            xmppConnectionService.sendIqPacket(id.account, request, (account, response) -> {
1274                ImmutableList.Builder<PeerConnection.IceServer> listBuilder = new ImmutableList.Builder<>();
1275                if (response.getType() == IqPacket.TYPE.RESULT) {
1276                    final Element services = response.findChild("services", Namespace.EXTERNAL_SERVICE_DISCOVERY);
1277                    final List<Element> children = services == null ? Collections.emptyList() : services.getChildren();
1278                    for (final Element child : children) {
1279                        if ("service".equals(child.getName())) {
1280                            final String type = child.getAttribute("type");
1281                            final String host = child.getAttribute("host");
1282                            final String sport = child.getAttribute("port");
1283                            final Integer port = sport == null ? null : Ints.tryParse(sport);
1284                            final String transport = child.getAttribute("transport");
1285                            final String username = child.getAttribute("username");
1286                            final String password = child.getAttribute("password");
1287                            if (Strings.isNullOrEmpty(host) || port == null) {
1288                                continue;
1289                            }
1290                            if (port < 0 || port > 65535) {
1291                                continue;
1292                            }
1293                            if (Arrays.asList("stun", "stuns", "turn", "turns").contains(type) && Arrays.asList("udp", "tcp").contains(transport)) {
1294                                if (Arrays.asList("stuns", "turns").contains(type) && "udp".equals(transport)) {
1295                                    Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": skipping invalid combination of udp/tls in external services");
1296                                    continue;
1297                                }
1298                                final PeerConnection.IceServer.Builder iceServerBuilder = PeerConnection.IceServer
1299                                        .builder(String.format("%s:%s:%s?transport=%s", type, IP.wrapIPv6(host), port, transport));
1300                                iceServerBuilder.setTlsCertPolicy(PeerConnection.TlsCertPolicy.TLS_CERT_POLICY_INSECURE_NO_CHECK);
1301                                if (username != null && password != null) {
1302                                    iceServerBuilder.setUsername(username);
1303                                    iceServerBuilder.setPassword(password);
1304                                } else if (Arrays.asList("turn", "turns").contains(type)) {
1305                                    //The WebRTC spec requires throwing an InvalidAccessError when username (from libwebrtc source coder)
1306                                    //https://chromium.googlesource.com/external/webrtc/+/master/pc/ice_server_parsing.cc
1307                                    Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": skipping " + type + "/" + transport + " without username and password");
1308                                    continue;
1309                                }
1310                                final PeerConnection.IceServer iceServer = iceServerBuilder.createIceServer();
1311                                Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": discovered ICE Server: " + iceServer);
1312                                listBuilder.add(iceServer);
1313                            }
1314                        }
1315                    }
1316                }
1317                final List<PeerConnection.IceServer> iceServers = listBuilder.build();
1318                if (iceServers.size() == 0) {
1319                    Log.w(Config.LOGTAG, id.account.getJid().asBareJid() + ": no ICE server found " + response);
1320                }
1321                onIceServersDiscovered.onIceServersDiscovered(iceServers);
1322            });
1323        } else {
1324            Log.w(Config.LOGTAG, id.account.getJid().asBareJid() + ": has no external service discovery");
1325            onIceServersDiscovered.onIceServersDiscovered(Collections.emptyList());
1326        }
1327    }
1328
1329    private void finish() {
1330        if (isTerminated()) {
1331            this.cancelRingingTimeout();
1332            this.webRTCWrapper.verifyClosed();
1333            this.jingleConnectionManager.setTerminalSessionState(id, getEndUserState(), getMedia());
1334            this.jingleConnectionManager.finishConnectionOrThrow(this);
1335        } else {
1336            throw new IllegalStateException(String.format("Unable to call finish from %s", this.state));
1337        }
1338    }
1339
1340    private void writeLogMessage(final State state) {
1341        final long started = this.rtpConnectionStarted;
1342        long duration = started <= 0 ? 0 : SystemClock.elapsedRealtime() - started;
1343        if (state == State.TERMINATED_SUCCESS || (state == State.TERMINATED_CONNECTIVITY_ERROR && duration > 0)) {
1344            writeLogMessageSuccess(duration);
1345        } else {
1346            writeLogMessageMissed();
1347        }
1348    }
1349
1350    private void writeLogMessageSuccess(final long duration) {
1351        this.message.setBody(new RtpSessionStatus(true, duration).toString());
1352        this.writeMessage();
1353    }
1354
1355    private void writeLogMessageMissed() {
1356        this.message.setBody(new RtpSessionStatus(false, 0).toString());
1357        this.writeMessage();
1358    }
1359
1360    private void writeMessage() {
1361        final Conversational conversational = message.getConversation();
1362        if (conversational instanceof Conversation) {
1363            ((Conversation) conversational).add(this.message);
1364            xmppConnectionService.createMessageAsync(message);
1365            xmppConnectionService.updateConversationUi();
1366        } else {
1367            throw new IllegalStateException("Somehow the conversation in a message was a stub");
1368        }
1369    }
1370
1371    public State getState() {
1372        return this.state;
1373    }
1374
1375    boolean isTerminated() {
1376        return TERMINATED.contains(this.state);
1377    }
1378
1379    public Optional<VideoTrack> getLocalVideoTrack() {
1380        return webRTCWrapper.getLocalVideoTrack();
1381    }
1382
1383    public Optional<VideoTrack> getRemoteVideoTrack() {
1384        return webRTCWrapper.getRemoteVideoTrack();
1385    }
1386
1387
1388    public EglBase.Context getEglBaseContext() {
1389        return webRTCWrapper.getEglBaseContext();
1390    }
1391
1392    void setProposedMedia(final Set<Media> media) {
1393        this.proposedMedia = media;
1394    }
1395
1396    public void fireStateUpdate() {
1397        final RtpEndUserState endUserState = getEndUserState();
1398        xmppConnectionService.notifyJingleRtpConnectionUpdate(id.account, id.with, id.sessionId, endUserState);
1399    }
1400
1401    private interface OnIceServersDiscovered {
1402        void onIceServersDiscovered(List<PeerConnection.IceServer> iceServers);
1403    }
1404
1405    private static class StateTransitionException extends Exception {
1406        private final State state;
1407
1408        private StateTransitionException(final State state) {
1409            this.state = state;
1410        }
1411    }
1412}