JingleRtpConnection.java

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