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