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