JingleRtpConnection.java

   1package eu.siacs.conversations.xmpp.jingle;
   2
   3import android.os.SystemClock;
   4import android.util.Log;
   5
   6import androidx.annotation.NonNull;
   7import androidx.annotation.Nullable;
   8
   9import com.google.common.base.Optional;
  10import com.google.common.base.Preconditions;
  11import com.google.common.base.Strings;
  12import com.google.common.base.Throwables;
  13import com.google.common.collect.Collections2;
  14import com.google.common.collect.ImmutableList;
  15import com.google.common.collect.ImmutableMap;
  16import com.google.common.collect.Sets;
  17import com.google.common.primitives.Ints;
  18import com.google.common.util.concurrent.FutureCallback;
  19import com.google.common.util.concurrent.Futures;
  20import com.google.common.util.concurrent.ListenableFuture;
  21import com.google.common.util.concurrent.MoreExecutors;
  22
  23import org.webrtc.EglBase;
  24import org.webrtc.IceCandidate;
  25import org.webrtc.PeerConnection;
  26import org.webrtc.VideoTrack;
  27
  28import java.util.ArrayDeque;
  29import java.util.Arrays;
  30import java.util.Collection;
  31import java.util.Collections;
  32import java.util.List;
  33import java.util.Map;
  34import java.util.Set;
  35import java.util.concurrent.ScheduledFuture;
  36import java.util.concurrent.TimeUnit;
  37
  38import eu.siacs.conversations.Config;
  39import eu.siacs.conversations.crypto.axolotl.AxolotlService;
  40import eu.siacs.conversations.crypto.axolotl.CryptoFailedException;
  41import eu.siacs.conversations.crypto.axolotl.FingerprintStatus;
  42import eu.siacs.conversations.entities.Account;
  43import eu.siacs.conversations.entities.Conversation;
  44import eu.siacs.conversations.entities.Conversational;
  45import eu.siacs.conversations.entities.Message;
  46import eu.siacs.conversations.entities.RtpSessionStatus;
  47import eu.siacs.conversations.services.AppRTCAudioManager;
  48import eu.siacs.conversations.utils.IP;
  49import eu.siacs.conversations.xml.Element;
  50import eu.siacs.conversations.xml.Namespace;
  51import eu.siacs.conversations.xmpp.Jid;
  52import eu.siacs.conversations.xmpp.jingle.stanzas.Group;
  53import eu.siacs.conversations.xmpp.jingle.stanzas.IceUdpTransportInfo;
  54import eu.siacs.conversations.xmpp.jingle.stanzas.JinglePacket;
  55import eu.siacs.conversations.xmpp.jingle.stanzas.Proceed;
  56import eu.siacs.conversations.xmpp.jingle.stanzas.Propose;
  57import eu.siacs.conversations.xmpp.jingle.stanzas.Reason;
  58import eu.siacs.conversations.xmpp.jingle.stanzas.RtpDescription;
  59import eu.siacs.conversations.xmpp.stanzas.IqPacket;
  60import eu.siacs.conversations.xmpp.stanzas.MessagePacket;
  61
  62public class JingleRtpConnection extends AbstractJingleConnection implements WebRTCWrapper.EventCallback {
  63
  64    public static final List<State> STATES_SHOWING_ONGOING_CALL = Arrays.asList(
  65            State.PROCEED,
  66            State.SESSION_INITIALIZED_PRE_APPROVED,
  67            State.SESSION_ACCEPTED
  68    );
  69    private static final long BUSY_TIME_OUT = 30;
  70    private static final List<State> TERMINATED = Arrays.asList(
  71            State.ACCEPTED,
  72            State.REJECTED,
  73            State.REJECTED_RACED,
  74            State.RETRACTED,
  75            State.RETRACTED_RACED,
  76            State.TERMINATED_SUCCESS,
  77            State.TERMINATED_DECLINED_OR_BUSY,
  78            State.TERMINATED_CONNECTIVITY_ERROR,
  79            State.TERMINATED_CANCEL_OR_TIMEOUT,
  80            State.TERMINATED_APPLICATION_FAILURE,
  81            State.TERMINATED_SECURITY_ERROR
  82    );
  83
  84    private static final Map<State, Collection<State>> VALID_TRANSITIONS;
  85
  86    static {
  87        final ImmutableMap.Builder<State, Collection<State>> transitionBuilder = new ImmutableMap.Builder<>();
  88        transitionBuilder.put(State.NULL, ImmutableList.of(
  89                State.PROPOSED,
  90                State.SESSION_INITIALIZED,
  91                State.TERMINATED_APPLICATION_FAILURE,
  92                State.TERMINATED_SECURITY_ERROR
  93        ));
  94        transitionBuilder.put(State.PROPOSED, ImmutableList.of(
  95                State.ACCEPTED,
  96                State.PROCEED,
  97                State.REJECTED,
  98                State.RETRACTED,
  99                State.TERMINATED_APPLICATION_FAILURE,
 100                State.TERMINATED_SECURITY_ERROR,
 101                State.TERMINATED_CONNECTIVITY_ERROR //only used when the xmpp connection rebinds
 102        ));
 103        transitionBuilder.put(State.PROCEED, ImmutableList.of(
 104                State.REJECTED_RACED,
 105                State.RETRACTED_RACED,
 106                State.SESSION_INITIALIZED_PRE_APPROVED,
 107                State.TERMINATED_SUCCESS,
 108                State.TERMINATED_APPLICATION_FAILURE,
 109                State.TERMINATED_SECURITY_ERROR,
 110                State.TERMINATED_CONNECTIVITY_ERROR //at this state used for error bounces of the proceed message
 111        ));
 112        transitionBuilder.put(State.SESSION_INITIALIZED, ImmutableList.of(
 113                State.SESSION_ACCEPTED,
 114                State.TERMINATED_SUCCESS,
 115                State.TERMINATED_DECLINED_OR_BUSY,
 116                State.TERMINATED_CONNECTIVITY_ERROR,  //at this state used for IQ errors and IQ timeouts
 117                State.TERMINATED_CANCEL_OR_TIMEOUT,
 118                State.TERMINATED_APPLICATION_FAILURE,
 119                State.TERMINATED_SECURITY_ERROR
 120        ));
 121        transitionBuilder.put(State.SESSION_INITIALIZED_PRE_APPROVED, ImmutableList.of(
 122                State.SESSION_ACCEPTED,
 123                State.TERMINATED_SUCCESS,
 124                State.TERMINATED_DECLINED_OR_BUSY,
 125                State.TERMINATED_CONNECTIVITY_ERROR,  //at this state used for IQ errors and IQ timeouts
 126                State.TERMINATED_CANCEL_OR_TIMEOUT,
 127                State.TERMINATED_APPLICATION_FAILURE,
 128                State.TERMINATED_SECURITY_ERROR
 129        ));
 130        transitionBuilder.put(State.SESSION_ACCEPTED, ImmutableList.of(
 131                State.TERMINATED_SUCCESS,
 132                State.TERMINATED_DECLINED_OR_BUSY,
 133                State.TERMINATED_CONNECTIVITY_ERROR,
 134                State.TERMINATED_CANCEL_OR_TIMEOUT,
 135                State.TERMINATED_APPLICATION_FAILURE,
 136                State.TERMINATED_SECURITY_ERROR
 137        ));
 138        VALID_TRANSITIONS = transitionBuilder.build();
 139    }
 140
 141    private final WebRTCWrapper webRTCWrapper = new WebRTCWrapper(this);
 142    private final ArrayDeque<Set<Map.Entry<String, RtpContentMap.DescriptionTransport>>> pendingIceCandidates = new ArrayDeque<>();
 143    private final OmemoVerification omemoVerification = new OmemoVerification();
 144    private final Message message;
 145    private State state = State.NULL;
 146    private StateTransitionException stateTransitionException;
 147    private Set<Media> proposedMedia;
 148    private RtpContentMap initiatorRtpContentMap;
 149    private RtpContentMap responderRtpContentMap;
 150    private long rtpConnectionStarted = 0; //time of 'connected'
 151    private long rtpConnectionEnded = 0;
 152    private ScheduledFuture<?> ringingTimeoutFuture;
 153
 154    JingleRtpConnection(JingleConnectionManager jingleConnectionManager, Id id, Jid initiator) {
 155        super(jingleConnectionManager, id, initiator);
 156        final Conversation conversation = jingleConnectionManager.getXmppConnectionService().findOrCreateConversation(
 157                id.account,
 158                id.with.asBareJid(),
 159                false,
 160                false
 161        );
 162        this.message = new Message(
 163                conversation,
 164                isInitiator() ? Message.STATUS_SEND : Message.STATUS_RECEIVED,
 165                Message.TYPE_RTP_SESSION,
 166                id.sessionId
 167        );
 168    }
 169
 170    private static State reasonToState(Reason reason) {
 171        switch (reason) {
 172            case SUCCESS:
 173                return State.TERMINATED_SUCCESS;
 174            case DECLINE:
 175            case BUSY:
 176                return State.TERMINATED_DECLINED_OR_BUSY;
 177            case CANCEL:
 178            case TIMEOUT:
 179                return State.TERMINATED_CANCEL_OR_TIMEOUT;
 180            case SECURITY_ERROR:
 181                return State.TERMINATED_SECURITY_ERROR;
 182            case FAILED_APPLICATION:
 183            case UNSUPPORTED_TRANSPORTS:
 184            case UNSUPPORTED_APPLICATIONS:
 185                return State.TERMINATED_APPLICATION_FAILURE;
 186            default:
 187                return State.TERMINATED_CONNECTIVITY_ERROR;
 188        }
 189    }
 190
 191    @Override
 192    synchronized void deliverPacket(final JinglePacket jinglePacket) {
 193        Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": packet delivered to JingleRtpConnection");
 194        switch (jinglePacket.getAction()) {
 195            case SESSION_INITIATE:
 196                receiveSessionInitiate(jinglePacket);
 197                break;
 198            case TRANSPORT_INFO:
 199                receiveTransportInfo(jinglePacket);
 200                break;
 201            case SESSION_ACCEPT:
 202                receiveSessionAccept(jinglePacket);
 203                break;
 204            case SESSION_TERMINATE:
 205                receiveSessionTerminate(jinglePacket);
 206                break;
 207            default:
 208                respondOk(jinglePacket);
 209                Log.d(Config.LOGTAG, String.format("%s: received unhandled jingle action %s", id.account.getJid().asBareJid(), jinglePacket.getAction()));
 210                break;
 211        }
 212    }
 213
 214    @Override
 215    synchronized void notifyRebound() {
 216        if (isTerminated()) {
 217            return;
 218        }
 219        webRTCWrapper.close();
 220        if (!isInitiator() && isInState(State.PROPOSED, State.SESSION_INITIALIZED)) {
 221            xmppConnectionService.getNotificationService().cancelIncomingCallNotification();
 222        }
 223        if (isInState(State.SESSION_INITIALIZED, State.SESSION_INITIALIZED_PRE_APPROVED, State.SESSION_ACCEPTED)) {
 224            //we might have already changed resources (full jid) at this point; so this might not even reach the other party
 225            sendSessionTerminate(Reason.CONNECTIVITY_ERROR);
 226        } else {
 227            transitionOrThrow(State.TERMINATED_CONNECTIVITY_ERROR);
 228            finish();
 229        }
 230    }
 231
 232    private void receiveSessionTerminate(final JinglePacket jinglePacket) {
 233        respondOk(jinglePacket);
 234        final JinglePacket.ReasonWrapper wrapper = jinglePacket.getReason();
 235        final State previous = this.state;
 236        Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": received session terminate reason=" + wrapper.reason + "(" + Strings.nullToEmpty(wrapper.text) + ") while in state " + previous);
 237        if (TERMINATED.contains(previous)) {
 238            Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": ignoring session terminate because already in " + previous);
 239            return;
 240        }
 241        webRTCWrapper.close();
 242        final State target = reasonToState(wrapper.reason);
 243        transitionOrThrow(target);
 244        writeLogMessage(target);
 245        if (previous == State.PROPOSED || previous == State.SESSION_INITIALIZED) {
 246            xmppConnectionService.getNotificationService().cancelIncomingCallNotification();
 247        }
 248        finish();
 249    }
 250
 251    private void receiveTransportInfo(final JinglePacket jinglePacket) {
 252        //Due to the asynchronicity of processing session-init we might move from NULL|PROCEED to INITIALIZED only after transport-info has been received
 253        if (isInState(State.NULL, State.PROCEED, State.SESSION_INITIALIZED, State.SESSION_INITIALIZED_PRE_APPROVED, State.SESSION_ACCEPTED)) {
 254            respondOk(jinglePacket);
 255            final RtpContentMap contentMap;
 256            try {
 257                contentMap = RtpContentMap.of(jinglePacket);
 258            } catch (IllegalArgumentException | NullPointerException e) {
 259                Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": improperly formatted contents; ignoring", e);
 260                return;
 261            }
 262            final Set<Map.Entry<String, RtpContentMap.DescriptionTransport>> candidates = contentMap.contents.entrySet();
 263            if (this.state == State.SESSION_ACCEPTED) {
 264                try {
 265                    processCandidates(candidates);
 266                } catch (final WebRTCWrapper.PeerConnectionNotInitialized e) {
 267                    Log.w(Config.LOGTAG, id.account.getJid().asBareJid() + ": PeerConnection was not initialized when processing transport info. this usually indicates a race condition that can be ignored");
 268                }
 269            } else {
 270                pendingIceCandidates.push(candidates);
 271            }
 272        } else {
 273            if (isTerminated()) {
 274                respondOk(jinglePacket);
 275                Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": ignoring out-of-order transport info; we where already terminated");
 276            } else {
 277                Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": received transport info while in state=" + this.state);
 278                terminateWithOutOfOrder(jinglePacket);
 279            }
 280        }
 281    }
 282
 283    private void processCandidates(final Set<Map.Entry<String, RtpContentMap.DescriptionTransport>> contents) {
 284        final RtpContentMap rtpContentMap = isInitiator() ? this.responderRtpContentMap : this.initiatorRtpContentMap;
 285        final Group originalGroup = rtpContentMap.group;
 286        final List<String> identificationTags = originalGroup == null ? rtpContentMap.getNames() : originalGroup.getIdentificationTags();
 287        if (identificationTags.size() == 0) {
 288            Log.w(Config.LOGTAG, id.account.getJid().asBareJid() + ": no identification tags found in initial offer. we won't be able to calculate mLineIndices");
 289        }
 290        processCandidates(identificationTags, contents);
 291    }
 292
 293    private void processCandidates(final List<String> indices, final Set<Map.Entry<String, RtpContentMap.DescriptionTransport>> contents) {
 294        for (final Map.Entry<String, RtpContentMap.DescriptionTransport> content : contents) {
 295            final String ufrag = content.getValue().transport.getAttribute("ufrag");
 296            for (final IceUdpTransportInfo.Candidate candidate : content.getValue().transport.getCandidates()) {
 297                final String sdp;
 298                try {
 299                    sdp = candidate.toSdpAttribute(ufrag);
 300                } catch (IllegalArgumentException e) {
 301                    Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": ignoring invalid ICE candidate " + e.getMessage());
 302                    continue;
 303                }
 304                final String sdpMid = content.getKey();
 305                final int mLineIndex = indices.indexOf(sdpMid);
 306                if (mLineIndex < 0) {
 307                    Log.w(Config.LOGTAG, "mLineIndex not found for " + sdpMid + ". available indices " + indices);
 308                }
 309                final IceCandidate iceCandidate = new IceCandidate(sdpMid, mLineIndex, sdp);
 310                Log.d(Config.LOGTAG, "received candidate: " + iceCandidate);
 311                this.webRTCWrapper.addIceCandidate(iceCandidate);
 312            }
 313        }
 314    }
 315
 316    private ListenableFuture<RtpContentMap> receiveRtpContentMap(final JinglePacket jinglePacket, final boolean expectVerification) {
 317        final RtpContentMap receivedContentMap;
 318        try {
 319            receivedContentMap = RtpContentMap.of(jinglePacket);
 320        } catch (final Exception e) {
 321            return Futures.immediateFailedFuture(e);
 322        }
 323        if (receivedContentMap instanceof OmemoVerifiedRtpContentMap) {
 324            final ListenableFuture<AxolotlService.OmemoVerifiedPayload<RtpContentMap>> future = id.account.getAxolotlService().decrypt((OmemoVerifiedRtpContentMap) receivedContentMap, id.with);
 325            return Futures.transform(future, omemoVerifiedPayload -> {
 326                //TODO test if an exception here triggers a correct abort
 327                omemoVerification.setOrEnsureEqual(omemoVerifiedPayload);
 328                Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": received verifiable DTLS fingerprint via " + omemoVerification);
 329                return omemoVerifiedPayload.getPayload();
 330            }, MoreExecutors.directExecutor());
 331        } else if (Config.REQUIRE_RTP_VERIFICATION || expectVerification) {
 332            return Futures.immediateFailedFuture(
 333                    new SecurityException("DTLS fingerprint was unexpectedly not verifiable")
 334            );
 335        } else {
 336            return Futures.immediateFuture(receivedContentMap);
 337        }
 338    }
 339
 340    private void receiveSessionInitiate(final JinglePacket jinglePacket) {
 341        if (isInitiator()) {
 342            Log.d(Config.LOGTAG, String.format("%s: received session-initiate even though we were initiating", id.account.getJid().asBareJid()));
 343            if (isTerminated()) {
 344                Log.d(Config.LOGTAG, String.format(
 345                        "%s: got a reason to terminate with out-of-order. but already in state %s",
 346                        id.account.getJid().asBareJid(),
 347                        getState()
 348                ));
 349                respondWithOutOfOrder(jinglePacket);
 350            } else {
 351                terminateWithOutOfOrder(jinglePacket);
 352            }
 353            return;
 354        }
 355        final ListenableFuture<RtpContentMap> future = receiveRtpContentMap(jinglePacket, false);
 356        Futures.addCallback(future, new FutureCallback<RtpContentMap>() {
 357            @Override
 358            public void onSuccess(@Nullable RtpContentMap rtpContentMap) {
 359                receiveSessionInitiate(jinglePacket, rtpContentMap);
 360            }
 361
 362            @Override
 363            public void onFailure(@NonNull final Throwable throwable) {
 364                respondOk(jinglePacket);
 365                sendSessionTerminate(Reason.ofThrowable(throwable), throwable.getMessage());
 366            }
 367        }, MoreExecutors.directExecutor());
 368    }
 369
 370    private void receiveSessionInitiate(final JinglePacket jinglePacket, final RtpContentMap contentMap) {
 371        try {
 372            contentMap.requireContentDescriptions();
 373            contentMap.requireDTLSFingerprint();
 374        } catch (final RuntimeException e) {
 375            Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": improperly formatted contents", Throwables.getRootCause(e));
 376            respondOk(jinglePacket);
 377            sendSessionTerminate(Reason.of(e), e.getMessage());
 378            return;
 379        }
 380        Log.d(Config.LOGTAG, "processing session-init with " + contentMap.contents.size() + " contents");
 381        final State target;
 382        if (this.state == State.PROCEED) {
 383            Preconditions.checkState(
 384                    proposedMedia != null && proposedMedia.size() > 0,
 385                    "proposed media must be set when processing pre-approved session-initiate"
 386            );
 387            if (!this.proposedMedia.equals(contentMap.getMedia())) {
 388                sendSessionTerminate(Reason.SECURITY_ERROR, String.format(
 389                        "Your session proposal (Jingle Message Initiation) included media %s but your session-initiate was %s",
 390                        this.proposedMedia,
 391                        contentMap.getMedia()
 392                ));
 393                return;
 394            }
 395            target = State.SESSION_INITIALIZED_PRE_APPROVED;
 396        } else {
 397            target = State.SESSION_INITIALIZED;
 398        }
 399        if (transition(target, () -> this.initiatorRtpContentMap = contentMap)) {
 400            respondOk(jinglePacket);
 401
 402            final Set<Map.Entry<String, RtpContentMap.DescriptionTransport>> candidates = contentMap.contents.entrySet();
 403            if (candidates.size() > 0) {
 404                pendingIceCandidates.push(candidates);
 405            }
 406            if (target == State.SESSION_INITIALIZED_PRE_APPROVED) {
 407                Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": automatically accepting session-initiate");
 408                sendSessionAccept();
 409            } else {
 410                Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": received not pre-approved session-initiate. start ringing");
 411                startRinging();
 412            }
 413        } else {
 414            Log.d(Config.LOGTAG, String.format("%s: received session-initiate while in state %s", id.account.getJid().asBareJid(), state));
 415            terminateWithOutOfOrder(jinglePacket);
 416        }
 417    }
 418
 419    private void receiveSessionAccept(final JinglePacket jinglePacket) {
 420        if (!isInitiator()) {
 421            Log.d(Config.LOGTAG, String.format("%s: received session-accept even though we were responding", id.account.getJid().asBareJid()));
 422            terminateWithOutOfOrder(jinglePacket);
 423            return;
 424        }
 425        final ListenableFuture<RtpContentMap> future = receiveRtpContentMap(jinglePacket, this.omemoVerification.hasFingerprint());
 426        Futures.addCallback(future, new FutureCallback<RtpContentMap>() {
 427            @Override
 428            public void onSuccess(@Nullable RtpContentMap rtpContentMap) {
 429                receiveSessionAccept(jinglePacket, rtpContentMap);
 430            }
 431
 432            @Override
 433            public void onFailure(@NonNull final Throwable throwable) {
 434                respondOk(jinglePacket);
 435                Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": improperly formatted contents in session-accept", throwable);
 436                webRTCWrapper.close();
 437                sendSessionTerminate(Reason.ofThrowable(throwable), throwable.getMessage());
 438            }
 439        }, MoreExecutors.directExecutor());
 440    }
 441
 442    private void receiveSessionAccept(final JinglePacket jinglePacket, final RtpContentMap contentMap) {
 443        try {
 444            contentMap.requireContentDescriptions();
 445            contentMap.requireDTLSFingerprint();
 446        } catch (final RuntimeException e) {
 447            respondOk(jinglePacket);
 448            Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": improperly formatted contents in session-accept", e);
 449            webRTCWrapper.close();
 450            sendSessionTerminate(Reason.of(e), e.getMessage());
 451            return;
 452        }
 453        final Set<Media> initiatorMedia = this.initiatorRtpContentMap.getMedia();
 454        if (!initiatorMedia.equals(contentMap.getMedia())) {
 455            sendSessionTerminate(Reason.SECURITY_ERROR, String.format(
 456                    "Your session-included included media %s but our session-initiate was %s",
 457                    this.proposedMedia,
 458                    contentMap.getMedia()
 459            ));
 460            return;
 461        }
 462        Log.d(Config.LOGTAG, "processing session-accept with " + contentMap.contents.size() + " contents");
 463        if (transition(State.SESSION_ACCEPTED)) {
 464            respondOk(jinglePacket);
 465            receiveSessionAccept(contentMap);
 466        } else {
 467            Log.d(Config.LOGTAG, String.format("%s: received session-accept while in state %s", id.account.getJid().asBareJid(), state));
 468            respondOk(jinglePacket);
 469        }
 470    }
 471
 472    private void receiveSessionAccept(final RtpContentMap contentMap) {
 473        this.responderRtpContentMap = contentMap;
 474        final SessionDescription sessionDescription;
 475        try {
 476            sessionDescription = SessionDescription.of(contentMap);
 477        } catch (final IllegalArgumentException | NullPointerException e) {
 478            Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": unable convert offer from session-accept to SDP", e);
 479            webRTCWrapper.close();
 480            sendSessionTerminate(Reason.FAILED_APPLICATION, e.getMessage());
 481            return;
 482        }
 483        final org.webrtc.SessionDescription answer = new org.webrtc.SessionDescription(
 484                org.webrtc.SessionDescription.Type.ANSWER,
 485                sessionDescription.toString()
 486        );
 487        try {
 488            this.webRTCWrapper.setRemoteDescription(answer).get();
 489        } catch (final Exception e) {
 490            Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": unable to set remote description after receiving session-accept", Throwables.getRootCause(e));
 491            webRTCWrapper.close();
 492            sendSessionTerminate(Reason.FAILED_APPLICATION);
 493            return;
 494        }
 495        final List<String> identificationTags = contentMap.group == null ? contentMap.getNames() : contentMap.group.getIdentificationTags();
 496        processCandidates(identificationTags, contentMap.contents.entrySet());
 497    }
 498
 499    private void sendSessionAccept() {
 500        final RtpContentMap rtpContentMap = this.initiatorRtpContentMap;
 501        if (rtpContentMap == null) {
 502            throw new IllegalStateException("initiator RTP Content Map has not been set");
 503        }
 504        final SessionDescription offer;
 505        try {
 506            offer = SessionDescription.of(rtpContentMap);
 507        } catch (final IllegalArgumentException | NullPointerException e) {
 508            Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": unable convert offer from session-initiate to SDP", e);
 509            webRTCWrapper.close();
 510            sendSessionTerminate(Reason.FAILED_APPLICATION, e.getMessage());
 511            return;
 512        }
 513        sendSessionAccept(rtpContentMap.getMedia(), offer);
 514    }
 515
 516    private void sendSessionAccept(final Set<Media> media, final SessionDescription offer) {
 517        discoverIceServers(iceServers -> sendSessionAccept(media, offer, iceServers));
 518    }
 519
 520    private synchronized void sendSessionAccept(final Set<Media> media, final SessionDescription offer, final List<PeerConnection.IceServer> iceServers) {
 521        if (isTerminated()) {
 522            Log.w(Config.LOGTAG, id.account.getJid().asBareJid() + ": ICE servers got discovered when session was already terminated. nothing to do.");
 523            return;
 524        }
 525        try {
 526            setupWebRTC(media, iceServers);
 527        } catch (final WebRTCWrapper.InitializationException e) {
 528            Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": unable to initialize WebRTC");
 529            webRTCWrapper.close();
 530            sendSessionTerminate(Reason.FAILED_APPLICATION);
 531            return;
 532        }
 533        final org.webrtc.SessionDescription sdp = new org.webrtc.SessionDescription(
 534                org.webrtc.SessionDescription.Type.OFFER,
 535                offer.toString()
 536        );
 537        try {
 538            this.webRTCWrapper.setRemoteDescription(sdp).get();
 539            addIceCandidatesFromBlackLog();
 540            org.webrtc.SessionDescription webRTCSessionDescription = this.webRTCWrapper.setLocalDescription().get();
 541            prepareSessionAccept(webRTCSessionDescription);
 542        } catch (final Exception e) {
 543            //TODO sending the error text is worthwhile as well. Especially for FailureToSet exceptions
 544            failureToAcceptSession(e);
 545        }
 546    }
 547
 548    private void failureToAcceptSession(final Throwable throwable) {
 549        if (isTerminated()) {
 550            return;
 551        }
 552        Log.d(Config.LOGTAG, "unable to send session accept", Throwables.getRootCause(throwable));
 553        webRTCWrapper.close();
 554        sendSessionTerminate(Reason.ofThrowable(throwable));
 555    }
 556
 557    private void addIceCandidatesFromBlackLog() {
 558        while (!this.pendingIceCandidates.isEmpty()) {
 559            processCandidates(this.pendingIceCandidates.poll());
 560            Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": added candidates from back log");
 561        }
 562    }
 563
 564    private void prepareSessionAccept(final org.webrtc.SessionDescription webRTCSessionDescription) {
 565        final SessionDescription sessionDescription = SessionDescription.parse(webRTCSessionDescription.description);
 566        final RtpContentMap respondingRtpContentMap = RtpContentMap.of(sessionDescription);
 567        this.responderRtpContentMap = respondingRtpContentMap;
 568        final ListenableFuture<RtpContentMap> outgoingContentMapFuture = prepareOutgoingContentMap(respondingRtpContentMap);
 569        Futures.addCallback(outgoingContentMapFuture,
 570                new FutureCallback<RtpContentMap>() {
 571                    @Override
 572                    public void onSuccess(final RtpContentMap outgoingContentMap) {
 573                        sendSessionAccept(outgoingContentMap);
 574                    }
 575
 576                    @Override
 577                    public void onFailure(@NonNull Throwable throwable) {
 578                        failureToAcceptSession(throwable);
 579                    }
 580                },
 581                MoreExecutors.directExecutor()
 582        );
 583    }
 584
 585    private void sendSessionAccept(final RtpContentMap rtpContentMap) {
 586        if (isTerminated()) {
 587            Log.w(Config.LOGTAG, id.account.getJid().asBareJid() + ": preparing session accept was too slow. already terminated. nothing to do.");
 588            return;
 589        }
 590        transitionOrThrow(State.SESSION_ACCEPTED);
 591        final JinglePacket sessionAccept = rtpContentMap.toJinglePacket(JinglePacket.Action.SESSION_ACCEPT, id.sessionId);
 592        send(sessionAccept);
 593    }
 594
 595    private ListenableFuture<RtpContentMap> prepareOutgoingContentMap(final RtpContentMap rtpContentMap) {
 596        if (this.omemoVerification.hasDeviceId()) {
 597            ListenableFuture<AxolotlService.OmemoVerifiedPayload<OmemoVerifiedRtpContentMap>> verifiedPayloadFuture = id.account.getAxolotlService()
 598                    .encrypt(rtpContentMap, id.with, omemoVerification.getDeviceId());
 599            return Futures.transform(verifiedPayloadFuture, verifiedPayload -> {
 600                omemoVerification.setOrEnsureEqual(verifiedPayload);
 601                return verifiedPayload.getPayload();
 602            }, MoreExecutors.directExecutor());
 603        } else {
 604            return Futures.immediateFuture(rtpContentMap);
 605        }
 606    }
 607
 608    synchronized void deliveryMessage(final Jid from, final Element message, final String serverMessageId, final long timestamp) {
 609        Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": delivered message to JingleRtpConnection " + message);
 610        switch (message.getName()) {
 611            case "propose":
 612                receivePropose(from, Propose.upgrade(message), serverMessageId, timestamp);
 613                break;
 614            case "proceed":
 615                receiveProceed(from, Proceed.upgrade(message), serverMessageId, timestamp);
 616                break;
 617            case "retract":
 618                receiveRetract(from, serverMessageId, timestamp);
 619                break;
 620            case "reject":
 621                receiveReject(from, serverMessageId, timestamp);
 622                break;
 623            case "accept":
 624                receiveAccept(from, serverMessageId, timestamp);
 625                break;
 626            default:
 627                break;
 628        }
 629    }
 630
 631    void deliverFailedProceed() {
 632        Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": receive message error for proceed message");
 633        if (transition(State.TERMINATED_CONNECTIVITY_ERROR)) {
 634            webRTCWrapper.close();
 635            Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": transitioned into connectivity error");
 636            this.finish();
 637        }
 638    }
 639
 640    private void receiveAccept(final Jid from, final String serverMsgId, final long timestamp) {
 641        final boolean originatedFromMyself = from.asBareJid().equals(id.account.getJid().asBareJid());
 642        if (originatedFromMyself) {
 643            if (transition(State.ACCEPTED)) {
 644                if (serverMsgId != null) {
 645                    this.message.setServerMsgId(serverMsgId);
 646                }
 647                this.message.setTime(timestamp);
 648                this.message.setCarbon(true); //indicate that call was accepted on other device
 649                this.writeLogMessageSuccess(0);
 650                this.xmppConnectionService.getNotificationService().cancelIncomingCallNotification();
 651                this.finish();
 652            } else {
 653                Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": unable to transition to accept because already in state=" + this.state);
 654            }
 655        } else {
 656            Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": ignoring 'accept' from " + from);
 657        }
 658    }
 659
 660    private void receiveReject(final Jid from, final String serverMsgId, final long timestamp) {
 661        final boolean originatedFromMyself = from.asBareJid().equals(id.account.getJid().asBareJid());
 662        //reject from another one of my clients
 663        if (originatedFromMyself) {
 664            receiveRejectFromMyself(serverMsgId, timestamp);
 665        } else if (isInitiator()) {
 666            if (from.equals(id.with)) {
 667                receiveRejectFromResponder();
 668            } else {
 669                Log.d(Config.LOGTAG, id.account.getJid() + ": ignoring reject from " + from + " for session with " + id.with);
 670            }
 671        } else {
 672            Log.d(Config.LOGTAG, id.account.getJid() + ": ignoring reject from " + from + " for session with " + id.with);
 673        }
 674    }
 675
 676    private void receiveRejectFromMyself(String serverMsgId, long timestamp) {
 677        if (transition(State.REJECTED)) {
 678            this.xmppConnectionService.getNotificationService().cancelIncomingCallNotification();
 679            this.finish();
 680            if (serverMsgId != null) {
 681                this.message.setServerMsgId(serverMsgId);
 682            }
 683            this.message.setTime(timestamp);
 684            this.message.setCarbon(true); //indicate that call was rejected on other device
 685            writeLogMessageMissed();
 686        } else {
 687            Log.d(Config.LOGTAG, "not able to transition into REJECTED because already in " + this.state);
 688        }
 689    }
 690
 691    private void receiveRejectFromResponder() {
 692        if (isInState(State.PROCEED)) {
 693            Log.d(Config.LOGTAG, id.account.getJid() + ": received reject while still in proceed. callee reconsidered");
 694            closeTransitionLogFinish(State.REJECTED_RACED);
 695            return;
 696        }
 697        if (isInState(State.SESSION_INITIALIZED_PRE_APPROVED)) {
 698            Log.d(Config.LOGTAG, id.account.getJid() + ": received reject while in SESSION_INITIATED_PRE_APPROVED. callee reconsidered before receiving session-init");
 699            closeTransitionLogFinish(State.TERMINATED_DECLINED_OR_BUSY);
 700            return;
 701        }
 702        Log.d(Config.LOGTAG, id.account.getJid() + ": ignoring reject from responder because already in state " + this.state);
 703    }
 704
 705    private void receivePropose(final Jid from, final Propose propose, final String serverMsgId, final long timestamp) {
 706        final boolean originatedFromMyself = from.asBareJid().equals(id.account.getJid().asBareJid());
 707        if (originatedFromMyself) {
 708            Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": saw proposal from myself. ignoring");
 709        } else if (transition(State.PROPOSED, () -> {
 710            final Collection<RtpDescription> descriptions = Collections2.transform(
 711                    Collections2.filter(propose.getDescriptions(), d -> d instanceof RtpDescription),
 712                    input -> (RtpDescription) input
 713            );
 714            final Collection<Media> media = Collections2.transform(descriptions, RtpDescription::getMedia);
 715            Preconditions.checkState(!media.contains(Media.UNKNOWN), "RTP descriptions contain unknown media");
 716            Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": received session proposal from " + from + " for " + media);
 717            this.proposedMedia = Sets.newHashSet(media);
 718        })) {
 719            if (serverMsgId != null) {
 720                this.message.setServerMsgId(serverMsgId);
 721            }
 722            this.message.setTime(timestamp);
 723            startRinging();
 724        } else {
 725            Log.d(Config.LOGTAG, id.account.getJid() + ": ignoring session proposal because already in " + state);
 726        }
 727    }
 728
 729    private void startRinging() {
 730        Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": received call from " + id.with + ". start ringing");
 731        ringingTimeoutFuture = jingleConnectionManager.schedule(this::ringingTimeout, BUSY_TIME_OUT, TimeUnit.SECONDS);
 732        xmppConnectionService.getNotificationService().startRinging(id, getMedia());
 733    }
 734
 735    private synchronized void ringingTimeout() {
 736        Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": timeout reached for ringing");
 737        switch (this.state) {
 738            case PROPOSED:
 739                message.markUnread();
 740                rejectCallFromProposed();
 741                break;
 742            case SESSION_INITIALIZED:
 743                message.markUnread();
 744                rejectCallFromSessionInitiate();
 745                break;
 746        }
 747    }
 748
 749    private void cancelRingingTimeout() {
 750        final ScheduledFuture<?> future = this.ringingTimeoutFuture;
 751        if (future != null && !future.isCancelled()) {
 752            future.cancel(false);
 753        }
 754    }
 755
 756    private void receiveProceed(final Jid from, final Proceed proceed, final String serverMsgId, final long timestamp) {
 757        final Set<Media> media = Preconditions.checkNotNull(this.proposedMedia, "Proposed media has to be set before handling proceed");
 758        Preconditions.checkState(media.size() > 0, "Proposed media should not be empty");
 759        if (from.equals(id.with)) {
 760            if (isInitiator()) {
 761                if (transition(State.PROCEED)) {
 762                    if (serverMsgId != null) {
 763                        this.message.setServerMsgId(serverMsgId);
 764                    }
 765                    this.message.setTime(timestamp);
 766                    final Integer remoteDeviceId = proceed.getDeviceId();
 767                    if (isOmemoEnabled()) {
 768                        this.omemoVerification.setDeviceId(remoteDeviceId);
 769                    } else {
 770                        if (remoteDeviceId != null) {
 771                            Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": remote party signaled support for OMEMO verification but we have OMEMO disabled");
 772                        }
 773                        this.omemoVerification.setDeviceId(null);
 774                    }
 775                    this.sendSessionInitiate(media, State.SESSION_INITIALIZED_PRE_APPROVED);
 776                } else {
 777                    Log.d(Config.LOGTAG, String.format("%s: ignoring proceed because already in %s", id.account.getJid().asBareJid(), this.state));
 778                }
 779            } else {
 780                Log.d(Config.LOGTAG, String.format("%s: ignoring proceed because we were not initializing", id.account.getJid().asBareJid()));
 781            }
 782        } else if (from.asBareJid().equals(id.account.getJid().asBareJid())) {
 783            if (transition(State.ACCEPTED)) {
 784                Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": moved session with " + id.with + " into state accepted after received carbon copied procced");
 785                this.xmppConnectionService.getNotificationService().cancelIncomingCallNotification();
 786                this.finish();
 787            }
 788        } else {
 789            Log.d(Config.LOGTAG, String.format("%s: ignoring proceed from %s. was expected from %s", id.account.getJid().asBareJid(), from, id.with));
 790        }
 791    }
 792
 793    private void receiveRetract(final Jid from, final String serverMsgId, final long timestamp) {
 794        if (from.equals(id.with)) {
 795            final State target = this.state == State.PROCEED ? State.RETRACTED_RACED : State.RETRACTED;
 796            if (transition(target)) {
 797                xmppConnectionService.getNotificationService().cancelIncomingCallNotification();
 798                Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": session with " + id.with + " has been retracted (serverMsgId=" + serverMsgId + ")");
 799                if (serverMsgId != null) {
 800                    this.message.setServerMsgId(serverMsgId);
 801                }
 802                this.message.setTime(timestamp);
 803                if (target == State.RETRACTED) {
 804                    this.message.markUnread();
 805                }
 806                writeLogMessageMissed();
 807                finish();
 808            } else {
 809                Log.d(Config.LOGTAG, "ignoring retract because already in " + this.state);
 810            }
 811        } else {
 812            //TODO parse retract from self
 813            Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": received retract from " + from + ". expected retract from" + id.with + ". ignoring");
 814        }
 815    }
 816
 817    public void sendSessionInitiate() {
 818        sendSessionInitiate(this.proposedMedia, State.SESSION_INITIALIZED);
 819    }
 820
 821    private void sendSessionInitiate(final Set<Media> media, final State targetState) {
 822        Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": prepare session-initiate");
 823        discoverIceServers(iceServers -> sendSessionInitiate(media, targetState, iceServers));
 824    }
 825
 826    private synchronized void sendSessionInitiate(final Set<Media> media, final State targetState, final List<PeerConnection.IceServer> iceServers) {
 827        if (isTerminated()) {
 828            Log.w(Config.LOGTAG, id.account.getJid().asBareJid() + ": ICE servers got discovered when session was already terminated. nothing to do.");
 829            return;
 830        }
 831        try {
 832            setupWebRTC(media, iceServers);
 833        } catch (final WebRTCWrapper.InitializationException e) {
 834            Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": unable to initialize WebRTC");
 835            webRTCWrapper.close();
 836            sendRetract(Reason.ofThrowable(e));
 837            return;
 838        }
 839        try {
 840            org.webrtc.SessionDescription webRTCSessionDescription = this.webRTCWrapper.setLocalDescription().get();
 841            prepareSessionInitiate(webRTCSessionDescription, targetState);
 842        } catch (final Exception e) {
 843            //TODO sending the error text is worthwhile as well. Especially for FailureToSet exceptions
 844            failureToInitiateSession(e, targetState);
 845        }
 846    }
 847
 848    private void failureToInitiateSession(final Throwable throwable, final State targetState) {
 849        if (isTerminated()) {
 850            return;
 851        }
 852        Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": unable to sendSessionInitiate", Throwables.getRootCause(throwable));
 853        webRTCWrapper.close();
 854        final Reason reason = Reason.ofThrowable(throwable);
 855        if (isInState(targetState)) {
 856            sendSessionTerminate(reason);
 857        } else {
 858            sendRetract(reason);
 859        }
 860    }
 861
 862    private void sendRetract(final Reason reason) {
 863        //TODO embed reason into retract
 864        sendJingleMessage("retract", id.with.asBareJid());
 865        transitionOrThrow(reasonToState(reason));
 866        this.finish();
 867    }
 868
 869    private void prepareSessionInitiate(final org.webrtc.SessionDescription webRTCSessionDescription, final State targetState) {
 870        final SessionDescription sessionDescription = SessionDescription.parse(webRTCSessionDescription.description);
 871        final RtpContentMap rtpContentMap = RtpContentMap.of(sessionDescription);
 872        this.initiatorRtpContentMap = rtpContentMap;
 873        final ListenableFuture<RtpContentMap> outgoingContentMapFuture = encryptSessionInitiate(rtpContentMap);
 874        Futures.addCallback(outgoingContentMapFuture, new FutureCallback<RtpContentMap>() {
 875            @Override
 876            public void onSuccess(final RtpContentMap outgoingContentMap) {
 877                sendSessionInitiate(outgoingContentMap, targetState);
 878            }
 879
 880            @Override
 881            public void onFailure(@NonNull final Throwable throwable) {
 882                failureToInitiateSession(throwable, targetState);
 883            }
 884        }, MoreExecutors.directExecutor());
 885    }
 886
 887    private void sendSessionInitiate(final RtpContentMap rtpContentMap, final State targetState) {
 888        if (isTerminated()) {
 889            Log.w(Config.LOGTAG, id.account.getJid().asBareJid() + ": preparing session was too slow. already terminated. nothing to do.");
 890            return;
 891        }
 892        this.transitionOrThrow(targetState);
 893        final JinglePacket sessionInitiate = rtpContentMap.toJinglePacket(JinglePacket.Action.SESSION_INITIATE, id.sessionId);
 894        send(sessionInitiate);
 895    }
 896
 897    private ListenableFuture<RtpContentMap> encryptSessionInitiate(final RtpContentMap rtpContentMap) {
 898        if (this.omemoVerification.hasDeviceId()) {
 899            final ListenableFuture<AxolotlService.OmemoVerifiedPayload<OmemoVerifiedRtpContentMap>> verifiedPayloadFuture = id.account.getAxolotlService()
 900                    .encrypt(rtpContentMap, id.with, omemoVerification.getDeviceId());
 901            final ListenableFuture<RtpContentMap> future = Futures.transform(verifiedPayloadFuture, verifiedPayload -> {
 902                omemoVerification.setSessionFingerprint(verifiedPayload.getFingerprint());
 903                return verifiedPayload.getPayload();
 904            }, MoreExecutors.directExecutor());
 905            if (Config.REQUIRE_RTP_VERIFICATION) {
 906                return future;
 907            }
 908            return Futures.catching(
 909                    future,
 910                    CryptoFailedException.class,
 911                    e -> {
 912                        Log.w(Config.LOGTAG, id.account.getJid().asBareJid() + ": unable to use OMEMO DTLS verification on outgoing session initiate. falling back", e);
 913                        return rtpContentMap;
 914                    },
 915                    MoreExecutors.directExecutor()
 916            );
 917        } else {
 918            return Futures.immediateFuture(rtpContentMap);
 919        }
 920    }
 921
 922    private void sendSessionTerminate(final Reason reason) {
 923        sendSessionTerminate(reason, null);
 924    }
 925
 926    private void sendSessionTerminate(final Reason reason, final String text) {
 927        final State previous = this.state;
 928        final State target = reasonToState(reason);
 929        transitionOrThrow(target);
 930        if (previous != State.NULL) {
 931            writeLogMessage(target);
 932        }
 933        final JinglePacket jinglePacket = new JinglePacket(JinglePacket.Action.SESSION_TERMINATE, id.sessionId);
 934        jinglePacket.setReason(reason, text);
 935        Log.d(Config.LOGTAG, jinglePacket.toString());
 936        send(jinglePacket);
 937        finish();
 938    }
 939
 940    private void sendTransportInfo(final String contentName, IceUdpTransportInfo.Candidate candidate) {
 941        final RtpContentMap transportInfo;
 942        try {
 943            final RtpContentMap rtpContentMap = isInitiator() ? this.initiatorRtpContentMap : this.responderRtpContentMap;
 944            transportInfo = rtpContentMap.transportInfo(contentName, candidate);
 945        } catch (final Exception e) {
 946            Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": unable to prepare transport-info from candidate for content=" + contentName);
 947            return;
 948        }
 949        final JinglePacket jinglePacket = transportInfo.toJinglePacket(JinglePacket.Action.TRANSPORT_INFO, id.sessionId);
 950        send(jinglePacket);
 951    }
 952
 953    private void send(final JinglePacket jinglePacket) {
 954        jinglePacket.setTo(id.with);
 955        xmppConnectionService.sendIqPacket(id.account, jinglePacket, this::handleIqResponse);
 956    }
 957
 958    private synchronized void handleIqResponse(final Account account, final IqPacket response) {
 959        if (response.getType() == IqPacket.TYPE.ERROR) {
 960            final String errorCondition = response.getErrorCondition();
 961            Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": received IQ-error from " + response.getFrom() + " in RTP session. " + errorCondition);
 962            if (isTerminated()) {
 963                Log.i(Config.LOGTAG, id.account.getJid().asBareJid() + ": ignoring error because session was already terminated");
 964                return;
 965            }
 966            this.webRTCWrapper.close();
 967            final State target;
 968            if (Arrays.asList(
 969                    "service-unavailable",
 970                    "recipient-unavailable",
 971                    "remote-server-not-found",
 972                    "remote-server-timeout"
 973            ).contains(errorCondition)) {
 974                target = State.TERMINATED_CONNECTIVITY_ERROR;
 975            } else {
 976                target = State.TERMINATED_APPLICATION_FAILURE;
 977            }
 978            transitionOrThrow(target);
 979            this.finish();
 980        } else if (response.getType() == IqPacket.TYPE.TIMEOUT) {
 981            Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": received IQ timeout in RTP session with " + id.with + ". terminating with connectivity error");
 982            if (isTerminated()) {
 983                Log.i(Config.LOGTAG, id.account.getJid().asBareJid() + ": ignoring error because session was already terminated");
 984                return;
 985            }
 986            this.webRTCWrapper.close();
 987            transitionOrThrow(State.TERMINATED_CONNECTIVITY_ERROR);
 988            this.finish();
 989        }
 990    }
 991
 992    private void terminateWithOutOfOrder(final JinglePacket jinglePacket) {
 993        Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": terminating session with out-of-order");
 994        this.webRTCWrapper.close();
 995        transitionOrThrow(State.TERMINATED_APPLICATION_FAILURE);
 996        respondWithOutOfOrder(jinglePacket);
 997        this.finish();
 998    }
 999
1000    private void respondWithOutOfOrder(final JinglePacket jinglePacket) {
1001        jingleConnectionManager.respondWithJingleError(id.account, jinglePacket, "out-of-order", "unexpected-request", "wait");
1002    }
1003
1004    private void respondOk(final JinglePacket jinglePacket) {
1005        xmppConnectionService.sendIqPacket(id.account, jinglePacket.generateResponse(IqPacket.TYPE.RESULT), null);
1006    }
1007
1008    public void throwStateTransitionException() {
1009        final StateTransitionException exception = this.stateTransitionException;
1010        if (exception != null) {
1011            throw new IllegalStateException(String.format("Transition to %s did not call finish", exception.state), exception);
1012        }
1013    }
1014
1015    public RtpEndUserState getEndUserState() {
1016        switch (this.state) {
1017            case NULL:
1018            case PROPOSED:
1019            case SESSION_INITIALIZED:
1020                if (isInitiator()) {
1021                    return RtpEndUserState.RINGING;
1022                } else {
1023                    return RtpEndUserState.INCOMING_CALL;
1024                }
1025            case PROCEED:
1026                if (isInitiator()) {
1027                    return RtpEndUserState.RINGING;
1028                } else {
1029                    return RtpEndUserState.ACCEPTING_CALL;
1030                }
1031            case SESSION_INITIALIZED_PRE_APPROVED:
1032                if (isInitiator()) {
1033                    return RtpEndUserState.RINGING;
1034                } else {
1035                    return RtpEndUserState.CONNECTING;
1036                }
1037            case SESSION_ACCEPTED:
1038                return getPeerConnectionStateAsEndUserState();
1039            case REJECTED:
1040            case REJECTED_RACED:
1041            case TERMINATED_DECLINED_OR_BUSY:
1042                if (isInitiator()) {
1043                    return RtpEndUserState.DECLINED_OR_BUSY;
1044                } else {
1045                    return RtpEndUserState.ENDED;
1046                }
1047            case TERMINATED_SUCCESS:
1048            case ACCEPTED:
1049            case RETRACTED:
1050            case TERMINATED_CANCEL_OR_TIMEOUT:
1051                return RtpEndUserState.ENDED;
1052            case RETRACTED_RACED:
1053                if (isInitiator()) {
1054                    return RtpEndUserState.ENDED;
1055                } else {
1056                    return RtpEndUserState.RETRACTED;
1057                }
1058            case TERMINATED_CONNECTIVITY_ERROR:
1059                return rtpConnectionStarted == 0 ? RtpEndUserState.CONNECTIVITY_ERROR : RtpEndUserState.CONNECTIVITY_LOST_ERROR;
1060            case TERMINATED_APPLICATION_FAILURE:
1061                return RtpEndUserState.APPLICATION_ERROR;
1062            case TERMINATED_SECURITY_ERROR:
1063                return RtpEndUserState.SECURITY_ERROR;
1064        }
1065        throw new IllegalStateException(String.format("%s has no equivalent EndUserState", this.state));
1066    }
1067
1068
1069    private RtpEndUserState getPeerConnectionStateAsEndUserState() {
1070        final PeerConnection.PeerConnectionState state;
1071        try {
1072            state = webRTCWrapper.getState();
1073        } catch (final WebRTCWrapper.PeerConnectionNotInitialized e) {
1074            //We usually close the WebRTCWrapper *before* transitioning so we might still
1075            //be in SESSION_ACCEPTED even though the peerConnection has been torn down
1076            return RtpEndUserState.ENDING_CALL;
1077        }
1078        switch (state) {
1079            case CONNECTED:
1080                return RtpEndUserState.CONNECTED;
1081            case NEW:
1082            case CONNECTING:
1083                return RtpEndUserState.CONNECTING;
1084            case CLOSED:
1085                return RtpEndUserState.ENDING_CALL;
1086            default:
1087                return rtpConnectionStarted == 0 ? RtpEndUserState.CONNECTIVITY_ERROR : RtpEndUserState.RECONNECTING;
1088        }
1089    }
1090
1091    public Set<Media> getMedia() {
1092        final State current = getState();
1093        if (current == State.NULL) {
1094            if (isInitiator()) {
1095                return Preconditions.checkNotNull(
1096                        this.proposedMedia,
1097                        "RTP connection has not been initialized properly"
1098                );
1099            }
1100            throw new IllegalStateException("RTP connection has not been initialized yet");
1101        }
1102        if (Arrays.asList(State.PROPOSED, State.PROCEED).contains(current)) {
1103            return Preconditions.checkNotNull(
1104                    this.proposedMedia,
1105                    "RTP connection has not been initialized properly"
1106            );
1107        }
1108        final RtpContentMap initiatorContentMap = initiatorRtpContentMap;
1109        if (initiatorContentMap != null) {
1110            return initiatorContentMap.getMedia();
1111        } else if (isTerminated()) {
1112            return Collections.emptySet(); //we might fail before we ever got a chance to set media
1113        } else {
1114            return Preconditions.checkNotNull(this.proposedMedia, "RTP connection has not been initialized properly");
1115        }
1116    }
1117
1118
1119    public boolean isVerified() {
1120        final String fingerprint = this.omemoVerification.getFingerprint();
1121        if (fingerprint == null) {
1122            return false;
1123        }
1124        final FingerprintStatus status = id.account.getAxolotlService().getFingerprintTrust(fingerprint);
1125        return status != null && status.isVerified();
1126    }
1127
1128    public synchronized void acceptCall() {
1129        switch (this.state) {
1130            case PROPOSED:
1131                cancelRingingTimeout();
1132                acceptCallFromProposed();
1133                break;
1134            case SESSION_INITIALIZED:
1135                cancelRingingTimeout();
1136                acceptCallFromSessionInitialized();
1137                break;
1138            case ACCEPTED:
1139                Log.w(Config.LOGTAG, id.account.getJid().asBareJid() + ": the call has already been accepted  with another client. UI was just lagging behind");
1140                break;
1141            case PROCEED:
1142            case SESSION_ACCEPTED:
1143                Log.w(Config.LOGTAG, id.account.getJid().asBareJid() + ": the call has already been accepted. user probably double tapped the UI");
1144                break;
1145            default:
1146                throw new IllegalStateException("Can not accept call from " + this.state);
1147        }
1148    }
1149
1150
1151    public void notifyPhoneCall() {
1152        Log.d(Config.LOGTAG, "a phone call has just been started. killing jingle rtp connections");
1153        if (Arrays.asList(State.PROPOSED, State.SESSION_INITIALIZED).contains(this.state)) {
1154            rejectCall();
1155        } else {
1156            endCall();
1157        }
1158    }
1159
1160    public synchronized void rejectCall() {
1161        if (isTerminated()) {
1162            Log.w(Config.LOGTAG, id.account.getJid().asBareJid() + ": received rejectCall() when session has already been terminated. nothing to do");
1163            return;
1164        }
1165        switch (this.state) {
1166            case PROPOSED:
1167                rejectCallFromProposed();
1168                break;
1169            case SESSION_INITIALIZED:
1170                rejectCallFromSessionInitiate();
1171                break;
1172            default:
1173                throw new IllegalStateException("Can not reject call from " + this.state);
1174        }
1175    }
1176
1177    public synchronized void endCall() {
1178        if (isTerminated()) {
1179            Log.w(Config.LOGTAG, id.account.getJid().asBareJid() + ": received endCall() when session has already been terminated. nothing to do");
1180            return;
1181        }
1182        if (isInState(State.PROPOSED) && !isInitiator()) {
1183            rejectCallFromProposed();
1184            return;
1185        }
1186        if (isInState(State.PROCEED)) {
1187            if (isInitiator()) {
1188                retractFromProceed();
1189            } else {
1190                rejectCallFromProceed();
1191            }
1192            return;
1193        }
1194        if (isInitiator() && isInState(State.SESSION_INITIALIZED, State.SESSION_INITIALIZED_PRE_APPROVED)) {
1195            this.webRTCWrapper.close();
1196            sendSessionTerminate(Reason.CANCEL);
1197            return;
1198        }
1199        if (isInState(State.SESSION_INITIALIZED)) {
1200            rejectCallFromSessionInitiate();
1201            return;
1202        }
1203        if (isInState(State.SESSION_INITIALIZED_PRE_APPROVED, State.SESSION_ACCEPTED)) {
1204            this.webRTCWrapper.close();
1205            sendSessionTerminate(Reason.SUCCESS);
1206            return;
1207        }
1208        if (isInState(State.TERMINATED_APPLICATION_FAILURE, State.TERMINATED_CONNECTIVITY_ERROR, State.TERMINATED_DECLINED_OR_BUSY)) {
1209            Log.d(Config.LOGTAG, "ignoring request to end call because already in state " + this.state);
1210            return;
1211        }
1212        throw new IllegalStateException("called 'endCall' while in state " + this.state + ". isInitiator=" + isInitiator());
1213    }
1214
1215    private void retractFromProceed() {
1216        Log.d(Config.LOGTAG, "retract from proceed");
1217        this.sendJingleMessage("retract");
1218        closeTransitionLogFinish(State.RETRACTED_RACED);
1219    }
1220
1221    private void closeTransitionLogFinish(final State state) {
1222        this.webRTCWrapper.close();
1223        transitionOrThrow(state);
1224        writeLogMessage(state);
1225        finish();
1226    }
1227
1228    private void setupWebRTC(final Set<Media> media, final List<PeerConnection.IceServer> iceServers) throws WebRTCWrapper.InitializationException {
1229        this.jingleConnectionManager.ensureConnectionIsRegistered(this);
1230        final AppRTCAudioManager.SpeakerPhonePreference speakerPhonePreference;
1231        if (media.contains(Media.VIDEO)) {
1232            speakerPhonePreference = AppRTCAudioManager.SpeakerPhonePreference.SPEAKER;
1233        } else {
1234            speakerPhonePreference = AppRTCAudioManager.SpeakerPhonePreference.EARPIECE;
1235        }
1236        this.webRTCWrapper.setup(this.xmppConnectionService, speakerPhonePreference);
1237        this.webRTCWrapper.initializePeerConnection(media, iceServers);
1238    }
1239
1240    private void acceptCallFromProposed() {
1241        transitionOrThrow(State.PROCEED);
1242        xmppConnectionService.getNotificationService().cancelIncomingCallNotification();
1243        this.sendJingleMessage("accept", id.account.getJid().asBareJid());
1244        this.sendJingleMessage("proceed");
1245    }
1246
1247    private void rejectCallFromProposed() {
1248        transitionOrThrow(State.REJECTED);
1249        writeLogMessageMissed();
1250        xmppConnectionService.getNotificationService().cancelIncomingCallNotification();
1251        this.sendJingleMessage("reject");
1252        finish();
1253    }
1254
1255    private void rejectCallFromProceed() {
1256        this.sendJingleMessage("reject");
1257        closeTransitionLogFinish(State.REJECTED_RACED);
1258    }
1259
1260    private void rejectCallFromSessionInitiate() {
1261        webRTCWrapper.close();
1262        sendSessionTerminate(Reason.DECLINE);
1263        xmppConnectionService.getNotificationService().cancelIncomingCallNotification();
1264    }
1265
1266    private void sendJingleMessage(final String action) {
1267        sendJingleMessage(action, id.with);
1268    }
1269
1270    private void sendJingleMessage(final String action, final Jid to) {
1271        final MessagePacket messagePacket = new MessagePacket();
1272        messagePacket.setType(MessagePacket.TYPE_CHAT); //we want to carbon copy those
1273        messagePacket.setTo(to);
1274        final Element intent = messagePacket.addChild(action, Namespace.JINGLE_MESSAGE).setAttribute("id", id.sessionId);
1275        if ("proceed".equals(action)) {
1276            messagePacket.setId(JINGLE_MESSAGE_PROCEED_ID_PREFIX + id.sessionId);
1277            if (isOmemoEnabled()) {
1278                final int deviceId = id.account.getAxolotlService().getOwnDeviceId();
1279                final Element device = intent.addChild("device", Namespace.OMEMO_DTLS_SRTP_VERIFICATION);
1280                device.setAttribute("id", deviceId);
1281            }
1282        }
1283        messagePacket.addChild("store", "urn:xmpp:hints");
1284        xmppConnectionService.sendMessagePacket(id.account, messagePacket);
1285    }
1286
1287    private boolean isOmemoEnabled() {
1288        final Conversational conversational = message.getConversation();
1289        if (conversational instanceof Conversation) {
1290            return ((Conversation) conversational).getNextEncryption() == Message.ENCRYPTION_AXOLOTL;
1291        }
1292        return false;
1293    }
1294
1295    private void acceptCallFromSessionInitialized() {
1296        xmppConnectionService.getNotificationService().cancelIncomingCallNotification();
1297        sendSessionAccept();
1298    }
1299
1300    private synchronized boolean isInState(State... state) {
1301        return Arrays.asList(state).contains(this.state);
1302    }
1303
1304    private boolean transition(final State target) {
1305        return transition(target, null);
1306    }
1307
1308    private synchronized boolean transition(final State target, final Runnable runnable) {
1309        final Collection<State> validTransitions = VALID_TRANSITIONS.get(this.state);
1310        if (validTransitions != null && validTransitions.contains(target)) {
1311            this.state = target;
1312            this.stateTransitionException = new StateTransitionException(target);
1313            if (runnable != null) {
1314                runnable.run();
1315            }
1316            Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": transitioned into " + target);
1317            updateEndUserState();
1318            updateOngoingCallNotification();
1319            return true;
1320        } else {
1321            return false;
1322        }
1323    }
1324
1325    void transitionOrThrow(final State target) {
1326        if (!transition(target)) {
1327            throw new IllegalStateException(String.format("Unable to transition from %s to %s", this.state, target));
1328        }
1329    }
1330
1331    @Override
1332    public void onIceCandidate(final IceCandidate iceCandidate) {
1333        final IceUdpTransportInfo.Candidate candidate = IceUdpTransportInfo.Candidate.fromSdpAttribute(iceCandidate.sdp);
1334        Log.d(Config.LOGTAG, "sending candidate: " + iceCandidate.toString());
1335        sendTransportInfo(iceCandidate.sdpMid, candidate);
1336    }
1337
1338    @Override
1339    public void onConnectionChange(final PeerConnection.PeerConnectionState oldState, final PeerConnection.PeerConnectionState newState) {
1340        Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": PeerConnectionState changed: " + oldState + "->" + newState);
1341        final boolean neverConnected = this.rtpConnectionStarted == 0;
1342        if (newState == PeerConnection.PeerConnectionState.CONNECTED && this.rtpConnectionStarted == 0) {
1343            this.rtpConnectionStarted = SystemClock.elapsedRealtime();
1344        }
1345        if (newState == PeerConnection.PeerConnectionState.CLOSED && this.rtpConnectionEnded == 0) {
1346            this.rtpConnectionEnded = SystemClock.elapsedRealtime();
1347        }
1348
1349        if (neverConnected && Arrays.asList(PeerConnection.PeerConnectionState.FAILED, PeerConnection.PeerConnectionState.DISCONNECTED).contains(newState)) {
1350            if (isTerminated()) {
1351                Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": not sending session-terminate after connectivity error because session is already in state " + this.state);
1352                return;
1353            }
1354            new Thread(this::closeWebRTCSessionAfterFailedConnection).start();
1355        } else if (newState == PeerConnection.PeerConnectionState.FAILED) {
1356            Log.d(Config.LOGTAG, "attempting to restart ICE");
1357            webRTCWrapper.restartIce();
1358        }
1359        updateEndUserState();
1360    }
1361
1362    @Override
1363    public void onRenegotiationNeeded() {
1364        Log.d(Config.LOGTAG, "onRenegotiationNeeded()");
1365    }
1366
1367    private void closeWebRTCSessionAfterFailedConnection() {
1368        this.webRTCWrapper.close();
1369        synchronized (this) {
1370            if (isTerminated()) {
1371                Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": no need to send session-terminate after failed connection. Other party already did");
1372                return;
1373            }
1374            sendSessionTerminate(Reason.CONNECTIVITY_ERROR);
1375        }
1376    }
1377
1378    public long getRtpConnectionStarted() {
1379        return this.rtpConnectionStarted;
1380    }
1381
1382    public long getRtpConnectionEnded() {
1383        return this.rtpConnectionEnded;
1384    }
1385
1386    public AppRTCAudioManager getAudioManager() {
1387        return webRTCWrapper.getAudioManager();
1388    }
1389
1390    public boolean isMicrophoneEnabled() {
1391        return webRTCWrapper.isMicrophoneEnabled();
1392    }
1393
1394    public boolean setMicrophoneEnabled(final boolean enabled) {
1395        return webRTCWrapper.setMicrophoneEnabled(enabled);
1396    }
1397
1398    public boolean isVideoEnabled() {
1399        return webRTCWrapper.isVideoEnabled();
1400    }
1401
1402    public void setVideoEnabled(final boolean enabled) {
1403        webRTCWrapper.setVideoEnabled(enabled);
1404    }
1405
1406    public boolean isCameraSwitchable() {
1407        return webRTCWrapper.isCameraSwitchable();
1408    }
1409
1410    public boolean isFrontCamera() {
1411        return webRTCWrapper.isFrontCamera();
1412    }
1413
1414    public ListenableFuture<Boolean> switchCamera() {
1415        return webRTCWrapper.switchCamera();
1416    }
1417
1418    @Override
1419    public void onAudioDeviceChanged(AppRTCAudioManager.AudioDevice selectedAudioDevice, Set<AppRTCAudioManager.AudioDevice> availableAudioDevices) {
1420        xmppConnectionService.notifyJingleRtpConnectionUpdate(selectedAudioDevice, availableAudioDevices);
1421    }
1422
1423    private void updateEndUserState() {
1424        final RtpEndUserState endUserState = getEndUserState();
1425        jingleConnectionManager.toneManager.transition(isInitiator(), endUserState, getMedia());
1426        xmppConnectionService.notifyJingleRtpConnectionUpdate(id.account, id.with, id.sessionId, endUserState);
1427    }
1428
1429    private void updateOngoingCallNotification() {
1430        if (STATES_SHOWING_ONGOING_CALL.contains(this.state)) {
1431            xmppConnectionService.setOngoingCall(id, getMedia());
1432        } else {
1433            xmppConnectionService.removeOngoingCall();
1434        }
1435    }
1436
1437    private void discoverIceServers(final OnIceServersDiscovered onIceServersDiscovered) {
1438        if (id.account.getXmppConnection().getFeatures().externalServiceDiscovery()) {
1439            final IqPacket request = new IqPacket(IqPacket.TYPE.GET);
1440            request.setTo(id.account.getDomain());
1441            request.addChild("services", Namespace.EXTERNAL_SERVICE_DISCOVERY);
1442            xmppConnectionService.sendIqPacket(id.account, request, (account, response) -> {
1443                ImmutableList.Builder<PeerConnection.IceServer> listBuilder = new ImmutableList.Builder<>();
1444                if (response.getType() == IqPacket.TYPE.RESULT) {
1445                    final Element services = response.findChild("services", Namespace.EXTERNAL_SERVICE_DISCOVERY);
1446                    final List<Element> children = services == null ? Collections.emptyList() : services.getChildren();
1447                    for (final Element child : children) {
1448                        if ("service".equals(child.getName())) {
1449                            final String type = child.getAttribute("type");
1450                            final String host = child.getAttribute("host");
1451                            final String sport = child.getAttribute("port");
1452                            final Integer port = sport == null ? null : Ints.tryParse(sport);
1453                            final String transport = child.getAttribute("transport");
1454                            final String username = child.getAttribute("username");
1455                            final String password = child.getAttribute("password");
1456                            if (Strings.isNullOrEmpty(host) || port == null) {
1457                                continue;
1458                            }
1459                            if (port < 0 || port > 65535) {
1460                                continue;
1461                            }
1462                            if (Arrays.asList("stun", "stuns", "turn", "turns").contains(type) && Arrays.asList("udp", "tcp").contains(transport)) {
1463                                if (Arrays.asList("stuns", "turns").contains(type) && "udp".equals(transport)) {
1464                                    Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": skipping invalid combination of udp/tls in external services");
1465                                    continue;
1466                                }
1467                                final PeerConnection.IceServer.Builder iceServerBuilder = PeerConnection.IceServer
1468                                        .builder(String.format("%s:%s:%s?transport=%s", type, IP.wrapIPv6(host), port, transport));
1469                                iceServerBuilder.setTlsCertPolicy(PeerConnection.TlsCertPolicy.TLS_CERT_POLICY_INSECURE_NO_CHECK);
1470                                if (username != null && password != null) {
1471                                    iceServerBuilder.setUsername(username);
1472                                    iceServerBuilder.setPassword(password);
1473                                } else if (Arrays.asList("turn", "turns").contains(type)) {
1474                                    //The WebRTC spec requires throwing an InvalidAccessError when username (from libwebrtc source coder)
1475                                    //https://chromium.googlesource.com/external/webrtc/+/master/pc/ice_server_parsing.cc
1476                                    Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": skipping " + type + "/" + transport + " without username and password");
1477                                    continue;
1478                                }
1479                                final PeerConnection.IceServer iceServer = iceServerBuilder.createIceServer();
1480                                Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": discovered ICE Server: " + iceServer);
1481                                listBuilder.add(iceServer);
1482                            }
1483                        }
1484                    }
1485                }
1486                final List<PeerConnection.IceServer> iceServers = listBuilder.build();
1487                if (iceServers.size() == 0) {
1488                    Log.w(Config.LOGTAG, id.account.getJid().asBareJid() + ": no ICE server found " + response);
1489                }
1490                onIceServersDiscovered.onIceServersDiscovered(iceServers);
1491            });
1492        } else {
1493            Log.w(Config.LOGTAG, id.account.getJid().asBareJid() + ": has no external service discovery");
1494            onIceServersDiscovered.onIceServersDiscovered(Collections.emptyList());
1495        }
1496    }
1497
1498    private void finish() {
1499        if (isTerminated()) {
1500            this.cancelRingingTimeout();
1501            this.webRTCWrapper.verifyClosed();
1502            this.jingleConnectionManager.setTerminalSessionState(id, getEndUserState(), getMedia());
1503            this.jingleConnectionManager.finishConnectionOrThrow(this);
1504        } else {
1505            throw new IllegalStateException(String.format("Unable to call finish from %s", this.state));
1506        }
1507    }
1508
1509    private void writeLogMessage(final State state) {
1510        final long started = this.rtpConnectionStarted;
1511        long duration = started <= 0 ? 0 : SystemClock.elapsedRealtime() - started;
1512        if (state == State.TERMINATED_SUCCESS || (state == State.TERMINATED_CONNECTIVITY_ERROR && duration > 0)) {
1513            writeLogMessageSuccess(duration);
1514        } else {
1515            writeLogMessageMissed();
1516        }
1517    }
1518
1519    private void writeLogMessageSuccess(final long duration) {
1520        this.message.setBody(new RtpSessionStatus(true, duration).toString());
1521        this.writeMessage();
1522    }
1523
1524    private void writeLogMessageMissed() {
1525        this.message.setBody(new RtpSessionStatus(false, 0).toString());
1526        this.writeMessage();
1527    }
1528
1529    private void writeMessage() {
1530        final Conversational conversational = message.getConversation();
1531        if (conversational instanceof Conversation) {
1532            ((Conversation) conversational).add(this.message);
1533            xmppConnectionService.createMessageAsync(message);
1534            xmppConnectionService.updateConversationUi();
1535        } else {
1536            throw new IllegalStateException("Somehow the conversation in a message was a stub");
1537        }
1538    }
1539
1540    public State getState() {
1541        return this.state;
1542    }
1543
1544    boolean isTerminated() {
1545        return TERMINATED.contains(this.state);
1546    }
1547
1548    public Optional<VideoTrack> getLocalVideoTrack() {
1549        return webRTCWrapper.getLocalVideoTrack();
1550    }
1551
1552    public Optional<VideoTrack> getRemoteVideoTrack() {
1553        return webRTCWrapper.getRemoteVideoTrack();
1554    }
1555
1556
1557    public EglBase.Context getEglBaseContext() {
1558        return webRTCWrapper.getEglBaseContext();
1559    }
1560
1561    void setProposedMedia(final Set<Media> media) {
1562        this.proposedMedia = media;
1563    }
1564
1565    public void fireStateUpdate() {
1566        final RtpEndUserState endUserState = getEndUserState();
1567        xmppConnectionService.notifyJingleRtpConnectionUpdate(id.account, id.with, id.sessionId, endUserState);
1568    }
1569
1570    private interface OnIceServersDiscovered {
1571        void onIceServersDiscovered(List<PeerConnection.IceServer> iceServers);
1572    }
1573
1574    private static class StateTransitionException extends Exception {
1575        private final State state;
1576
1577        private StateTransitionException(final State state) {
1578            this.state = state;
1579        }
1580    }
1581}