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 target = reasonToState(reason);
 661        transitionOrThrow(target);
 662        writeLogMessage(target);
 663        final JinglePacket jinglePacket = new JinglePacket(JinglePacket.Action.SESSION_TERMINATE, id.sessionId);
 664        jinglePacket.setReason(reason, text);
 665        Log.d(Config.LOGTAG, jinglePacket.toString());
 666        send(jinglePacket);
 667        finish();
 668    }
 669
 670    private void sendTransportInfo(final String contentName, IceUdpTransportInfo.Candidate candidate) {
 671        final RtpContentMap transportInfo;
 672        try {
 673            final RtpContentMap rtpContentMap = isInitiator() ? this.initiatorRtpContentMap : this.responderRtpContentMap;
 674            transportInfo = rtpContentMap.transportInfo(contentName, candidate);
 675        } catch (Exception e) {
 676            Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": unable to prepare transport-info from candidate for content=" + contentName);
 677            return;
 678        }
 679        final JinglePacket jinglePacket = transportInfo.toJinglePacket(JinglePacket.Action.TRANSPORT_INFO, id.sessionId);
 680        send(jinglePacket);
 681    }
 682
 683    private void send(final JinglePacket jinglePacket) {
 684        jinglePacket.setTo(id.with);
 685        xmppConnectionService.sendIqPacket(id.account, jinglePacket, this::handleIqResponse);
 686    }
 687
 688    private synchronized void handleIqResponse(final Account account, final IqPacket response) {
 689        if (response.getType() == IqPacket.TYPE.ERROR) {
 690            final String errorCondition = response.getErrorCondition();
 691            Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": received IQ-error from " + response.getFrom() + " in RTP session. " + errorCondition);
 692            if (isTerminated()) {
 693                Log.i(Config.LOGTAG, id.account.getJid().asBareJid() + ": ignoring error because session was already terminated");
 694                return;
 695            }
 696            this.webRTCWrapper.close();
 697            final State target;
 698            if (Arrays.asList(
 699                    "service-unavailable",
 700                    "recipient-unavailable",
 701                    "remote-server-not-found",
 702                    "remote-server-timeout"
 703            ).contains(errorCondition)) {
 704                target = State.TERMINATED_CONNECTIVITY_ERROR;
 705            } else {
 706                target = State.TERMINATED_APPLICATION_FAILURE;
 707            }
 708            transitionOrThrow(target);
 709            this.finish();
 710        } else if (response.getType() == IqPacket.TYPE.TIMEOUT) {
 711            Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": received IQ timeout in RTP session with " + id.with + ". terminating with connectivity error");
 712            if (isTerminated()) {
 713                Log.i(Config.LOGTAG, id.account.getJid().asBareJid() + ": ignoring error because session was already terminated");
 714                return;
 715            }
 716            this.webRTCWrapper.close();
 717            transitionOrThrow(State.TERMINATED_CONNECTIVITY_ERROR);
 718            this.finish();
 719        }
 720    }
 721
 722    private void terminateWithOutOfOrder(final JinglePacket jinglePacket) {
 723        Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": terminating session with out-of-order");
 724        this.webRTCWrapper.close();
 725        transitionOrThrow(State.TERMINATED_APPLICATION_FAILURE);
 726        respondWithOutOfOrder(jinglePacket);
 727        this.finish();
 728    }
 729
 730    private void respondWithOutOfOrder(final JinglePacket jinglePacket) {
 731        jingleConnectionManager.respondWithJingleError(id.account, jinglePacket, "out-of-order", "unexpected-request", "wait");
 732    }
 733
 734    private void respondOk(final JinglePacket jinglePacket) {
 735        xmppConnectionService.sendIqPacket(id.account, jinglePacket.generateResponse(IqPacket.TYPE.RESULT), null);
 736    }
 737
 738    public RtpEndUserState getEndUserState() {
 739        switch (this.state) {
 740            case PROPOSED:
 741            case SESSION_INITIALIZED:
 742                if (isInitiator()) {
 743                    return RtpEndUserState.RINGING;
 744                } else {
 745                    return RtpEndUserState.INCOMING_CALL;
 746                }
 747            case PROCEED:
 748                if (isInitiator()) {
 749                    return RtpEndUserState.RINGING;
 750                } else {
 751                    return RtpEndUserState.ACCEPTING_CALL;
 752                }
 753            case SESSION_INITIALIZED_PRE_APPROVED:
 754                if (isInitiator()) {
 755                    return RtpEndUserState.RINGING;
 756                } else {
 757                    return RtpEndUserState.CONNECTING;
 758                }
 759            case SESSION_ACCEPTED:
 760                final PeerConnection.PeerConnectionState state = webRTCWrapper.getState();
 761                if (state == PeerConnection.PeerConnectionState.CONNECTED) {
 762                    return RtpEndUserState.CONNECTED;
 763                } else if (state == PeerConnection.PeerConnectionState.NEW || state == PeerConnection.PeerConnectionState.CONNECTING) {
 764                    return RtpEndUserState.CONNECTING;
 765                } else if (state == PeerConnection.PeerConnectionState.CLOSED) {
 766                    return RtpEndUserState.ENDING_CALL;
 767                } else {
 768                    return RtpEndUserState.CONNECTIVITY_ERROR;
 769                }
 770            case REJECTED:
 771            case TERMINATED_DECLINED_OR_BUSY:
 772                if (isInitiator()) {
 773                    return RtpEndUserState.DECLINED_OR_BUSY;
 774                } else {
 775                    return RtpEndUserState.ENDED;
 776                }
 777            case TERMINATED_SUCCESS:
 778            case ACCEPTED:
 779            case RETRACTED:
 780            case TERMINATED_CANCEL_OR_TIMEOUT:
 781                return RtpEndUserState.ENDED;
 782            case TERMINATED_CONNECTIVITY_ERROR:
 783                return RtpEndUserState.CONNECTIVITY_ERROR;
 784            case TERMINATED_APPLICATION_FAILURE:
 785                return RtpEndUserState.APPLICATION_ERROR;
 786        }
 787        throw new IllegalStateException(String.format("%s has no equivalent EndUserState", this.state));
 788    }
 789
 790    public Set<Media> getMedia() {
 791        if (isInState(State.NULL)) {
 792            throw new IllegalStateException("RTP connection has not been initialized yet");
 793        }
 794        if (isInState(State.PROPOSED, State.PROCEED)) {
 795            return Preconditions.checkNotNull(this.proposedMedia, "RTP connection has not been initialized properly");
 796        }
 797        final RtpContentMap initiatorContentMap = initiatorRtpContentMap;
 798        if (initiatorContentMap != null) {
 799            return initiatorContentMap.getMedia();
 800        } else {
 801            return Preconditions.checkNotNull(this.proposedMedia, "RTP connection has not been initialized properly");
 802        }
 803    }
 804
 805
 806    public synchronized void acceptCall() {
 807        switch (this.state) {
 808            case PROPOSED:
 809                cancelRingingTimeout();
 810                acceptCallFromProposed();
 811                break;
 812            case SESSION_INITIALIZED:
 813                cancelRingingTimeout();
 814                acceptCallFromSessionInitialized();
 815                break;
 816            case ACCEPTED:
 817                Log.w(Config.LOGTAG, id.account.getJid().asBareJid() + ": the call has already been accepted  with another client. UI was just lagging behind");
 818                break;
 819            case PROCEED:
 820            case SESSION_ACCEPTED:
 821                Log.w(Config.LOGTAG, id.account.getJid().asBareJid() + ": the call has already been accepted. user probably double tapped the UI");
 822                break;
 823            default:
 824                throw new IllegalStateException("Can not accept call from " + this.state);
 825        }
 826    }
 827
 828    public synchronized void rejectCall() {
 829        switch (this.state) {
 830            case PROPOSED:
 831                rejectCallFromProposed();
 832                break;
 833            case SESSION_INITIALIZED:
 834                rejectCallFromSessionInitiate();
 835                break;
 836            default:
 837                throw new IllegalStateException("Can not reject call from " + this.state);
 838        }
 839    }
 840
 841    public synchronized void endCall() {
 842        if (isTerminated()) {
 843            Log.w(Config.LOGTAG, id.account.getJid().asBareJid() + ": received endCall() when session has already been terminated. nothing to do");
 844            return;
 845        }
 846        if (isInState(State.PROPOSED) && !isInitiator()) {
 847            rejectCallFromProposed();
 848            return;
 849        }
 850        if (isInState(State.PROCEED)) {
 851            Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": ending call while in state PROCEED just means ending the connection");
 852            this.jingleConnectionManager.endSession(id, State.TERMINATED_SUCCESS);
 853            this.webRTCWrapper.close();
 854            this.finish();
 855            transitionOrThrow(State.TERMINATED_SUCCESS); //arguably this wasn't success; but not a real failure either
 856            return;
 857        }
 858        if (isInitiator() && isInState(State.SESSION_INITIALIZED, State.SESSION_INITIALIZED_PRE_APPROVED)) {
 859            this.webRTCWrapper.close();
 860            sendSessionTerminate(Reason.CANCEL);
 861            return;
 862        }
 863        if (isInState(State.SESSION_INITIALIZED)) {
 864            rejectCallFromSessionInitiate();
 865            return;
 866        }
 867        if (isInState(State.SESSION_INITIALIZED_PRE_APPROVED, State.SESSION_ACCEPTED)) {
 868            this.webRTCWrapper.close();
 869            sendSessionTerminate(Reason.SUCCESS);
 870            return;
 871        }
 872        if (isInState(State.TERMINATED_APPLICATION_FAILURE, State.TERMINATED_CONNECTIVITY_ERROR, State.TERMINATED_DECLINED_OR_BUSY)) {
 873            Log.d(Config.LOGTAG, "ignoring request to end call because already in state " + this.state);
 874            return;
 875        }
 876        throw new IllegalStateException("called 'endCall' while in state " + this.state + ". isInitiator=" + isInitiator());
 877    }
 878
 879    private void setupWebRTC(final Set<Media> media, final List<PeerConnection.IceServer> iceServers) throws WebRTCWrapper.InitializationException {
 880        this.jingleConnectionManager.ensureConnectionIsRegistered(this);
 881        final AppRTCAudioManager.SpeakerPhonePreference speakerPhonePreference;
 882        if (media.contains(Media.VIDEO)) {
 883            speakerPhonePreference = AppRTCAudioManager.SpeakerPhonePreference.SPEAKER;
 884        } else {
 885            speakerPhonePreference = AppRTCAudioManager.SpeakerPhonePreference.EARPIECE;
 886        }
 887        this.webRTCWrapper.setup(this.xmppConnectionService, speakerPhonePreference);
 888        this.webRTCWrapper.initializePeerConnection(media, iceServers);
 889    }
 890
 891    private void acceptCallFromProposed() {
 892        transitionOrThrow(State.PROCEED);
 893        xmppConnectionService.getNotificationService().cancelIncomingCallNotification();
 894        this.sendJingleMessage("accept", id.account.getJid().asBareJid());
 895        this.sendJingleMessage("proceed");
 896    }
 897
 898    private void rejectCallFromProposed() {
 899        transitionOrThrow(State.REJECTED);
 900        writeLogMessageMissed();
 901        xmppConnectionService.getNotificationService().cancelIncomingCallNotification();
 902        this.sendJingleMessage("reject");
 903        finish();
 904    }
 905
 906    private void rejectCallFromSessionInitiate() {
 907        webRTCWrapper.close();
 908        sendSessionTerminate(Reason.DECLINE);
 909        xmppConnectionService.getNotificationService().cancelIncomingCallNotification();
 910    }
 911
 912    private void sendJingleMessage(final String action) {
 913        sendJingleMessage(action, id.with);
 914    }
 915
 916    private void sendJingleMessage(final String action, final Jid to) {
 917        final MessagePacket messagePacket = new MessagePacket();
 918        if ("proceed".equals(action)) {
 919            messagePacket.setId(JINGLE_MESSAGE_PROCEED_ID_PREFIX + id.sessionId);
 920        }
 921        messagePacket.setType(MessagePacket.TYPE_CHAT); //we want to carbon copy those
 922        messagePacket.setTo(to);
 923        messagePacket.addChild(action, Namespace.JINGLE_MESSAGE).setAttribute("id", id.sessionId);
 924        messagePacket.addChild("store", "urn:xmpp:hints");
 925        xmppConnectionService.sendMessagePacket(id.account, messagePacket);
 926    }
 927
 928    private void acceptCallFromSessionInitialized() {
 929        xmppConnectionService.getNotificationService().cancelIncomingCallNotification();
 930        sendSessionAccept();
 931    }
 932
 933    private synchronized boolean isInState(State... state) {
 934        return Arrays.asList(state).contains(this.state);
 935    }
 936
 937    private boolean transition(final State target) {
 938        return transition(target, null);
 939    }
 940
 941    private synchronized boolean transition(final State target, final Runnable runnable) {
 942        final Collection<State> validTransitions = VALID_TRANSITIONS.get(this.state);
 943        if (validTransitions != null && validTransitions.contains(target)) {
 944            this.state = target;
 945            if (runnable != null) {
 946                runnable.run();
 947            }
 948            Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": transitioned into " + target);
 949            updateEndUserState();
 950            updateOngoingCallNotification();
 951            return true;
 952        } else {
 953            return false;
 954        }
 955    }
 956
 957    void transitionOrThrow(final State target) {
 958        if (!transition(target)) {
 959            throw new IllegalStateException(String.format("Unable to transition from %s to %s", this.state, target));
 960        }
 961    }
 962
 963    @Override
 964    public void onIceCandidate(final IceCandidate iceCandidate) {
 965        final IceUdpTransportInfo.Candidate candidate = IceUdpTransportInfo.Candidate.fromSdpAttribute(iceCandidate.sdp);
 966        Log.d(Config.LOGTAG, "sending candidate: " + iceCandidate.toString());
 967        sendTransportInfo(iceCandidate.sdpMid, candidate);
 968    }
 969
 970    @Override
 971    public void onConnectionChange(final PeerConnection.PeerConnectionState newState) {
 972        Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": PeerConnectionState changed to " + newState);
 973        if (newState == PeerConnection.PeerConnectionState.CONNECTED && this.rtpConnectionStarted == 0) {
 974            this.rtpConnectionStarted = SystemClock.elapsedRealtime();
 975        }
 976        //TODO 'DISCONNECTED' might be an opportunity to renew the offer and send a transport-replace
 977        //TODO exact syntax is yet to be determined but transport-replace sounds like the most reasonable
 978        //as there is no content-replace
 979        if (Arrays.asList(PeerConnection.PeerConnectionState.FAILED, PeerConnection.PeerConnectionState.DISCONNECTED).contains(newState)) {
 980            if (isTerminated()) {
 981                Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": not sending session-terminate after connectivity error because session is already in state " + this.state);
 982                return;
 983            }
 984            new Thread(this::closeWebRTCSessionAfterFailedConnection).start();
 985        } else {
 986            updateEndUserState();
 987        }
 988    }
 989
 990    private void closeWebRTCSessionAfterFailedConnection() {
 991        this.webRTCWrapper.close();
 992        synchronized (this) {
 993            if (isTerminated()) {
 994                Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": no need to send session-terminate after failed connection. Other party already did");
 995                return;
 996            }
 997            sendSessionTerminate(Reason.CONNECTIVITY_ERROR);
 998        }
 999    }
1000
1001    public AppRTCAudioManager getAudioManager() {
1002        return webRTCWrapper.getAudioManager();
1003    }
1004
1005    public boolean isMicrophoneEnabled() {
1006        return webRTCWrapper.isMicrophoneEnabled();
1007    }
1008
1009    public void setMicrophoneEnabled(final boolean enabled) {
1010        webRTCWrapper.setMicrophoneEnabled(enabled);
1011    }
1012
1013    public boolean isVideoEnabled() {
1014        return webRTCWrapper.isVideoEnabled();
1015    }
1016
1017    public void setVideoEnabled(final boolean enabled) {
1018        webRTCWrapper.setVideoEnabled(enabled);
1019    }
1020
1021    @Override
1022    public void onAudioDeviceChanged(AppRTCAudioManager.AudioDevice selectedAudioDevice, Set<AppRTCAudioManager.AudioDevice> availableAudioDevices) {
1023        xmppConnectionService.notifyJingleRtpConnectionUpdate(selectedAudioDevice, availableAudioDevices);
1024    }
1025
1026    private void updateEndUserState() {
1027        xmppConnectionService.notifyJingleRtpConnectionUpdate(id.account, id.with, id.sessionId, getEndUserState());
1028    }
1029
1030    private void updateOngoingCallNotification() {
1031        if (STATES_SHOWING_ONGOING_CALL.contains(this.state)) {
1032            xmppConnectionService.setOngoingCall(id, getMedia());
1033        } else {
1034            xmppConnectionService.removeOngoingCall();
1035        }
1036    }
1037
1038    private void discoverIceServers(final OnIceServersDiscovered onIceServersDiscovered) {
1039        if (id.account.getXmppConnection().getFeatures().externalServiceDiscovery()) {
1040            final IqPacket request = new IqPacket(IqPacket.TYPE.GET);
1041            request.setTo(Jid.of(id.account.getJid().getDomain()));
1042            request.addChild("services", Namespace.EXTERNAL_SERVICE_DISCOVERY);
1043            xmppConnectionService.sendIqPacket(id.account, request, (account, response) -> {
1044                ImmutableList.Builder<PeerConnection.IceServer> listBuilder = new ImmutableList.Builder<>();
1045                if (response.getType() == IqPacket.TYPE.RESULT) {
1046                    final Element services = response.findChild("services", Namespace.EXTERNAL_SERVICE_DISCOVERY);
1047                    final List<Element> children = services == null ? Collections.emptyList() : services.getChildren();
1048                    for (final Element child : children) {
1049                        if ("service".equals(child.getName())) {
1050                            final String type = child.getAttribute("type");
1051                            final String host = child.getAttribute("host");
1052                            final String sport = child.getAttribute("port");
1053                            final Integer port = sport == null ? null : Ints.tryParse(sport);
1054                            final String transport = child.getAttribute("transport");
1055                            final String username = child.getAttribute("username");
1056                            final String password = child.getAttribute("password");
1057                            if (Strings.isNullOrEmpty(host) || port == null) {
1058                                continue;
1059                            }
1060                            if (port < 0 || port > 65535) {
1061                                continue;
1062                            }
1063                            if (Arrays.asList("stun", "stuns", "turn", "turns").contains(type) && Arrays.asList("udp", "tcp").contains(transport)) {
1064                                if (Arrays.asList("stuns", "turns").contains(type) && "udp".equals(transport)) {
1065                                    Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": skipping invalid combination of udp/tls in external services");
1066                                    continue;
1067                                }
1068                                //TODO wrap ipv6 addresses
1069                                PeerConnection.IceServer.Builder iceServerBuilder = PeerConnection.IceServer.builder(String.format("%s:%s:%s?transport=%s", type, host, port, transport));
1070                                if (username != null && password != null) {
1071                                    iceServerBuilder.setUsername(username);
1072                                    iceServerBuilder.setPassword(password);
1073                                } else if (Arrays.asList("turn", "turns").contains(type)) {
1074                                    //The WebRTC spec requires throwing an InvalidAccessError when username (from libwebrtc source coder)
1075                                    //https://chromium.googlesource.com/external/webrtc/+/master/pc/ice_server_parsing.cc
1076                                    Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": skipping " + type + "/" + transport + " without username and password");
1077                                    continue;
1078                                }
1079                                final PeerConnection.IceServer iceServer = iceServerBuilder.createIceServer();
1080                                Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": discovered ICE Server: " + iceServer);
1081                                listBuilder.add(iceServer);
1082                            }
1083                        }
1084                    }
1085                }
1086                List<PeerConnection.IceServer> iceServers = listBuilder.build();
1087                if (iceServers.size() == 0) {
1088                    Log.w(Config.LOGTAG, id.account.getJid().asBareJid() + ": no ICE server found " + response);
1089                }
1090                onIceServersDiscovered.onIceServersDiscovered(iceServers);
1091            });
1092        } else {
1093            Log.w(Config.LOGTAG, id.account.getJid().asBareJid() + ": has no external service discovery");
1094            onIceServersDiscovered.onIceServersDiscovered(Collections.emptyList());
1095        }
1096    }
1097
1098    private void finish() {
1099        this.cancelRingingTimeout();
1100        this.webRTCWrapper.verifyClosed();
1101        this.jingleConnectionManager.finishConnection(this);
1102    }
1103
1104    private void writeLogMessage(final State state) {
1105        final long started = this.rtpConnectionStarted;
1106        long duration = started <= 0 ? 0 : SystemClock.elapsedRealtime() - started;
1107        if (state == State.TERMINATED_SUCCESS || (state == State.TERMINATED_CONNECTIVITY_ERROR && duration > 0)) {
1108            writeLogMessageSuccess(duration);
1109        } else {
1110            writeLogMessageMissed();
1111        }
1112    }
1113
1114    private void writeLogMessageSuccess(final long duration) {
1115        this.message.setBody(new RtpSessionStatus(true, duration).toString());
1116        this.writeMessage();
1117    }
1118
1119    private void writeLogMessageMissed() {
1120        this.message.setBody(new RtpSessionStatus(false, 0).toString());
1121        this.writeMessage();
1122    }
1123
1124    private void writeMessage() {
1125        final Conversational conversational = message.getConversation();
1126        if (conversational instanceof Conversation) {
1127            ((Conversation) conversational).add(this.message);
1128            xmppConnectionService.databaseBackend.createMessage(message);
1129            xmppConnectionService.updateConversationUi();
1130        } else {
1131            throw new IllegalStateException("Somehow the conversation in a message was a stub");
1132        }
1133    }
1134
1135    public State getState() {
1136        return this.state;
1137    }
1138
1139    public boolean isTerminated() {
1140        return TERMINATED.contains(this.state);
1141    }
1142
1143    public Optional<VideoTrack> geLocalVideoTrack() {
1144        return webRTCWrapper.getLocalVideoTrack();
1145    }
1146
1147    public Optional<VideoTrack> getRemoteVideoTrack() {
1148        return webRTCWrapper.getRemoteVideoTrack();
1149    }
1150
1151
1152    public EglBase.Context getEglBaseContext() {
1153        return webRTCWrapper.getEglBaseContext();
1154    }
1155
1156    void setProposedMedia(final Set<Media> media) {
1157        this.proposedMedia = media;
1158    }
1159
1160    private interface OnIceServersDiscovered {
1161        void onIceServersDiscovered(List<PeerConnection.IceServer> iceServers);
1162    }
1163}