SessionDescription.java

  1package eu.siacs.conversations.xmpp.jingle;
  2
  3import android.util.Log;
  4import android.util.Pair;
  5
  6import com.google.common.base.CharMatcher;
  7import com.google.common.base.Joiner;
  8import com.google.common.base.Strings;
  9import com.google.common.collect.ArrayListMultimap;
 10import com.google.common.collect.ImmutableList;
 11
 12import java.util.List;
 13import java.util.Locale;
 14import java.util.Map;
 15
 16import eu.siacs.conversations.Config;
 17import eu.siacs.conversations.xml.Namespace;
 18import eu.siacs.conversations.xmpp.jingle.stanzas.Group;
 19import eu.siacs.conversations.xmpp.jingle.stanzas.IceUdpTransportInfo;
 20import eu.siacs.conversations.xmpp.jingle.stanzas.RtpDescription;
 21
 22public class SessionDescription {
 23
 24    public final static String LINE_DIVIDER = "\r\n";
 25    private final static String HARDCODED_MEDIA_PROTOCOL = "UDP/TLS/RTP/SAVPF"; //probably only true for DTLS-SRTP aka when we have a fingerprint
 26    private final static int HARDCODED_MEDIA_PORT = 9;
 27    private final static String HARDCODED_ICE_OPTIONS = "trickle renomination";
 28    private final static String HARDCODED_CONNECTION = "IN IP4 0.0.0.0";
 29
 30    public final int version;
 31    public final String name;
 32    public final String connectionData;
 33    public final ArrayListMultimap<String, String> attributes;
 34    public final List<Media> media;
 35
 36
 37    public SessionDescription(int version, String name, String connectionData, ArrayListMultimap<String, String> attributes, List<Media> media) {
 38        this.version = version;
 39        this.name = name;
 40        this.connectionData = connectionData;
 41        this.attributes = attributes;
 42        this.media = media;
 43    }
 44
 45    private static void appendAttributes(StringBuilder s, ArrayListMultimap<String, String> attributes) {
 46        for (Map.Entry<String, String> attribute : attributes.entries()) {
 47            final String key = attribute.getKey();
 48            final String value = attribute.getValue();
 49            s.append("a=").append(key);
 50            if (!Strings.isNullOrEmpty(value)) {
 51                s.append(':').append(value);
 52            }
 53            s.append(LINE_DIVIDER);
 54        }
 55    }
 56
 57    public static SessionDescription parse(final String input) {
 58        final SessionDescriptionBuilder sessionDescriptionBuilder = new SessionDescriptionBuilder();
 59        MediaBuilder currentMediaBuilder = null;
 60        ArrayListMultimap<String, String> attributeMap = ArrayListMultimap.create();
 61        ImmutableList.Builder<Media> mediaBuilder = new ImmutableList.Builder<>();
 62        for (final String line : input.split(LINE_DIVIDER)) {
 63            final String[] pair = line.trim().split("=", 2);
 64            if (pair.length < 2 || pair[0].length() != 1) {
 65                Log.d(Config.LOGTAG, "skipping sdp parsing on line " + line);
 66                continue;
 67            }
 68            final char key = pair[0].charAt(0);
 69            final String value = pair[1];
 70            switch (key) {
 71                case 'v':
 72                    sessionDescriptionBuilder.setVersion(ignorantIntParser(value));
 73                    break;
 74                case 'c':
 75                    if (currentMediaBuilder != null) {
 76                        currentMediaBuilder.setConnectionData(value);
 77                    } else {
 78                        sessionDescriptionBuilder.setConnectionData(value);
 79                    }
 80                    break;
 81                case 's':
 82                    sessionDescriptionBuilder.setName(value);
 83                    break;
 84                case 'a':
 85                    final Pair<String, String> attribute = parseAttribute(value);
 86                    attributeMap.put(attribute.first, attribute.second);
 87                    break;
 88                case 'm':
 89                    if (currentMediaBuilder == null) {
 90                        sessionDescriptionBuilder.setAttributes(attributeMap);
 91                        ;
 92                    } else {
 93                        currentMediaBuilder.setAttributes(attributeMap);
 94                        mediaBuilder.add(currentMediaBuilder.createMedia());
 95                    }
 96                    attributeMap = ArrayListMultimap.create();
 97                    currentMediaBuilder = new MediaBuilder();
 98                    final String[] parts = value.split(" ");
 99                    if (parts.length >= 3) {
100                        currentMediaBuilder.setMedia(parts[0]);
101                        currentMediaBuilder.setPort(ignorantIntParser(parts[1]));
102                        currentMediaBuilder.setProtocol(parts[2]);
103                        ImmutableList.Builder<Integer> formats = new ImmutableList.Builder<>();
104                        for (int i = 3; i < parts.length; ++i) {
105                            formats.add(ignorantIntParser(parts[i]));
106                        }
107                        currentMediaBuilder.setFormats(formats.build());
108                    } else {
109                        Log.d(Config.LOGTAG, "skipping media line " + line);
110                    }
111                    break;
112            }
113
114        }
115        if (currentMediaBuilder != null) {
116            currentMediaBuilder.setAttributes(attributeMap);
117            mediaBuilder.add(currentMediaBuilder.createMedia());
118        } else {
119            sessionDescriptionBuilder.setAttributes(attributeMap);
120        }
121        sessionDescriptionBuilder.setMedia(mediaBuilder.build());
122        return sessionDescriptionBuilder.createSessionDescription();
123    }
124
125    public static SessionDescription of(final RtpContentMap contentMap) {
126        final SessionDescriptionBuilder sessionDescriptionBuilder = new SessionDescriptionBuilder();
127        final ArrayListMultimap<String, String> attributeMap = ArrayListMultimap.create();
128        final ImmutableList.Builder<Media> mediaListBuilder = new ImmutableList.Builder<>();
129        final Group group = contentMap.group;
130        if (group != null) {
131            final String semantics = group.getSemantics();
132            checkNoWhitespace(semantics, "group semantics value must not contain any whitespace");
133            attributeMap.put("group", group.getSemantics() + " " + Joiner.on(' ').join(group.getIdentificationTags()));
134        }
135
136        attributeMap.put("msid-semantic", " WMS my-media-stream");
137
138        for (final Map.Entry<String, RtpContentMap.DescriptionTransport> entry : contentMap.contents.entrySet()) {
139            final String name = entry.getKey();
140            RtpContentMap.DescriptionTransport descriptionTransport = entry.getValue();
141            RtpDescription description = descriptionTransport.description;
142            IceUdpTransportInfo transport = descriptionTransport.transport;
143            final ArrayListMultimap<String, String> mediaAttributes = ArrayListMultimap.create();
144            final String ufrag = transport.getAttribute("ufrag");
145            final String pwd = transport.getAttribute("pwd");
146            if (Strings.isNullOrEmpty(ufrag)) {
147                throw new IllegalArgumentException("Transport element is missing required ufrag attribute");
148            }
149            checkNoWhitespace(ufrag, "ufrag value must not contain any whitespaces");
150            mediaAttributes.put("ice-ufrag", ufrag);
151            if (Strings.isNullOrEmpty(pwd)) {
152                throw new IllegalArgumentException("Transport element is missing required pwd attribute");
153            }
154            checkNoWhitespace(pwd, "pwd value must not contain any whitespaces");
155            mediaAttributes.put("ice-pwd", pwd);
156            mediaAttributes.put("ice-options", HARDCODED_ICE_OPTIONS);
157            final IceUdpTransportInfo.Fingerprint fingerprint = transport.getFingerprint();
158            if (fingerprint != null) {
159                mediaAttributes.put("fingerprint", fingerprint.getHash() + " " + fingerprint.getContent());
160                mediaAttributes.put("setup", fingerprint.getSetup());
161            }
162            final ImmutableList.Builder<Integer> formatBuilder = new ImmutableList.Builder<>();
163            for (RtpDescription.PayloadType payloadType : description.getPayloadTypes()) {
164                final String id = payloadType.getId();
165                if (Strings.isNullOrEmpty(id)) {
166                    throw new IllegalArgumentException("Payload type is missing id");
167                }
168                if (!isInt(id)) {
169                    throw new IllegalArgumentException("Payload id is not numeric");
170                }
171                formatBuilder.add(payloadType.getIntId());
172                mediaAttributes.put("rtpmap", payloadType.toSdpAttribute());
173                final List<RtpDescription.Parameter> parameters = payloadType.getParameters();
174                if (parameters.size() == 1) {
175                    mediaAttributes.put("fmtp", RtpDescription.Parameter.toSdpString(id, parameters.get(0)));
176                } else if (parameters.size() > 0) {
177                    mediaAttributes.put("fmtp", RtpDescription.Parameter.toSdpString(id, parameters));
178                }
179                for (RtpDescription.FeedbackNegotiation feedbackNegotiation : payloadType.getFeedbackNegotiations()) {
180                    final String type = feedbackNegotiation.getType();
181                    final String subtype = feedbackNegotiation.getSubType();
182                    if (Strings.isNullOrEmpty(type)) {
183                        throw new IllegalArgumentException("a feedback for payload-type " + id + " negotiation is missing type");
184                    }
185                    checkNoWhitespace(type, "feedback negotiation type must not contain whitespace");
186                    mediaAttributes.put("rtcp-fb", id + " " + type + (Strings.isNullOrEmpty(subtype) ? "" : " " + subtype));
187                }
188                for (RtpDescription.FeedbackNegotiationTrrInt feedbackNegotiationTrrInt : payloadType.feedbackNegotiationTrrInts()) {
189                    mediaAttributes.put("rtcp-fb", id + " trr-int " + feedbackNegotiationTrrInt.getValue());
190                }
191            }
192
193            for (RtpDescription.FeedbackNegotiation feedbackNegotiation : description.getFeedbackNegotiations()) {
194                final String type = feedbackNegotiation.getType();
195                final String subtype = feedbackNegotiation.getSubType();
196                if (Strings.isNullOrEmpty(type)) {
197                    throw new IllegalArgumentException("a feedback negotiation is missing type");
198                }
199                checkNoWhitespace(type, "feedback negotiation type must not contain whitespace");
200                mediaAttributes.put("rtcp-fb", "* " + type + (Strings.isNullOrEmpty(subtype) ? "" : " " + subtype));
201            }
202            for (RtpDescription.FeedbackNegotiationTrrInt feedbackNegotiationTrrInt : description.feedbackNegotiationTrrInts()) {
203                mediaAttributes.put("rtcp-fb", "* trr-int " + feedbackNegotiationTrrInt.getValue());
204            }
205            for (RtpDescription.RtpHeaderExtension extension : description.getHeaderExtensions()) {
206                final String id = extension.getId();
207                final String uri = extension.getUri();
208                if (Strings.isNullOrEmpty(id)) {
209                    throw new IllegalArgumentException("A header extension is missing id");
210                }
211                checkNoWhitespace(id, "header extension id must not contain whitespace");
212                if (Strings.isNullOrEmpty(uri)) {
213                    throw new IllegalArgumentException("A header extension is missing uri");
214                }
215                checkNoWhitespace(uri, "feedback negotiation uri must not contain whitespace");
216                mediaAttributes.put("extmap", id + " " + uri);
217            }
218            for (RtpDescription.SourceGroup sourceGroup : description.getSourceGroups()) {
219                final String semantics = sourceGroup.getSemantics();
220                final List<String> groups = sourceGroup.getSsrcs();
221                if (Strings.isNullOrEmpty(semantics)) {
222                    throw new IllegalArgumentException("A SSRC group is missing semantics attribute");
223                }
224                checkNoWhitespace(semantics, "source group semantics must not contain whitespace");
225                if (groups.size() == 0) {
226                    throw new IllegalArgumentException("A SSRC group is missing SSRC ids");
227                }
228                mediaAttributes.put("ssrc-group", String.format("%s %s", semantics, Joiner.on(' ').join(groups)));
229            }
230            for (RtpDescription.Source source : description.getSources()) {
231                for (RtpDescription.Source.Parameter parameter : source.getParameters()) {
232                    final String id = source.getSsrcId();
233                    final String parameterName = parameter.getParameterName();
234                    final String parameterValue = parameter.getParameterValue();
235                    if (Strings.isNullOrEmpty(id)) {
236                        throw new IllegalArgumentException("A source specific media attribute is missing the id");
237                    }
238                    checkNoWhitespace(id, "A source specific media attributes must not contain whitespaces");
239                    if (Strings.isNullOrEmpty(parameterName)) {
240                        throw new IllegalArgumentException("A source specific media attribute is missing its name");
241                    }
242                    if (Strings.isNullOrEmpty(parameterValue)) {
243                        throw new IllegalArgumentException("A source specific media attribute is missing its value");
244                    }
245                    mediaAttributes.put("ssrc", id + " " + parameterName + ":" + parameterValue);
246                }
247            }
248
249            mediaAttributes.put("mid", name);
250
251            //random additional attributes
252            mediaAttributes.put("rtcp", "9 IN IP4 0.0.0.0");
253            mediaAttributes.put("sendrecv", "");
254
255            if (description.hasChild("rtcp-mux", Namespace.JINGLE_APPS_RTP)) {
256                mediaAttributes.put("rtcp-mux", "");
257            }
258
259            final MediaBuilder mediaBuilder = new MediaBuilder();
260            mediaBuilder.setMedia(description.getMedia().toString().toLowerCase(Locale.ROOT));
261            mediaBuilder.setConnectionData(HARDCODED_CONNECTION);
262            mediaBuilder.setPort(HARDCODED_MEDIA_PORT);
263            mediaBuilder.setProtocol(HARDCODED_MEDIA_PROTOCOL);
264            mediaBuilder.setAttributes(mediaAttributes);
265            mediaBuilder.setFormats(formatBuilder.build());
266            mediaListBuilder.add(mediaBuilder.createMedia());
267
268        }
269        sessionDescriptionBuilder.setVersion(0);
270        sessionDescriptionBuilder.setName("-");
271        sessionDescriptionBuilder.setMedia(mediaListBuilder.build());
272        sessionDescriptionBuilder.setAttributes(attributeMap);
273
274        return sessionDescriptionBuilder.createSessionDescription();
275    }
276
277    public static String checkNoWhitespace(final String input, final String message) {
278        if (CharMatcher.whitespace().matchesAnyOf(input)) {
279            throw new IllegalArgumentException(message);
280        }
281        return input;
282    }
283
284    public static int ignorantIntParser(final String input) {
285        try {
286            return Integer.parseInt(input);
287        } catch (NumberFormatException e) {
288            return 0;
289        }
290    }
291
292    public static boolean isInt(final String input) {
293        if (input == null) {
294            return false;
295        }
296        try {
297            Integer.parseInt(input);
298            return true;
299        } catch (NumberFormatException e) {
300            return false;
301        }
302    }
303
304    public static Pair<String, String> parseAttribute(final String input) {
305        final String[] pair = input.split(":", 2);
306        if (pair.length == 2) {
307            return new Pair<>(pair[0], pair[1]);
308        } else {
309            return new Pair<>(pair[0], "");
310        }
311    }
312
313    @Override
314    public String toString() {
315        final StringBuilder s = new StringBuilder()
316                .append("v=").append(version).append(LINE_DIVIDER)
317                //TODO randomize or static
318                .append("o=- 8770656990916039506 2 IN IP4 127.0.0.1").append(LINE_DIVIDER) //what ever that means
319                .append("s=").append(name).append(LINE_DIVIDER)
320                .append("t=0 0").append(LINE_DIVIDER);
321        appendAttributes(s, attributes);
322        for (Media media : this.media) {
323            s.append("m=").append(media.media).append(' ').append(media.port).append(' ').append(media.protocol).append(' ').append(Joiner.on(' ').join(media.formats)).append(LINE_DIVIDER);
324            s.append("c=").append(media.connectionData).append(LINE_DIVIDER);
325            appendAttributes(s, media.attributes);
326        }
327        return s.toString();
328    }
329
330    public static class Media {
331        public final String media;
332        public final int port;
333        public final String protocol;
334        public final List<Integer> formats;
335        public final String connectionData;
336        public final ArrayListMultimap<String, String> attributes;
337
338        public Media(String media, int port, String protocol, List<Integer> formats, String connectionData, ArrayListMultimap<String, String> attributes) {
339            this.media = media;
340            this.port = port;
341            this.protocol = protocol;
342            this.formats = formats;
343            this.connectionData = connectionData;
344            this.attributes = attributes;
345        }
346    }
347
348}