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.AudioSource;
9import org.webrtc.AudioTrack;
10import org.webrtc.DataChannel;
11import org.webrtc.IceCandidate;
12import org.webrtc.MediaConstraints;
13import org.webrtc.MediaStream;
14import org.webrtc.PeerConnection;
15import org.webrtc.PeerConnectionFactory;
16import org.webrtc.RtpReceiver;
17import org.webrtc.SdpObserver;
18
19import java.util.Collection;
20import java.util.Collections;
21import java.util.Map;
22
23import eu.siacs.conversations.Config;
24import eu.siacs.conversations.xml.Element;
25import eu.siacs.conversations.xml.Namespace;
26import eu.siacs.conversations.xmpp.jingle.stanzas.IceUdpTransportInfo;
27import eu.siacs.conversations.xmpp.jingle.stanzas.JinglePacket;
28import eu.siacs.conversations.xmpp.jingle.stanzas.RtpDescription;
29import eu.siacs.conversations.xmpp.stanzas.MessagePacket;
30import rocks.xmpp.addr.Jid;
31
32public class JingleRtpConnection extends AbstractJingleConnection {
33
34 private static final Map<State, Collection<State>> VALID_TRANSITIONS;
35
36 static {
37 final ImmutableMap.Builder<State, Collection<State>> transitionBuilder = new ImmutableMap.Builder<>();
38 transitionBuilder.put(State.NULL, ImmutableList.of(State.PROPOSED, State.SESSION_INITIALIZED));
39 transitionBuilder.put(State.PROPOSED, ImmutableList.of(State.ACCEPTED, State.PROCEED));
40 transitionBuilder.put(State.PROCEED, ImmutableList.of(State.SESSION_INITIALIZED));
41 VALID_TRANSITIONS = transitionBuilder.build();
42 }
43
44 private State state = State.NULL;
45 private RtpContentMap initialRtpContentMap;
46
47
48 public JingleRtpConnection(JingleConnectionManager jingleConnectionManager, Id id, Jid initiator) {
49 super(jingleConnectionManager, id, initiator);
50 }
51
52 @Override
53 void deliverPacket(final JinglePacket jinglePacket) {
54 Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": packet delivered to JingleRtpConnection");
55 switch (jinglePacket.getAction()) {
56 case SESSION_INITIATE:
57 receiveSessionInitiate(jinglePacket);
58 break;
59 default:
60 Log.d(Config.LOGTAG, String.format("%s: received unhandled jingle action %s", id.account.getJid().asBareJid(), jinglePacket.getAction()));
61 break;
62 }
63 }
64
65 private void receiveSessionInitiate(final JinglePacket jinglePacket) {
66 if (isInitiator()) {
67 Log.d(Config.LOGTAG, String.format("%s: received session-initiate even though we were initiating", id.account.getJid().asBareJid()));
68 //TODO respond with out-of-order
69 return;
70 }
71 final RtpContentMap contentMap;
72 try {
73 contentMap = RtpContentMap.of(jinglePacket);
74 } catch (IllegalArgumentException | NullPointerException e) {
75 Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": improperly formatted contents", e);
76 return;
77 }
78 Log.d(Config.LOGTAG, "processing session-init with " + contentMap.contents.size() + " contents");
79 final State oldState = this.state;
80 if (transition(State.SESSION_INITIALIZED)) {
81 if (oldState == State.PROCEED) {
82 processContents(contentMap);
83 sendSessionAccept();
84 } else {
85 //TODO start ringing
86 }
87 } else {
88 Log.d(Config.LOGTAG, String.format("%s: received session-initiate while in state %s", id.account.getJid().asBareJid(), state));
89 }
90 }
91
92 private void processContents(final RtpContentMap contentMap) {
93 for (Map.Entry<String, RtpContentMap.DescriptionTransport> content : contentMap.contents.entrySet()) {
94 final RtpContentMap.DescriptionTransport descriptionTransport = content.getValue();
95 final RtpDescription rtpDescription = descriptionTransport.description;
96 Log.d(Config.LOGTAG, "receive content with name " + content.getKey() + " and media=" + rtpDescription.getMedia());
97 for (RtpDescription.PayloadType payloadType : rtpDescription.getPayloadTypes()) {
98 Log.d(Config.LOGTAG, "payload type: " + payloadType.toString());
99 }
100 for (RtpDescription.RtpHeaderExtension extension : rtpDescription.getHeaderExtensions()) {
101 Log.d(Config.LOGTAG, "extension: " + extension.toString());
102 }
103 final IceUdpTransportInfo iceUdpTransportInfo = descriptionTransport.transport;
104 Log.d(Config.LOGTAG, "transport: " + descriptionTransport.transport);
105 Log.d(Config.LOGTAG, "fingerprint " + iceUdpTransportInfo.getFingerprint());
106 }
107 }
108
109 void deliveryMessage(final Jid from, final Element message) {
110 Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": delivered message to JingleRtpConnection " + message);
111 switch (message.getName()) {
112 case "propose":
113 receivePropose(from, message);
114 break;
115 case "proceed":
116 receiveProceed(from, message);
117 default:
118 break;
119 }
120 }
121
122 private void receivePropose(final Jid from, final Element propose) {
123 final boolean originatedFromMyself = from.asBareJid().equals(id.account.getJid().asBareJid());
124 if (originatedFromMyself) {
125 Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": saw proposal from mysql. ignoring");
126 } else if (transition(State.PROPOSED)) {
127 //TODO start ringing or something
128 pickUpCall();
129 } else {
130 Log.d(Config.LOGTAG, id.account.getJid() + ": ignoring session proposal because already in " + state);
131 }
132 }
133
134 private void receiveProceed(final Jid from, final Element proceed) {
135 if (from.equals(id.with)) {
136 if (isInitiator()) {
137 if (transition(State.PROCEED)) {
138 this.sendSessionInitiate();
139 } else {
140 Log.d(Config.LOGTAG, String.format("%s: ignoring proceed because already in %s", id.account.getJid().asBareJid(), this.state));
141 }
142 } else {
143 Log.d(Config.LOGTAG, String.format("%s: ignoring proceed because we were not initializing", id.account.getJid().asBareJid()));
144 }
145 } else {
146 Log.d(Config.LOGTAG, String.format("%s: ignoring proceed from %s. was expected from %s", id.account.getJid().asBareJid(), from, id.with));
147 }
148 }
149
150 private void sendSessionInitiate() {
151 setupWebRTC();
152 Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": prepare session-initiate");
153 }
154
155 private void sendSessionInitiate(RtpContentMap rtpContentMap) {
156 this.initialRtpContentMap = rtpContentMap;
157 final JinglePacket sessionInitiate = rtpContentMap.toJinglePacket(JinglePacket.Action.SESSION_INITIATE, id.sessionId);
158 Log.d(Config.LOGTAG, sessionInitiate.toString());
159 Log.d(Config.LOGTAG,"here is what we think the sdp looks like"+SessionDescription.of(rtpContentMap).toString());
160 send(sessionInitiate);
161 }
162
163 private void sendTransportInfo(final String contentName, IceUdpTransportInfo.Candidate candidate) {
164 final RtpContentMap transportInfo;
165 try {
166 transportInfo = this.initialRtpContentMap.transportInfo(contentName, candidate);
167 } catch (Exception e) {
168 Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": unable to prepare transport-info from candidate for content=" + contentName);
169 return;
170 }
171 final JinglePacket jinglePacket = transportInfo.toJinglePacket(JinglePacket.Action.TRANSPORT_INFO, id.sessionId);
172 Log.d(Config.LOGTAG, jinglePacket.toString());
173 send(jinglePacket);
174 }
175
176 private void send(final JinglePacket jinglePacket) {
177 jinglePacket.setTo(id.with);
178 //TODO track errors
179 xmppConnectionService.sendIqPacket(id.account, jinglePacket, null);
180 }
181
182
183 private void sendSessionAccept() {
184 Log.d(Config.LOGTAG, "sending session-accept");
185 }
186
187 public void pickUpCall() {
188 switch (this.state) {
189 case PROPOSED:
190 pickupCallFromProposed();
191 break;
192 case SESSION_INITIALIZED:
193 pickupCallFromSessionInitialized();
194 break;
195 default:
196 throw new IllegalStateException("Can not pick up call from " + this.state);
197 }
198 }
199
200 private void setupWebRTC() {
201 PeerConnectionFactory.initialize(
202 PeerConnectionFactory.InitializationOptions.builder(xmppConnectionService).createInitializationOptions()
203 );
204 final PeerConnectionFactory.Options options = new PeerConnectionFactory.Options();
205 PeerConnectionFactory peerConnectionFactory = PeerConnectionFactory.builder().createPeerConnectionFactory();
206
207 final AudioSource audioSource = peerConnectionFactory.createAudioSource(new MediaConstraints());
208
209 final AudioTrack audioTrack = peerConnectionFactory.createAudioTrack("my-audio-track", audioSource);
210 final MediaStream stream = peerConnectionFactory.createLocalMediaStream("my-media-stream");
211 stream.addTrack(audioTrack);
212
213
214 PeerConnection peerConnection = peerConnectionFactory.createPeerConnection(Collections.emptyList(), new PeerConnection.Observer() {
215 @Override
216 public void onSignalingChange(PeerConnection.SignalingState signalingState) {
217
218 }
219
220 @Override
221 public void onIceConnectionChange(PeerConnection.IceConnectionState iceConnectionState) {
222
223 }
224
225 @Override
226 public void onIceConnectionReceivingChange(boolean b) {
227
228 }
229
230 @Override
231 public void onIceGatheringChange(PeerConnection.IceGatheringState iceGatheringState) {
232 Log.d(Config.LOGTAG, "onIceGatheringChange() " + iceGatheringState);
233 }
234
235 @Override
236 public void onIceCandidate(IceCandidate iceCandidate) {
237 IceUdpTransportInfo.Candidate candidate = IceUdpTransportInfo.Candidate.fromSdpAttribute(iceCandidate.sdp);
238 Log.d(Config.LOGTAG, "onIceCandidate: " + iceCandidate.sdp);
239 sendTransportInfo(iceCandidate.sdpMid, candidate);
240
241 }
242
243 @Override
244 public void onIceCandidatesRemoved(IceCandidate[] iceCandidates) {
245
246 }
247
248 @Override
249 public void onAddStream(MediaStream mediaStream) {
250
251 }
252
253 @Override
254 public void onRemoveStream(MediaStream mediaStream) {
255
256 }
257
258 @Override
259 public void onDataChannel(DataChannel dataChannel) {
260
261 }
262
263 @Override
264 public void onRenegotiationNeeded() {
265
266 }
267
268 @Override
269 public void onAddTrack(RtpReceiver rtpReceiver, MediaStream[] mediaStreams) {
270
271 }
272 });
273
274 peerConnection.addStream(stream);
275
276 peerConnection.createOffer(new SdpObserver() {
277
278 @Override
279 public void onCreateSuccess(org.webrtc.SessionDescription description) {
280 final SessionDescription sessionDescription = SessionDescription.parse(description.description);
281 Log.d(Config.LOGTAG, "description: " + description.description);
282 final RtpContentMap rtpContentMap = RtpContentMap.of(sessionDescription);
283 sendSessionInitiate(rtpContentMap);
284 peerConnection.setLocalDescription(new SdpObserver() {
285 @Override
286 public void onCreateSuccess(org.webrtc.SessionDescription sessionDescription) {
287
288 }
289
290 @Override
291 public void onSetSuccess() {
292 Log.d(Config.LOGTAG, "onSetSuccess()");
293 }
294
295 @Override
296 public void onCreateFailure(String s) {
297
298 }
299
300 @Override
301 public void onSetFailure(String s) {
302
303 }
304 }, description);
305 }
306
307 @Override
308 public void onSetSuccess() {
309
310 }
311
312 @Override
313 public void onCreateFailure(String s) {
314
315 }
316
317 @Override
318 public void onSetFailure(String s) {
319
320 }
321 }, new MediaConstraints());
322 }
323
324 private void pickupCallFromProposed() {
325 transitionOrThrow(State.PROCEED);
326 final MessagePacket messagePacket = new MessagePacket();
327 messagePacket.setTo(id.with);
328 //Note that Movim needs 'accept', correct is 'proceed' https://github.com/movim/movim/issues/916
329 messagePacket.addChild("proceed", Namespace.JINGLE_MESSAGE).setAttribute("id", id.sessionId);
330 Log.d(Config.LOGTAG, messagePacket.toString());
331 xmppConnectionService.sendMessagePacket(id.account, messagePacket);
332 }
333
334 private void pickupCallFromSessionInitialized() {
335
336 }
337
338 private synchronized boolean transition(final State target) {
339 final Collection<State> validTransitions = VALID_TRANSITIONS.get(this.state);
340 if (validTransitions != null && validTransitions.contains(target)) {
341 this.state = target;
342 Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": transitioned into " + target);
343 return true;
344 } else {
345 return false;
346 }
347 }
348
349 public void transitionOrThrow(final State target) {
350 if (!transition(target)) {
351 throw new IllegalStateException(String.format("Unable to transition from %s to %s", this.state, target));
352 }
353 }
354}