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