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