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";
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 } else {
92 currentMediaBuilder.setAttributes(attributeMap);
93 mediaBuilder.add(currentMediaBuilder.createMedia());
94 }
95 attributeMap = ArrayListMultimap.create();
96 currentMediaBuilder = new MediaBuilder();
97 final String[] parts = value.split(" ");
98 if (parts.length >= 3) {
99 currentMediaBuilder.setMedia(parts[0]);
100 currentMediaBuilder.setPort(ignorantIntParser(parts[1]));
101 currentMediaBuilder.setProtocol(parts[2]);
102 ImmutableList.Builder<Integer> formats = new ImmutableList.Builder<>();
103 for (int i = 3; i < parts.length; ++i) {
104 formats.add(ignorantIntParser(parts[i]));
105 }
106 currentMediaBuilder.setFormats(formats.build());
107 } else {
108 Log.d(Config.LOGTAG, "skipping media line " + line);
109 }
110 break;
111 }
112
113 }
114 if (currentMediaBuilder != null) {
115 currentMediaBuilder.setAttributes(attributeMap);
116 mediaBuilder.add(currentMediaBuilder.createMedia());
117 } else {
118 sessionDescriptionBuilder.setAttributes(attributeMap);
119 }
120 sessionDescriptionBuilder.setMedia(mediaBuilder.build());
121 return sessionDescriptionBuilder.createSessionDescription();
122 }
123
124 public static SessionDescription of(final RtpContentMap contentMap) {
125 final SessionDescriptionBuilder sessionDescriptionBuilder = new SessionDescriptionBuilder();
126 final ArrayListMultimap<String, String> attributeMap = ArrayListMultimap.create();
127 final ImmutableList.Builder<Media> mediaListBuilder = new ImmutableList.Builder<>();
128 final Group group = contentMap.group;
129 if (group != null) {
130 final String semantics = group.getSemantics();
131 checkNoWhitespace(semantics, "group semantics value must not contain any whitespace");
132 attributeMap.put("group", group.getSemantics() + " " + Joiner.on(' ').join(group.getIdentificationTags()));
133 }
134
135 attributeMap.put("msid-semantic", " WMS my-media-stream");
136
137 for (final Map.Entry<String, RtpContentMap.DescriptionTransport> entry : contentMap.contents.entrySet()) {
138 final String name = entry.getKey();
139 RtpContentMap.DescriptionTransport descriptionTransport = entry.getValue();
140 RtpDescription description = descriptionTransport.description;
141 IceUdpTransportInfo transport = descriptionTransport.transport;
142 final ArrayListMultimap<String, String> mediaAttributes = ArrayListMultimap.create();
143 final String ufrag = transport.getAttribute("ufrag");
144 final String pwd = transport.getAttribute("pwd");
145 if (Strings.isNullOrEmpty(ufrag)) {
146 throw new IllegalArgumentException("Transport element is missing required ufrag attribute");
147 }
148 checkNoWhitespace(ufrag, "ufrag value must not contain any whitespaces");
149 mediaAttributes.put("ice-ufrag", ufrag);
150 if (Strings.isNullOrEmpty(pwd)) {
151 throw new IllegalArgumentException("Transport element is missing required pwd attribute");
152 }
153 checkNoWhitespace(pwd, "pwd value must not contain any whitespaces");
154 mediaAttributes.put("ice-pwd", pwd);
155 mediaAttributes.put("ice-options", HARDCODED_ICE_OPTIONS);
156 final IceUdpTransportInfo.Fingerprint fingerprint = transport.getFingerprint();
157 if (fingerprint != null) {
158 mediaAttributes.put("fingerprint", fingerprint.getHash() + " " + fingerprint.getContent());
159 mediaAttributes.put("setup", fingerprint.getSetup());
160 }
161 final ImmutableList.Builder<Integer> formatBuilder = new ImmutableList.Builder<>();
162 for (RtpDescription.PayloadType payloadType : description.getPayloadTypes()) {
163 final String id = payloadType.getId();
164 if (Strings.isNullOrEmpty(id)) {
165 throw new IllegalArgumentException("Payload type is missing id");
166 }
167 if (!isInt(id)) {
168 throw new IllegalArgumentException("Payload id is not numeric");
169 }
170 formatBuilder.add(payloadType.getIntId());
171 mediaAttributes.put("rtpmap", payloadType.toSdpAttribute());
172 final List<RtpDescription.Parameter> parameters = payloadType.getParameters();
173 if (parameters.size() == 1) {
174 mediaAttributes.put("fmtp", RtpDescription.Parameter.toSdpString(id, parameters.get(0)));
175 } else if (parameters.size() > 0) {
176 mediaAttributes.put("fmtp", RtpDescription.Parameter.toSdpString(id, parameters));
177 }
178 for (RtpDescription.FeedbackNegotiation feedbackNegotiation : payloadType.getFeedbackNegotiations()) {
179 final String type = feedbackNegotiation.getType();
180 final String subtype = feedbackNegotiation.getSubType();
181 if (Strings.isNullOrEmpty(type)) {
182 throw new IllegalArgumentException("a feedback for payload-type " + id + " negotiation is missing type");
183 }
184 checkNoWhitespace(type, "feedback negotiation type must not contain whitespace");
185 mediaAttributes.put("rtcp-fb", id + " " + type + (Strings.isNullOrEmpty(subtype) ? "" : " " + subtype));
186 }
187 for (RtpDescription.FeedbackNegotiationTrrInt feedbackNegotiationTrrInt : payloadType.feedbackNegotiationTrrInts()) {
188 mediaAttributes.put("rtcp-fb", id + " trr-int " + feedbackNegotiationTrrInt.getValue());
189 }
190 }
191
192 for (RtpDescription.FeedbackNegotiation feedbackNegotiation : description.getFeedbackNegotiations()) {
193 final String type = feedbackNegotiation.getType();
194 final String subtype = feedbackNegotiation.getSubType();
195 if (Strings.isNullOrEmpty(type)) {
196 throw new IllegalArgumentException("a feedback negotiation is missing type");
197 }
198 checkNoWhitespace(type, "feedback negotiation type must not contain whitespace");
199 mediaAttributes.put("rtcp-fb", "* " + type + (Strings.isNullOrEmpty(subtype) ? "" : " " + subtype));
200 }
201 for (final RtpDescription.FeedbackNegotiationTrrInt feedbackNegotiationTrrInt : description.feedbackNegotiationTrrInts()) {
202 mediaAttributes.put("rtcp-fb", "* trr-int " + feedbackNegotiationTrrInt.getValue());
203 }
204 for (final RtpDescription.RtpHeaderExtension extension : description.getHeaderExtensions()) {
205 final String id = extension.getId();
206 final String uri = extension.getUri();
207 if (Strings.isNullOrEmpty(id)) {
208 throw new IllegalArgumentException("A header extension is missing id");
209 }
210 checkNoWhitespace(id, "header extension id must not contain whitespace");
211 if (Strings.isNullOrEmpty(uri)) {
212 throw new IllegalArgumentException("A header extension is missing uri");
213 }
214 checkNoWhitespace(uri, "feedback negotiation uri must not contain whitespace");
215 mediaAttributes.put("extmap", id + " " + uri);
216 }
217
218 if (description.hasChild("extmap-allow-mixed", Namespace.JINGLE_RTP_HEADER_EXTENSIONS)) {
219 mediaAttributes.put("extmap-allow-mixed", "");
220 }
221
222 for (final RtpDescription.SourceGroup sourceGroup : description.getSourceGroups()) {
223 final String semantics = sourceGroup.getSemantics();
224 final List<String> groups = sourceGroup.getSsrcs();
225 if (Strings.isNullOrEmpty(semantics)) {
226 throw new IllegalArgumentException("A SSRC group is missing semantics attribute");
227 }
228 checkNoWhitespace(semantics, "source group semantics must not contain whitespace");
229 if (groups.size() == 0) {
230 throw new IllegalArgumentException("A SSRC group is missing SSRC ids");
231 }
232 mediaAttributes.put("ssrc-group", String.format("%s %s", semantics, Joiner.on(' ').join(groups)));
233 }
234 for (final RtpDescription.Source source : description.getSources()) {
235 for (final RtpDescription.Source.Parameter parameter : source.getParameters()) {
236 final String id = source.getSsrcId();
237 final String parameterName = parameter.getParameterName();
238 final String parameterValue = parameter.getParameterValue();
239 if (Strings.isNullOrEmpty(id)) {
240 throw new IllegalArgumentException("A source specific media attribute is missing the id");
241 }
242 checkNoWhitespace(id, "A source specific media attributes must not contain whitespaces");
243 if (Strings.isNullOrEmpty(parameterName)) {
244 throw new IllegalArgumentException("A source specific media attribute is missing its name");
245 }
246 if (Strings.isNullOrEmpty(parameterValue)) {
247 throw new IllegalArgumentException("A source specific media attribute is missing its value");
248 }
249 mediaAttributes.put("ssrc", id + " " + parameterName + ":" + parameterValue);
250 }
251 }
252
253 mediaAttributes.put("mid", name);
254
255 //random additional attributes
256 mediaAttributes.put("rtcp", "9 IN IP4 0.0.0.0");
257 mediaAttributes.put("sendrecv", "");
258
259 if (description.hasChild("rtcp-mux", Namespace.JINGLE_APPS_RTP)) {
260 mediaAttributes.put("rtcp-mux", "");
261 }
262
263 final MediaBuilder mediaBuilder = new MediaBuilder();
264 mediaBuilder.setMedia(description.getMedia().toString().toLowerCase(Locale.ROOT));
265 mediaBuilder.setConnectionData(HARDCODED_CONNECTION);
266 mediaBuilder.setPort(HARDCODED_MEDIA_PORT);
267 mediaBuilder.setProtocol(HARDCODED_MEDIA_PROTOCOL);
268 mediaBuilder.setAttributes(mediaAttributes);
269 mediaBuilder.setFormats(formatBuilder.build());
270 mediaListBuilder.add(mediaBuilder.createMedia());
271
272 }
273 sessionDescriptionBuilder.setVersion(0);
274 sessionDescriptionBuilder.setName("-");
275 sessionDescriptionBuilder.setMedia(mediaListBuilder.build());
276 sessionDescriptionBuilder.setAttributes(attributeMap);
277
278 return sessionDescriptionBuilder.createSessionDescription();
279 }
280
281 public static String checkNoWhitespace(final String input, final String message) {
282 if (CharMatcher.whitespace().matchesAnyOf(input)) {
283 throw new IllegalArgumentException(message);
284 }
285 return input;
286 }
287
288 public static int ignorantIntParser(final String input) {
289 try {
290 return Integer.parseInt(input);
291 } catch (NumberFormatException e) {
292 return 0;
293 }
294 }
295
296 public static boolean isInt(final String input) {
297 if (input == null) {
298 return false;
299 }
300 try {
301 Integer.parseInt(input);
302 return true;
303 } catch (NumberFormatException e) {
304 return false;
305 }
306 }
307
308 public static Pair<String, String> parseAttribute(final String input) {
309 final String[] pair = input.split(":", 2);
310 if (pair.length == 2) {
311 return new Pair<>(pair[0], pair[1]);
312 } else {
313 return new Pair<>(pair[0], "");
314 }
315 }
316
317 @Override
318 public String toString() {
319 final StringBuilder s = new StringBuilder()
320 .append("v=").append(version).append(LINE_DIVIDER)
321 //TODO randomize or static
322 .append("o=- 8770656990916039506 2 IN IP4 127.0.0.1").append(LINE_DIVIDER) //what ever that means
323 .append("s=").append(name).append(LINE_DIVIDER)
324 .append("t=0 0").append(LINE_DIVIDER);
325 appendAttributes(s, attributes);
326 for (Media media : this.media) {
327 s.append("m=").append(media.media).append(' ').append(media.port).append(' ').append(media.protocol).append(' ').append(Joiner.on(' ').join(media.formats)).append(LINE_DIVIDER);
328 s.append("c=").append(media.connectionData).append(LINE_DIVIDER);
329 appendAttributes(s, media.attributes);
330 }
331 return s.toString();
332 }
333
334 public static class Media {
335 public final String media;
336 public final int port;
337 public final String protocol;
338 public final List<Integer> formats;
339 public final String connectionData;
340 public final ArrayListMultimap<String, String> attributes;
341
342 public Media(String media, int port, String protocol, List<Integer> formats, String connectionData, ArrayListMultimap<String, String> attributes) {
343 this.media = media;
344 this.port = port;
345 this.protocol = protocol;
346 this.formats = formats;
347 this.connectionData = connectionData;
348 this.attributes = attributes;
349 }
350 }
351
352}