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