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