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 Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": improperly formatted contents", Throwables.getRootCause(e));
287 respondOk(jinglePacket);
288 sendSessionTerminate(Reason.of(e), e.getMessage());
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).get();
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", Throwables.getRootCause(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 if (isTerminated()) {
817 return Collections.emptySet(); //we might fail before we ever got a chance to set media
818 } else {
819 return Preconditions.checkNotNull(this.proposedMedia, "RTP connection has not been initialized properly");
820 }
821 }
822
823
824 public synchronized void acceptCall() {
825 switch (this.state) {
826 case PROPOSED:
827 cancelRingingTimeout();
828 acceptCallFromProposed();
829 break;
830 case SESSION_INITIALIZED:
831 cancelRingingTimeout();
832 acceptCallFromSessionInitialized();
833 break;
834 case ACCEPTED:
835 Log.w(Config.LOGTAG, id.account.getJid().asBareJid() + ": the call has already been accepted with another client. UI was just lagging behind");
836 break;
837 case PROCEED:
838 case SESSION_ACCEPTED:
839 Log.w(Config.LOGTAG, id.account.getJid().asBareJid() + ": the call has already been accepted. user probably double tapped the UI");
840 break;
841 default:
842 throw new IllegalStateException("Can not accept call from " + this.state);
843 }
844 }
845
846 public synchronized void rejectCall() {
847 switch (this.state) {
848 case PROPOSED:
849 rejectCallFromProposed();
850 break;
851 case SESSION_INITIALIZED:
852 rejectCallFromSessionInitiate();
853 break;
854 default:
855 throw new IllegalStateException("Can not reject call from " + this.state);
856 }
857 }
858
859 public synchronized void endCall() {
860 if (isTerminated()) {
861 Log.w(Config.LOGTAG, id.account.getJid().asBareJid() + ": received endCall() when session has already been terminated. nothing to do");
862 return;
863 }
864 if (isInState(State.PROPOSED) && !isInitiator()) {
865 rejectCallFromProposed();
866 return;
867 }
868 if (isInState(State.PROCEED)) {
869 Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": ending call while in state PROCEED just means ending the connection");
870 this.jingleConnectionManager.endSession(id, State.TERMINATED_SUCCESS);
871 this.webRTCWrapper.close();
872 this.finish();
873 transitionOrThrow(State.TERMINATED_SUCCESS); //arguably this wasn't success; but not a real failure either
874 return;
875 }
876 if (isInitiator() && isInState(State.SESSION_INITIALIZED, State.SESSION_INITIALIZED_PRE_APPROVED)) {
877 this.webRTCWrapper.close();
878 sendSessionTerminate(Reason.CANCEL);
879 return;
880 }
881 if (isInState(State.SESSION_INITIALIZED)) {
882 rejectCallFromSessionInitiate();
883 return;
884 }
885 if (isInState(State.SESSION_INITIALIZED_PRE_APPROVED, State.SESSION_ACCEPTED)) {
886 this.webRTCWrapper.close();
887 sendSessionTerminate(Reason.SUCCESS);
888 return;
889 }
890 if (isInState(State.TERMINATED_APPLICATION_FAILURE, State.TERMINATED_CONNECTIVITY_ERROR, State.TERMINATED_DECLINED_OR_BUSY)) {
891 Log.d(Config.LOGTAG, "ignoring request to end call because already in state " + this.state);
892 return;
893 }
894 throw new IllegalStateException("called 'endCall' while in state " + this.state + ". isInitiator=" + isInitiator());
895 }
896
897 private void setupWebRTC(final Set<Media> media, final List<PeerConnection.IceServer> iceServers) throws WebRTCWrapper.InitializationException {
898 this.jingleConnectionManager.ensureConnectionIsRegistered(this);
899 final AppRTCAudioManager.SpeakerPhonePreference speakerPhonePreference;
900 if (media.contains(Media.VIDEO)) {
901 speakerPhonePreference = AppRTCAudioManager.SpeakerPhonePreference.SPEAKER;
902 } else {
903 speakerPhonePreference = AppRTCAudioManager.SpeakerPhonePreference.EARPIECE;
904 }
905 this.webRTCWrapper.setup(this.xmppConnectionService, speakerPhonePreference);
906 this.webRTCWrapper.initializePeerConnection(media, iceServers);
907 }
908
909 private void acceptCallFromProposed() {
910 transitionOrThrow(State.PROCEED);
911 xmppConnectionService.getNotificationService().cancelIncomingCallNotification();
912 this.sendJingleMessage("accept", id.account.getJid().asBareJid());
913 this.sendJingleMessage("proceed");
914 }
915
916 private void rejectCallFromProposed() {
917 transitionOrThrow(State.REJECTED);
918 writeLogMessageMissed();
919 xmppConnectionService.getNotificationService().cancelIncomingCallNotification();
920 this.sendJingleMessage("reject");
921 finish();
922 }
923
924 private void rejectCallFromSessionInitiate() {
925 webRTCWrapper.close();
926 sendSessionTerminate(Reason.DECLINE);
927 xmppConnectionService.getNotificationService().cancelIncomingCallNotification();
928 }
929
930 private void sendJingleMessage(final String action) {
931 sendJingleMessage(action, id.with);
932 }
933
934 private void sendJingleMessage(final String action, final Jid to) {
935 final MessagePacket messagePacket = new MessagePacket();
936 if ("proceed".equals(action)) {
937 messagePacket.setId(JINGLE_MESSAGE_PROCEED_ID_PREFIX + id.sessionId);
938 }
939 messagePacket.setType(MessagePacket.TYPE_CHAT); //we want to carbon copy those
940 messagePacket.setTo(to);
941 messagePacket.addChild(action, Namespace.JINGLE_MESSAGE).setAttribute("id", id.sessionId);
942 messagePacket.addChild("store", "urn:xmpp:hints");
943 xmppConnectionService.sendMessagePacket(id.account, messagePacket);
944 }
945
946 private void acceptCallFromSessionInitialized() {
947 xmppConnectionService.getNotificationService().cancelIncomingCallNotification();
948 sendSessionAccept();
949 }
950
951 private synchronized boolean isInState(State... state) {
952 return Arrays.asList(state).contains(this.state);
953 }
954
955 private boolean transition(final State target) {
956 return transition(target, null);
957 }
958
959 private synchronized boolean transition(final State target, final Runnable runnable) {
960 final Collection<State> validTransitions = VALID_TRANSITIONS.get(this.state);
961 if (validTransitions != null && validTransitions.contains(target)) {
962 this.state = target;
963 if (runnable != null) {
964 runnable.run();
965 }
966 Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": transitioned into " + target);
967 updateEndUserState();
968 updateOngoingCallNotification();
969 return true;
970 } else {
971 return false;
972 }
973 }
974
975 void transitionOrThrow(final State target) {
976 if (!transition(target)) {
977 throw new IllegalStateException(String.format("Unable to transition from %s to %s", this.state, target));
978 }
979 }
980
981 @Override
982 public void onIceCandidate(final IceCandidate iceCandidate) {
983 final IceUdpTransportInfo.Candidate candidate = IceUdpTransportInfo.Candidate.fromSdpAttribute(iceCandidate.sdp);
984 Log.d(Config.LOGTAG, "sending candidate: " + iceCandidate.toString());
985 sendTransportInfo(iceCandidate.sdpMid, candidate);
986 }
987
988 @Override
989 public void onConnectionChange(final PeerConnection.PeerConnectionState newState) {
990 Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": PeerConnectionState changed to " + newState);
991 if (newState == PeerConnection.PeerConnectionState.CONNECTED && this.rtpConnectionStarted == 0) {
992 this.rtpConnectionStarted = SystemClock.elapsedRealtime();
993 }
994 //TODO 'DISCONNECTED' might be an opportunity to renew the offer and send a transport-replace
995 //TODO exact syntax is yet to be determined but transport-replace sounds like the most reasonable
996 //as there is no content-replace
997 if (Arrays.asList(PeerConnection.PeerConnectionState.FAILED, PeerConnection.PeerConnectionState.DISCONNECTED).contains(newState)) {
998 if (isTerminated()) {
999 Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": not sending session-terminate after connectivity error because session is already in state " + this.state);
1000 return;
1001 }
1002 new Thread(this::closeWebRTCSessionAfterFailedConnection).start();
1003 } else {
1004 updateEndUserState();
1005 }
1006 }
1007
1008 private void closeWebRTCSessionAfterFailedConnection() {
1009 this.webRTCWrapper.close();
1010 synchronized (this) {
1011 if (isTerminated()) {
1012 Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": no need to send session-terminate after failed connection. Other party already did");
1013 return;
1014 }
1015 sendSessionTerminate(Reason.CONNECTIVITY_ERROR);
1016 }
1017 }
1018
1019 public AppRTCAudioManager getAudioManager() {
1020 return webRTCWrapper.getAudioManager();
1021 }
1022
1023 public boolean isMicrophoneEnabled() {
1024 return webRTCWrapper.isMicrophoneEnabled();
1025 }
1026
1027 public void setMicrophoneEnabled(final boolean enabled) {
1028 webRTCWrapper.setMicrophoneEnabled(enabled);
1029 }
1030
1031 public boolean isVideoEnabled() {
1032 return webRTCWrapper.isVideoEnabled();
1033 }
1034
1035 public void setVideoEnabled(final boolean enabled) {
1036 webRTCWrapper.setVideoEnabled(enabled);
1037 }
1038
1039 @Override
1040 public void onAudioDeviceChanged(AppRTCAudioManager.AudioDevice selectedAudioDevice, Set<AppRTCAudioManager.AudioDevice> availableAudioDevices) {
1041 xmppConnectionService.notifyJingleRtpConnectionUpdate(selectedAudioDevice, availableAudioDevices);
1042 }
1043
1044 private void updateEndUserState() {
1045 final RtpEndUserState endUserState = getEndUserState();
1046 jingleConnectionManager.toneManager.transition(isInitiator(), endUserState, getMedia());
1047 xmppConnectionService.notifyJingleRtpConnectionUpdate(id.account, id.with, id.sessionId, endUserState);
1048 }
1049
1050 private void updateOngoingCallNotification() {
1051 if (STATES_SHOWING_ONGOING_CALL.contains(this.state)) {
1052 xmppConnectionService.setOngoingCall(id, getMedia());
1053 } else {
1054 xmppConnectionService.removeOngoingCall();
1055 }
1056 }
1057
1058 private void discoverIceServers(final OnIceServersDiscovered onIceServersDiscovered) {
1059 if (id.account.getXmppConnection().getFeatures().externalServiceDiscovery()) {
1060 final IqPacket request = new IqPacket(IqPacket.TYPE.GET);
1061 request.setTo(Jid.of(id.account.getJid().getDomain()));
1062 request.addChild("services", Namespace.EXTERNAL_SERVICE_DISCOVERY);
1063 xmppConnectionService.sendIqPacket(id.account, request, (account, response) -> {
1064 ImmutableList.Builder<PeerConnection.IceServer> listBuilder = new ImmutableList.Builder<>();
1065 if (response.getType() == IqPacket.TYPE.RESULT) {
1066 final Element services = response.findChild("services", Namespace.EXTERNAL_SERVICE_DISCOVERY);
1067 final List<Element> children = services == null ? Collections.emptyList() : services.getChildren();
1068 for (final Element child : children) {
1069 if ("service".equals(child.getName())) {
1070 final String type = child.getAttribute("type");
1071 final String host = child.getAttribute("host");
1072 final String sport = child.getAttribute("port");
1073 final Integer port = sport == null ? null : Ints.tryParse(sport);
1074 final String transport = child.getAttribute("transport");
1075 final String username = child.getAttribute("username");
1076 final String password = child.getAttribute("password");
1077 if (Strings.isNullOrEmpty(host) || port == null) {
1078 continue;
1079 }
1080 if (port < 0 || port > 65535) {
1081 continue;
1082 }
1083 if (Arrays.asList("stun", "stuns", "turn", "turns").contains(type) && Arrays.asList("udp", "tcp").contains(transport)) {
1084 if (Arrays.asList("stuns", "turns").contains(type) && "udp".equals(transport)) {
1085 Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": skipping invalid combination of udp/tls in external services");
1086 continue;
1087 }
1088 //TODO wrap ipv6 addresses
1089 PeerConnection.IceServer.Builder iceServerBuilder = PeerConnection.IceServer.builder(String.format("%s:%s:%s?transport=%s", type, host, port, transport));
1090 if (username != null && password != null) {
1091 iceServerBuilder.setUsername(username);
1092 iceServerBuilder.setPassword(password);
1093 } else if (Arrays.asList("turn", "turns").contains(type)) {
1094 //The WebRTC spec requires throwing an InvalidAccessError when username (from libwebrtc source coder)
1095 //https://chromium.googlesource.com/external/webrtc/+/master/pc/ice_server_parsing.cc
1096 Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": skipping " + type + "/" + transport + " without username and password");
1097 continue;
1098 }
1099 final PeerConnection.IceServer iceServer = iceServerBuilder.createIceServer();
1100 Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": discovered ICE Server: " + iceServer);
1101 listBuilder.add(iceServer);
1102 }
1103 }
1104 }
1105 }
1106 List<PeerConnection.IceServer> iceServers = listBuilder.build();
1107 if (iceServers.size() == 0) {
1108 Log.w(Config.LOGTAG, id.account.getJid().asBareJid() + ": no ICE server found " + response);
1109 }
1110 onIceServersDiscovered.onIceServersDiscovered(iceServers);
1111 });
1112 } else {
1113 Log.w(Config.LOGTAG, id.account.getJid().asBareJid() + ": has no external service discovery");
1114 onIceServersDiscovered.onIceServersDiscovered(Collections.emptyList());
1115 }
1116 }
1117
1118 private void finish() {
1119 this.cancelRingingTimeout();
1120 this.webRTCWrapper.verifyClosed();
1121 this.jingleConnectionManager.finishConnection(this);
1122 }
1123
1124 private void writeLogMessage(final State state) {
1125 final long started = this.rtpConnectionStarted;
1126 long duration = started <= 0 ? 0 : SystemClock.elapsedRealtime() - started;
1127 if (state == State.TERMINATED_SUCCESS || (state == State.TERMINATED_CONNECTIVITY_ERROR && duration > 0)) {
1128 writeLogMessageSuccess(duration);
1129 } else {
1130 writeLogMessageMissed();
1131 }
1132 }
1133
1134 private void writeLogMessageSuccess(final long duration) {
1135 this.message.setBody(new RtpSessionStatus(true, duration).toString());
1136 this.writeMessage();
1137 }
1138
1139 private void writeLogMessageMissed() {
1140 this.message.setBody(new RtpSessionStatus(false, 0).toString());
1141 this.writeMessage();
1142 }
1143
1144 private void writeMessage() {
1145 final Conversational conversational = message.getConversation();
1146 if (conversational instanceof Conversation) {
1147 ((Conversation) conversational).add(this.message);
1148 xmppConnectionService.databaseBackend.createMessage(message);
1149 xmppConnectionService.updateConversationUi();
1150 } else {
1151 throw new IllegalStateException("Somehow the conversation in a message was a stub");
1152 }
1153 }
1154
1155 public State getState() {
1156 return this.state;
1157 }
1158
1159 public boolean isTerminated() {
1160 return TERMINATED.contains(this.state);
1161 }
1162
1163 public Optional<VideoTrack> getLocalVideoTrack() {
1164 return webRTCWrapper.getLocalVideoTrack();
1165 }
1166
1167 public Optional<VideoTrack> getRemoteVideoTrack() {
1168 return webRTCWrapper.getRemoteVideoTrack();
1169 }
1170
1171
1172 public EglBase.Context getEglBaseContext() {
1173 return webRTCWrapper.getEglBaseContext();
1174 }
1175
1176 void setProposedMedia(final Set<Media> media) {
1177 this.proposedMedia = media;
1178 }
1179
1180 private interface OnIceServersDiscovered {
1181 void onIceServersDiscovered(List<PeerConnection.IceServer> iceServers);
1182 }
1183}