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