JingleRtpConnection.java

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