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    public synchronized void rejectCall() {
 905        if (isTerminated()) {
 906            Log.w(Config.LOGTAG, id.account.getJid().asBareJid() + ": received rejectCall() when session has already been terminated. nothing to do");
 907            return;
 908        }
 909        switch (this.state) {
 910            case PROPOSED:
 911                rejectCallFromProposed();
 912                break;
 913            case SESSION_INITIALIZED:
 914                rejectCallFromSessionInitiate();
 915                break;
 916            default:
 917                throw new IllegalStateException("Can not reject call from " + this.state);
 918        }
 919    }
 920
 921    public synchronized void endCall() {
 922        if (isTerminated()) {
 923            Log.w(Config.LOGTAG, id.account.getJid().asBareJid() + ": received endCall() when session has already been terminated. nothing to do");
 924            return;
 925        }
 926        if (isInState(State.PROPOSED) && !isInitiator()) {
 927            rejectCallFromProposed();
 928            return;
 929        }
 930        if (isInState(State.PROCEED)) {
 931            Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": ending call while in state PROCEED just means ending the connection");
 932            this.webRTCWrapper.close();
 933            transitionOrThrow(State.TERMINATED_SUCCESS); //arguably this wasn't success; but not a real failure either
 934            this.finish();
 935            return;
 936        }
 937        if (isInitiator() && isInState(State.SESSION_INITIALIZED, State.SESSION_INITIALIZED_PRE_APPROVED)) {
 938            this.webRTCWrapper.close();
 939            sendSessionTerminate(Reason.CANCEL);
 940            return;
 941        }
 942        if (isInState(State.SESSION_INITIALIZED)) {
 943            rejectCallFromSessionInitiate();
 944            return;
 945        }
 946        if (isInState(State.SESSION_INITIALIZED_PRE_APPROVED, State.SESSION_ACCEPTED)) {
 947            this.webRTCWrapper.close();
 948            sendSessionTerminate(Reason.SUCCESS);
 949            return;
 950        }
 951        if (isInState(State.TERMINATED_APPLICATION_FAILURE, State.TERMINATED_CONNECTIVITY_ERROR, State.TERMINATED_DECLINED_OR_BUSY)) {
 952            Log.d(Config.LOGTAG, "ignoring request to end call because already in state " + this.state);
 953            return;
 954        }
 955        throw new IllegalStateException("called 'endCall' while in state " + this.state + ". isInitiator=" + isInitiator());
 956    }
 957
 958    private void setupWebRTC(final Set<Media> media, final List<PeerConnection.IceServer> iceServers) throws WebRTCWrapper.InitializationException {
 959        this.jingleConnectionManager.ensureConnectionIsRegistered(this);
 960        final AppRTCAudioManager.SpeakerPhonePreference speakerPhonePreference;
 961        if (media.contains(Media.VIDEO)) {
 962            speakerPhonePreference = AppRTCAudioManager.SpeakerPhonePreference.SPEAKER;
 963        } else {
 964            speakerPhonePreference = AppRTCAudioManager.SpeakerPhonePreference.EARPIECE;
 965        }
 966        this.webRTCWrapper.setup(this.xmppConnectionService, speakerPhonePreference);
 967        this.webRTCWrapper.initializePeerConnection(media, iceServers);
 968    }
 969
 970    private void acceptCallFromProposed() {
 971        transitionOrThrow(State.PROCEED);
 972        xmppConnectionService.getNotificationService().cancelIncomingCallNotification();
 973        this.sendJingleMessage("accept", id.account.getJid().asBareJid());
 974        this.sendJingleMessage("proceed");
 975    }
 976
 977    private void rejectCallFromProposed() {
 978        transitionOrThrow(State.REJECTED);
 979        writeLogMessageMissed();
 980        xmppConnectionService.getNotificationService().cancelIncomingCallNotification();
 981        this.sendJingleMessage("reject");
 982        finish();
 983    }
 984
 985    private void rejectCallFromSessionInitiate() {
 986        webRTCWrapper.close();
 987        sendSessionTerminate(Reason.DECLINE);
 988        xmppConnectionService.getNotificationService().cancelIncomingCallNotification();
 989    }
 990
 991    private void sendJingleMessage(final String action) {
 992        sendJingleMessage(action, id.with);
 993    }
 994
 995    private void sendJingleMessage(final String action, final Jid to) {
 996        final MessagePacket messagePacket = new MessagePacket();
 997        if ("proceed".equals(action)) {
 998            messagePacket.setId(JINGLE_MESSAGE_PROCEED_ID_PREFIX + id.sessionId);
 999        }
1000        messagePacket.setType(MessagePacket.TYPE_CHAT); //we want to carbon copy those
1001        messagePacket.setTo(to);
1002        messagePacket.addChild(action, Namespace.JINGLE_MESSAGE).setAttribute("id", id.sessionId);
1003        messagePacket.addChild("store", "urn:xmpp:hints");
1004        xmppConnectionService.sendMessagePacket(id.account, messagePacket);
1005    }
1006
1007    private void acceptCallFromSessionInitialized() {
1008        xmppConnectionService.getNotificationService().cancelIncomingCallNotification();
1009        sendSessionAccept();
1010    }
1011
1012    private synchronized boolean isInState(State... state) {
1013        return Arrays.asList(state).contains(this.state);
1014    }
1015
1016    private boolean transition(final State target) {
1017        return transition(target, null);
1018    }
1019
1020    private synchronized boolean transition(final State target, final Runnable runnable) {
1021        final Collection<State> validTransitions = VALID_TRANSITIONS.get(this.state);
1022        if (validTransitions != null && validTransitions.contains(target)) {
1023            this.state = target;
1024            this.stateTransitionException = new StateTransitionException(target);
1025            if (runnable != null) {
1026                runnable.run();
1027            }
1028            Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": transitioned into " + target);
1029            updateEndUserState();
1030            updateOngoingCallNotification();
1031            return true;
1032        } else {
1033            return false;
1034        }
1035    }
1036
1037    void transitionOrThrow(final State target) {
1038        if (!transition(target)) {
1039            throw new IllegalStateException(String.format("Unable to transition from %s to %s", this.state, target));
1040        }
1041    }
1042
1043    @Override
1044    public void onIceCandidate(final IceCandidate iceCandidate) {
1045        final IceUdpTransportInfo.Candidate candidate = IceUdpTransportInfo.Candidate.fromSdpAttribute(iceCandidate.sdp);
1046        Log.d(Config.LOGTAG, "sending candidate: " + iceCandidate.toString());
1047        sendTransportInfo(iceCandidate.sdpMid, candidate);
1048    }
1049
1050    @Override
1051    public void onConnectionChange(final PeerConnection.PeerConnectionState newState) {
1052        Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": PeerConnectionState changed to " + newState);
1053        if (newState == PeerConnection.PeerConnectionState.CONNECTED && this.rtpConnectionStarted == 0) {
1054            this.rtpConnectionStarted = SystemClock.elapsedRealtime();
1055        }
1056        if (newState == PeerConnection.PeerConnectionState.CLOSED && this.rtpConnectionEnded == 0) {
1057            this.rtpConnectionEnded = SystemClock.elapsedRealtime();
1058        }
1059        //TODO 'DISCONNECTED' might be an opportunity to renew the offer and send a transport-replace
1060        //TODO exact syntax is yet to be determined but transport-replace sounds like the most reasonable
1061        //as there is no content-replace
1062        if (Arrays.asList(PeerConnection.PeerConnectionState.FAILED, PeerConnection.PeerConnectionState.DISCONNECTED).contains(newState)) {
1063            if (isTerminated()) {
1064                Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": not sending session-terminate after connectivity error because session is already in state " + this.state);
1065                return;
1066            }
1067            new Thread(this::closeWebRTCSessionAfterFailedConnection).start();
1068        } else {
1069            updateEndUserState();
1070        }
1071    }
1072
1073    private void closeWebRTCSessionAfterFailedConnection() {
1074        this.webRTCWrapper.close();
1075        synchronized (this) {
1076            if (isTerminated()) {
1077                Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": no need to send session-terminate after failed connection. Other party already did");
1078                return;
1079            }
1080            sendSessionTerminate(Reason.CONNECTIVITY_ERROR);
1081        }
1082    }
1083
1084    public long getRtpConnectionStarted() {
1085        return this.rtpConnectionStarted;
1086    }
1087
1088    public long getRtpConnectionEnded() {
1089        return this.rtpConnectionEnded;
1090    }
1091
1092    public AppRTCAudioManager getAudioManager() {
1093        return webRTCWrapper.getAudioManager();
1094    }
1095
1096    public boolean isMicrophoneEnabled() {
1097        return webRTCWrapper.isMicrophoneEnabled();
1098    }
1099
1100    public boolean setMicrophoneEnabled(final boolean enabled) {
1101        return webRTCWrapper.setMicrophoneEnabled(enabled);
1102    }
1103
1104    public boolean isVideoEnabled() {
1105        return webRTCWrapper.isVideoEnabled();
1106    }
1107
1108    public void setVideoEnabled(final boolean enabled) {
1109        webRTCWrapper.setVideoEnabled(enabled);
1110    }
1111
1112    public boolean isCameraSwitchable() {
1113        return webRTCWrapper.isCameraSwitchable();
1114    }
1115
1116    public boolean isFrontCamera() {
1117        return webRTCWrapper.isFrontCamera();
1118    }
1119
1120    public ListenableFuture<Boolean> switchCamera() {
1121        return webRTCWrapper.switchCamera();
1122    }
1123
1124    @Override
1125    public void onAudioDeviceChanged(AppRTCAudioManager.AudioDevice selectedAudioDevice, Set<AppRTCAudioManager.AudioDevice> availableAudioDevices) {
1126        xmppConnectionService.notifyJingleRtpConnectionUpdate(selectedAudioDevice, availableAudioDevices);
1127    }
1128
1129    private void updateEndUserState() {
1130        final RtpEndUserState endUserState = getEndUserState();
1131        jingleConnectionManager.toneManager.transition(isInitiator(), endUserState, getMedia());
1132        xmppConnectionService.notifyJingleRtpConnectionUpdate(id.account, id.with, id.sessionId, endUserState);
1133    }
1134
1135    private void updateOngoingCallNotification() {
1136        if (STATES_SHOWING_ONGOING_CALL.contains(this.state)) {
1137            xmppConnectionService.setOngoingCall(id, getMedia());
1138        } else {
1139            xmppConnectionService.removeOngoingCall();
1140        }
1141    }
1142
1143    private void discoverIceServers(final OnIceServersDiscovered onIceServersDiscovered) {
1144        if (id.account.getXmppConnection().getFeatures().externalServiceDiscovery()) {
1145            final IqPacket request = new IqPacket(IqPacket.TYPE.GET);
1146            request.setTo(id.account.getDomain());
1147            request.addChild("services", Namespace.EXTERNAL_SERVICE_DISCOVERY);
1148            xmppConnectionService.sendIqPacket(id.account, request, (account, response) -> {
1149                ImmutableList.Builder<PeerConnection.IceServer> listBuilder = new ImmutableList.Builder<>();
1150                if (response.getType() == IqPacket.TYPE.RESULT) {
1151                    final Element services = response.findChild("services", Namespace.EXTERNAL_SERVICE_DISCOVERY);
1152                    final List<Element> children = services == null ? Collections.emptyList() : services.getChildren();
1153                    for (final Element child : children) {
1154                        if ("service".equals(child.getName())) {
1155                            final String type = child.getAttribute("type");
1156                            final String host = child.getAttribute("host");
1157                            final String sport = child.getAttribute("port");
1158                            final Integer port = sport == null ? null : Ints.tryParse(sport);
1159                            final String transport = child.getAttribute("transport");
1160                            final String username = child.getAttribute("username");
1161                            final String password = child.getAttribute("password");
1162                            if (Strings.isNullOrEmpty(host) || port == null) {
1163                                continue;
1164                            }
1165                            if (port < 0 || port > 65535) {
1166                                continue;
1167                            }
1168                            if (Arrays.asList("stun", "stuns", "turn", "turns").contains(type) && Arrays.asList("udp", "tcp").contains(transport)) {
1169                                if (Arrays.asList("stuns", "turns").contains(type) && "udp".equals(transport)) {
1170                                    Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": skipping invalid combination of udp/tls in external services");
1171                                    continue;
1172                                }
1173                                final PeerConnection.IceServer.Builder iceServerBuilder = PeerConnection.IceServer
1174                                        .builder(String.format("%s:%s:%s?transport=%s", type, IP.wrapIPv6(host), port, transport));
1175                                iceServerBuilder.setTlsCertPolicy(PeerConnection.TlsCertPolicy.TLS_CERT_POLICY_INSECURE_NO_CHECK);
1176                                if (username != null && password != null) {
1177                                    iceServerBuilder.setUsername(username);
1178                                    iceServerBuilder.setPassword(password);
1179                                } else if (Arrays.asList("turn", "turns").contains(type)) {
1180                                    //The WebRTC spec requires throwing an InvalidAccessError when username (from libwebrtc source coder)
1181                                    //https://chromium.googlesource.com/external/webrtc/+/master/pc/ice_server_parsing.cc
1182                                    Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": skipping " + type + "/" + transport + " without username and password");
1183                                    continue;
1184                                }
1185                                final PeerConnection.IceServer iceServer = iceServerBuilder.createIceServer();
1186                                Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": discovered ICE Server: " + iceServer);
1187                                listBuilder.add(iceServer);
1188                            }
1189                        }
1190                    }
1191                }
1192                final List<PeerConnection.IceServer> iceServers = listBuilder.build();
1193                if (iceServers.size() == 0) {
1194                    Log.w(Config.LOGTAG, id.account.getJid().asBareJid() + ": no ICE server found " + response);
1195                }
1196                onIceServersDiscovered.onIceServersDiscovered(iceServers);
1197            });
1198        } else {
1199            Log.w(Config.LOGTAG, id.account.getJid().asBareJid() + ": has no external service discovery");
1200            onIceServersDiscovered.onIceServersDiscovered(Collections.emptyList());
1201        }
1202    }
1203
1204    private void finish() {
1205        if (isTerminated()) {
1206            this.cancelRingingTimeout();
1207            this.webRTCWrapper.verifyClosed();
1208            this.jingleConnectionManager.setTerminalSessionState(id, getEndUserState(), getMedia());
1209            this.jingleConnectionManager.finishConnectionOrThrow(this);
1210        } else {
1211            throw new IllegalStateException(String.format("Unable to call finish from %s", this.state));
1212        }
1213    }
1214
1215    private void writeLogMessage(final State state) {
1216        final long started = this.rtpConnectionStarted;
1217        long duration = started <= 0 ? 0 : SystemClock.elapsedRealtime() - started;
1218        if (state == State.TERMINATED_SUCCESS || (state == State.TERMINATED_CONNECTIVITY_ERROR && duration > 0)) {
1219            writeLogMessageSuccess(duration);
1220        } else {
1221            writeLogMessageMissed();
1222        }
1223    }
1224
1225    private void writeLogMessageSuccess(final long duration) {
1226        this.message.setBody(new RtpSessionStatus(true, duration).toString());
1227        this.writeMessage();
1228    }
1229
1230    private void writeLogMessageMissed() {
1231        this.message.setBody(new RtpSessionStatus(false, 0).toString());
1232        this.writeMessage();
1233    }
1234
1235    private void writeMessage() {
1236        final Conversational conversational = message.getConversation();
1237        if (conversational instanceof Conversation) {
1238            ((Conversation) conversational).add(this.message);
1239            xmppConnectionService.createMessageAsync(message);
1240            xmppConnectionService.updateConversationUi();
1241        } else {
1242            throw new IllegalStateException("Somehow the conversation in a message was a stub");
1243        }
1244    }
1245
1246    public State getState() {
1247        return this.state;
1248    }
1249
1250    boolean isTerminated() {
1251        return TERMINATED.contains(this.state);
1252    }
1253
1254    public Optional<VideoTrack> getLocalVideoTrack() {
1255        return webRTCWrapper.getLocalVideoTrack();
1256    }
1257
1258    public Optional<VideoTrack> getRemoteVideoTrack() {
1259        return webRTCWrapper.getRemoteVideoTrack();
1260    }
1261
1262
1263    public EglBase.Context getEglBaseContext() {
1264        return webRTCWrapper.getEglBaseContext();
1265    }
1266
1267    void setProposedMedia(final Set<Media> media) {
1268        this.proposedMedia = media;
1269    }
1270
1271    public void fireStateUpdate() {
1272        final RtpEndUserState endUserState = getEndUserState();
1273        xmppConnectionService.notifyJingleRtpConnectionUpdate(id.account, id.with, id.sessionId, endUserState);
1274    }
1275
1276    private interface OnIceServersDiscovered {
1277        void onIceServersDiscovered(List<PeerConnection.IceServer> iceServers);
1278    }
1279
1280    private static class StateTransitionException extends Exception {
1281        private final State state;
1282
1283        private StateTransitionException(final State state) {
1284            this.state = state;
1285        }
1286    }
1287}