1package eu.siacs.conversations.xmpp.jingle;
2
3import android.util.Log;
4
5import com.google.common.collect.ImmutableList;
6import com.google.common.collect.ImmutableMap;
7
8import org.webrtc.IceCandidate;
9
10import java.util.ArrayDeque;
11import java.util.Arrays;
12import java.util.Collection;
13import java.util.Collections;
14import java.util.List;
15import java.util.Map;
16
17import eu.siacs.conversations.Config;
18import eu.siacs.conversations.xml.Element;
19import eu.siacs.conversations.xml.Namespace;
20import eu.siacs.conversations.xmpp.jingle.stanzas.Group;
21import eu.siacs.conversations.xmpp.jingle.stanzas.IceUdpTransportInfo;
22import eu.siacs.conversations.xmpp.jingle.stanzas.JinglePacket;
23import eu.siacs.conversations.xmpp.stanzas.MessagePacket;
24import rocks.xmpp.addr.Jid;
25
26public class JingleRtpConnection extends AbstractJingleConnection implements WebRTCWrapper.EventCallback {
27
28 private static final Map<State, Collection<State>> VALID_TRANSITIONS;
29
30 static {
31 final ImmutableMap.Builder<State, Collection<State>> transitionBuilder = new ImmutableMap.Builder<>();
32 transitionBuilder.put(State.NULL, ImmutableList.of(State.PROPOSED, State.SESSION_INITIALIZED));
33 transitionBuilder.put(State.PROPOSED, ImmutableList.of(State.ACCEPTED, State.PROCEED));
34 transitionBuilder.put(State.PROCEED, ImmutableList.of(State.SESSION_INITIALIZED));
35 transitionBuilder.put(State.SESSION_INITIALIZED, ImmutableList.of(State.SESSION_ACCEPTED));
36 VALID_TRANSITIONS = transitionBuilder.build();
37 }
38
39 private final WebRTCWrapper webRTCWrapper = new WebRTCWrapper(this);
40 private final ArrayDeque<IceCandidate> pendingIceCandidates = new ArrayDeque<>();
41 private State state = State.NULL;
42 private RtpContentMap initiatorRtpContentMap;
43 private RtpContentMap responderRtpContentMap;
44
45
46 public JingleRtpConnection(JingleConnectionManager jingleConnectionManager, Id id, Jid initiator) {
47 super(jingleConnectionManager, id, initiator);
48 }
49
50 @Override
51 void deliverPacket(final JinglePacket jinglePacket) {
52 Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": packet delivered to JingleRtpConnection");
53 switch (jinglePacket.getAction()) {
54 case SESSION_INITIATE:
55 receiveSessionInitiate(jinglePacket);
56 break;
57 case TRANSPORT_INFO:
58 receiveTransportInfo(jinglePacket);
59 break;
60 default:
61 Log.d(Config.LOGTAG, String.format("%s: received unhandled jingle action %s", id.account.getJid().asBareJid(), jinglePacket.getAction()));
62 break;
63 }
64 }
65
66 private void receiveTransportInfo(final JinglePacket jinglePacket) {
67 if (isInState(State.SESSION_INITIALIZED, State.SESSION_ACCEPTED)) {
68 final RtpContentMap contentMap;
69 try {
70 contentMap = RtpContentMap.of(jinglePacket);
71 } catch (IllegalArgumentException | NullPointerException e) {
72 Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": improperly formatted contents", e);
73 return;
74 }
75 //TODO pick proper rtpContentMap
76 final Group originalGroup = this.initiatorRtpContentMap != null ? this.initiatorRtpContentMap.group : null;
77 final List<String> identificationTags = originalGroup == null ? Collections.emptyList() : originalGroup.getIdentificationTags();
78 if (identificationTags.size() == 0) {
79 Log.w(Config.LOGTAG, id.account.getJid().asBareJid() + ": no identification tags found in initial offer. we won't be able to calculate mLineIndices");
80 }
81 for (final Map.Entry<String, RtpContentMap.DescriptionTransport> content : contentMap.contents.entrySet()) {
82 final String ufrag = content.getValue().transport.getAttribute("ufrag");
83 for (final IceUdpTransportInfo.Candidate candidate : content.getValue().transport.getCandidates()) {
84 final String sdp = candidate.toSdpAttribute(ufrag);
85 final String sdpMid = content.getKey();
86 final int mLineIndex = identificationTags.indexOf(sdpMid);
87 final IceCandidate iceCandidate = new IceCandidate(sdpMid, mLineIndex, sdp);
88 Log.d(Config.LOGTAG, "received candidate: " + iceCandidate);
89 if (isInState(State.SESSION_ACCEPTED)) {
90 this.webRTCWrapper.addIceCandidate(iceCandidate);
91 } else {
92 this.pendingIceCandidates.push(iceCandidate);
93 }
94 }
95 }
96 } else {
97 Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": received transport info while in state=" + this.state);
98 }
99 }
100
101 private void receiveSessionInitiate(final JinglePacket jinglePacket) {
102 if (isInitiator()) {
103 Log.d(Config.LOGTAG, String.format("%s: received session-initiate even though we were initiating", id.account.getJid().asBareJid()));
104 //TODO respond with out-of-order
105 return;
106 }
107 final RtpContentMap contentMap;
108 try {
109 contentMap = RtpContentMap.of(jinglePacket);
110 contentMap.requireContentDescriptions();
111 } catch (IllegalArgumentException | IllegalStateException | NullPointerException e) {
112 Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": improperly formatted contents", e);
113 return;
114 }
115 Log.d(Config.LOGTAG, "processing session-init with " + contentMap.contents.size() + " contents");
116 final State oldState = this.state;
117 if (transition(State.SESSION_INITIALIZED)) {
118 this.initiatorRtpContentMap = contentMap;
119 if (oldState == State.PROCEED) {
120 Log.d(Config.LOGTAG, "automatically accepting");
121 sendSessionAccept();
122 } else {
123 Log.d(Config.LOGTAG, "start ringing");
124 //TODO start ringing
125 }
126 } else {
127 Log.d(Config.LOGTAG, String.format("%s: received session-initiate while in state %s", id.account.getJid().asBareJid(), state));
128 }
129 }
130
131 private void sendSessionAccept() {
132 final RtpContentMap rtpContentMap = this.initiatorRtpContentMap;
133 if (rtpContentMap == null) {
134 throw new IllegalStateException("intital RTP Content Map has not been set");
135 }
136 setupWebRTC();
137 final org.webrtc.SessionDescription offer = new org.webrtc.SessionDescription(
138 org.webrtc.SessionDescription.Type.OFFER,
139 SessionDescription.of(rtpContentMap).toString()
140 );
141 try {
142 this.webRTCWrapper.setRemoteDescription(offer).get();
143 org.webrtc.SessionDescription webRTCSessionDescription = this.webRTCWrapper.createAnswer().get();
144 this.webRTCWrapper.setLocalDescription(webRTCSessionDescription);
145 final SessionDescription sessionDescription = SessionDescription.parse(webRTCSessionDescription.description);
146 final RtpContentMap respondingRtpContentMap = RtpContentMap.of(sessionDescription);
147 sendSessionAccept(respondingRtpContentMap);
148 } catch (Exception e) {
149 Log.d(Config.LOGTAG, "unable to send session accept", e);
150
151 }
152 }
153
154 private void sendSessionAccept(final RtpContentMap rtpContentMap) {
155 this.responderRtpContentMap = rtpContentMap;
156 this.transitionOrThrow(State.SESSION_ACCEPTED);
157 final JinglePacket sessionAccept = rtpContentMap.toJinglePacket(JinglePacket.Action.SESSION_ACCEPT, id.sessionId);
158 Log.d(Config.LOGTAG, sessionAccept.toString());
159 send(sessionAccept);
160 }
161
162 void deliveryMessage(final Jid from, final Element message) {
163 Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": delivered message to JingleRtpConnection " + message);
164 switch (message.getName()) {
165 case "propose":
166 receivePropose(from, message);
167 break;
168 case "proceed":
169 receiveProceed(from, message);
170 default:
171 break;
172 }
173 }
174
175 private void receivePropose(final Jid from, final Element propose) {
176 final boolean originatedFromMyself = from.asBareJid().equals(id.account.getJid().asBareJid());
177 //TODO we can use initiator logic here
178 if (originatedFromMyself) {
179 Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": saw proposal from mysql. ignoring");
180 } else if (transition(State.PROPOSED)) {
181 //TODO start ringing or something
182 pickUpCall();
183 } else {
184 Log.d(Config.LOGTAG, id.account.getJid() + ": ignoring session proposal because already in " + state);
185 }
186 }
187
188 private void receiveProceed(final Jid from, final Element proceed) {
189 if (from.equals(id.with)) {
190 if (isInitiator()) {
191 if (transition(State.PROCEED)) {
192 this.sendSessionInitiate();
193 } else {
194 Log.d(Config.LOGTAG, String.format("%s: ignoring proceed because already in %s", id.account.getJid().asBareJid(), this.state));
195 }
196 } else {
197 Log.d(Config.LOGTAG, String.format("%s: ignoring proceed because we were not initializing", id.account.getJid().asBareJid()));
198 }
199 } else {
200 Log.d(Config.LOGTAG, String.format("%s: ignoring proceed from %s. was expected from %s", id.account.getJid().asBareJid(), from, id.with));
201 }
202 }
203
204 private void sendSessionInitiate() {
205 Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": prepare session-initiate");
206 setupWebRTC();
207 try {
208 org.webrtc.SessionDescription webRTCSessionDescription = this.webRTCWrapper.createOffer().get();
209 final SessionDescription sessionDescription = SessionDescription.parse(webRTCSessionDescription.description);
210 Log.d(Config.LOGTAG, "description: " + webRTCSessionDescription.description);
211 final RtpContentMap rtpContentMap = RtpContentMap.of(sessionDescription);
212 sendSessionInitiate(rtpContentMap);
213 this.webRTCWrapper.setLocalDescription(webRTCSessionDescription).get();
214 } catch (Exception e) {
215 Log.d(Config.LOGTAG, "unable to sendSessionInitiate", e);
216 }
217 }
218
219 private void sendSessionInitiate(RtpContentMap rtpContentMap) {
220 this.initiatorRtpContentMap = rtpContentMap;
221 this.transitionOrThrow(State.SESSION_INITIALIZED);
222 final JinglePacket sessionInitiate = rtpContentMap.toJinglePacket(JinglePacket.Action.SESSION_INITIATE, id.sessionId);
223 Log.d(Config.LOGTAG, sessionInitiate.toString());
224 send(sessionInitiate);
225 }
226
227 private void sendTransportInfo(final String contentName, IceUdpTransportInfo.Candidate candidate) {
228 final RtpContentMap transportInfo;
229 try {
230 //TODO when responding use responderRtpContentMap
231 transportInfo = this.initiatorRtpContentMap.transportInfo(contentName, candidate);
232 } catch (Exception e) {
233 Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": unable to prepare transport-info from candidate for content=" + contentName);
234 return;
235 }
236 final JinglePacket jinglePacket = transportInfo.toJinglePacket(JinglePacket.Action.TRANSPORT_INFO, id.sessionId);
237 Log.d(Config.LOGTAG, jinglePacket.toString());
238 send(jinglePacket);
239 }
240
241 private void send(final JinglePacket jinglePacket) {
242 jinglePacket.setTo(id.with);
243 //TODO track errors
244 xmppConnectionService.sendIqPacket(id.account, jinglePacket, null);
245 }
246
247
248 public void pickUpCall() {
249 switch (this.state) {
250 case PROPOSED:
251 pickupCallFromProposed();
252 break;
253 case SESSION_INITIALIZED:
254 pickupCallFromSessionInitialized();
255 break;
256 default:
257 throw new IllegalStateException("Can not pick up call from " + this.state);
258 }
259 }
260
261 private void setupWebRTC() {
262 this.webRTCWrapper.setup(this.xmppConnectionService);
263 this.webRTCWrapper.initializePeerConnection();
264 }
265
266 private void pickupCallFromProposed() {
267 transitionOrThrow(State.PROCEED);
268 final MessagePacket messagePacket = new MessagePacket();
269 messagePacket.setTo(id.with);
270 //Note that Movim needs 'accept', correct is 'proceed' https://github.com/movim/movim/issues/916
271 messagePacket.addChild("proceed", Namespace.JINGLE_MESSAGE).setAttribute("id", id.sessionId);
272 Log.d(Config.LOGTAG, messagePacket.toString());
273 xmppConnectionService.sendMessagePacket(id.account, messagePacket);
274 }
275
276 private void pickupCallFromSessionInitialized() {
277
278 }
279
280 private synchronized boolean isInState(State... state) {
281 return Arrays.asList(state).contains(this.state);
282 }
283
284 private synchronized boolean transition(final State target) {
285 final Collection<State> validTransitions = VALID_TRANSITIONS.get(this.state);
286 if (validTransitions != null && validTransitions.contains(target)) {
287 this.state = target;
288 Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": transitioned into " + target);
289 return true;
290 } else {
291 return false;
292 }
293 }
294
295 public void transitionOrThrow(final State target) {
296 if (!transition(target)) {
297 throw new IllegalStateException(String.format("Unable to transition from %s to %s", this.state, target));
298 }
299 }
300
301 @Override
302 public void onIceCandidate(final IceCandidate iceCandidate) {
303 final IceUdpTransportInfo.Candidate candidate = IceUdpTransportInfo.Candidate.fromSdpAttribute(iceCandidate.sdp);
304 Log.d(Config.LOGTAG, "onIceCandidate: " + iceCandidate.sdp + " mLineIndex=" + iceCandidate.sdpMLineIndex);
305 sendTransportInfo(iceCandidate.sdpMid, candidate);
306 }
307}