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