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
 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        send(sessionInitiate);
160    }
161
162    private void sendTransportInfo(final String contentName, IceUdpTransportInfo.Candidate candidate) {
163        final RtpContentMap transportInfo;
164        try {
165            transportInfo = this.initialRtpContentMap.transportInfo(contentName, candidate);
166        } catch (Exception e) {
167            Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": unable to prepare transport-info from candidate for content=" + contentName);
168            return;
169        }
170        final JinglePacket jinglePacket = transportInfo.toJinglePacket(JinglePacket.Action.TRANSPORT_INFO, id.sessionId);
171        Log.d(Config.LOGTAG, jinglePacket.toString());
172        send(jinglePacket);
173    }
174
175    private void send(final JinglePacket jinglePacket) {
176        jinglePacket.setTo(id.with);
177        //TODO track errors
178        xmppConnectionService.sendIqPacket(id.account, jinglePacket, null);
179    }
180
181
182    private void sendSessionAccept() {
183        Log.d(Config.LOGTAG, "sending session-accept");
184    }
185
186    public void pickUpCall() {
187        switch (this.state) {
188            case PROPOSED:
189                pickupCallFromProposed();
190                break;
191            case SESSION_INITIALIZED:
192                pickupCallFromSessionInitialized();
193                break;
194            default:
195                throw new IllegalStateException("Can not pick up call from " + this.state);
196        }
197    }
198
199    private void setupWebRTC() {
200        PeerConnectionFactory.initialize(
201                PeerConnectionFactory.InitializationOptions.builder(xmppConnectionService).createInitializationOptions()
202        );
203        final PeerConnectionFactory.Options options = new PeerConnectionFactory.Options();
204        PeerConnectionFactory peerConnectionFactory = PeerConnectionFactory.builder().createPeerConnectionFactory();
205
206        final AudioSource audioSource = peerConnectionFactory.createAudioSource(new MediaConstraints());
207
208        final AudioTrack audioTrack = peerConnectionFactory.createAudioTrack("my-audio-track", audioSource);
209        final MediaStream stream = peerConnectionFactory.createLocalMediaStream("my-media-stream");
210        stream.addTrack(audioTrack);
211
212
213        PeerConnection peerConnection = peerConnectionFactory.createPeerConnection(Collections.emptyList(), new PeerConnection.Observer() {
214            @Override
215            public void onSignalingChange(PeerConnection.SignalingState signalingState) {
216
217            }
218
219            @Override
220            public void onIceConnectionChange(PeerConnection.IceConnectionState iceConnectionState) {
221
222            }
223
224            @Override
225            public void onIceConnectionReceivingChange(boolean b) {
226
227            }
228
229            @Override
230            public void onIceGatheringChange(PeerConnection.IceGatheringState iceGatheringState) {
231                Log.d(Config.LOGTAG, "onIceGatheringChange() " + iceGatheringState);
232            }
233
234            @Override
235            public void onIceCandidate(IceCandidate iceCandidate) {
236                IceUdpTransportInfo.Candidate candidate = IceUdpTransportInfo.Candidate.fromSdpAttribute(iceCandidate.sdp);
237                Log.d(Config.LOGTAG, "onIceCandidate: " + iceCandidate.sdp);
238                Log.d(Config.LOGTAG, "xml: " + candidate.toString());
239                Log.d(Config.LOGTAG, "mid: " + iceCandidate.sdpMid);
240                sendTransportInfo(iceCandidate.sdpMid, candidate);
241
242            }
243
244            @Override
245            public void onIceCandidatesRemoved(IceCandidate[] iceCandidates) {
246
247            }
248
249            @Override
250            public void onAddStream(MediaStream mediaStream) {
251
252            }
253
254            @Override
255            public void onRemoveStream(MediaStream mediaStream) {
256
257            }
258
259            @Override
260            public void onDataChannel(DataChannel dataChannel) {
261
262            }
263
264            @Override
265            public void onRenegotiationNeeded() {
266
267            }
268
269            @Override
270            public void onAddTrack(RtpReceiver rtpReceiver, MediaStream[] mediaStreams) {
271
272            }
273        });
274
275        peerConnection.addStream(stream);
276
277        peerConnection.createOffer(new SdpObserver() {
278
279            @Override
280            public void onCreateSuccess(org.webrtc.SessionDescription description) {
281                final SessionDescription sessionDescription = SessionDescription.parse(description.description);
282                Log.d(Config.LOGTAG, "description: " + description.description);
283                final RtpContentMap rtpContentMap = RtpContentMap.of(sessionDescription);
284                sendSessionInitiate(rtpContentMap);
285                peerConnection.setLocalDescription(new SdpObserver() {
286                    @Override
287                    public void onCreateSuccess(org.webrtc.SessionDescription sessionDescription) {
288
289                    }
290
291                    @Override
292                    public void onSetSuccess() {
293                        Log.d(Config.LOGTAG, "onSetSuccess()");
294                    }
295
296                    @Override
297                    public void onCreateFailure(String s) {
298
299                    }
300
301                    @Override
302                    public void onSetFailure(String s) {
303
304                    }
305                }, description);
306            }
307
308            @Override
309            public void onSetSuccess() {
310
311            }
312
313            @Override
314            public void onCreateFailure(String s) {
315
316            }
317
318            @Override
319            public void onSetFailure(String s) {
320
321            }
322        }, new MediaConstraints());
323    }
324
325    private void pickupCallFromProposed() {
326        transitionOrThrow(State.PROCEED);
327        final MessagePacket messagePacket = new MessagePacket();
328        messagePacket.setTo(id.with);
329        //Note that Movim needs 'accept', correct is 'proceed' https://github.com/movim/movim/issues/916
330        messagePacket.addChild("proceed", Namespace.JINGLE_MESSAGE).setAttribute("id", id.sessionId);
331        Log.d(Config.LOGTAG, messagePacket.toString());
332        xmppConnectionService.sendMessagePacket(id.account, messagePacket);
333    }
334
335    private void pickupCallFromSessionInitialized() {
336
337    }
338
339    private synchronized boolean transition(final State target) {
340        final Collection<State> validTransitions = VALID_TRANSITIONS.get(this.state);
341        if (validTransitions != null && validTransitions.contains(target)) {
342            this.state = target;
343            Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": transitioned into " + target);
344            return true;
345        } else {
346            return false;
347        }
348    }
349
350    public void transitionOrThrow(final State target) {
351        if (!transition(target)) {
352            throw new IllegalStateException(String.format("Unable to transition from %s to %s", this.state, target));
353        }
354    }
355}