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