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