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