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