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