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