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