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