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 (transition(State.PROPOSED)) {
 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            if (serverMsgId != null) {
 513                this.message.setServerMsgId(serverMsgId);
 514            }
 515            this.message.setTime(timestamp);
 516            startRinging();
 517        } else {
 518            Log.d(Config.LOGTAG, id.account.getJid() + ": ignoring session proposal because already in " + state);
 519        }
 520    }
 521
 522    private void startRinging() {
 523        Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": received call from " + id.with + ". start ringing");
 524        xmppConnectionService.getNotificationService().showIncomingCallNotification(id);
 525    }
 526
 527    private void receiveProceed(final Jid from, final String serverMsgId, final long timestamp) {
 528        final Set<Media> media = Preconditions.checkNotNull(this.proposedMedia, "Proposed media has to be set before handling proceed");
 529        Preconditions.checkState(media.size() > 0, "Proposed media should not be empty");
 530        if (from.equals(id.with)) {
 531            if (isInitiator()) {
 532                if (transition(State.PROCEED)) {
 533                    if (serverMsgId != null) {
 534                        this.message.setServerMsgId(serverMsgId);
 535                    }
 536                    this.message.setTime(timestamp);
 537                    this.sendSessionInitiate(media, State.SESSION_INITIALIZED_PRE_APPROVED);
 538                } else {
 539                    Log.d(Config.LOGTAG, String.format("%s: ignoring proceed because already in %s", id.account.getJid().asBareJid(), this.state));
 540                }
 541            } else {
 542                Log.d(Config.LOGTAG, String.format("%s: ignoring proceed because we were not initializing", id.account.getJid().asBareJid()));
 543            }
 544        } else if (from.asBareJid().equals(id.account.getJid().asBareJid())) {
 545            if (transition(State.ACCEPTED)) {
 546                Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": moved session with " + id.with + " into state accepted after received carbon copied procced");
 547                this.xmppConnectionService.getNotificationService().cancelIncomingCallNotification();
 548                this.jingleConnectionManager.finishConnection(this);
 549            }
 550        } else {
 551            Log.d(Config.LOGTAG, String.format("%s: ignoring proceed from %s. was expected from %s", id.account.getJid().asBareJid(), from, id.with));
 552        }
 553    }
 554
 555    private void receiveRetract(final Jid from, final String serverMsgId, final long timestamp) {
 556        if (from.equals(id.with)) {
 557            if (transition(State.RETRACTED)) {
 558                xmppConnectionService.getNotificationService().cancelIncomingCallNotification();
 559                Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": session with " + id.with + " has been retracted (serverMsgId=" + serverMsgId + ")");
 560                if (serverMsgId != null) {
 561                    this.message.setServerMsgId(serverMsgId);
 562                }
 563                this.message.setTime(timestamp);
 564                writeLogMessageMissed();
 565                jingleConnectionManager.finishConnection(this);
 566            } else {
 567                Log.d(Config.LOGTAG, "ignoring retract because already in " + this.state);
 568            }
 569        } else {
 570            Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": received retract from " + from + ". expected retract from" + id.with + ". ignoring");
 571        }
 572    }
 573
 574    private void sendSessionInitiate(final Set<Media> media, final State targetState) {
 575        Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": prepare session-initiate");
 576        discoverIceServers(iceServers -> sendSessionInitiate(media, targetState, iceServers));
 577    }
 578
 579    private synchronized void sendSessionInitiate(final Set<Media> media, final State targetState, final List<PeerConnection.IceServer> iceServers) {
 580        if (TERMINATED.contains(this.state)) {
 581            Log.w(Config.LOGTAG, id.account.getJid().asBareJid() + ": ICE servers got discovered when session was already terminated. nothing to do.");
 582            return;
 583        }
 584        try {
 585            setupWebRTC(media, iceServers);
 586        } catch (WebRTCWrapper.InitializationException e) {
 587            Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": unable to initialize webrtc");
 588            transitionOrThrow(State.TERMINATED_APPLICATION_FAILURE);
 589            return;
 590        }
 591        try {
 592            org.webrtc.SessionDescription webRTCSessionDescription = this.webRTCWrapper.createOffer().get();
 593            final SessionDescription sessionDescription = SessionDescription.parse(webRTCSessionDescription.description);
 594            Log.d(Config.LOGTAG, "description: " + webRTCSessionDescription.description);
 595            final RtpContentMap rtpContentMap = RtpContentMap.of(sessionDescription);
 596            sendSessionInitiate(rtpContentMap, targetState);
 597            this.webRTCWrapper.setLocalDescription(webRTCSessionDescription).get();
 598        } catch (final Exception e) {
 599            Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": unable to sendSessionInitiate", e);
 600            webRTCWrapper.close();
 601            if (isInState(targetState)) {
 602                sendSessionTerminate(Reason.FAILED_APPLICATION);
 603            } else {
 604                transitionOrThrow(State.TERMINATED_APPLICATION_FAILURE);
 605            }
 606        }
 607    }
 608
 609    private void sendSessionInitiate(RtpContentMap rtpContentMap, final State targetState) {
 610        this.initiatorRtpContentMap = rtpContentMap;
 611        this.transitionOrThrow(targetState);
 612        final JinglePacket sessionInitiate = rtpContentMap.toJinglePacket(JinglePacket.Action.SESSION_INITIATE, id.sessionId);
 613        send(sessionInitiate);
 614    }
 615
 616    private void sendSessionTerminate(final Reason reason) {
 617        sendSessionTerminate(reason, null);
 618    }
 619
 620    private void sendSessionTerminate(final Reason reason, final String text) {
 621        final State target = reasonToState(reason);
 622        transitionOrThrow(target);
 623        writeLogMessage(target);
 624        final JinglePacket jinglePacket = new JinglePacket(JinglePacket.Action.SESSION_TERMINATE, id.sessionId);
 625        jinglePacket.setReason(reason, text);
 626        Log.d(Config.LOGTAG,jinglePacket.toString());
 627        send(jinglePacket);
 628        jingleConnectionManager.finishConnection(this);
 629    }
 630
 631    private void sendTransportInfo(final String contentName, IceUdpTransportInfo.Candidate candidate) {
 632        final RtpContentMap transportInfo;
 633        try {
 634            final RtpContentMap rtpContentMap = isInitiator() ? this.initiatorRtpContentMap : this.responderRtpContentMap;
 635            transportInfo = rtpContentMap.transportInfo(contentName, candidate);
 636        } catch (Exception e) {
 637            Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": unable to prepare transport-info from candidate for content=" + contentName);
 638            return;
 639        }
 640        final JinglePacket jinglePacket = transportInfo.toJinglePacket(JinglePacket.Action.TRANSPORT_INFO, id.sessionId);
 641        send(jinglePacket);
 642    }
 643
 644    private void send(final JinglePacket jinglePacket) {
 645        jinglePacket.setTo(id.with);
 646        xmppConnectionService.sendIqPacket(id.account, jinglePacket, (account, response) -> {
 647            if (response.getType() == IqPacket.TYPE.ERROR) {
 648                final String errorCondition = response.getErrorCondition();
 649                Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": received IQ-error from " + response.getFrom() + " in RTP session. " + errorCondition);
 650                this.webRTCWrapper.close();
 651                final State target;
 652                if (Arrays.asList(
 653                        "service-unavailable",
 654                        "recipient-unavailable",
 655                        "remote-server-not-found",
 656                        "remote-server-timeout"
 657                ).contains(errorCondition)) {
 658                    target = State.TERMINATED_CONNECTIVITY_ERROR;
 659                } else {
 660                    target = State.TERMINATED_APPLICATION_FAILURE;
 661                }
 662                if (transition(target)) {
 663                    Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": terminated session with " + id.with);
 664                } else {
 665                    Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": not transitioning because already at state=" + this.state);
 666                }
 667
 668            } else if (response.getType() == IqPacket.TYPE.TIMEOUT) {
 669                this.webRTCWrapper.close();
 670                Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": received IQ timeout in RTP session with " + id.with + ". terminating with connectivity error");
 671                transition(State.TERMINATED_CONNECTIVITY_ERROR);
 672                this.jingleConnectionManager.finishConnection(this);
 673            }
 674        });
 675    }
 676
 677    private void terminateWithOutOfOrder(final JinglePacket jinglePacket) {
 678        Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": terminating session with out-of-order");
 679        webRTCWrapper.close();
 680        transitionOrThrow(State.TERMINATED_APPLICATION_FAILURE);
 681        respondWithOutOfOrder(jinglePacket);
 682        jingleConnectionManager.finishConnection(this);
 683    }
 684
 685    private void respondWithOutOfOrder(final JinglePacket jinglePacket) {
 686        jingleConnectionManager.respondWithJingleError(id.account, jinglePacket, "out-of-order", "unexpected-request", "wait");
 687    }
 688
 689    private void respondOk(final JinglePacket jinglePacket) {
 690        xmppConnectionService.sendIqPacket(id.account, jinglePacket.generateResponse(IqPacket.TYPE.RESULT), null);
 691    }
 692
 693    public RtpEndUserState getEndUserState() {
 694        switch (this.state) {
 695            case PROPOSED:
 696            case SESSION_INITIALIZED:
 697                if (isInitiator()) {
 698                    return RtpEndUserState.RINGING;
 699                } else {
 700                    return RtpEndUserState.INCOMING_CALL;
 701                }
 702            case PROCEED:
 703                if (isInitiator()) {
 704                    return RtpEndUserState.RINGING;
 705                } else {
 706                    return RtpEndUserState.ACCEPTING_CALL;
 707                }
 708            case SESSION_INITIALIZED_PRE_APPROVED:
 709                if (isInitiator()) {
 710                    return RtpEndUserState.RINGING;
 711                } else {
 712                    return RtpEndUserState.CONNECTING;
 713                }
 714            case SESSION_ACCEPTED:
 715                final PeerConnection.PeerConnectionState state = webRTCWrapper.getState();
 716                if (state == PeerConnection.PeerConnectionState.CONNECTED) {
 717                    return RtpEndUserState.CONNECTED;
 718                } else if (state == PeerConnection.PeerConnectionState.NEW || state == PeerConnection.PeerConnectionState.CONNECTING) {
 719                    return RtpEndUserState.CONNECTING;
 720                } else if (state == PeerConnection.PeerConnectionState.CLOSED) {
 721                    return RtpEndUserState.ENDING_CALL;
 722                } else if (state == PeerConnection.PeerConnectionState.FAILED) {
 723                    return RtpEndUserState.CONNECTIVITY_ERROR;
 724                } else {
 725                    return RtpEndUserState.ENDING_CALL;
 726                }
 727            case REJECTED:
 728            case TERMINATED_DECLINED_OR_BUSY:
 729                if (isInitiator()) {
 730                    return RtpEndUserState.DECLINED_OR_BUSY;
 731                } else {
 732                    return RtpEndUserState.ENDED;
 733                }
 734            case TERMINATED_SUCCESS:
 735            case ACCEPTED:
 736            case RETRACTED:
 737            case TERMINATED_CANCEL_OR_TIMEOUT:
 738                return RtpEndUserState.ENDED;
 739            case TERMINATED_CONNECTIVITY_ERROR:
 740                return RtpEndUserState.CONNECTIVITY_ERROR;
 741            case TERMINATED_APPLICATION_FAILURE:
 742                return RtpEndUserState.APPLICATION_ERROR;
 743        }
 744        throw new IllegalStateException(String.format("%s has no equivalent EndUserState", this.state));
 745    }
 746
 747
 748    public synchronized void acceptCall() {
 749        switch (this.state) {
 750            case PROPOSED:
 751                acceptCallFromProposed();
 752                break;
 753            case SESSION_INITIALIZED:
 754                acceptCallFromSessionInitialized();
 755                break;
 756            default:
 757                throw new IllegalStateException("Can not accept call from " + this.state);
 758        }
 759    }
 760
 761    public synchronized void rejectCall() {
 762        switch (this.state) {
 763            case PROPOSED:
 764                rejectCallFromProposed();
 765                break;
 766            case SESSION_INITIALIZED:
 767                rejectCallFromSessionInitiate();
 768                break;
 769            default:
 770                throw new IllegalStateException("Can not reject call from " + this.state);
 771        }
 772    }
 773
 774    public synchronized void endCall() {
 775        if (TERMINATED.contains(this.state)) {
 776            Log.w(Config.LOGTAG, id.account.getJid().asBareJid() + ": received endCall() when session has already been terminated. nothing to do");
 777            return;
 778        }
 779        if (isInState(State.PROPOSED) && !isInitiator()) {
 780            rejectCallFromProposed();
 781            return;
 782        }
 783        if (isInState(State.PROCEED)) {
 784            Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": ending call while in state PROCEED just means ending the connection");
 785            webRTCWrapper.close();
 786            jingleConnectionManager.finishConnection(this);
 787            transitionOrThrow(State.TERMINATED_SUCCESS); //arguably this wasn't success; but not a real failure either
 788            return;
 789        }
 790        if (isInitiator() && isInState(State.SESSION_INITIALIZED, State.SESSION_INITIALIZED_PRE_APPROVED)) {
 791            webRTCWrapper.close();
 792            sendSessionTerminate(Reason.CANCEL);
 793            return;
 794        }
 795        if (isInState(State.SESSION_INITIALIZED)) {
 796            rejectCallFromSessionInitiate();
 797            return;
 798        }
 799        if (isInState(State.SESSION_INITIALIZED_PRE_APPROVED, State.SESSION_ACCEPTED)) {
 800            webRTCWrapper.close();
 801            sendSessionTerminate(Reason.SUCCESS);
 802            return;
 803        }
 804        if (isInState(State.TERMINATED_APPLICATION_FAILURE, State.TERMINATED_CONNECTIVITY_ERROR, State.TERMINATED_DECLINED_OR_BUSY)) {
 805            Log.d(Config.LOGTAG, "ignoring request to end call because already in state " + this.state);
 806            return;
 807        }
 808        throw new IllegalStateException("called 'endCall' while in state " + this.state + ". isInitiator=" + isInitiator());
 809    }
 810
 811    private void setupWebRTC(final Set<Media> media, final List<PeerConnection.IceServer> iceServers) throws WebRTCWrapper.InitializationException {
 812        this.webRTCWrapper.setup(this.xmppConnectionService);
 813        this.webRTCWrapper.initializePeerConnection(media, iceServers);
 814    }
 815
 816    private void acceptCallFromProposed() {
 817        transitionOrThrow(State.PROCEED);
 818        xmppConnectionService.getNotificationService().cancelIncomingCallNotification();
 819        this.sendJingleMessage("accept", id.account.getJid().asBareJid());
 820        this.sendJingleMessage("proceed");
 821    }
 822
 823    private void rejectCallFromProposed() {
 824        transitionOrThrow(State.REJECTED);
 825        writeLogMessageMissed();
 826        xmppConnectionService.getNotificationService().cancelIncomingCallNotification();
 827        this.sendJingleMessage("reject");
 828        jingleConnectionManager.finishConnection(this);
 829    }
 830
 831    private void rejectCallFromSessionInitiate() {
 832        webRTCWrapper.close();
 833        sendSessionTerminate(Reason.DECLINE);
 834        xmppConnectionService.getNotificationService().cancelIncomingCallNotification();
 835    }
 836
 837    private void sendJingleMessage(final String action) {
 838        sendJingleMessage(action, id.with);
 839    }
 840
 841    private void sendJingleMessage(final String action, final Jid to) {
 842        final MessagePacket messagePacket = new MessagePacket();
 843        if ("proceed".equals(action)) {
 844            messagePacket.setId(JINGLE_MESSAGE_PROCEED_ID_PREFIX + id.sessionId);
 845        }
 846        messagePacket.setType(MessagePacket.TYPE_CHAT); //we want to carbon copy those
 847        messagePacket.setTo(to);
 848        messagePacket.addChild(action, Namespace.JINGLE_MESSAGE).setAttribute("id", id.sessionId);
 849        messagePacket.addChild("store", "urn:xmpp:hints");
 850        xmppConnectionService.sendMessagePacket(id.account, messagePacket);
 851    }
 852
 853    private void acceptCallFromSessionInitialized() {
 854        xmppConnectionService.getNotificationService().cancelIncomingCallNotification();
 855        sendSessionAccept();
 856    }
 857
 858    private synchronized boolean isInState(State... state) {
 859        return Arrays.asList(state).contains(this.state);
 860    }
 861
 862    private synchronized boolean transition(final State target) {
 863        final Collection<State> validTransitions = VALID_TRANSITIONS.get(this.state);
 864        if (validTransitions != null && validTransitions.contains(target)) {
 865            this.state = target;
 866            Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": transitioned into " + target);
 867            updateEndUserState();
 868            updateOngoingCallNotification();
 869            return true;
 870        } else {
 871            return false;
 872        }
 873    }
 874
 875    public void transitionOrThrow(final State target) {
 876        if (!transition(target)) {
 877            throw new IllegalStateException(String.format("Unable to transition from %s to %s", this.state, target));
 878        }
 879    }
 880
 881    @Override
 882    public void onIceCandidate(final IceCandidate iceCandidate) {
 883        final IceUdpTransportInfo.Candidate candidate = IceUdpTransportInfo.Candidate.fromSdpAttribute(iceCandidate.sdp);
 884        Log.d(Config.LOGTAG, "sending candidate: " + iceCandidate.toString());
 885        sendTransportInfo(iceCandidate.sdpMid, candidate);
 886    }
 887
 888    @Override
 889    public void onConnectionChange(final PeerConnection.PeerConnectionState newState) {
 890        Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": PeerConnectionState changed to " + newState);
 891        updateEndUserState();
 892        if (newState == PeerConnection.PeerConnectionState.CONNECTED && this.rtpConnectionStarted == 0) {
 893            this.rtpConnectionStarted = SystemClock.elapsedRealtime();
 894        }
 895        if (newState == PeerConnection.PeerConnectionState.FAILED) {
 896            if (TERMINATED.contains(this.state)) {
 897                Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": not sending session-terminate after connectivity error because session is already in state " + this.state);
 898                return;
 899            }
 900            sendSessionTerminate(Reason.CONNECTIVITY_ERROR);
 901        }
 902    }
 903
 904    public AppRTCAudioManager getAudioManager() {
 905        return webRTCWrapper.getAudioManager();
 906    }
 907
 908    public boolean isMicrophoneEnabled() {
 909        return webRTCWrapper.isMicrophoneEnabled();
 910    }
 911
 912    public void setMicrophoneEnabled(final boolean enabled) {
 913        webRTCWrapper.setMicrophoneEnabled(enabled);
 914    }
 915
 916    @Override
 917    public void onAudioDeviceChanged(AppRTCAudioManager.AudioDevice selectedAudioDevice, Set<AppRTCAudioManager.AudioDevice> availableAudioDevices) {
 918        xmppConnectionService.notifyJingleRtpConnectionUpdate(selectedAudioDevice, availableAudioDevices);
 919    }
 920
 921    private void updateEndUserState() {
 922        xmppConnectionService.notifyJingleRtpConnectionUpdate(id.account, id.with, id.sessionId, getEndUserState());
 923    }
 924
 925    private void updateOngoingCallNotification() {
 926        if (STATES_SHOWING_ONGOING_CALL.contains(this.state)) {
 927            xmppConnectionService.setOngoingCall(id);
 928        } else {
 929            xmppConnectionService.removeOngoingCall(id);
 930        }
 931    }
 932
 933    private void discoverIceServers(final OnIceServersDiscovered onIceServersDiscovered) {
 934        if (id.account.getXmppConnection().getFeatures().extendedServiceDiscovery()) {
 935            final IqPacket request = new IqPacket(IqPacket.TYPE.GET);
 936            request.setTo(Jid.of(id.account.getJid().getDomain()));
 937            request.addChild("services", Namespace.EXTERNAL_SERVICE_DISCOVERY);
 938            xmppConnectionService.sendIqPacket(id.account, request, (account, response) -> {
 939                ImmutableList.Builder<PeerConnection.IceServer> listBuilder = new ImmutableList.Builder<>();
 940                if (response.getType() == IqPacket.TYPE.RESULT) {
 941                    final Element services = response.findChild("services", Namespace.EXTERNAL_SERVICE_DISCOVERY);
 942                    final List<Element> children = services == null ? Collections.emptyList() : services.getChildren();
 943                    for (final Element child : children) {
 944                        if ("service".equals(child.getName())) {
 945                            final String type = child.getAttribute("type");
 946                            final String host = child.getAttribute("host");
 947                            final String sport = child.getAttribute("port");
 948                            final Integer port = sport == null ? null : Ints.tryParse(sport);
 949                            final String transport = child.getAttribute("transport");
 950                            final String username = child.getAttribute("username");
 951                            final String password = child.getAttribute("password");
 952                            if (Strings.isNullOrEmpty(host) || port == null) {
 953                                continue;
 954                            }
 955                            if (port < 0 || port > 65535) {
 956                                continue;
 957                            }
 958                            if (Arrays.asList("stun", "turn").contains(type) || Arrays.asList("udp", "tcp").contains(transport)) {
 959                                //TODO wrap ipv6 addresses
 960                                PeerConnection.IceServer.Builder iceServerBuilder = PeerConnection.IceServer.builder(String.format("%s:%s:%s?transport=%s", type, host, port, transport));
 961                                if (username != null && password != null) {
 962                                    iceServerBuilder.setUsername(username);
 963                                    iceServerBuilder.setPassword(password);
 964                                } else if (Arrays.asList("turn", "turns").contains(type)) {
 965                                    //The WebRTC spec requires throwing an InvalidAccessError when username (from libwebrtc source coder)
 966                                    //https://chromium.googlesource.com/external/webrtc/+/master/pc/ice_server_parsing.cc
 967                                    Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": skipping " + type + "/" + transport + " without username and password");
 968                                    continue;
 969                                }
 970                                final PeerConnection.IceServer iceServer = iceServerBuilder.createIceServer();
 971                                Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": discovered ICE Server: " + iceServer);
 972                                listBuilder.add(iceServer);
 973                            }
 974                        }
 975                    }
 976                }
 977                List<PeerConnection.IceServer> iceServers = listBuilder.build();
 978                if (iceServers.size() == 0) {
 979                    Log.w(Config.LOGTAG, id.account.getJid().asBareJid() + ": no ICE server found " + response);
 980                }
 981                onIceServersDiscovered.onIceServersDiscovered(iceServers);
 982            });
 983        } else {
 984            Log.w(Config.LOGTAG, id.account.getJid().asBareJid() + ": has no external service discovery");
 985            onIceServersDiscovered.onIceServersDiscovered(Collections.emptyList());
 986        }
 987    }
 988
 989    private void writeLogMessage(final State state) {
 990        final long started = this.rtpConnectionStarted;
 991        long duration = started <= 0 ? 0 : SystemClock.elapsedRealtime() - started;
 992        if (state == State.TERMINATED_SUCCESS || (state == State.TERMINATED_CONNECTIVITY_ERROR && duration > 0)) {
 993            writeLogMessageSuccess(duration);
 994        } else {
 995            writeLogMessageMissed();
 996        }
 997    }
 998
 999    private void writeLogMessageSuccess(final long duration) {
1000        this.message.setBody(new RtpSessionStatus(true, duration).toString());
1001        this.writeMessage();
1002    }
1003
1004    private void writeLogMessageMissed() {
1005        this.message.setBody(new RtpSessionStatus(false, 0).toString());
1006        this.writeMessage();
1007    }
1008
1009    private void writeMessage() {
1010        final Conversational conversational = message.getConversation();
1011        if (conversational instanceof Conversation) {
1012            ((Conversation) conversational).add(this.message);
1013            xmppConnectionService.databaseBackend.createMessage(message);
1014            xmppConnectionService.updateConversationUi();
1015        } else {
1016            throw new IllegalStateException("Somehow the conversation in a message was a stub");
1017        }
1018    }
1019
1020    public State getState() {
1021        return this.state;
1022    }
1023
1024    public Optional<VideoTrack> geLocalVideoTrack() {
1025        return webRTCWrapper.getLocalVideoTrack();
1026    }
1027
1028    public Optional<VideoTrack> getRemoteVideoTrack() {
1029        return webRTCWrapper.getRemoteVideoTrack();
1030    }
1031
1032
1033    public EglBase.Context getEglBaseContext() {
1034        return webRTCWrapper.getEglBaseContext();
1035    }
1036
1037    public void setProposedMedia(final Set<Media> media) {
1038        this.proposedMedia = media;
1039    }
1040
1041    private interface OnIceServersDiscovered {
1042        void onIceServersDiscovered(List<PeerConnection.IceServer> iceServers);
1043    }
1044}