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