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