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