summaryrefslogtreecommitdiffstats
path: root/voip/java/android/net/sip/SdpSessionDescription.java
blob: f6ae83791e52e2001c933b70880492f57095557b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
/*
 * Copyright (C) 2010 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package android.net.sip;

import gov.nist.javax.sdp.SessionDescriptionImpl;
import gov.nist.javax.sdp.fields.AttributeField;
import gov.nist.javax.sdp.fields.ConnectionField;
import gov.nist.javax.sdp.fields.MediaField;
import gov.nist.javax.sdp.fields.OriginField;
import gov.nist.javax.sdp.fields.ProtoVersionField;
import gov.nist.javax.sdp.fields.SessionNameField;
import gov.nist.javax.sdp.fields.TimeField;
import gov.nist.javax.sdp.parser.SDPAnnounceParser;

import android.util.Log;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Vector;
import javax.sdp.Connection;
import javax.sdp.MediaDescription;
import javax.sdp.SdpException;

/**
 * A session description that follows SDP (Session Description Protocol).
 * Refer to <a href="http://tools.ietf.org/html/rfc4566">RFC 4566</a>.
 * @hide
 */
public class SdpSessionDescription extends SessionDescription {
    private static final String TAG = "SDP";
    private static final String AUDIO = "audio";
    private static final String RTPMAP = "rtpmap";
    private static final String PTIME = "ptime";
    private static final String SENDONLY = "sendonly";
    private static final String RECVONLY = "recvonly";
    private static final String INACTIVE = "inactive";

    private SessionDescriptionImpl mSessionDescription;

    /**
     * The audio codec information parsed from "rtpmap".
     */
    public static class AudioCodec {
        public final int payloadType;
        public final String name;
        public final int sampleRate;
        public final int sampleCount;

        public AudioCodec(int payloadType, String name, int sampleRate,
                int sampleCount) {
            this.payloadType = payloadType;
            this.name = name;
            this.sampleRate = sampleRate;
            this.sampleCount = sampleCount;
        }
    }

    /**
     * The builder class used to create an {@link SdpSessionDescription} object.
     */
    public static class Builder {
        private SdpSessionDescription mSdp = new SdpSessionDescription();
        private SessionDescriptionImpl mSessionDescription;

        public Builder(String sessionName) throws SdpException {
            mSessionDescription = new SessionDescriptionImpl();
            mSdp.mSessionDescription = mSessionDescription;
            try {
                ProtoVersionField proto = new ProtoVersionField();
                proto.setVersion(0);
                mSessionDescription.addField(proto);

                TimeField time = new TimeField();
                time.setZero();
                mSessionDescription.addField(time);

                SessionNameField session = new SessionNameField();
                session.setValue(sessionName);
                mSessionDescription.addField(session);
            } catch (Exception e) {
                throwSdpException(e);
            }
        }

        public Builder setConnectionInfo(String networkType, String addressType,
                String addr) throws SdpException {
            try {
                ConnectionField connection = new ConnectionField();
                connection.setNetworkType(networkType);
                connection.setAddressType(addressType);
                connection.setAddress(addr);
                mSessionDescription.addField(connection);
            } catch (Exception e) {
                throwSdpException(e);
            }
            return this;
        }

        public Builder setOrigin(SipProfile user, long sessionId,
                long sessionVersion, String networkType, String addressType,
                String address) throws SdpException {
            try {
                OriginField origin = new OriginField();
                origin.setUsername(user.getUserName());
                origin.setSessionId(sessionId);
                origin.setSessionVersion(sessionVersion);
                origin.setAddressType(addressType);
                origin.setNetworkType(networkType);
                origin.setAddress(address);
                mSessionDescription.addField(origin);
            } catch (Exception e) {
                throwSdpException(e);
            }
            return this;
        }

        public Builder addMedia(String media, int port, int numPorts,
                String transport, Integer... types) throws SdpException {
            MediaField field = new MediaField();
            Vector<Integer> typeVector = new Vector<Integer>();
            Collections.addAll(typeVector, types);
            try {
                field.setMediaType(media);
                field.setMediaPort(port);
                field.setPortCount(numPorts);
                field.setProtocol(transport);
                field.setMediaFormats(typeVector);
                mSessionDescription.addField(field);
            } catch (Exception e) {
                throwSdpException(e);
            }
           return this;
        }

        public Builder addMediaAttribute(String type, String name, String value)
                throws SdpException {
            try {
                MediaDescription md = mSdp.getMediaDescription(type);
                if (md == null) {
                    throw new SdpException("Should add media first!");
                }
                AttributeField attribute = new AttributeField();
                attribute.setName(name);
                attribute.setValueAllowNull(value);
                mSessionDescription.addField(attribute);
            } catch (Exception e) {
                throwSdpException(e);
            }
            return this;
        }

        public Builder addSessionAttribute(String name, String value)
                throws SdpException {
            try {
                AttributeField attribute = new AttributeField();
                attribute.setName(name);
                attribute.setValueAllowNull(value);
                mSessionDescription.addField(attribute);
            } catch (Exception e) {
                throwSdpException(e);
            }
            return this;
        }

        private void throwSdpException(Exception e) throws SdpException {
            if (e instanceof SdpException) {
                throw (SdpException) e;
            } else {
                throw new SdpException(e.toString(), e);
            }
        }

        public String build() {
            return mSdp.toString();
        }
    }

    private SdpSessionDescription() {
    }

    /**
     * Constructor.
     *
     * @param sdpString an SDP session description to parse
     */
    public SdpSessionDescription(String sdpString) throws SdpException {
        try {
            mSessionDescription = new SDPAnnounceParser(sdpString).parse();
        } catch (ParseException e) {
            throw new SdpException(e.toString(), e);
        }
        verify();
    }

    /**
     * Constructor.
     *
     * @param content a raw SDP session description to parse
     */
    public SdpSessionDescription(byte[] content) throws SdpException {
        this(new String(content));
    }

    private void verify() throws SdpException {
        // make sure the syntax is correct over the fields we're interested in
        Vector<MediaDescription> descriptions = (Vector<MediaDescription>)
                mSessionDescription.getMediaDescriptions(false);
        for (MediaDescription md : descriptions) {
            md.getMedia().getMediaPort();
            Connection connection = md.getConnection();
            if (connection != null) connection.getAddress();
            md.getMedia().getFormats();
        }
        Connection connection = mSessionDescription.getConnection();
        if (connection != null) connection.getAddress();
    }

    /**
     * Gets the connection address of the media.
     *
     * @param type the media type; e.g., "AUDIO"
     * @return the media connection address of the peer
     */
    public String getPeerMediaAddress(String type) {
        try {
            MediaDescription md = getMediaDescription(type);
            Connection connection = md.getConnection();
            if (connection == null) {
                connection = mSessionDescription.getConnection();
            }
            return ((connection == null) ? null : connection.getAddress());
        } catch (SdpException e) {
            // should not occur
            return null;
        }
    }

    /**
     * Gets the connection port number of the media.
     *
     * @param type the media type; e.g., "AUDIO"
     * @return the media connection port number of the peer
     */
    public int getPeerMediaPort(String type) {
        try {
            MediaDescription md = getMediaDescription(type);
            return md.getMedia().getMediaPort();
        } catch (SdpException e) {
            // should not occur
            return -1;
        }
    }

    private boolean containsAttribute(String type, String name) {
        if (name == null) return false;
        MediaDescription md = getMediaDescription(type);
        Vector<AttributeField> v = (Vector<AttributeField>)
                md.getAttributeFields();
        for (AttributeField field : v) {
            if (name.equals(field.getAttribute().getName())) return true;
        }
        return false;
    }

    /**
     * Checks if the media is "sendonly".
     *
     * @param type the media type; e.g., "AUDIO"
     * @return true if the media is "sendonly"
     */
    public boolean isSendOnly(String type) {
        boolean answer = containsAttribute(type, SENDONLY);
        Log.d(TAG, "   sendonly? " + answer);
        return answer;
    }

    /**
     * Checks if the media is "recvonly".
     *
     * @param type the media type; e.g., "AUDIO"
     * @return true if the media is "recvonly"
     */
    public boolean isReceiveOnly(String type) {
        boolean answer = containsAttribute(type, RECVONLY);
        Log.d(TAG, "   recvonly? " + answer);
        return answer;
    }

    /**
     * Checks if the media is in sending; i.e., not "recvonly" and not
     * "inactive".
     *
     * @param type the media type; e.g., "AUDIO"
     * @return true if the media is sending
     */
    public boolean isSending(String type) {
        boolean answer = !containsAttribute(type, RECVONLY)
                && !containsAttribute(type, INACTIVE);

        Log.d(TAG, "   sending? " + answer);
        return answer;
    }

    /**
     * Checks if the media is in receiving; i.e., not "sendonly" and not
     * "inactive".
     *
     * @param type the media type; e.g., "AUDIO"
     * @return true if the media is receiving
     */
    public boolean isReceiving(String type) {
        boolean answer = !containsAttribute(type, SENDONLY)
                && !containsAttribute(type, INACTIVE);
        Log.d(TAG, "   receiving? " + answer);
        return answer;
    }

    private AudioCodec parseAudioCodec(String rtpmap, int ptime) {
        String[] ss = rtpmap.split(" ");
        int payloadType = Integer.parseInt(ss[0]);

        ss = ss[1].split("/");
        String name = ss[0];
        int sampleRate = Integer.parseInt(ss[1]);
        int channelCount = 1;
        if (ss.length > 2) channelCount = Integer.parseInt(ss[2]);
        int sampleCount = sampleRate / (1000 / ptime) * channelCount;
        return new AudioCodec(payloadType, name, sampleRate, sampleCount);
    }

    /**
     * Gets the list of audio codecs in this session description.
     *
     * @return the list of audio codecs in this session description
     */
    public List<AudioCodec> getAudioCodecs() {
        MediaDescription md = getMediaDescription(AUDIO);
        if (md == null) return new ArrayList<AudioCodec>();

        // FIXME: what happens if ptime is missing
        int ptime = 20;
        try {
            String value = md.getAttribute(PTIME);
            if (value != null) ptime = Integer.parseInt(value);
        } catch (Throwable t) {
            Log.w(TAG, "getCodecs(): ignored: " + t);
        }

        List<AudioCodec> codecs = new ArrayList<AudioCodec>();
        Vector<AttributeField> v = (Vector<AttributeField>)
                md.getAttributeFields();
        for (AttributeField field : v) {
            try {
                if (RTPMAP.equals(field.getName())) {
                    AudioCodec codec = parseAudioCodec(field.getValue(), ptime);
                    if (codec != null) codecs.add(codec);
                }
            } catch (Throwable t) {
                Log.w(TAG, "getCodecs(): ignored: " + t);
            }
        }
        return codecs;
    }

    /**
     * Gets the media description of the specified type.
     *
     * @param type the media type; e.g., "AUDIO"
     * @return the media description of the specified type
     */
    public MediaDescription getMediaDescription(String type) {
        MediaDescription[] all = getMediaDescriptions();
        if ((all == null) || (all.length == 0)) return null;
        for (MediaDescription md : all) {
            String t = md.getMedia().getMedia();
            if (t.equalsIgnoreCase(type)) return md;
        }
        return null;
    }

    /**
     * Gets all the media descriptions in this session description.
     *
     * @return all the media descriptions in this session description
     */
    public MediaDescription[] getMediaDescriptions() {
        try {
            Vector<MediaDescription> descriptions = (Vector<MediaDescription>)
                    mSessionDescription.getMediaDescriptions(false);
            MediaDescription[] all = new MediaDescription[descriptions.size()];
            return descriptions.toArray(all);
        } catch (SdpException e) {
            Log.e(TAG, "getMediaDescriptions", e);
        }
        return null;
    }

    @Override
    public String getType() {
        return "sdp";
    }

    @Override
    public byte[] getContent() {
          return mSessionDescription.toString().getBytes();
    }

    @Override
    public String toString() {
        return mSessionDescription.toString();
    }
}