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