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