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