pjsip: Extend 'asymmetric_rtp_codec' option to include us changing.
[asterisk/asterisk.git] / res / res_pjsip_sdp_rtp.c
1 /*
2  * Asterisk -- An open source telephony toolkit.
3  *
4  * Copyright (C) 2013, Digium, Inc.
5  *
6  * Joshua Colp <jcolp@digium.com>
7  * Kevin Harwell <kharwell@digium.com>
8  *
9  * See http://www.asterisk.org for more information about
10  * the Asterisk project. Please do not directly contact
11  * any of the maintainers of this project for assistance;
12  * the project provides a web site, mailing lists and IRC
13  * channels for your use.
14  *
15  * This program is free software, distributed under the terms of
16  * the GNU General Public License Version 2. See the LICENSE file
17  * at the top of the source tree.
18  */
19
20 /*! \file
21  *
22  * \author Joshua Colp <jcolp@digium.com>
23  *
24  * \brief SIP SDP media stream handling
25  */
26
27 /*** MODULEINFO
28         <depend>pjproject</depend>
29         <depend>res_pjsip</depend>
30         <depend>res_pjsip_session</depend>
31         <support_level>core</support_level>
32  ***/
33
34 #include "asterisk.h"
35
36 #include <pjsip.h>
37 #include <pjsip_ua.h>
38 #include <pjmedia.h>
39 #include <pjlib.h>
40
41 #include "asterisk/utils.h"
42 #include "asterisk/module.h"
43 #include "asterisk/format.h"
44 #include "asterisk/format_cap.h"
45 #include "asterisk/rtp_engine.h"
46 #include "asterisk/netsock2.h"
47 #include "asterisk/channel.h"
48 #include "asterisk/causes.h"
49 #include "asterisk/sched.h"
50 #include "asterisk/acl.h"
51 #include "asterisk/sdp_srtp.h"
52 #include "asterisk/dsp.h"
53 #include "asterisk/linkedlists.h"       /* for AST_LIST_NEXT */
54
55 #include "asterisk/res_pjsip.h"
56 #include "asterisk/res_pjsip_session.h"
57
58 /*! \brief Scheduler for RTCP purposes */
59 static struct ast_sched_context *sched;
60
61 /*! \brief Address for RTP */
62 static struct ast_sockaddr address_rtp;
63
64 static const char STR_AUDIO[] = "audio";
65 static const int FD_AUDIO = 0;
66
67 static const char STR_VIDEO[] = "video";
68 static const int FD_VIDEO = 2;
69
70 /*! \brief Retrieves an ast_format_type based on the given stream_type */
71 static enum ast_media_type stream_to_media_type(const char *stream_type)
72 {
73         if (!strcasecmp(stream_type, STR_AUDIO)) {
74                 return AST_MEDIA_TYPE_AUDIO;
75         } else if (!strcasecmp(stream_type, STR_VIDEO)) {
76                 return AST_MEDIA_TYPE_VIDEO;
77         }
78
79         return 0;
80 }
81
82 /*! \brief Get the starting descriptor for a media type */
83 static int media_type_to_fdno(enum ast_media_type media_type)
84 {
85         switch (media_type) {
86         case AST_MEDIA_TYPE_AUDIO: return FD_AUDIO;
87         case AST_MEDIA_TYPE_VIDEO: return FD_VIDEO;
88         case AST_MEDIA_TYPE_TEXT:
89         case AST_MEDIA_TYPE_UNKNOWN:
90         case AST_MEDIA_TYPE_IMAGE:
91         case AST_MEDIA_TYPE_END: break;
92         }
93         return -1;
94 }
95
96 /*! \brief Remove all other cap types but the one given */
97 static void format_cap_only_type(struct ast_format_cap *caps, enum ast_media_type media_type)
98 {
99         int i = 0;
100         while (i <= AST_MEDIA_TYPE_TEXT) {
101                 if (i != media_type && i != AST_MEDIA_TYPE_UNKNOWN) {
102                         ast_format_cap_remove_by_type(caps, i);
103                 }
104                 i += 1;
105         }
106 }
107
108 static int send_keepalive(const void *data)
109 {
110         struct ast_sip_session_media *session_media = (struct ast_sip_session_media *) data;
111         struct ast_rtp_instance *rtp = session_media->rtp;
112         int keepalive;
113         time_t interval;
114         int send_keepalive;
115
116         if (!rtp) {
117                 return 0;
118         }
119
120         keepalive = ast_rtp_instance_get_keepalive(rtp);
121
122         if (!ast_sockaddr_isnull(&session_media->direct_media_addr)) {
123                 ast_debug(3, "Not sending RTP keepalive on RTP instance %p since direct media is in use\n", rtp);
124                 return keepalive * 1000;
125         }
126
127         interval = time(NULL) - ast_rtp_instance_get_last_tx(rtp);
128         send_keepalive = interval >= keepalive;
129
130         ast_debug(3, "It has been %d seconds since RTP was last sent on instance %p. %sending keepalive\n",
131                         (int) interval, rtp, send_keepalive ? "S" : "Not s");
132
133         if (send_keepalive) {
134                 ast_rtp_instance_sendcng(rtp, 0);
135                 return keepalive * 1000;
136         }
137
138         return (keepalive - interval) * 1000;
139 }
140
141 /*! \brief Check whether RTP is being received or not */
142 static int rtp_check_timeout(const void *data)
143 {
144         struct ast_sip_session_media *session_media = (struct ast_sip_session_media *)data;
145         struct ast_rtp_instance *rtp = session_media->rtp;
146         int elapsed;
147         struct ast_channel *chan;
148
149         if (!rtp) {
150                 return 0;
151         }
152
153         elapsed = time(NULL) - ast_rtp_instance_get_last_rx(rtp);
154         if (elapsed < ast_rtp_instance_get_timeout(rtp)) {
155                 return (ast_rtp_instance_get_timeout(rtp) - elapsed) * 1000;
156         }
157
158         chan = ast_channel_get_by_name(ast_rtp_instance_get_channel_id(rtp));
159         if (!chan) {
160                 return 0;
161         }
162
163         ast_log(LOG_NOTICE, "Disconnecting channel '%s' for lack of RTP activity in %d seconds\n",
164                 ast_channel_name(chan), elapsed);
165
166         ast_channel_lock(chan);
167         ast_channel_hangupcause_set(chan, AST_CAUSE_REQUESTED_CHAN_UNAVAIL);
168         ast_channel_unlock(chan);
169
170         ast_softhangup(chan, AST_SOFTHANGUP_DEV);
171         ast_channel_unref(chan);
172
173         return 0;
174 }
175
176 /*!
177  * \brief Enable RTCP on an RTP session.
178  */
179 static void enable_rtcp(struct ast_sip_session *session, struct ast_sip_session_media *session_media,
180         const struct pjmedia_sdp_media *remote_media)
181 {
182         enum ast_rtp_instance_rtcp rtcp_type;
183
184         if (session->endpoint->media.rtcp_mux && session_media->remote_rtcp_mux) {
185                 rtcp_type = AST_RTP_INSTANCE_RTCP_MUX;
186         } else {
187                 rtcp_type = AST_RTP_INSTANCE_RTCP_STANDARD;
188         }
189
190         ast_rtp_instance_set_prop(session_media->rtp, AST_RTP_PROPERTY_RTCP, rtcp_type);
191 }
192
193 /*! \brief Internal function which creates an RTP instance */
194 static int create_rtp(struct ast_sip_session *session, struct ast_sip_session_media *session_media)
195 {
196         struct ast_rtp_engine_ice *ice;
197         struct ast_sockaddr temp_media_address;
198         struct ast_sockaddr *media_address =  &address_rtp;
199
200         if (session->endpoint->media.bind_rtp_to_media_address && !ast_strlen_zero(session->endpoint->media.address)) {
201                 if (ast_sockaddr_parse(&temp_media_address, session->endpoint->media.address, 0)) {
202                         ast_debug(1, "Endpoint %s: Binding RTP media to %s\n",
203                                 ast_sorcery_object_get_id(session->endpoint),
204                                 session->endpoint->media.address);
205                         media_address = &temp_media_address;
206                 } else {
207                         ast_debug(1, "Endpoint %s: RTP media address invalid: %s\n",
208                                 ast_sorcery_object_get_id(session->endpoint),
209                                 session->endpoint->media.address);
210                 }
211         } else {
212                 struct ast_sip_transport *transport;
213
214                 transport = ast_sorcery_retrieve_by_id(ast_sip_get_sorcery(), "transport",
215                         session->endpoint->transport);
216                 if (transport) {
217                         struct ast_sip_transport_state *trans_state;
218
219                         trans_state = ast_sip_get_transport_state(ast_sorcery_object_get_id(transport));
220                         if (trans_state) {
221                                 char hoststr[PJ_INET6_ADDRSTRLEN];
222
223                                 pj_sockaddr_print(&trans_state->host, hoststr, sizeof(hoststr), 0);
224                                 if (ast_sockaddr_parse(&temp_media_address, hoststr, 0)) {
225                                         ast_debug(1, "Transport %s bound to %s: Using it for RTP media.\n",
226                                                 session->endpoint->transport, hoststr);
227                                         media_address = &temp_media_address;
228                                 } else {
229                                         ast_debug(1, "Transport %s bound to %s: Invalid for RTP media.\n",
230                                                 session->endpoint->transport, hoststr);
231                                 }
232                                 ao2_ref(trans_state, -1);
233                         }
234                         ao2_ref(transport, -1);
235                 }
236         }
237
238         if (!(session_media->rtp = ast_rtp_instance_new(session->endpoint->media.rtp.engine, sched, media_address, NULL))) {
239                 ast_log(LOG_ERROR, "Unable to create RTP instance using RTP engine '%s'\n", session->endpoint->media.rtp.engine);
240                 return -1;
241         }
242
243         ast_rtp_instance_set_prop(session_media->rtp, AST_RTP_PROPERTY_NAT, session->endpoint->media.rtp.symmetric);
244
245         if (!session->endpoint->media.rtp.ice_support && (ice = ast_rtp_instance_get_ice(session_media->rtp))) {
246                 ice->stop(session_media->rtp);
247         }
248
249         if (session->endpoint->dtmf == AST_SIP_DTMF_RFC_4733 || session->endpoint->dtmf == AST_SIP_DTMF_AUTO) {
250                 ast_rtp_instance_dtmf_mode_set(session_media->rtp, AST_RTP_DTMF_MODE_RFC2833);
251                 ast_rtp_instance_set_prop(session_media->rtp, AST_RTP_PROPERTY_DTMF, 1);
252         } else if (session->endpoint->dtmf == AST_SIP_DTMF_INBAND) {
253                 ast_rtp_instance_dtmf_mode_set(session_media->rtp, AST_RTP_DTMF_MODE_INBAND);
254         }
255
256         if (!strcmp(session_media->stream_type, STR_AUDIO) &&
257                         (session->endpoint->media.tos_audio || session->endpoint->media.cos_audio)) {
258                 ast_rtp_instance_set_qos(session_media->rtp, session->endpoint->media.tos_audio,
259                                 session->endpoint->media.cos_audio, "SIP RTP Audio");
260         } else if (!strcmp(session_media->stream_type, STR_VIDEO) &&
261                         (session->endpoint->media.tos_video || session->endpoint->media.cos_video)) {
262                 ast_rtp_instance_set_qos(session_media->rtp, session->endpoint->media.tos_video,
263                                 session->endpoint->media.cos_video, "SIP RTP Video");
264         }
265
266         ast_rtp_instance_set_last_rx(session_media->rtp, time(NULL));
267
268         return 0;
269 }
270
271 static void get_codecs(struct ast_sip_session *session, const struct pjmedia_sdp_media *stream, struct ast_rtp_codecs *codecs,
272        struct ast_sip_session_media *session_media)
273 {
274         pjmedia_sdp_attr *attr;
275         pjmedia_sdp_rtpmap *rtpmap;
276         pjmedia_sdp_fmtp fmtp;
277         struct ast_format *format;
278         int i, num = 0, tel_event = 0;
279         char name[256];
280         char media[20];
281         char fmt_param[256];
282         enum ast_rtp_options options = session->endpoint->media.g726_non_standard ?
283                 AST_RTP_OPT_G726_NONSTANDARD : 0;
284
285         ast_rtp_codecs_payloads_initialize(codecs);
286
287         /* Iterate through provided formats */
288         for (i = 0; i < stream->desc.fmt_count; ++i) {
289                 /* The payload is kept as a string for things like t38 but for video it is always numerical */
290                 ast_rtp_codecs_payloads_set_m_type(codecs, NULL, pj_strtoul(&stream->desc.fmt[i]));
291                 /* Look for the optional rtpmap attribute */
292                 if (!(attr = pjmedia_sdp_media_find_attr2(stream, "rtpmap", &stream->desc.fmt[i]))) {
293                         continue;
294                 }
295
296                 /* Interpret the attribute as an rtpmap */
297                 if ((pjmedia_sdp_attr_to_rtpmap(session->inv_session->pool_prov, attr, &rtpmap)) != PJ_SUCCESS) {
298                         continue;
299                 }
300
301                 ast_copy_pj_str(name, &rtpmap->enc_name, sizeof(name));
302                 if (strcmp(name, "telephone-event") == 0) {
303                         tel_event++;
304                 }
305
306                 ast_copy_pj_str(media, (pj_str_t*)&stream->desc.media, sizeof(media));
307                 ast_rtp_codecs_payloads_set_rtpmap_type_rate(codecs, NULL,
308                         pj_strtoul(&stream->desc.fmt[i]), media, name, options, rtpmap->clock_rate);
309                 /* Look for an optional associated fmtp attribute */
310                 if (!(attr = pjmedia_sdp_media_find_attr2(stream, "fmtp", &rtpmap->pt))) {
311                         continue;
312                 }
313
314                 if ((pjmedia_sdp_attr_get_fmtp(attr, &fmtp)) == PJ_SUCCESS) {
315                         ast_copy_pj_str(fmt_param, &fmtp.fmt, sizeof(fmt_param));
316                         if (sscanf(fmt_param, "%30d", &num) != 1) {
317                                 continue;
318                         }
319
320                         if ((format = ast_rtp_codecs_get_payload_format(codecs, num))) {
321                                 struct ast_format *format_parsed;
322
323                                 ast_copy_pj_str(fmt_param, &fmtp.fmt_param, sizeof(fmt_param));
324
325                                 format_parsed = ast_format_parse_sdp_fmtp(format, fmt_param);
326                                 if (format_parsed) {
327                                         ast_rtp_codecs_payload_replace_format(codecs, num, format_parsed);
328                                         ao2_ref(format_parsed, -1);
329                                 }
330
331                                 ao2_ref(format, -1);
332                         }
333                 }
334         }
335         if (!tel_event && (session->endpoint->dtmf == AST_SIP_DTMF_AUTO)) {
336                 ast_rtp_instance_dtmf_mode_set(session_media->rtp, AST_RTP_DTMF_MODE_INBAND);
337         }
338         /* Get the packetization, if it exists */
339         if ((attr = pjmedia_sdp_media_find_attr2(stream, "ptime", NULL))) {
340                 unsigned long framing = pj_strtoul(pj_strltrim(&attr->value));
341                 if (framing && session->endpoint->media.rtp.use_ptime) {
342                         ast_rtp_codecs_set_framing(codecs, framing);
343                 }
344         }
345 }
346
347 static int set_caps(struct ast_sip_session *session,
348         struct ast_sip_session_media *session_media,
349         const struct pjmedia_sdp_media *stream,
350         int is_offer)
351 {
352         RAII_VAR(struct ast_format_cap *, caps, NULL, ao2_cleanup);
353         RAII_VAR(struct ast_format_cap *, peer, NULL, ao2_cleanup);
354         RAII_VAR(struct ast_format_cap *, joint, NULL, ao2_cleanup);
355         enum ast_media_type media_type = stream_to_media_type(session_media->stream_type);
356         struct ast_rtp_codecs codecs = AST_RTP_CODECS_NULL_INIT;
357         int fmts = 0;
358         int direct_media_enabled = !ast_sockaddr_isnull(&session_media->direct_media_addr) &&
359                 ast_format_cap_count(session->direct_media_cap);
360         int dsp_features = 0;
361
362         if (!(caps = ast_format_cap_alloc(AST_FORMAT_CAP_FLAG_DEFAULT)) ||
363             !(peer = ast_format_cap_alloc(AST_FORMAT_CAP_FLAG_DEFAULT)) ||
364             !(joint = ast_format_cap_alloc(AST_FORMAT_CAP_FLAG_DEFAULT))) {
365                 ast_log(LOG_ERROR, "Failed to allocate %s capabilities\n", session_media->stream_type);
366                 return -1;
367         }
368
369         /* get the endpoint capabilities */
370         if (direct_media_enabled) {
371                 ast_format_cap_get_compatible(session->endpoint->media.codecs, session->direct_media_cap, caps);
372                 format_cap_only_type(caps, media_type);
373         } else {
374                 ast_format_cap_append_from_cap(caps, session->endpoint->media.codecs, media_type);
375         }
376
377         /* get the capabilities on the peer */
378         get_codecs(session, stream, &codecs,  session_media);
379         ast_rtp_codecs_payload_formats(&codecs, peer, &fmts);
380
381         /* get the joint capabilities between peer and endpoint */
382         ast_format_cap_get_compatible(caps, peer, joint);
383         if (!ast_format_cap_count(joint)) {
384                 struct ast_str *usbuf = ast_str_alloca(AST_FORMAT_CAP_NAMES_LEN);
385                 struct ast_str *thembuf = ast_str_alloca(AST_FORMAT_CAP_NAMES_LEN);
386
387                 ast_rtp_codecs_payloads_destroy(&codecs);
388                 ast_log(LOG_NOTICE, "No joint capabilities for '%s' media stream between our configuration(%s) and incoming SDP(%s)\n",
389                         session_media->stream_type,
390                         ast_format_cap_get_names(caps, &usbuf),
391                         ast_format_cap_get_names(peer, &thembuf));
392                 return -1;
393         }
394
395         if (is_offer) {
396                 /*
397                  * Setup rx payload type mapping to prefer the mapping
398                  * from the peer that the RFC says we SHOULD use.
399                  */
400                 ast_rtp_codecs_payloads_xover(&codecs, &codecs, NULL);
401         }
402         ast_rtp_codecs_payloads_copy(&codecs, ast_rtp_instance_get_codecs(session_media->rtp),
403                 session_media->rtp);
404
405         ast_format_cap_append_from_cap(session->req_caps, joint, AST_MEDIA_TYPE_UNKNOWN);
406
407         if (session->channel) {
408                 ast_channel_lock(session->channel);
409                 ast_format_cap_remove_by_type(caps, AST_MEDIA_TYPE_UNKNOWN);
410                 ast_format_cap_append_from_cap(caps, ast_channel_nativeformats(session->channel),
411                         AST_MEDIA_TYPE_UNKNOWN);
412                 ast_format_cap_remove_by_type(caps, media_type);
413
414                 if (session->endpoint->preferred_codec_only){
415                         struct ast_format *preferred_fmt = ast_format_cap_get_format(joint, 0);
416                         ast_format_cap_append(caps, preferred_fmt, 0);
417                         ao2_ref(preferred_fmt, -1);
418                 } else if (!session->endpoint->asymmetric_rtp_codec) {
419                         struct ast_format *best;
420                         /*
421                          * If we don't allow the sending codec to be changed on our side
422                          * then get the best codec from the joint capabilities of the media
423                          * type and use only that. This ensures the core won't start sending
424                          * out a format that we aren't currently sending.
425                          */
426
427                         best = ast_format_cap_get_best_by_type(joint, media_type);
428                         if (best) {
429                                 ast_format_cap_append(caps, best, ast_format_cap_get_framing(joint));
430                                 ao2_ref(best, -1);
431                         }
432                 } else {
433                         ast_format_cap_append_from_cap(caps, joint, media_type);
434                 }
435
436                 /*
437                  * Apply the new formats to the channel, potentially changing
438                  * raw read/write formats and translation path while doing so.
439                  */
440                 ast_channel_nativeformats_set(session->channel, caps);
441                 if (media_type == AST_MEDIA_TYPE_AUDIO) {
442                         ast_set_read_format(session->channel, ast_channel_readformat(session->channel));
443                         ast_set_write_format(session->channel, ast_channel_writeformat(session->channel));
444                 }
445                 if ((session->endpoint->dtmf == AST_SIP_DTMF_AUTO)
446                     && (ast_rtp_instance_dtmf_mode_get(session_media->rtp) == AST_RTP_DTMF_MODE_RFC2833)
447                     && (session->dsp)) {
448                         dsp_features = ast_dsp_get_features(session->dsp);
449                         dsp_features &= ~DSP_FEATURE_DIGIT_DETECT;
450                         if (dsp_features) {
451                                 ast_dsp_set_features(session->dsp, dsp_features);
452                         } else {
453                                 ast_dsp_free(session->dsp);
454                                 session->dsp = NULL;
455                         }
456                 }
457
458                 if (ast_channel_is_bridged(session->channel)) {
459                         ast_channel_set_unbridged_nolock(session->channel, 1);
460                 }
461
462                 ast_channel_unlock(session->channel);
463         }
464
465         ast_rtp_codecs_payloads_destroy(&codecs);
466         return 0;
467 }
468
469 static pjmedia_sdp_attr* generate_rtpmap_attr(struct ast_sip_session *session, pjmedia_sdp_media *media, pj_pool_t *pool,
470                                               int rtp_code, int asterisk_format, struct ast_format *format, int code)
471 {
472         extern pj_bool_t pjsip_use_compact_form;
473         pjmedia_sdp_rtpmap rtpmap;
474         pjmedia_sdp_attr *attr = NULL;
475         char tmp[64];
476         enum ast_rtp_options options = session->endpoint->media.g726_non_standard ?
477                 AST_RTP_OPT_G726_NONSTANDARD : 0;
478
479         snprintf(tmp, sizeof(tmp), "%d", rtp_code);
480         pj_strdup2(pool, &media->desc.fmt[media->desc.fmt_count++], tmp);
481
482         if (rtp_code <= AST_RTP_PT_LAST_STATIC && pjsip_use_compact_form) {
483                 return NULL;
484         }
485
486         rtpmap.pt = media->desc.fmt[media->desc.fmt_count - 1];
487         rtpmap.clock_rate = ast_rtp_lookup_sample_rate2(asterisk_format, format, code);
488         pj_strdup2(pool, &rtpmap.enc_name, ast_rtp_lookup_mime_subtype2(asterisk_format, format, code, options));
489         if (!pj_stricmp2(&rtpmap.enc_name, "opus")) {
490                 pj_cstr(&rtpmap.param, "2");
491         } else {
492                 pj_cstr(&rtpmap.param, NULL);
493         }
494
495         pjmedia_sdp_rtpmap_to_attr(pool, &rtpmap, &attr);
496
497         return attr;
498 }
499
500 static pjmedia_sdp_attr* generate_fmtp_attr(pj_pool_t *pool, struct ast_format *format, int rtp_code)
501 {
502         struct ast_str *fmtp0 = ast_str_alloca(256);
503         pj_str_t fmtp1;
504         pjmedia_sdp_attr *attr = NULL;
505         char *tmp;
506
507         ast_format_generate_sdp_fmtp(format, rtp_code, &fmtp0);
508         if (ast_str_strlen(fmtp0)) {
509                 tmp = ast_str_buffer(fmtp0) + ast_str_strlen(fmtp0) - 1;
510                 /* remove any carriage return line feeds */
511                 while (*tmp == '\r' || *tmp == '\n') --tmp;
512                 *++tmp = '\0';
513                 /* ast...generate gives us everything, just need value */
514                 tmp = strchr(ast_str_buffer(fmtp0), ':');
515                 if (tmp && tmp[1] != '\0') {
516                         fmtp1 = pj_str(tmp + 1);
517                 } else {
518                         fmtp1 = pj_str(ast_str_buffer(fmtp0));
519                 }
520                 attr = pjmedia_sdp_attr_create(pool, "fmtp", &fmtp1);
521         }
522         return attr;
523 }
524
525 /*! \brief Function which adds ICE attributes to a media stream */
526 static void add_ice_to_stream(struct ast_sip_session *session, struct ast_sip_session_media *session_media, pj_pool_t *pool, pjmedia_sdp_media *media)
527 {
528         struct ast_rtp_engine_ice *ice;
529         struct ao2_container *candidates;
530         const char *username, *password;
531         pj_str_t stmp;
532         pjmedia_sdp_attr *attr;
533         struct ao2_iterator it_candidates;
534         struct ast_rtp_engine_ice_candidate *candidate;
535
536         if (!session->endpoint->media.rtp.ice_support || !(ice = ast_rtp_instance_get_ice(session_media->rtp)) ||
537                 !(candidates = ice->get_local_candidates(session_media->rtp))) {
538                 return;
539         }
540
541         if ((username = ice->get_ufrag(session_media->rtp))) {
542                 attr = pjmedia_sdp_attr_create(pool, "ice-ufrag", pj_cstr(&stmp, username));
543                 media->attr[media->attr_count++] = attr;
544         }
545
546         if ((password = ice->get_password(session_media->rtp))) {
547                 attr = pjmedia_sdp_attr_create(pool, "ice-pwd", pj_cstr(&stmp, password));
548                 media->attr[media->attr_count++] = attr;
549         }
550
551         it_candidates = ao2_iterator_init(candidates, 0);
552         for (; (candidate = ao2_iterator_next(&it_candidates)); ao2_ref(candidate, -1)) {
553                 struct ast_str *attr_candidate = ast_str_create(128);
554
555                 ast_str_set(&attr_candidate, -1, "%s %u %s %d %s ", candidate->foundation, candidate->id, candidate->transport,
556                                         candidate->priority, ast_sockaddr_stringify_addr_remote(&candidate->address));
557                 ast_str_append(&attr_candidate, -1, "%s typ ", ast_sockaddr_stringify_port(&candidate->address));
558
559                 switch (candidate->type) {
560                         case AST_RTP_ICE_CANDIDATE_TYPE_HOST:
561                                 ast_str_append(&attr_candidate, -1, "host");
562                                 break;
563                         case AST_RTP_ICE_CANDIDATE_TYPE_SRFLX:
564                                 ast_str_append(&attr_candidate, -1, "srflx");
565                                 break;
566                         case AST_RTP_ICE_CANDIDATE_TYPE_RELAYED:
567                                 ast_str_append(&attr_candidate, -1, "relay");
568                                 break;
569                 }
570
571                 if (!ast_sockaddr_isnull(&candidate->relay_address)) {
572                         ast_str_append(&attr_candidate, -1, " raddr %s rport", ast_sockaddr_stringify_addr_remote(&candidate->relay_address));
573                         ast_str_append(&attr_candidate, -1, " %s", ast_sockaddr_stringify_port(&candidate->relay_address));
574                 }
575
576                 attr = pjmedia_sdp_attr_create(pool, "candidate", pj_cstr(&stmp, ast_str_buffer(attr_candidate)));
577                 media->attr[media->attr_count++] = attr;
578
579                 ast_free(attr_candidate);
580         }
581
582         ao2_iterator_destroy(&it_candidates);
583         ao2_ref(candidates, -1);
584 }
585
586 /*! \brief Function which processes ICE attributes in an audio stream */
587 static void process_ice_attributes(struct ast_sip_session *session, struct ast_sip_session_media *session_media,
588                                    const struct pjmedia_sdp_session *remote, const struct pjmedia_sdp_media *remote_stream)
589 {
590         struct ast_rtp_engine_ice *ice;
591         const pjmedia_sdp_attr *attr;
592         char attr_value[256];
593         unsigned int attr_i;
594
595         /* If ICE support is not enabled or available exit early */
596         if (!session->endpoint->media.rtp.ice_support || !(ice = ast_rtp_instance_get_ice(session_media->rtp))) {
597                 return;
598         }
599
600         attr = pjmedia_sdp_media_find_attr2(remote_stream, "ice-ufrag", NULL);
601         if (!attr) {
602                 attr = pjmedia_sdp_attr_find2(remote->attr_count, remote->attr, "ice-ufrag", NULL);
603         }
604         if (attr) {
605                 ast_copy_pj_str(attr_value, (pj_str_t*)&attr->value, sizeof(attr_value));
606                 ice->set_authentication(session_media->rtp, attr_value, NULL);
607         } else {
608                 return;
609         }
610
611         attr = pjmedia_sdp_media_find_attr2(remote_stream, "ice-pwd", NULL);
612         if (!attr) {
613                 attr = pjmedia_sdp_attr_find2(remote->attr_count, remote->attr, "ice-pwd", NULL);
614         }
615         if (attr) {
616                 ast_copy_pj_str(attr_value, (pj_str_t*)&attr->value, sizeof(attr_value));
617                 ice->set_authentication(session_media->rtp, NULL, attr_value);
618         } else {
619                 return;
620         }
621
622         if (pjmedia_sdp_media_find_attr2(remote_stream, "ice-lite", NULL)) {
623                 ice->ice_lite(session_media->rtp);
624         }
625
626         /* Find all of the candidates */
627         for (attr_i = 0; attr_i < remote_stream->attr_count; ++attr_i) {
628                 char foundation[32], transport[32], address[PJ_INET6_ADDRSTRLEN + 1], cand_type[6], relay_address[PJ_INET6_ADDRSTRLEN + 1] = "";
629                 unsigned int port, relay_port = 0;
630                 struct ast_rtp_engine_ice_candidate candidate = { 0, };
631
632                 attr = remote_stream->attr[attr_i];
633
634                 /* If this is not a candidate line skip it */
635                 if (pj_strcmp2(&attr->name, "candidate")) {
636                         continue;
637                 }
638
639                 ast_copy_pj_str(attr_value, (pj_str_t*)&attr->value, sizeof(attr_value));
640
641                 if (sscanf(attr_value, "%31s %30u %31s %30u %46s %30u typ %5s %*s %23s %*s %30u", foundation, &candidate.id, transport,
642                         (unsigned *)&candidate.priority, address, &port, cand_type, relay_address, &relay_port) < 7) {
643                         /* Candidate did not parse properly */
644                         continue;
645                 }
646
647                 if (session->endpoint->media.rtcp_mux && session_media->remote_rtcp_mux && candidate.id > 1) {
648                         /* Remote side may have offered RTP and RTCP candidates. However, if we're using RTCP MUX,
649                          * then we should ignore RTCP candidates.
650                          */
651                         continue;
652                 }
653
654                 candidate.foundation = foundation;
655                 candidate.transport = transport;
656
657                 ast_sockaddr_parse(&candidate.address, address, PARSE_PORT_FORBID);
658                 ast_sockaddr_set_port(&candidate.address, port);
659
660                 if (!strcasecmp(cand_type, "host")) {
661                         candidate.type = AST_RTP_ICE_CANDIDATE_TYPE_HOST;
662                 } else if (!strcasecmp(cand_type, "srflx")) {
663                         candidate.type = AST_RTP_ICE_CANDIDATE_TYPE_SRFLX;
664                 } else if (!strcasecmp(cand_type, "relay")) {
665                         candidate.type = AST_RTP_ICE_CANDIDATE_TYPE_RELAYED;
666                 } else {
667                         continue;
668                 }
669
670                 if (!ast_strlen_zero(relay_address)) {
671                         ast_sockaddr_parse(&candidate.relay_address, relay_address, PARSE_PORT_FORBID);
672                 }
673
674                 if (relay_port) {
675                         ast_sockaddr_set_port(&candidate.relay_address, relay_port);
676                 }
677
678                 ice->add_remote_candidate(session_media->rtp, &candidate);
679         }
680
681         ice->set_role(session_media->rtp, pjmedia_sdp_neg_was_answer_remote(session->inv_session->neg) == PJ_TRUE ?
682                 AST_RTP_ICE_ROLE_CONTROLLING : AST_RTP_ICE_ROLE_CONTROLLED);
683         ice->start(session_media->rtp);
684 }
685
686 /*! \brief figure out if media stream has crypto lines for sdes */
687 static int media_stream_has_crypto(const struct pjmedia_sdp_media *stream)
688 {
689         int i;
690
691         for (i = 0; i < stream->attr_count; i++) {
692                 pjmedia_sdp_attr *attr;
693
694                 /* check the stream for the required crypto attribute */
695                 attr = stream->attr[i];
696                 if (pj_strcmp2(&attr->name, "crypto")) {
697                         continue;
698                 }
699
700                 return 1;
701         }
702
703         return 0;
704 }
705
706 /*! \brief figure out media transport encryption type from the media transport string */
707 static enum ast_sip_session_media_encryption get_media_encryption_type(pj_str_t transport,
708         const struct pjmedia_sdp_media *stream, unsigned int *optimistic)
709 {
710         RAII_VAR(char *, transport_str, ast_strndup(transport.ptr, transport.slen), ast_free);
711
712         *optimistic = 0;
713
714         if (!transport_str) {
715                 return AST_SIP_MEDIA_TRANSPORT_INVALID;
716         }
717         if (strstr(transport_str, "UDP/TLS")) {
718                 return AST_SIP_MEDIA_ENCRYPT_DTLS;
719         } else if (strstr(transport_str, "SAVP")) {
720                 return AST_SIP_MEDIA_ENCRYPT_SDES;
721         } else if (media_stream_has_crypto(stream)) {
722                 *optimistic = 1;
723                 return AST_SIP_MEDIA_ENCRYPT_SDES;
724         } else {
725                 return AST_SIP_MEDIA_ENCRYPT_NONE;
726         }
727 }
728
729 /*!
730  * \brief Checks whether the encryption offered in SDP is compatible with the endpoint's configuration
731  * \internal
732  *
733  * \param endpoint_encryption Media encryption configured for the endpoint
734  * \param stream pjmedia_sdp_media stream description
735  *
736  * \retval AST_SIP_MEDIA_TRANSPORT_INVALID on encryption mismatch
737  * \retval The encryption requested in the SDP
738  */
739 static enum ast_sip_session_media_encryption check_endpoint_media_transport(
740         struct ast_sip_endpoint *endpoint,
741         const struct pjmedia_sdp_media *stream)
742 {
743         enum ast_sip_session_media_encryption incoming_encryption;
744         char transport_end = stream->desc.transport.ptr[stream->desc.transport.slen - 1];
745         unsigned int optimistic;
746
747         if ((transport_end == 'F' && !endpoint->media.rtp.use_avpf)
748                 || (transport_end != 'F' && endpoint->media.rtp.use_avpf)) {
749                 return AST_SIP_MEDIA_TRANSPORT_INVALID;
750         }
751
752         incoming_encryption = get_media_encryption_type(stream->desc.transport, stream, &optimistic);
753
754         if (incoming_encryption == endpoint->media.rtp.encryption) {
755                 return incoming_encryption;
756         }
757
758         if (endpoint->media.rtp.force_avp ||
759                 endpoint->media.rtp.encryption_optimistic) {
760                 return incoming_encryption;
761         }
762
763         /* If an optimistic offer has been made but encryption is not enabled consider it as having
764          * no offer of crypto at all instead of invalid so the session proceeds.
765          */
766         if (optimistic) {
767                 return AST_SIP_MEDIA_ENCRYPT_NONE;
768         }
769
770         return AST_SIP_MEDIA_TRANSPORT_INVALID;
771 }
772
773 static int setup_srtp(struct ast_sip_session_media *session_media)
774 {
775         if (!session_media->srtp) {
776                 session_media->srtp = ast_sdp_srtp_alloc();
777                 if (!session_media->srtp) {
778                         return -1;
779                 }
780         }
781
782         if (!session_media->srtp->crypto) {
783                 session_media->srtp->crypto = ast_sdp_crypto_alloc();
784                 if (!session_media->srtp->crypto) {
785                         return -1;
786                 }
787         }
788
789         return 0;
790 }
791
792 static int setup_dtls_srtp(struct ast_sip_session *session,
793         struct ast_sip_session_media *session_media)
794 {
795         struct ast_rtp_engine_dtls *dtls;
796
797         if (!session->endpoint->media.rtp.dtls_cfg.enabled || !session_media->rtp) {
798                 return -1;
799         }
800
801         dtls = ast_rtp_instance_get_dtls(session_media->rtp);
802         if (!dtls) {
803                 return -1;
804         }
805
806         session->endpoint->media.rtp.dtls_cfg.suite = ((session->endpoint->media.rtp.srtp_tag_32) ? AST_AES_CM_128_HMAC_SHA1_32 : AST_AES_CM_128_HMAC_SHA1_80);
807         if (dtls->set_configuration(session_media->rtp, &session->endpoint->media.rtp.dtls_cfg)) {
808                 ast_log(LOG_ERROR, "Attempted to set an invalid DTLS-SRTP configuration on RTP instance '%p'\n",
809                         session_media->rtp);
810                 return -1;
811         }
812
813         if (setup_srtp(session_media)) {
814                 return -1;
815         }
816         return 0;
817 }
818
819 static void apply_dtls_attrib(struct ast_sip_session_media *session_media,
820         pjmedia_sdp_attr *attr)
821 {
822         struct ast_rtp_engine_dtls *dtls = ast_rtp_instance_get_dtls(session_media->rtp);
823         pj_str_t *value;
824
825         if (!attr->value.ptr || !dtls) {
826                 return;
827         }
828
829         value = pj_strtrim(&attr->value);
830
831         if (!pj_strcmp2(&attr->name, "setup")) {
832                 if (!pj_stricmp2(value, "active")) {
833                         dtls->set_setup(session_media->rtp, AST_RTP_DTLS_SETUP_ACTIVE);
834                 } else if (!pj_stricmp2(value, "passive")) {
835                         dtls->set_setup(session_media->rtp, AST_RTP_DTLS_SETUP_PASSIVE);
836                 } else if (!pj_stricmp2(value, "actpass")) {
837                         dtls->set_setup(session_media->rtp, AST_RTP_DTLS_SETUP_ACTPASS);
838                 } else if (!pj_stricmp2(value, "holdconn")) {
839                         dtls->set_setup(session_media->rtp, AST_RTP_DTLS_SETUP_HOLDCONN);
840                 } else {
841                         ast_log(LOG_WARNING, "Unsupported setup attribute value '%*s'\n", (int)value->slen, value->ptr);
842                 }
843         } else if (!pj_strcmp2(&attr->name, "connection")) {
844                 if (!pj_stricmp2(value, "new")) {
845                         dtls->reset(session_media->rtp);
846                 } else if (!pj_stricmp2(value, "existing")) {
847                         /* Do nothing */
848                 } else {
849                         ast_log(LOG_WARNING, "Unsupported connection attribute value '%*s'\n", (int)value->slen, value->ptr);
850                 }
851         } else if (!pj_strcmp2(&attr->name, "fingerprint")) {
852                 char hash_value[256], hash[32];
853                 char fingerprint_text[value->slen + 1];
854                 ast_copy_pj_str(fingerprint_text, value, sizeof(fingerprint_text));
855                         if (sscanf(fingerprint_text, "%31s %255s", hash, hash_value) == 2) {
856                         if (!strcasecmp(hash, "sha-1")) {
857                                 dtls->set_fingerprint(session_media->rtp, AST_RTP_DTLS_HASH_SHA1, hash_value);
858                         } else if (!strcasecmp(hash, "sha-256")) {
859                                 dtls->set_fingerprint(session_media->rtp, AST_RTP_DTLS_HASH_SHA256, hash_value);
860                         } else {
861                                 ast_log(LOG_WARNING, "Unsupported fingerprint hash type '%s'\n",
862                                 hash);
863                         }
864                 }
865         }
866 }
867
868 static int parse_dtls_attrib(struct ast_sip_session_media *session_media,
869         const struct pjmedia_sdp_session *sdp,
870         const struct pjmedia_sdp_media *stream)
871 {
872         int i;
873
874         for (i = 0; i < sdp->attr_count; i++) {
875                 apply_dtls_attrib(session_media, sdp->attr[i]);
876         }
877
878         for (i = 0; i < stream->attr_count; i++) {
879                 apply_dtls_attrib(session_media, stream->attr[i]);
880         }
881
882         ast_set_flag(session_media->srtp, AST_SRTP_CRYPTO_OFFER_OK);
883
884         return 0;
885 }
886
887 static int setup_sdes_srtp(struct ast_sip_session_media *session_media,
888         const struct pjmedia_sdp_media *stream)
889 {
890         int i;
891
892         for (i = 0; i < stream->attr_count; i++) {
893                 pjmedia_sdp_attr *attr;
894                 RAII_VAR(char *, crypto_str, NULL, ast_free);
895
896                 /* check the stream for the required crypto attribute */
897                 attr = stream->attr[i];
898                 if (pj_strcmp2(&attr->name, "crypto")) {
899                         continue;
900                 }
901
902                 crypto_str = ast_strndup(attr->value.ptr, attr->value.slen);
903                 if (!crypto_str) {
904                         return -1;
905                 }
906
907                 if (setup_srtp(session_media)) {
908                         return -1;
909                 }
910
911                 if (!ast_sdp_crypto_process(session_media->rtp, session_media->srtp, crypto_str)) {
912                         /* found a valid crypto attribute */
913                         return 0;
914                 }
915
916                 ast_debug(1, "Ignoring crypto offer with unsupported parameters: %s\n", crypto_str);
917         }
918
919         /* no usable crypto attributes found */
920         return -1;
921 }
922
923 static int setup_media_encryption(struct ast_sip_session *session,
924         struct ast_sip_session_media *session_media,
925         const struct pjmedia_sdp_session *sdp,
926         const struct pjmedia_sdp_media *stream)
927 {
928         switch (session_media->encryption) {
929         case AST_SIP_MEDIA_ENCRYPT_SDES:
930                 if (setup_sdes_srtp(session_media, stream)) {
931                         return -1;
932                 }
933                 break;
934         case AST_SIP_MEDIA_ENCRYPT_DTLS:
935                 if (setup_dtls_srtp(session, session_media)) {
936                         return -1;
937                 }
938                 if (parse_dtls_attrib(session_media, sdp, stream)) {
939                         return -1;
940                 }
941                 break;
942         case AST_SIP_MEDIA_TRANSPORT_INVALID:
943         case AST_SIP_MEDIA_ENCRYPT_NONE:
944                 break;
945         }
946
947         return 0;
948 }
949
950 static void set_ice_components(struct ast_sip_session *session, struct ast_sip_session_media *session_media)
951 {
952         struct ast_rtp_engine_ice *ice;
953
954         ast_assert(session_media->rtp != NULL);
955
956         ice = ast_rtp_instance_get_ice(session_media->rtp);
957         if (!session->endpoint->media.rtp.ice_support || !ice) {
958                 return;
959         }
960
961         if (session->endpoint->media.rtcp_mux && session_media->remote_rtcp_mux) {
962                 /* We both support RTCP mux. Only one ICE component necessary */
963                 ice->change_components(session_media->rtp, 1);
964         } else {
965                 /* They either don't support RTCP mux or we don't know if they do yet. */
966                 ice->change_components(session_media->rtp, 2);
967         }
968 }
969
970 /*! \brief Function which negotiates an incoming media stream */
971 static int negotiate_incoming_sdp_stream(struct ast_sip_session *session, struct ast_sip_session_media *session_media,
972                                          const struct pjmedia_sdp_session *sdp, const struct pjmedia_sdp_media *stream)
973 {
974         char host[NI_MAXHOST];
975         RAII_VAR(struct ast_sockaddr *, addrs, NULL, ast_free);
976         enum ast_media_type media_type = stream_to_media_type(session_media->stream_type);
977         enum ast_sip_session_media_encryption encryption = AST_SIP_MEDIA_ENCRYPT_NONE;
978         int res;
979
980         /* If port is 0, ignore this media stream */
981         if (!stream->desc.port) {
982                 ast_debug(3, "Media stream '%s' is already declined\n", session_media->stream_type);
983                 return 0;
984         }
985
986         /* If no type formats have been configured reject this stream */
987         if (!ast_format_cap_has_type(session->endpoint->media.codecs, media_type)) {
988                 ast_debug(3, "Endpoint has no codecs for media type '%s', declining stream\n", session_media->stream_type);
989                 return 0;
990         }
991
992         /* Ensure incoming transport is compatible with the endpoint's configuration */
993         if (!session->endpoint->media.rtp.use_received_transport) {
994                 encryption = check_endpoint_media_transport(session->endpoint, stream);
995
996                 if (encryption == AST_SIP_MEDIA_TRANSPORT_INVALID) {
997                         return -1;
998                 }
999         }
1000
1001         ast_copy_pj_str(host, stream->conn ? &stream->conn->addr : &sdp->conn->addr, sizeof(host));
1002
1003         /* Ensure that the address provided is valid */
1004         if (ast_sockaddr_resolve(&addrs, host, PARSE_PORT_FORBID, AST_AF_UNSPEC) <= 0) {
1005                 /* The provided host was actually invalid so we error out this negotiation */
1006                 return -1;
1007         }
1008
1009         /* Using the connection information create an appropriate RTP instance */
1010         if (!session_media->rtp && create_rtp(session, session_media)) {
1011                 return -1;
1012         }
1013
1014         session_media->remote_rtcp_mux = (pjmedia_sdp_media_find_attr2(stream, "rtcp-mux", NULL) != NULL);
1015         set_ice_components(session, session_media);
1016
1017         enable_rtcp(session, session_media, stream);
1018
1019         res = setup_media_encryption(session, session_media, sdp, stream);
1020         if (res) {
1021                 if (!session->endpoint->media.rtp.encryption_optimistic ||
1022                         !pj_strncmp2(&stream->desc.transport, "RTP/SAVP", 8)) {
1023                         /* If optimistic encryption is disabled and crypto should have been enabled
1024                          * but was not this session must fail. This must also fail if crypto was
1025                          * required in the offer but could not be set up.
1026                          */
1027                         return -1;
1028                 }
1029                 /* There is no encryption, sad. */
1030                 session_media->encryption = AST_SIP_MEDIA_ENCRYPT_NONE;
1031         }
1032
1033         /* If we've been explicitly configured to use the received transport OR if
1034          * encryption is on and crypto is present use the received transport.
1035          * This is done in case of optimistic because it may come in as RTP/AVP or RTP/SAVP depending
1036          * on the configuration of the remote endpoint (optimistic themselves or mandatory).
1037          */
1038         if ((session->endpoint->media.rtp.use_received_transport) ||
1039                 ((encryption == AST_SIP_MEDIA_ENCRYPT_SDES) && !res)) {
1040                 pj_strdup(session->inv_session->pool, &session_media->transport, &stream->desc.transport);
1041         }
1042
1043         if (set_caps(session, session_media, stream, 1)) {
1044                 return 0;
1045         }
1046         return 1;
1047 }
1048
1049 static int add_crypto_to_stream(struct ast_sip_session *session,
1050         struct ast_sip_session_media *session_media,
1051         pj_pool_t *pool, pjmedia_sdp_media *media)
1052 {
1053         pj_str_t stmp;
1054         pjmedia_sdp_attr *attr;
1055         enum ast_rtp_dtls_hash hash;
1056         const char *crypto_attribute;
1057         struct ast_rtp_engine_dtls *dtls;
1058         struct ast_sdp_srtp *tmp;
1059         static const pj_str_t STR_NEW = { "new", 3 };
1060         static const pj_str_t STR_EXISTING = { "existing", 8 };
1061         static const pj_str_t STR_ACTIVE = { "active", 6 };
1062         static const pj_str_t STR_PASSIVE = { "passive", 7 };
1063         static const pj_str_t STR_ACTPASS = { "actpass", 7 };
1064         static const pj_str_t STR_HOLDCONN = { "holdconn", 8 };
1065
1066         switch (session_media->encryption) {
1067         case AST_SIP_MEDIA_ENCRYPT_NONE:
1068         case AST_SIP_MEDIA_TRANSPORT_INVALID:
1069                 break;
1070         case AST_SIP_MEDIA_ENCRYPT_SDES:
1071                 if (!session_media->srtp) {
1072                         session_media->srtp = ast_sdp_srtp_alloc();
1073                         if (!session_media->srtp) {
1074                                 return -1;
1075                         }
1076                 }
1077
1078                 tmp = session_media->srtp;
1079
1080                 do {
1081                         crypto_attribute = ast_sdp_srtp_get_attrib(tmp,
1082                                 0 /* DTLS running? No */,
1083                                 session->endpoint->media.rtp.srtp_tag_32 /* 32 byte tag length? */);
1084                         if (!crypto_attribute) {
1085                                 /* No crypto attribute to add, bad news */
1086                                 return -1;
1087                         }
1088
1089                         attr = pjmedia_sdp_attr_create(pool, "crypto",
1090                                 pj_cstr(&stmp, crypto_attribute));
1091                         media->attr[media->attr_count++] = attr;
1092                 } while ((tmp = AST_LIST_NEXT(tmp, sdp_srtp_list)));
1093
1094                 break;
1095         case AST_SIP_MEDIA_ENCRYPT_DTLS:
1096                 if (setup_dtls_srtp(session, session_media)) {
1097                         return -1;
1098                 }
1099
1100                 dtls = ast_rtp_instance_get_dtls(session_media->rtp);
1101                 if (!dtls) {
1102                         return -1;
1103                 }
1104
1105                 switch (dtls->get_connection(session_media->rtp)) {
1106                 case AST_RTP_DTLS_CONNECTION_NEW:
1107                         attr = pjmedia_sdp_attr_create(pool, "connection", &STR_NEW);
1108                         media->attr[media->attr_count++] = attr;
1109                         break;
1110                 case AST_RTP_DTLS_CONNECTION_EXISTING:
1111                         attr = pjmedia_sdp_attr_create(pool, "connection", &STR_EXISTING);
1112                         media->attr[media->attr_count++] = attr;
1113                         break;
1114                 default:
1115                         break;
1116                 }
1117
1118                 switch (dtls->get_setup(session_media->rtp)) {
1119                 case AST_RTP_DTLS_SETUP_ACTIVE:
1120                         attr = pjmedia_sdp_attr_create(pool, "setup", &STR_ACTIVE);
1121                         media->attr[media->attr_count++] = attr;
1122                         break;
1123                 case AST_RTP_DTLS_SETUP_PASSIVE:
1124                         attr = pjmedia_sdp_attr_create(pool, "setup", &STR_PASSIVE);
1125                         media->attr[media->attr_count++] = attr;
1126                         break;
1127                 case AST_RTP_DTLS_SETUP_ACTPASS:
1128                         attr = pjmedia_sdp_attr_create(pool, "setup", &STR_ACTPASS);
1129                         media->attr[media->attr_count++] = attr;
1130                         break;
1131                 case AST_RTP_DTLS_SETUP_HOLDCONN:
1132                         attr = pjmedia_sdp_attr_create(pool, "setup", &STR_HOLDCONN);
1133                         media->attr[media->attr_count++] = attr;
1134                         break;
1135                 default:
1136                         break;
1137                 }
1138
1139                 hash = dtls->get_fingerprint_hash(session_media->rtp);
1140                 crypto_attribute = dtls->get_fingerprint(session_media->rtp);
1141                 if (crypto_attribute && (hash == AST_RTP_DTLS_HASH_SHA1 || hash == AST_RTP_DTLS_HASH_SHA256)) {
1142                         RAII_VAR(struct ast_str *, fingerprint, ast_str_create(64), ast_free);
1143                         if (!fingerprint) {
1144                                 return -1;
1145                         }
1146
1147                         if (hash == AST_RTP_DTLS_HASH_SHA1) {
1148                                 ast_str_set(&fingerprint, 0, "SHA-1 %s", crypto_attribute);
1149                         } else {
1150                                 ast_str_set(&fingerprint, 0, "SHA-256 %s", crypto_attribute);
1151                         }
1152
1153                         attr = pjmedia_sdp_attr_create(pool, "fingerprint", pj_cstr(&stmp, ast_str_buffer(fingerprint)));
1154                         media->attr[media->attr_count++] = attr;
1155                 }
1156                 break;
1157         }
1158
1159         return 0;
1160 }
1161
1162 /*! \brief Function which creates an outgoing stream */
1163 static int create_outgoing_sdp_stream(struct ast_sip_session *session, struct ast_sip_session_media *session_media,
1164                                       struct pjmedia_sdp_session *sdp)
1165 {
1166         pj_pool_t *pool = session->inv_session->pool_prov;
1167         static const pj_str_t STR_IN = { "IN", 2 };
1168         static const pj_str_t STR_IP4 = { "IP4", 3};
1169         static const pj_str_t STR_IP6 = { "IP6", 3};
1170         static const pj_str_t STR_SENDRECV = { "sendrecv", 8 };
1171         static const pj_str_t STR_SENDONLY = { "sendonly", 8 };
1172         pjmedia_sdp_media *media;
1173         const char *hostip = NULL;
1174         struct ast_sockaddr addr;
1175         char tmp[512];
1176         pj_str_t stmp;
1177         pjmedia_sdp_attr *attr;
1178         int index = 0;
1179         int noncodec = (session->endpoint->dtmf == AST_SIP_DTMF_RFC_4733 || session->endpoint->dtmf == AST_SIP_DTMF_AUTO) ? AST_RTP_DTMF : 0;
1180         int min_packet_size = 0, max_packet_size = 0;
1181         int rtp_code;
1182         RAII_VAR(struct ast_format_cap *, caps, NULL, ao2_cleanup);
1183         enum ast_media_type media_type = stream_to_media_type(session_media->stream_type);
1184         int use_override_prefs = ast_format_cap_count(session->req_caps);
1185
1186         int direct_media_enabled = !ast_sockaddr_isnull(&session_media->direct_media_addr) &&
1187                 ast_format_cap_count(session->direct_media_cap);
1188
1189         if ((use_override_prefs && !ast_format_cap_has_type(session->req_caps, media_type)) ||
1190             (!use_override_prefs && !ast_format_cap_has_type(session->endpoint->media.codecs, media_type))) {
1191                 /* If no type formats are configured don't add a stream */
1192                 return 0;
1193         } else if (!session_media->rtp && create_rtp(session, session_media)) {
1194                 return -1;
1195         }
1196
1197         set_ice_components(session, session_media);
1198         enable_rtcp(session, session_media, NULL);
1199
1200         if (!(media = pj_pool_zalloc(pool, sizeof(struct pjmedia_sdp_media))) ||
1201                 !(media->conn = pj_pool_zalloc(pool, sizeof(struct pjmedia_sdp_conn)))) {
1202                 return -1;
1203         }
1204
1205         if (add_crypto_to_stream(session, session_media, pool, media)) {
1206                 return -1;
1207         }
1208
1209         media->desc.media = pj_str(session_media->stream_type);
1210         if (pj_strlen(&session_media->transport)) {
1211                 /* If a transport has already been specified use it */
1212                 media->desc.transport = session_media->transport;
1213         } else {
1214                 media->desc.transport = pj_str(ast_sdp_get_rtp_profile(
1215                         /* Optimistic encryption places crypto in the normal RTP/AVP profile */
1216                         !session->endpoint->media.rtp.encryption_optimistic &&
1217                                 (session_media->encryption == AST_SIP_MEDIA_ENCRYPT_SDES),
1218                         session_media->rtp, session->endpoint->media.rtp.use_avpf,
1219                         session->endpoint->media.rtp.force_avp));
1220         }
1221
1222         /* Add connection level details */
1223         if (direct_media_enabled) {
1224                 hostip = ast_sockaddr_stringify_fmt(&session_media->direct_media_addr, AST_SOCKADDR_STR_ADDR);
1225         } else if (ast_strlen_zero(session->endpoint->media.address)) {
1226                 hostip = ast_sip_get_host_ip_string(session->endpoint->media.rtp.ipv6 ? pj_AF_INET6() : pj_AF_INET());
1227         } else {
1228                 hostip = session->endpoint->media.address;
1229         }
1230
1231         if (ast_strlen_zero(hostip)) {
1232                 ast_log(LOG_ERROR, "No local host IP available for stream %s\n", session_media->stream_type);
1233                 return -1;
1234         }
1235
1236         media->conn->net_type = STR_IN;
1237         /* Assume that the connection will use IPv4 until proven otherwise */
1238         media->conn->addr_type = STR_IP4;
1239         pj_strdup2(pool, &media->conn->addr, hostip);
1240
1241         if (!ast_strlen_zero(session->endpoint->media.address)) {
1242                 pj_sockaddr ip;
1243
1244                 if ((pj_sockaddr_parse(pj_AF_UNSPEC(), 0, &media->conn->addr, &ip) == PJ_SUCCESS) &&
1245                         (ip.addr.sa_family == pj_AF_INET6())) {
1246                         media->conn->addr_type = STR_IP6;
1247                 }
1248         }
1249
1250         ast_rtp_instance_get_local_address(session_media->rtp, &addr);
1251         media->desc.port = direct_media_enabled ? ast_sockaddr_port(&session_media->direct_media_addr) : (pj_uint16_t) ast_sockaddr_port(&addr);
1252         media->desc.port_count = 1;
1253
1254         /* Add ICE attributes and candidates */
1255         add_ice_to_stream(session, session_media, pool, media);
1256
1257         if (!(caps = ast_format_cap_alloc(AST_FORMAT_CAP_FLAG_DEFAULT))) {
1258                 ast_log(LOG_ERROR, "Failed to allocate %s capabilities\n", session_media->stream_type);
1259                 return -1;
1260         }
1261
1262         if (direct_media_enabled) {
1263                 ast_format_cap_get_compatible(session->endpoint->media.codecs, session->direct_media_cap, caps);
1264         } else if (!ast_format_cap_count(session->req_caps) ||
1265                 !ast_format_cap_iscompatible(session->req_caps, session->endpoint->media.codecs)) {
1266                 ast_format_cap_append_from_cap(caps, session->endpoint->media.codecs, media_type);
1267         } else {
1268                 ast_format_cap_append_from_cap(caps, session->req_caps, media_type);
1269         }
1270
1271         for (index = 0; index < ast_format_cap_count(caps); ++index) {
1272                 struct ast_format *format = ast_format_cap_get_format(caps, index);
1273
1274                 if (ast_format_get_type(format) != media_type) {
1275                         ao2_ref(format, -1);
1276                         continue;
1277                 }
1278
1279                 if ((rtp_code = ast_rtp_codecs_payload_code(ast_rtp_instance_get_codecs(session_media->rtp), 1, format, 0)) == -1) {
1280                         ast_log(LOG_WARNING,"Unable to get rtp codec payload code for %s\n", ast_format_get_name(format));
1281                         ao2_ref(format, -1);
1282                         continue;
1283                 }
1284
1285                 if ((attr = generate_rtpmap_attr(session, media, pool, rtp_code, 1, format, 0))) {
1286                         media->attr[media->attr_count++] = attr;
1287                 }
1288
1289                 if ((attr = generate_fmtp_attr(pool, format, rtp_code))) {
1290                         media->attr[media->attr_count++] = attr;
1291                 }
1292
1293                 if (ast_format_get_maximum_ms(format) &&
1294                         ((ast_format_get_maximum_ms(format) < max_packet_size) || !max_packet_size)) {
1295                         max_packet_size = ast_format_get_maximum_ms(format);
1296                 }
1297                 ao2_ref(format, -1);
1298
1299                 if (media->desc.fmt_count == PJMEDIA_MAX_SDP_FMT) {
1300                         break;
1301                 }
1302         }
1303
1304         /* Add non-codec formats */
1305         if (media_type != AST_MEDIA_TYPE_VIDEO && media->desc.fmt_count < PJMEDIA_MAX_SDP_FMT) {
1306                 for (index = 1LL; index <= AST_RTP_MAX; index <<= 1) {
1307                         if (!(noncodec & index)) {
1308                                 continue;
1309                         }
1310                         rtp_code = ast_rtp_codecs_payload_code(
1311                                 ast_rtp_instance_get_codecs(session_media->rtp), 0, NULL, index);
1312                         if (rtp_code == -1) {
1313                                 continue;
1314                         }
1315
1316                         if ((attr = generate_rtpmap_attr(session, media, pool, rtp_code, 0, NULL, index))) {
1317                                 media->attr[media->attr_count++] = attr;
1318                         }
1319
1320                         if (index == AST_RTP_DTMF) {
1321                                 snprintf(tmp, sizeof(tmp), "%d 0-16", rtp_code);
1322                                 attr = pjmedia_sdp_attr_create(pool, "fmtp", pj_cstr(&stmp, tmp));
1323                                 media->attr[media->attr_count++] = attr;
1324                         }
1325
1326                         if (media->desc.fmt_count == PJMEDIA_MAX_SDP_FMT) {
1327                                 break;
1328                         }
1329                 }
1330         }
1331
1332         /* If no formats were actually added to the media stream don't add it to the SDP */
1333         if (!media->desc.fmt_count) {
1334                 return 1;
1335         }
1336
1337         /* If ptime is set add it as an attribute */
1338         min_packet_size = ast_rtp_codecs_get_framing(ast_rtp_instance_get_codecs(session_media->rtp));
1339         if (!min_packet_size) {
1340                 min_packet_size = ast_format_cap_get_framing(caps);
1341         }
1342         if (min_packet_size) {
1343                 snprintf(tmp, sizeof(tmp), "%d", min_packet_size);
1344                 attr = pjmedia_sdp_attr_create(pool, "ptime", pj_cstr(&stmp, tmp));
1345                 media->attr[media->attr_count++] = attr;
1346         }
1347
1348         if (max_packet_size) {
1349                 snprintf(tmp, sizeof(tmp), "%d", max_packet_size);
1350                 attr = pjmedia_sdp_attr_create(pool, "maxptime", pj_cstr(&stmp, tmp));
1351                 media->attr[media->attr_count++] = attr;
1352         }
1353
1354         /* Add the sendrecv attribute - we purposely don't keep track because pjmedia-sdp will automatically change our offer for us */
1355         attr = PJ_POOL_ZALLOC_T(pool, pjmedia_sdp_attr);
1356         attr->name = !session_media->locally_held ? STR_SENDRECV : STR_SENDONLY;
1357         media->attr[media->attr_count++] = attr;
1358
1359         /* If we've got rtcp-mux enabled, just unconditionally offer it in all SDPs */
1360         if (session->endpoint->media.rtcp_mux) {
1361                 attr = pjmedia_sdp_attr_create(pool, "rtcp-mux", NULL);
1362                 pjmedia_sdp_attr_add(&media->attr_count, media->attr, attr);
1363         }
1364
1365         /* Add the media stream to the SDP */
1366         sdp->media[sdp->media_count++] = media;
1367
1368         return 1;
1369 }
1370
1371 static int apply_negotiated_sdp_stream(struct ast_sip_session *session, struct ast_sip_session_media *session_media,
1372                                        const struct pjmedia_sdp_session *local, const struct pjmedia_sdp_media *local_stream,
1373                                        const struct pjmedia_sdp_session *remote, const struct pjmedia_sdp_media *remote_stream)
1374 {
1375         RAII_VAR(struct ast_sockaddr *, addrs, NULL, ast_free);
1376         enum ast_media_type media_type = stream_to_media_type(session_media->stream_type);
1377         char host[NI_MAXHOST];
1378         int fdno, res;
1379
1380         if (!session->channel) {
1381                 return 1;
1382         }
1383
1384         if (!local_stream->desc.port || !remote_stream->desc.port) {
1385                 return 1;
1386         }
1387
1388         /* Ensure incoming transport is compatible with the endpoint's configuration */
1389         if (!session->endpoint->media.rtp.use_received_transport &&
1390                 check_endpoint_media_transport(session->endpoint, remote_stream) == AST_SIP_MEDIA_TRANSPORT_INVALID) {
1391                 return -1;
1392         }
1393
1394         /* Create an RTP instance if need be */
1395         if (!session_media->rtp && create_rtp(session, session_media)) {
1396                 return -1;
1397         }
1398
1399         session_media->remote_rtcp_mux = (pjmedia_sdp_media_find_attr2(remote_stream, "rtcp-mux", NULL) != NULL);
1400         set_ice_components(session, session_media);
1401
1402         enable_rtcp(session, session_media, remote_stream);
1403
1404         res = setup_media_encryption(session, session_media, remote, remote_stream);
1405         if (!session->endpoint->media.rtp.encryption_optimistic && res) {
1406                 /* If optimistic encryption is disabled and crypto should have been enabled but was not
1407                  * this session must fail.
1408                  */
1409                 return -1;
1410         }
1411
1412         if (!remote_stream->conn && !remote->conn) {
1413                 return 1;
1414         }
1415
1416         ast_copy_pj_str(host, remote_stream->conn ? &remote_stream->conn->addr : &remote->conn->addr, sizeof(host));
1417
1418         /* Ensure that the address provided is valid */
1419         if (ast_sockaddr_resolve(&addrs, host, PARSE_PORT_FORBID, AST_AF_UNSPEC) <= 0) {
1420                 /* The provided host was actually invalid so we error out this negotiation */
1421                 return -1;
1422         }
1423
1424         /* Apply connection information to the RTP instance */
1425         ast_sockaddr_set_port(addrs, remote_stream->desc.port);
1426         ast_rtp_instance_set_remote_address(session_media->rtp, addrs);
1427         if (set_caps(session, session_media, remote_stream, 0)) {
1428                 return 1;
1429         }
1430
1431         if ((fdno = media_type_to_fdno(media_type)) < 0) {
1432                 return -1;
1433         }
1434         ast_channel_set_fd(session->channel, fdno, ast_rtp_instance_fd(session_media->rtp, 0));
1435         if (!session->endpoint->media.rtcp_mux || !session_media->remote_rtcp_mux) {
1436                 ast_channel_set_fd(session->channel, fdno + 1, ast_rtp_instance_fd(session_media->rtp, 1));
1437         }
1438
1439         /* If ICE support is enabled find all the needed attributes */
1440         process_ice_attributes(session, session_media, remote, remote_stream);
1441
1442         /* Ensure the RTP instance is active */
1443         ast_rtp_instance_activate(session_media->rtp);
1444
1445         /* audio stream handles music on hold */
1446         if (media_type != AST_MEDIA_TYPE_AUDIO) {
1447                 if ((pjmedia_sdp_neg_was_answer_remote(session->inv_session->neg) == PJ_FALSE)
1448                         && (session->inv_session->state == PJSIP_INV_STATE_CONFIRMED)) {
1449                         ast_queue_control(session->channel, AST_CONTROL_UPDATE_RTP_PEER);
1450                 }
1451                 return 1;
1452         }
1453
1454         if (ast_sockaddr_isnull(addrs) ||
1455                 ast_sockaddr_is_any(addrs) ||
1456                 pjmedia_sdp_media_find_attr2(remote_stream, "sendonly", NULL) ||
1457                 pjmedia_sdp_media_find_attr2(remote_stream, "inactive", NULL)) {
1458                 if (!session_media->remotely_held) {
1459                         /* The remote side has put us on hold */
1460                         ast_queue_hold(session->channel, session->endpoint->mohsuggest);
1461                         ast_rtp_instance_stop(session_media->rtp);
1462                         ast_queue_frame(session->channel, &ast_null_frame);
1463                         session_media->remotely_held = 1;
1464                 }
1465         } else if (session_media->remotely_held) {
1466                 /* The remote side has taken us off hold */
1467                 ast_queue_unhold(session->channel);
1468                 ast_queue_frame(session->channel, &ast_null_frame);
1469                 session_media->remotely_held = 0;
1470         } else if ((pjmedia_sdp_neg_was_answer_remote(session->inv_session->neg) == PJ_FALSE)
1471                 && (session->inv_session->state == PJSIP_INV_STATE_CONFIRMED)) {
1472                 ast_queue_control(session->channel, AST_CONTROL_UPDATE_RTP_PEER);
1473         }
1474
1475         /* This purposely resets the encryption to the configured in case it gets added later */
1476         session_media->encryption = session->endpoint->media.rtp.encryption;
1477
1478         if (session->endpoint->media.rtp.keepalive > 0 &&
1479                         stream_to_media_type(session_media->stream_type) == AST_MEDIA_TYPE_AUDIO) {
1480                 ast_rtp_instance_set_keepalive(session_media->rtp, session->endpoint->media.rtp.keepalive);
1481                 /* Schedule the initial keepalive early in case this is being used to punch holes through
1482                  * a NAT. This way there won't be an awkward delay before media starts flowing in some
1483                  * scenarios.
1484                  */
1485                 AST_SCHED_DEL(sched, session_media->keepalive_sched_id);
1486                 session_media->keepalive_sched_id = ast_sched_add_variable(sched, 500, send_keepalive,
1487                         session_media, 1);
1488         }
1489
1490         /* As the channel lock is not held during this process the scheduled item won't block if
1491          * it is hanging up the channel at the same point we are applying this negotiated SDP.
1492          */
1493         AST_SCHED_DEL(sched, session_media->timeout_sched_id);
1494
1495         /* Due to the fact that we only ever have one scheduled timeout item for when we are both
1496          * off hold and on hold we don't need to store the two timeouts differently on the RTP
1497          * instance itself.
1498          */
1499         ast_rtp_instance_set_timeout(session_media->rtp, 0);
1500         if (session->endpoint->media.rtp.timeout && !session_media->remotely_held) {
1501                 ast_rtp_instance_set_timeout(session_media->rtp, session->endpoint->media.rtp.timeout);
1502         } else if (session->endpoint->media.rtp.timeout_hold && session_media->remotely_held) {
1503                 ast_rtp_instance_set_timeout(session_media->rtp, session->endpoint->media.rtp.timeout_hold);
1504         }
1505
1506         if (ast_rtp_instance_get_timeout(session_media->rtp)) {
1507                 session_media->timeout_sched_id = ast_sched_add_variable(sched,
1508                         ast_rtp_instance_get_timeout(session_media->rtp) * 1000, rtp_check_timeout,
1509                         session_media, 1);
1510         }
1511
1512         return 1;
1513 }
1514
1515 /*! \brief Function which updates the media stream with external media address, if applicable */
1516 static void change_outgoing_sdp_stream_media_address(pjsip_tx_data *tdata, struct pjmedia_sdp_media *stream, struct ast_sip_transport *transport)
1517 {
1518         RAII_VAR(struct ast_sip_transport_state *, transport_state, ast_sip_get_transport_state(ast_sorcery_object_get_id(transport)), ao2_cleanup);
1519         char host[NI_MAXHOST];
1520         struct ast_sockaddr addr = { { 0, } };
1521
1522         /* If the stream has been rejected there will be no connection line */
1523         if (!stream->conn || !transport_state) {
1524                 return;
1525         }
1526
1527         ast_copy_pj_str(host, &stream->conn->addr, sizeof(host));
1528         ast_sockaddr_parse(&addr, host, PARSE_PORT_FORBID);
1529
1530         /* Is the address within the SDP inside the same network? */
1531         if (transport_state->localnet
1532                 && ast_apply_ha(transport_state->localnet, &addr) == AST_SENSE_ALLOW) {
1533                 return;
1534         }
1535         ast_debug(5, "Setting media address to %s\n", transport->external_media_address);
1536         pj_strdup2(tdata->pool, &stream->conn->addr, transport->external_media_address);
1537 }
1538
1539 /*! \brief Function which stops the RTP instance */
1540 static void stream_stop(struct ast_sip_session_media *session_media)
1541 {
1542         if (!session_media->rtp) {
1543                 return;
1544         }
1545
1546         AST_SCHED_DEL(sched, session_media->keepalive_sched_id);
1547         AST_SCHED_DEL(sched, session_media->timeout_sched_id);
1548         ast_rtp_instance_stop(session_media->rtp);
1549 }
1550
1551 /*! \brief Function which destroys the RTP instance when session ends */
1552 static void stream_destroy(struct ast_sip_session_media *session_media)
1553 {
1554         if (session_media->rtp) {
1555                 stream_stop(session_media);
1556                 ast_rtp_instance_destroy(session_media->rtp);
1557         }
1558         session_media->rtp = NULL;
1559 }
1560
1561 /*! \brief SDP handler for 'audio' media stream */
1562 static struct ast_sip_session_sdp_handler audio_sdp_handler = {
1563         .id = STR_AUDIO,
1564         .negotiate_incoming_sdp_stream = negotiate_incoming_sdp_stream,
1565         .create_outgoing_sdp_stream = create_outgoing_sdp_stream,
1566         .apply_negotiated_sdp_stream = apply_negotiated_sdp_stream,
1567         .change_outgoing_sdp_stream_media_address = change_outgoing_sdp_stream_media_address,
1568         .stream_stop = stream_stop,
1569         .stream_destroy = stream_destroy,
1570 };
1571
1572 /*! \brief SDP handler for 'video' media stream */
1573 static struct ast_sip_session_sdp_handler video_sdp_handler = {
1574         .id = STR_VIDEO,
1575         .negotiate_incoming_sdp_stream = negotiate_incoming_sdp_stream,
1576         .create_outgoing_sdp_stream = create_outgoing_sdp_stream,
1577         .apply_negotiated_sdp_stream = apply_negotiated_sdp_stream,
1578         .change_outgoing_sdp_stream_media_address = change_outgoing_sdp_stream_media_address,
1579         .stream_stop = stream_stop,
1580         .stream_destroy = stream_destroy,
1581 };
1582
1583 static int video_info_incoming_request(struct ast_sip_session *session, struct pjsip_rx_data *rdata)
1584 {
1585         struct pjsip_transaction *tsx;
1586         pjsip_tx_data *tdata;
1587
1588         if (!session->channel
1589                 || !ast_sip_is_content_type(&rdata->msg_info.msg->body->content_type,
1590                         "application",
1591                         "media_control+xml")) {
1592                 return 0;
1593         }
1594
1595         tsx = pjsip_rdata_get_tsx(rdata);
1596
1597         ast_queue_control(session->channel, AST_CONTROL_VIDUPDATE);
1598
1599         if (pjsip_dlg_create_response(session->inv_session->dlg, rdata, 200, NULL, &tdata) == PJ_SUCCESS) {
1600                 pjsip_dlg_send_response(session->inv_session->dlg, tsx, tdata);
1601         }
1602
1603         return 0;
1604 }
1605
1606 static struct ast_sip_session_supplement video_info_supplement = {
1607         .method = "INFO",
1608         .incoming_request = video_info_incoming_request,
1609 };
1610
1611 /*! \brief Unloads the sdp RTP/AVP module from Asterisk */
1612 static int unload_module(void)
1613 {
1614         ast_sip_session_unregister_supplement(&video_info_supplement);
1615         ast_sip_session_unregister_sdp_handler(&video_sdp_handler, STR_VIDEO);
1616         ast_sip_session_unregister_sdp_handler(&audio_sdp_handler, STR_AUDIO);
1617
1618         if (sched) {
1619                 ast_sched_context_destroy(sched);
1620         }
1621
1622         return 0;
1623 }
1624
1625 /*!
1626  * \brief Load the module
1627  *
1628  * Module loading including tests for configuration or dependencies.
1629  * This function can return AST_MODULE_LOAD_FAILURE, AST_MODULE_LOAD_DECLINE,
1630  * or AST_MODULE_LOAD_SUCCESS. If a dependency or environment variable fails
1631  * tests return AST_MODULE_LOAD_FAILURE. If the module can not load the
1632  * configuration file or other non-critical problem return
1633  * AST_MODULE_LOAD_DECLINE. On success return AST_MODULE_LOAD_SUCCESS.
1634  */
1635 static int load_module(void)
1636 {
1637         CHECK_PJSIP_SESSION_MODULE_LOADED();
1638
1639         if (ast_check_ipv6()) {
1640                 ast_sockaddr_parse(&address_rtp, "::", 0);
1641         } else {
1642                 ast_sockaddr_parse(&address_rtp, "0.0.0.0", 0);
1643         }
1644
1645         if (!(sched = ast_sched_context_create())) {
1646                 ast_log(LOG_ERROR, "Unable to create scheduler context.\n");
1647                 goto end;
1648         }
1649
1650         if (ast_sched_start_thread(sched)) {
1651                 ast_log(LOG_ERROR, "Unable to create scheduler context thread.\n");
1652                 goto end;
1653         }
1654
1655         if (ast_sip_session_register_sdp_handler(&audio_sdp_handler, STR_AUDIO)) {
1656                 ast_log(LOG_ERROR, "Unable to register SDP handler for %s stream type\n", STR_AUDIO);
1657                 goto end;
1658         }
1659
1660         if (ast_sip_session_register_sdp_handler(&video_sdp_handler, STR_VIDEO)) {
1661                 ast_log(LOG_ERROR, "Unable to register SDP handler for %s stream type\n", STR_VIDEO);
1662                 goto end;
1663         }
1664
1665         ast_sip_session_register_supplement(&video_info_supplement);
1666
1667         return AST_MODULE_LOAD_SUCCESS;
1668 end:
1669         unload_module();
1670
1671         return AST_MODULE_LOAD_DECLINE;
1672 }
1673
1674 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_LOAD_ORDER, "PJSIP SDP RTP/AVP stream handler",
1675         .support_level = AST_MODULE_SUPPORT_CORE,
1676         .load = load_module,
1677         .unload = unload_module,
1678         .load_pri = AST_MODPRI_CHANNEL_DRIVER,
1679 );