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