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