Removing registrar_expire from basic-pbx config
[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 #include "asterisk/stream.h"
55 #include "asterisk/format_cache.h"
56
57 #include "asterisk/res_pjsip.h"
58 #include "asterisk/res_pjsip_session.h"
59
60 /*! \brief Scheduler for RTCP purposes */
61 static struct ast_sched_context *sched;
62
63 /*! \brief Address for RTP */
64 static struct ast_sockaddr address_rtp;
65
66 static const char STR_AUDIO[] = "audio";
67 static const char STR_VIDEO[] = "video";
68
69 static int send_keepalive(const void *data)
70 {
71         struct ast_sip_session_media *session_media = (struct ast_sip_session_media *) data;
72         struct ast_rtp_instance *rtp = session_media->rtp;
73         int keepalive;
74         time_t interval;
75         int send_keepalive;
76
77         if (!rtp) {
78                 return 0;
79         }
80
81         keepalive = ast_rtp_instance_get_keepalive(rtp);
82
83         if (!ast_sockaddr_isnull(&session_media->direct_media_addr)) {
84                 ast_debug(3, "Not sending RTP keepalive on RTP instance %p since direct media is in use\n", rtp);
85                 return keepalive * 1000;
86         }
87
88         interval = time(NULL) - ast_rtp_instance_get_last_tx(rtp);
89         send_keepalive = interval >= keepalive;
90
91         ast_debug(3, "It has been %d seconds since RTP was last sent on instance %p. %sending keepalive\n",
92                         (int) interval, rtp, send_keepalive ? "S" : "Not s");
93
94         if (send_keepalive) {
95                 ast_rtp_instance_sendcng(rtp, 0);
96                 return keepalive * 1000;
97         }
98
99         return (keepalive - interval) * 1000;
100 }
101
102 /*! \brief Check whether RTP is being received or not */
103 static int rtp_check_timeout(const void *data)
104 {
105         struct ast_sip_session_media *session_media = (struct ast_sip_session_media *)data;
106         struct ast_rtp_instance *rtp = session_media->rtp;
107         int elapsed;
108         struct ast_channel *chan;
109
110         if (!rtp) {
111                 return 0;
112         }
113
114         elapsed = time(NULL) - ast_rtp_instance_get_last_rx(rtp);
115         if (elapsed < ast_rtp_instance_get_timeout(rtp)) {
116                 return (ast_rtp_instance_get_timeout(rtp) - elapsed) * 1000;
117         }
118
119         chan = ast_channel_get_by_name(ast_rtp_instance_get_channel_id(rtp));
120         if (!chan) {
121                 return 0;
122         }
123
124         ast_log(LOG_NOTICE, "Disconnecting channel '%s' for lack of RTP activity in %d seconds\n",
125                 ast_channel_name(chan), elapsed);
126
127         ast_channel_lock(chan);
128         ast_channel_hangupcause_set(chan, AST_CAUSE_REQUESTED_CHAN_UNAVAIL);
129         ast_channel_unlock(chan);
130
131         ast_softhangup(chan, AST_SOFTHANGUP_DEV);
132         ast_channel_unref(chan);
133
134         return 0;
135 }
136
137 /*!
138  * \brief Enable RTCP on an RTP session.
139  */
140 static void enable_rtcp(struct ast_sip_session *session, struct ast_sip_session_media *session_media,
141         const struct pjmedia_sdp_media *remote_media)
142 {
143         enum ast_rtp_instance_rtcp rtcp_type;
144
145         if (session->endpoint->media.rtcp_mux && session_media->remote_rtcp_mux) {
146                 rtcp_type = AST_RTP_INSTANCE_RTCP_MUX;
147         } else {
148                 rtcp_type = AST_RTP_INSTANCE_RTCP_STANDARD;
149         }
150
151         ast_rtp_instance_set_prop(session_media->rtp, AST_RTP_PROPERTY_RTCP, rtcp_type);
152 }
153
154 /*!
155  * \brief Enable an RTP extension on an RTP session.
156  */
157 static void enable_rtp_extension(struct ast_sip_session *session, struct ast_sip_session_media *session_media,
158         enum ast_rtp_extension extension, enum ast_rtp_extension_direction direction,
159         const pjmedia_sdp_session *sdp)
160 {
161         int id = -1;
162
163         /* For a bundle group the local unique identifier space is shared across all streams within
164          * it.
165          */
166         if (session_media->bundle_group != -1) {
167                 int index;
168
169                 for (index = 0; index < sdp->media_count; ++index) {
170                         struct ast_sip_session_media *other_session_media;
171                         int other_id;
172
173                         if (index >= AST_VECTOR_SIZE(&session->pending_media_state->sessions)) {
174                                 break;
175                         }
176
177                         other_session_media = AST_VECTOR_GET(&session->pending_media_state->sessions, index);
178                         if (!other_session_media->rtp || other_session_media->bundle_group != session_media->bundle_group) {
179                                 continue;
180                         }
181
182                         other_id = ast_rtp_instance_extmap_get_id(other_session_media->rtp, extension);
183                         if (other_id == -1) {
184                                 /* Worst case we have to fall back to the highest available free local unique identifier
185                                  * for the bundle group.
186                                  */
187                                 other_id = ast_rtp_instance_extmap_count(other_session_media->rtp) + 1;
188                                 if (id < other_id) {
189                                         id = other_id;
190                                 }
191                                 continue;
192                         }
193
194                         id = other_id;
195                         break;
196                 }
197         }
198
199         ast_rtp_instance_extmap_enable(session_media->rtp, id, extension, direction);
200 }
201
202 /*! \brief Internal function which creates an RTP instance */
203 static int create_rtp(struct ast_sip_session *session, struct ast_sip_session_media *session_media,
204         const pjmedia_sdp_session *sdp)
205 {
206         struct ast_rtp_engine_ice *ice;
207         struct ast_sockaddr temp_media_address;
208         struct ast_sockaddr *media_address =  &address_rtp;
209
210         if (session->endpoint->media.bind_rtp_to_media_address && !ast_strlen_zero(session->endpoint->media.address)) {
211                 if (ast_sockaddr_parse(&temp_media_address, session->endpoint->media.address, 0)) {
212                         ast_debug(1, "Endpoint %s: Binding RTP media to %s\n",
213                                 ast_sorcery_object_get_id(session->endpoint),
214                                 session->endpoint->media.address);
215                         media_address = &temp_media_address;
216                 } else {
217                         ast_debug(1, "Endpoint %s: RTP media address invalid: %s\n",
218                                 ast_sorcery_object_get_id(session->endpoint),
219                                 session->endpoint->media.address);
220                 }
221         } else {
222                 struct ast_sip_transport *transport;
223
224                 transport = ast_sorcery_retrieve_by_id(ast_sip_get_sorcery(), "transport",
225                         session->endpoint->transport);
226                 if (transport) {
227                         struct ast_sip_transport_state *trans_state;
228
229                         trans_state = ast_sip_get_transport_state(ast_sorcery_object_get_id(transport));
230                         if (trans_state) {
231                                 char hoststr[PJ_INET6_ADDRSTRLEN];
232
233                                 pj_sockaddr_print(&trans_state->host, hoststr, sizeof(hoststr), 0);
234                                 if (ast_sockaddr_parse(&temp_media_address, hoststr, 0)) {
235                                         ast_debug(1, "Transport %s bound to %s: Using it for RTP media.\n",
236                                                 session->endpoint->transport, hoststr);
237                                         media_address = &temp_media_address;
238                                 } else {
239                                         ast_debug(1, "Transport %s bound to %s: Invalid for RTP media.\n",
240                                                 session->endpoint->transport, hoststr);
241                                 }
242                                 ao2_ref(trans_state, -1);
243                         }
244                         ao2_ref(transport, -1);
245                 }
246         }
247
248         if (!(session_media->rtp = ast_rtp_instance_new(session->endpoint->media.rtp.engine, sched, media_address, NULL))) {
249                 ast_log(LOG_ERROR, "Unable to create RTP instance using RTP engine '%s'\n", session->endpoint->media.rtp.engine);
250                 return -1;
251         }
252
253         ast_rtp_instance_set_prop(session_media->rtp, AST_RTP_PROPERTY_NAT, session->endpoint->media.rtp.symmetric);
254         ast_rtp_instance_set_prop(session_media->rtp, AST_RTP_PROPERTY_ASYMMETRIC_CODEC, session->endpoint->asymmetric_rtp_codec);
255
256         if (!session->endpoint->media.rtp.ice_support && (ice = ast_rtp_instance_get_ice(session_media->rtp))) {
257                 ice->stop(session_media->rtp);
258         }
259
260         if (session->dtmf == AST_SIP_DTMF_RFC_4733 || session->dtmf == AST_SIP_DTMF_AUTO || session->dtmf == AST_SIP_DTMF_AUTO_INFO) {
261                 ast_rtp_instance_dtmf_mode_set(session_media->rtp, AST_RTP_DTMF_MODE_RFC2833);
262                 ast_rtp_instance_set_prop(session_media->rtp, AST_RTP_PROPERTY_DTMF, 1);
263         } else if (session->dtmf == AST_SIP_DTMF_INBAND) {
264                 ast_rtp_instance_dtmf_mode_set(session_media->rtp, AST_RTP_DTMF_MODE_INBAND);
265         }
266
267         if (session_media->type == AST_MEDIA_TYPE_AUDIO &&
268                         (session->endpoint->media.tos_audio || session->endpoint->media.cos_audio)) {
269                 ast_rtp_instance_set_qos(session_media->rtp, session->endpoint->media.tos_audio,
270                                 session->endpoint->media.cos_audio, "SIP RTP Audio");
271         } else if (session_media->type == AST_MEDIA_TYPE_VIDEO) {
272                 ast_rtp_instance_set_prop(session_media->rtp, AST_RTP_PROPERTY_RETRANS_RECV, session->endpoint->media.webrtc);
273                 ast_rtp_instance_set_prop(session_media->rtp, AST_RTP_PROPERTY_RETRANS_SEND, session->endpoint->media.webrtc);
274                 ast_rtp_instance_set_prop(session_media->rtp, AST_RTP_PROPERTY_REMB, session->endpoint->media.webrtc);
275                 enable_rtp_extension(session, session_media, AST_RTP_EXTENSION_ABS_SEND_TIME, AST_RTP_EXTENSION_DIRECTION_SENDRECV, sdp);
276                 if (session->endpoint->media.tos_video || session->endpoint->media.cos_video) {
277                         ast_rtp_instance_set_qos(session_media->rtp, session->endpoint->media.tos_video,
278                                         session->endpoint->media.cos_video, "SIP RTP Video");
279                 }
280         }
281
282         ast_rtp_instance_set_last_rx(session_media->rtp, time(NULL));
283
284         return 0;
285 }
286
287 static void get_codecs(struct ast_sip_session *session, const struct pjmedia_sdp_media *stream, struct ast_rtp_codecs *codecs,
288         struct ast_sip_session_media *session_media)
289 {
290         pjmedia_sdp_attr *attr;
291         pjmedia_sdp_rtpmap *rtpmap;
292         pjmedia_sdp_fmtp fmtp;
293         struct ast_format *format;
294         int i, num = 0, tel_event = 0;
295         char name[256];
296         char media[20];
297         char fmt_param[256];
298         enum ast_rtp_options options = session->endpoint->media.g726_non_standard ?
299                 AST_RTP_OPT_G726_NONSTANDARD : 0;
300
301         ast_rtp_codecs_payloads_initialize(codecs);
302
303         /* Iterate through provided formats */
304         for (i = 0; i < stream->desc.fmt_count; ++i) {
305                 /* The payload is kept as a string for things like t38 but for video it is always numerical */
306                 ast_rtp_codecs_payloads_set_m_type(codecs, NULL, pj_strtoul(&stream->desc.fmt[i]));
307                 /* Look for the optional rtpmap attribute */
308                 if (!(attr = pjmedia_sdp_media_find_attr2(stream, "rtpmap", &stream->desc.fmt[i]))) {
309                         continue;
310                 }
311
312                 /* Interpret the attribute as an rtpmap */
313                 if ((pjmedia_sdp_attr_to_rtpmap(session->inv_session->pool_prov, attr, &rtpmap)) != PJ_SUCCESS) {
314                         continue;
315                 }
316
317                 ast_copy_pj_str(name, &rtpmap->enc_name, sizeof(name));
318                 if (strcmp(name, "telephone-event") == 0) {
319                         tel_event++;
320                 }
321
322                 ast_copy_pj_str(media, (pj_str_t*)&stream->desc.media, sizeof(media));
323                 ast_rtp_codecs_payloads_set_rtpmap_type_rate(codecs, NULL,
324                         pj_strtoul(&stream->desc.fmt[i]), media, name, options, rtpmap->clock_rate);
325                 /* Look for an optional associated fmtp attribute */
326                 if (!(attr = pjmedia_sdp_media_find_attr2(stream, "fmtp", &rtpmap->pt))) {
327                         continue;
328                 }
329
330                 if ((pjmedia_sdp_attr_get_fmtp(attr, &fmtp)) == PJ_SUCCESS) {
331                         ast_copy_pj_str(fmt_param, &fmtp.fmt, sizeof(fmt_param));
332                         if (sscanf(fmt_param, "%30d", &num) != 1) {
333                                 continue;
334                         }
335
336                         if ((format = ast_rtp_codecs_get_payload_format(codecs, num))) {
337                                 struct ast_format *format_parsed;
338
339                                 ast_copy_pj_str(fmt_param, &fmtp.fmt_param, sizeof(fmt_param));
340
341                                 format_parsed = ast_format_parse_sdp_fmtp(format, fmt_param);
342                                 if (format_parsed) {
343                                         ast_rtp_codecs_payload_replace_format(codecs, num, format_parsed);
344                                         ao2_ref(format_parsed, -1);
345                                 }
346
347                                 ao2_ref(format, -1);
348                         }
349                 }
350         }
351         if (!tel_event && (session->dtmf == AST_SIP_DTMF_AUTO)) {
352                 ast_rtp_instance_dtmf_mode_set(session_media->rtp, AST_RTP_DTMF_MODE_INBAND);
353         }
354
355         if (session->dtmf == AST_SIP_DTMF_AUTO_INFO) {
356                 if  (tel_event) {
357                         ast_rtp_instance_dtmf_mode_set(session_media->rtp, AST_RTP_DTMF_MODE_RFC2833);
358                 } else {
359                         ast_rtp_instance_dtmf_mode_set(session_media->rtp, AST_RTP_DTMF_MODE_NONE);
360                 }
361         }
362
363
364         /* Get the packetization, if it exists */
365         if ((attr = pjmedia_sdp_media_find_attr2(stream, "ptime", NULL))) {
366                 unsigned long framing = pj_strtoul(pj_strltrim(&attr->value));
367                 if (framing && session->endpoint->media.rtp.use_ptime) {
368                         ast_rtp_codecs_set_framing(codecs, framing);
369                 }
370         }
371 }
372
373 static int set_caps(struct ast_sip_session *session,
374         struct ast_sip_session_media *session_media,
375         struct ast_sip_session_media *session_media_transport,
376         const struct pjmedia_sdp_media *stream,
377         int is_offer, struct ast_stream *asterisk_stream)
378 {
379         RAII_VAR(struct ast_format_cap *, caps, NULL, ao2_cleanup);
380         RAII_VAR(struct ast_format_cap *, peer, NULL, ao2_cleanup);
381         RAII_VAR(struct ast_format_cap *, joint, NULL, ao2_cleanup);
382         RAII_VAR(struct ast_format_cap *, endpoint_caps, NULL, ao2_cleanup);
383         enum ast_media_type media_type = session_media->type;
384         struct ast_rtp_codecs codecs = AST_RTP_CODECS_NULL_INIT;
385         int fmts = 0;
386         int direct_media_enabled = !ast_sockaddr_isnull(&session_media->direct_media_addr) &&
387                 ast_format_cap_count(session->direct_media_cap);
388         int dsp_features = 0;
389
390         if (!(caps = ast_format_cap_alloc(AST_FORMAT_CAP_FLAG_DEFAULT)) ||
391             !(peer = ast_format_cap_alloc(AST_FORMAT_CAP_FLAG_DEFAULT)) ||
392             !(joint = ast_format_cap_alloc(AST_FORMAT_CAP_FLAG_DEFAULT))) {
393                 ast_log(LOG_ERROR, "Failed to allocate %s capabilities\n",
394                         ast_codec_media_type2str(session_media->type));
395                 return -1;
396         }
397
398         /* get the endpoint capabilities */
399         if (direct_media_enabled) {
400                 ast_format_cap_get_compatible(session->endpoint->media.codecs, session->direct_media_cap, caps);
401         } else {
402                 ast_format_cap_append_from_cap(caps, session->endpoint->media.codecs, media_type);
403         }
404
405         /* get the capabilities on the peer */
406         get_codecs(session, stream, &codecs,  session_media);
407         ast_rtp_codecs_payload_formats(&codecs, peer, &fmts);
408
409         /* get the joint capabilities between peer and endpoint */
410         ast_format_cap_get_compatible(caps, peer, joint);
411         if (!ast_format_cap_count(joint)) {
412                 struct ast_str *usbuf = ast_str_alloca(AST_FORMAT_CAP_NAMES_LEN);
413                 struct ast_str *thembuf = ast_str_alloca(AST_FORMAT_CAP_NAMES_LEN);
414
415                 ast_rtp_codecs_payloads_destroy(&codecs);
416                 ast_log(LOG_NOTICE, "No joint capabilities for '%s' media stream between our configuration(%s) and incoming SDP(%s)\n",
417                         ast_codec_media_type2str(session_media->type),
418                         ast_format_cap_get_names(caps, &usbuf),
419                         ast_format_cap_get_names(peer, &thembuf));
420                 return -1;
421         }
422
423         if (is_offer) {
424                 /*
425                  * Setup rx payload type mapping to prefer the mapping
426                  * from the peer that the RFC says we SHOULD use.
427                  */
428                 ast_rtp_codecs_payloads_xover(&codecs, &codecs, NULL);
429         }
430         ast_rtp_codecs_payloads_copy(&codecs, ast_rtp_instance_get_codecs(session_media->rtp),
431                 session_media->rtp);
432
433         ast_stream_set_formats(asterisk_stream, joint);
434
435         /* If this is a bundled stream then apply the payloads to RTP instance acting as transport to prevent conflicts */
436         if (session_media_transport != session_media && session_media->bundled) {
437                 int index;
438
439                 for (index = 0; index < ast_format_cap_count(joint); ++index) {
440                         struct ast_format *format = ast_format_cap_get_format(joint, index);
441                         int rtp_code;
442
443                         /* Ensure this payload is in the bundle group transport codecs, this purposely doesn't check the return value for
444                          * things as the format is guaranteed to have a payload already.
445                          */
446                         rtp_code = ast_rtp_codecs_payload_code(ast_rtp_instance_get_codecs(session_media->rtp), 1, format, 0);
447                         ast_rtp_codecs_payload_set_rx(ast_rtp_instance_get_codecs(session_media_transport->rtp), rtp_code, format);
448
449                         ao2_ref(format, -1);
450                 }
451         }
452
453         if (session->channel && ast_sip_session_is_pending_stream_default(session, asterisk_stream)) {
454                 ast_channel_lock(session->channel);
455                 ast_format_cap_remove_by_type(caps, AST_MEDIA_TYPE_UNKNOWN);
456                 ast_format_cap_append_from_cap(caps, ast_channel_nativeformats(session->channel),
457                         AST_MEDIA_TYPE_UNKNOWN);
458                 ast_format_cap_remove_by_type(caps, media_type);
459
460                 if (session->endpoint->preferred_codec_only){
461                         struct ast_format *preferred_fmt = ast_format_cap_get_format(joint, 0);
462                         ast_format_cap_append(caps, preferred_fmt, 0);
463                         ao2_ref(preferred_fmt, -1);
464                 } else if (!session->endpoint->asymmetric_rtp_codec) {
465                         struct ast_format *best;
466                         /*
467                          * If we don't allow the sending codec to be changed on our side
468                          * then get the best codec from the joint capabilities of the media
469                          * type and use only that. This ensures the core won't start sending
470                          * out a format that we aren't currently sending.
471                          */
472
473                         best = ast_format_cap_get_best_by_type(joint, media_type);
474                         if (best) {
475                                 ast_format_cap_append(caps, best, ast_format_cap_get_framing(joint));
476                                 ao2_ref(best, -1);
477                         }
478                 } else {
479                         ast_format_cap_append_from_cap(caps, joint, media_type);
480                 }
481
482                 /*
483                  * Apply the new formats to the channel, potentially changing
484                  * raw read/write formats and translation path while doing so.
485                  */
486                 ast_channel_nativeformats_set(session->channel, caps);
487                 if (media_type == AST_MEDIA_TYPE_AUDIO) {
488                         ast_set_read_format(session->channel, ast_channel_readformat(session->channel));
489                         ast_set_write_format(session->channel, ast_channel_writeformat(session->channel));
490                 }
491
492                 if ( ((session->dtmf == AST_SIP_DTMF_AUTO) || (session->dtmf == AST_SIP_DTMF_AUTO_INFO) )
493                     && (ast_rtp_instance_dtmf_mode_get(session_media->rtp) == AST_RTP_DTMF_MODE_RFC2833)
494                     && (session->dsp)) {
495                         dsp_features = ast_dsp_get_features(session->dsp);
496                         dsp_features &= ~DSP_FEATURE_DIGIT_DETECT;
497                         if (dsp_features) {
498                                 ast_dsp_set_features(session->dsp, dsp_features);
499                         } else {
500                                 ast_dsp_free(session->dsp);
501                                 session->dsp = NULL;
502                         }
503                 }
504
505                 if (ast_channel_is_bridged(session->channel)) {
506                         ast_channel_set_unbridged_nolock(session->channel, 1);
507                 }
508
509                 ast_channel_unlock(session->channel);
510         }
511
512         ast_rtp_codecs_payloads_destroy(&codecs);
513         return 0;
514 }
515
516 static pjmedia_sdp_attr* generate_rtpmap_attr(struct ast_sip_session *session, pjmedia_sdp_media *media, pj_pool_t *pool,
517                                               int rtp_code, int asterisk_format, struct ast_format *format, int code)
518 {
519 #ifndef HAVE_PJSIP_ENDPOINT_COMPACT_FORM
520         extern pj_bool_t pjsip_use_compact_form;
521 #else
522         pj_bool_t pjsip_use_compact_form = pjsip_cfg()->endpt.use_compact_form;
523 #endif
524         pjmedia_sdp_rtpmap rtpmap;
525         pjmedia_sdp_attr *attr = NULL;
526         char tmp[64];
527         enum ast_rtp_options options = session->endpoint->media.g726_non_standard ?
528                 AST_RTP_OPT_G726_NONSTANDARD : 0;
529
530         snprintf(tmp, sizeof(tmp), "%d", rtp_code);
531         pj_strdup2(pool, &media->desc.fmt[media->desc.fmt_count++], tmp);
532
533         if (rtp_code <= AST_RTP_PT_LAST_STATIC && pjsip_use_compact_form) {
534                 return NULL;
535         }
536
537         rtpmap.pt = media->desc.fmt[media->desc.fmt_count - 1];
538         rtpmap.clock_rate = ast_rtp_lookup_sample_rate2(asterisk_format, format, code);
539         pj_strdup2(pool, &rtpmap.enc_name, ast_rtp_lookup_mime_subtype2(asterisk_format, format, code, options));
540         if (!pj_stricmp2(&rtpmap.enc_name, "opus")) {
541                 pj_cstr(&rtpmap.param, "2");
542         } else {
543                 pj_cstr(&rtpmap.param, NULL);
544         }
545
546         pjmedia_sdp_rtpmap_to_attr(pool, &rtpmap, &attr);
547
548         return attr;
549 }
550
551 static pjmedia_sdp_attr* generate_fmtp_attr(pj_pool_t *pool, struct ast_format *format, int rtp_code)
552 {
553         struct ast_str *fmtp0 = ast_str_alloca(256);
554         pj_str_t fmtp1;
555         pjmedia_sdp_attr *attr = NULL;
556         char *tmp;
557
558         ast_format_generate_sdp_fmtp(format, rtp_code, &fmtp0);
559         if (ast_str_strlen(fmtp0)) {
560                 tmp = ast_str_buffer(fmtp0) + ast_str_strlen(fmtp0) - 1;
561                 /* remove any carriage return line feeds */
562                 while (*tmp == '\r' || *tmp == '\n') --tmp;
563                 *++tmp = '\0';
564                 /* ast...generate gives us everything, just need value */
565                 tmp = strchr(ast_str_buffer(fmtp0), ':');
566                 if (tmp && tmp[1] != '\0') {
567                         fmtp1 = pj_str(tmp + 1);
568                 } else {
569                         fmtp1 = pj_str(ast_str_buffer(fmtp0));
570                 }
571                 attr = pjmedia_sdp_attr_create(pool, "fmtp", &fmtp1);
572         }
573         return attr;
574 }
575
576 /*! \brief Function which adds ICE attributes to a media stream */
577 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,
578         unsigned int include_candidates)
579 {
580         struct ast_rtp_engine_ice *ice;
581         struct ao2_container *candidates;
582         const char *username, *password;
583         pj_str_t stmp;
584         pjmedia_sdp_attr *attr;
585         struct ao2_iterator it_candidates;
586         struct ast_rtp_engine_ice_candidate *candidate;
587
588         if (!session->endpoint->media.rtp.ice_support || !(ice = ast_rtp_instance_get_ice(session_media->rtp))) {
589                 return;
590         }
591
592         if (!session_media->remote_ice) {
593                 return;
594         }
595
596         if ((username = ice->get_ufrag(session_media->rtp))) {
597                 attr = pjmedia_sdp_attr_create(pool, "ice-ufrag", pj_cstr(&stmp, username));
598                 media->attr[media->attr_count++] = attr;
599         }
600
601         if ((password = ice->get_password(session_media->rtp))) {
602                 attr = pjmedia_sdp_attr_create(pool, "ice-pwd", pj_cstr(&stmp, password));
603                 media->attr[media->attr_count++] = attr;
604         }
605
606         if (!include_candidates) {
607                 return;
608         }
609
610         candidates = ice->get_local_candidates(session_media->rtp);
611         if (!candidates) {
612                 return;
613         }
614
615         it_candidates = ao2_iterator_init(candidates, 0);
616         for (; (candidate = ao2_iterator_next(&it_candidates)); ao2_ref(candidate, -1)) {
617                 struct ast_str *attr_candidate = ast_str_create(128);
618
619                 ast_str_set(&attr_candidate, -1, "%s %u %s %d %s ", candidate->foundation, candidate->id, candidate->transport,
620                                         candidate->priority, ast_sockaddr_stringify_addr_remote(&candidate->address));
621                 ast_str_append(&attr_candidate, -1, "%s typ ", ast_sockaddr_stringify_port(&candidate->address));
622
623                 switch (candidate->type) {
624                         case AST_RTP_ICE_CANDIDATE_TYPE_HOST:
625                                 ast_str_append(&attr_candidate, -1, "host");
626                                 break;
627                         case AST_RTP_ICE_CANDIDATE_TYPE_SRFLX:
628                                 ast_str_append(&attr_candidate, -1, "srflx");
629                                 break;
630                         case AST_RTP_ICE_CANDIDATE_TYPE_RELAYED:
631                                 ast_str_append(&attr_candidate, -1, "relay");
632                                 break;
633                 }
634
635                 if (!ast_sockaddr_isnull(&candidate->relay_address)) {
636                         ast_str_append(&attr_candidate, -1, " raddr %s rport", ast_sockaddr_stringify_addr_remote(&candidate->relay_address));
637                         ast_str_append(&attr_candidate, -1, " %s", ast_sockaddr_stringify_port(&candidate->relay_address));
638                 }
639
640                 attr = pjmedia_sdp_attr_create(pool, "candidate", pj_cstr(&stmp, ast_str_buffer(attr_candidate)));
641                 media->attr[media->attr_count++] = attr;
642
643                 ast_free(attr_candidate);
644         }
645
646         ao2_iterator_destroy(&it_candidates);
647         ao2_ref(candidates, -1);
648 }
649
650 /*! \brief Function which checks for ice attributes in an audio stream */
651 static void check_ice_support(struct ast_sip_session *session, struct ast_sip_session_media *session_media,
652                                    const struct pjmedia_sdp_media *remote_stream)
653 {
654         struct ast_rtp_engine_ice *ice;
655         const pjmedia_sdp_attr *attr;
656         unsigned int attr_i;
657
658         if (!session->endpoint->media.rtp.ice_support || !(ice = ast_rtp_instance_get_ice(session_media->rtp))) {
659                 session_media->remote_ice = 0;
660                 return;
661         }
662
663         /* Find all of the candidates */
664         for (attr_i = 0; attr_i < remote_stream->attr_count; ++attr_i) {
665                 attr = remote_stream->attr[attr_i];
666                 if (!pj_strcmp2(&attr->name, "candidate")) {
667                         session_media->remote_ice = 1;
668                         break;
669                 }
670         }
671
672         if (attr_i == remote_stream->attr_count) {
673                 session_media->remote_ice = 0;
674         }
675 }
676
677 /*! \brief Function which processes ICE attributes in an audio stream */
678 static void process_ice_attributes(struct ast_sip_session *session, struct ast_sip_session_media *session_media,
679                                    const struct pjmedia_sdp_session *remote, const struct pjmedia_sdp_media *remote_stream)
680 {
681         struct ast_rtp_engine_ice *ice;
682         const pjmedia_sdp_attr *attr;
683         char attr_value[256];
684         unsigned int attr_i;
685
686         /* If ICE support is not enabled or available exit early */
687         if (!session->endpoint->media.rtp.ice_support || !(ice = ast_rtp_instance_get_ice(session_media->rtp))) {
688                 return;
689         }
690
691         attr = pjmedia_sdp_media_find_attr2(remote_stream, "ice-ufrag", NULL);
692         if (!attr) {
693                 attr = pjmedia_sdp_attr_find2(remote->attr_count, remote->attr, "ice-ufrag", NULL);
694         }
695         if (attr) {
696                 ast_copy_pj_str(attr_value, (pj_str_t*)&attr->value, sizeof(attr_value));
697                 ice->set_authentication(session_media->rtp, attr_value, NULL);
698         } else {
699                 return;
700         }
701
702         attr = pjmedia_sdp_media_find_attr2(remote_stream, "ice-pwd", NULL);
703         if (!attr) {
704                 attr = pjmedia_sdp_attr_find2(remote->attr_count, remote->attr, "ice-pwd", NULL);
705         }
706         if (attr) {
707                 ast_copy_pj_str(attr_value, (pj_str_t*)&attr->value, sizeof(attr_value));
708                 ice->set_authentication(session_media->rtp, NULL, attr_value);
709         } else {
710                 return;
711         }
712
713         if (pjmedia_sdp_media_find_attr2(remote_stream, "ice-lite", NULL)) {
714                 ice->ice_lite(session_media->rtp);
715         }
716
717         /* Find all of the candidates */
718         for (attr_i = 0; attr_i < remote_stream->attr_count; ++attr_i) {
719                 char foundation[33], transport[32], address[PJ_INET6_ADDRSTRLEN + 1], cand_type[6], relay_address[PJ_INET6_ADDRSTRLEN + 1] = "";
720                 unsigned int port, relay_port = 0;
721                 struct ast_rtp_engine_ice_candidate candidate = { 0, };
722
723                 attr = remote_stream->attr[attr_i];
724
725                 /* If this is not a candidate line skip it */
726                 if (pj_strcmp2(&attr->name, "candidate")) {
727                         continue;
728                 }
729
730                 ast_copy_pj_str(attr_value, (pj_str_t*)&attr->value, sizeof(attr_value));
731
732                 if (sscanf(attr_value, "%32s %30u %31s %30u %46s %30u typ %5s %*s %23s %*s %30u", foundation, &candidate.id, transport,
733                         (unsigned *)&candidate.priority, address, &port, cand_type, relay_address, &relay_port) < 7) {
734                         /* Candidate did not parse properly */
735                         continue;
736                 }
737
738                 if (session->endpoint->media.rtcp_mux && session_media->remote_rtcp_mux && candidate.id > 1) {
739                         /* Remote side may have offered RTP and RTCP candidates. However, if we're using RTCP MUX,
740                          * then we should ignore RTCP candidates.
741                          */
742                         continue;
743                 }
744
745                 candidate.foundation = foundation;
746                 candidate.transport = transport;
747
748                 ast_sockaddr_parse(&candidate.address, address, PARSE_PORT_FORBID);
749                 ast_sockaddr_set_port(&candidate.address, port);
750
751                 if (!strcasecmp(cand_type, "host")) {
752                         candidate.type = AST_RTP_ICE_CANDIDATE_TYPE_HOST;
753                 } else if (!strcasecmp(cand_type, "srflx")) {
754                         candidate.type = AST_RTP_ICE_CANDIDATE_TYPE_SRFLX;
755                 } else if (!strcasecmp(cand_type, "relay")) {
756                         candidate.type = AST_RTP_ICE_CANDIDATE_TYPE_RELAYED;
757                 } else {
758                         continue;
759                 }
760
761                 if (!ast_strlen_zero(relay_address)) {
762                         ast_sockaddr_parse(&candidate.relay_address, relay_address, PARSE_PORT_FORBID);
763                 }
764
765                 if (relay_port) {
766                         ast_sockaddr_set_port(&candidate.relay_address, relay_port);
767                 }
768
769                 ice->add_remote_candidate(session_media->rtp, &candidate);
770         }
771
772         ice->set_role(session_media->rtp, pjmedia_sdp_neg_was_answer_remote(session->inv_session->neg) == PJ_TRUE ?
773                 AST_RTP_ICE_ROLE_CONTROLLING : AST_RTP_ICE_ROLE_CONTROLLED);
774         ice->start(session_media->rtp);
775 }
776
777 /*! \brief figure out if media stream has crypto lines for sdes */
778 static int media_stream_has_crypto(const struct pjmedia_sdp_media *stream)
779 {
780         int i;
781
782         for (i = 0; i < stream->attr_count; i++) {
783                 pjmedia_sdp_attr *attr;
784
785                 /* check the stream for the required crypto attribute */
786                 attr = stream->attr[i];
787                 if (pj_strcmp2(&attr->name, "crypto")) {
788                         continue;
789                 }
790
791                 return 1;
792         }
793
794         return 0;
795 }
796
797 /*! \brief figure out media transport encryption type from the media transport string */
798 static enum ast_sip_session_media_encryption get_media_encryption_type(pj_str_t transport,
799         const struct pjmedia_sdp_media *stream, unsigned int *optimistic)
800 {
801         RAII_VAR(char *, transport_str, ast_strndup(transport.ptr, transport.slen), ast_free);
802
803         *optimistic = 0;
804
805         if (!transport_str) {
806                 return AST_SIP_MEDIA_TRANSPORT_INVALID;
807         }
808         if (strstr(transport_str, "UDP/TLS")) {
809                 return AST_SIP_MEDIA_ENCRYPT_DTLS;
810         } else if (strstr(transport_str, "SAVP")) {
811                 return AST_SIP_MEDIA_ENCRYPT_SDES;
812         } else if (media_stream_has_crypto(stream)) {
813                 *optimistic = 1;
814                 return AST_SIP_MEDIA_ENCRYPT_SDES;
815         } else {
816                 return AST_SIP_MEDIA_ENCRYPT_NONE;
817         }
818 }
819
820 /*!
821  * \brief Checks whether the encryption offered in SDP is compatible with the endpoint's configuration
822  * \internal
823  *
824  * \param endpoint_encryption Media encryption configured for the endpoint
825  * \param stream pjmedia_sdp_media stream description
826  *
827  * \retval AST_SIP_MEDIA_TRANSPORT_INVALID on encryption mismatch
828  * \retval The encryption requested in the SDP
829  */
830 static enum ast_sip_session_media_encryption check_endpoint_media_transport(
831         struct ast_sip_endpoint *endpoint,
832         const struct pjmedia_sdp_media *stream)
833 {
834         enum ast_sip_session_media_encryption incoming_encryption;
835         char transport_end = stream->desc.transport.ptr[stream->desc.transport.slen - 1];
836         unsigned int optimistic;
837
838         if ((transport_end == 'F' && !endpoint->media.rtp.use_avpf)
839                 || (transport_end != 'F' && endpoint->media.rtp.use_avpf)) {
840                 return AST_SIP_MEDIA_TRANSPORT_INVALID;
841         }
842
843         incoming_encryption = get_media_encryption_type(stream->desc.transport, stream, &optimistic);
844
845         if (incoming_encryption == endpoint->media.rtp.encryption) {
846                 return incoming_encryption;
847         }
848
849         if (endpoint->media.rtp.force_avp ||
850                 endpoint->media.rtp.encryption_optimistic) {
851                 return incoming_encryption;
852         }
853
854         /* If an optimistic offer has been made but encryption is not enabled consider it as having
855          * no offer of crypto at all instead of invalid so the session proceeds.
856          */
857         if (optimistic) {
858                 return AST_SIP_MEDIA_ENCRYPT_NONE;
859         }
860
861         return AST_SIP_MEDIA_TRANSPORT_INVALID;
862 }
863
864 static int setup_srtp(struct ast_sip_session_media *session_media)
865 {
866         if (!session_media->srtp) {
867                 session_media->srtp = ast_sdp_srtp_alloc();
868                 if (!session_media->srtp) {
869                         return -1;
870                 }
871         }
872
873         if (!session_media->srtp->crypto) {
874                 session_media->srtp->crypto = ast_sdp_crypto_alloc();
875                 if (!session_media->srtp->crypto) {
876                         return -1;
877                 }
878         }
879
880         return 0;
881 }
882
883 static int setup_dtls_srtp(struct ast_sip_session *session,
884         struct ast_sip_session_media *session_media)
885 {
886         struct ast_rtp_engine_dtls *dtls;
887
888         if (!session->endpoint->media.rtp.dtls_cfg.enabled || !session_media->rtp) {
889                 return -1;
890         }
891
892         dtls = ast_rtp_instance_get_dtls(session_media->rtp);
893         if (!dtls) {
894                 return -1;
895         }
896
897         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);
898         if (dtls->set_configuration(session_media->rtp, &session->endpoint->media.rtp.dtls_cfg)) {
899                 ast_log(LOG_ERROR, "Attempted to set an invalid DTLS-SRTP configuration on RTP instance '%p'\n",
900                         session_media->rtp);
901                 return -1;
902         }
903
904         if (setup_srtp(session_media)) {
905                 return -1;
906         }
907         return 0;
908 }
909
910 static void apply_dtls_attrib(struct ast_sip_session_media *session_media,
911         pjmedia_sdp_attr *attr)
912 {
913         struct ast_rtp_engine_dtls *dtls = ast_rtp_instance_get_dtls(session_media->rtp);
914         pj_str_t *value;
915
916         if (!attr->value.ptr || !dtls) {
917                 return;
918         }
919
920         value = pj_strtrim(&attr->value);
921
922         if (!pj_strcmp2(&attr->name, "setup")) {
923                 if (!pj_stricmp2(value, "active")) {
924                         dtls->set_setup(session_media->rtp, AST_RTP_DTLS_SETUP_ACTIVE);
925                 } else if (!pj_stricmp2(value, "passive")) {
926                         dtls->set_setup(session_media->rtp, AST_RTP_DTLS_SETUP_PASSIVE);
927                 } else if (!pj_stricmp2(value, "actpass")) {
928                         dtls->set_setup(session_media->rtp, AST_RTP_DTLS_SETUP_ACTPASS);
929                 } else if (!pj_stricmp2(value, "holdconn")) {
930                         dtls->set_setup(session_media->rtp, AST_RTP_DTLS_SETUP_HOLDCONN);
931                 } else {
932                         ast_log(LOG_WARNING, "Unsupported setup attribute value '%*s'\n", (int)value->slen, value->ptr);
933                 }
934         } else if (!pj_strcmp2(&attr->name, "connection")) {
935                 if (!pj_stricmp2(value, "new")) {
936                         dtls->reset(session_media->rtp);
937                 } else if (!pj_stricmp2(value, "existing")) {
938                         /* Do nothing */
939                 } else {
940                         ast_log(LOG_WARNING, "Unsupported connection attribute value '%*s'\n", (int)value->slen, value->ptr);
941                 }
942         } else if (!pj_strcmp2(&attr->name, "fingerprint")) {
943                 char hash_value[256], hash[32];
944                 char fingerprint_text[value->slen + 1];
945                 ast_copy_pj_str(fingerprint_text, value, sizeof(fingerprint_text));
946                         if (sscanf(fingerprint_text, "%31s %255s", hash, hash_value) == 2) {
947                         if (!strcasecmp(hash, "sha-1")) {
948                                 dtls->set_fingerprint(session_media->rtp, AST_RTP_DTLS_HASH_SHA1, hash_value);
949                         } else if (!strcasecmp(hash, "sha-256")) {
950                                 dtls->set_fingerprint(session_media->rtp, AST_RTP_DTLS_HASH_SHA256, hash_value);
951                         } else {
952                                 ast_log(LOG_WARNING, "Unsupported fingerprint hash type '%s'\n",
953                                 hash);
954                         }
955                 }
956         }
957 }
958
959 static int parse_dtls_attrib(struct ast_sip_session_media *session_media,
960         const struct pjmedia_sdp_session *sdp,
961         const struct pjmedia_sdp_media *stream)
962 {
963         int i;
964
965         for (i = 0; i < sdp->attr_count; i++) {
966                 apply_dtls_attrib(session_media, sdp->attr[i]);
967         }
968
969         for (i = 0; i < stream->attr_count; i++) {
970                 apply_dtls_attrib(session_media, stream->attr[i]);
971         }
972
973         ast_set_flag(session_media->srtp, AST_SRTP_CRYPTO_OFFER_OK);
974
975         return 0;
976 }
977
978 static int setup_sdes_srtp(struct ast_sip_session_media *session_media,
979         const struct pjmedia_sdp_media *stream)
980 {
981         int i;
982
983         for (i = 0; i < stream->attr_count; i++) {
984                 pjmedia_sdp_attr *attr;
985                 RAII_VAR(char *, crypto_str, NULL, ast_free);
986
987                 /* check the stream for the required crypto attribute */
988                 attr = stream->attr[i];
989                 if (pj_strcmp2(&attr->name, "crypto")) {
990                         continue;
991                 }
992
993                 crypto_str = ast_strndup(attr->value.ptr, attr->value.slen);
994                 if (!crypto_str) {
995                         return -1;
996                 }
997
998                 if (setup_srtp(session_media)) {
999                         return -1;
1000                 }
1001
1002                 if (!ast_sdp_crypto_process(session_media->rtp, session_media->srtp, crypto_str)) {
1003                         /* found a valid crypto attribute */
1004                         return 0;
1005                 }
1006
1007                 ast_debug(1, "Ignoring crypto offer with unsupported parameters: %s\n", crypto_str);
1008         }
1009
1010         /* no usable crypto attributes found */
1011         return -1;
1012 }
1013
1014 static int setup_media_encryption(struct ast_sip_session *session,
1015         struct ast_sip_session_media *session_media,
1016         const struct pjmedia_sdp_session *sdp,
1017         const struct pjmedia_sdp_media *stream)
1018 {
1019         switch (session_media->encryption) {
1020         case AST_SIP_MEDIA_ENCRYPT_SDES:
1021                 if (setup_sdes_srtp(session_media, stream)) {
1022                         return -1;
1023                 }
1024                 break;
1025         case AST_SIP_MEDIA_ENCRYPT_DTLS:
1026                 if (setup_dtls_srtp(session, session_media)) {
1027                         return -1;
1028                 }
1029                 if (parse_dtls_attrib(session_media, sdp, stream)) {
1030                         return -1;
1031                 }
1032                 break;
1033         case AST_SIP_MEDIA_TRANSPORT_INVALID:
1034         case AST_SIP_MEDIA_ENCRYPT_NONE:
1035                 break;
1036         }
1037
1038         return 0;
1039 }
1040
1041 static void set_ice_components(struct ast_sip_session *session, struct ast_sip_session_media *session_media)
1042 {
1043         struct ast_rtp_engine_ice *ice;
1044
1045         ast_assert(session_media->rtp != NULL);
1046
1047         ice = ast_rtp_instance_get_ice(session_media->rtp);
1048         if (!session->endpoint->media.rtp.ice_support || !ice) {
1049                 return;
1050         }
1051
1052         if (session->endpoint->media.rtcp_mux && session_media->remote_rtcp_mux) {
1053                 /* We both support RTCP mux. Only one ICE component necessary */
1054                 ice->change_components(session_media->rtp, 1);
1055         } else {
1056                 /* They either don't support RTCP mux or we don't know if they do yet. */
1057                 ice->change_components(session_media->rtp, 2);
1058         }
1059 }
1060
1061 /*! \brief Function which adds ssrc attributes to a media stream */
1062 static void add_ssrc_to_stream(struct ast_sip_session *session, struct ast_sip_session_media *session_media, pj_pool_t *pool, pjmedia_sdp_media *media)
1063 {
1064         pj_str_t stmp;
1065         pjmedia_sdp_attr *attr;
1066         char tmp[128];
1067
1068         if (!session->endpoint->media.bundle || session_media->bundle_group == -1) {
1069                 return;
1070         }
1071
1072         snprintf(tmp, sizeof(tmp), "%u cname:%s", ast_rtp_instance_get_ssrc(session_media->rtp), ast_rtp_instance_get_cname(session_media->rtp));
1073         attr = pjmedia_sdp_attr_create(pool, "ssrc", pj_cstr(&stmp, tmp));
1074         media->attr[media->attr_count++] = attr;
1075 }
1076
1077 /*! \brief Function which processes ssrc attributes in a stream */
1078 static void process_ssrc_attributes(struct ast_sip_session *session, struct ast_sip_session_media *session_media,
1079                                    const struct pjmedia_sdp_media *remote_stream)
1080 {
1081         int index;
1082
1083         if (!session->endpoint->media.bundle) {
1084                 return;
1085         }
1086
1087         for (index = 0; index < remote_stream->attr_count; ++index) {
1088                 pjmedia_sdp_attr *attr = remote_stream->attr[index];
1089                 char attr_value[pj_strlen(&attr->value) + 1];
1090                 char *ssrc_attribute_name, *ssrc_attribute_value = NULL;
1091                 unsigned int ssrc;
1092
1093                 /* We only care about ssrc attributes */
1094                 if (pj_strcmp2(&attr->name, "ssrc")) {
1095                         continue;
1096                 }
1097
1098                 ast_copy_pj_str(attr_value, &attr->value, sizeof(attr_value));
1099
1100                 if ((ssrc_attribute_name = strchr(attr_value, ' '))) {
1101                         /* This has an actual attribute */
1102                         *ssrc_attribute_name++ = '\0';
1103                         ssrc_attribute_value = strchr(ssrc_attribute_name, ':');
1104                         if (ssrc_attribute_value) {
1105                                 /* Values are actually optional according to the spec */
1106                                 *ssrc_attribute_value++ = '\0';
1107                         }
1108                 }
1109
1110                 if (sscanf(attr_value, "%30u", &ssrc) < 1) {
1111                         continue;
1112                 }
1113
1114                 /* If we are currently negotiating as a result of the remote side renegotiating then
1115                  * determine if the source for this stream has changed.
1116                  */
1117                 if (pjmedia_sdp_neg_get_state(session->inv_session->neg) == PJMEDIA_SDP_NEG_STATE_REMOTE_OFFER &&
1118                         session->active_media_state) {
1119                         struct ast_rtp_instance_stats stats = { 0, };
1120
1121                         if (!ast_rtp_instance_get_stats(session_media->rtp, &stats, AST_RTP_INSTANCE_STAT_REMOTE_SSRC) &&
1122                                 stats.remote_ssrc != ssrc) {
1123                                 session_media->changed = 1;
1124                         }
1125                 }
1126
1127                 ast_rtp_instance_set_remote_ssrc(session_media->rtp, ssrc);
1128         }
1129 }
1130
1131 static void add_msid_to_stream(struct ast_sip_session *session,
1132         struct ast_sip_session_media *session_media, pj_pool_t *pool, pjmedia_sdp_media *media,
1133         struct ast_stream *stream)
1134 {
1135         pj_str_t stmp;
1136         pjmedia_sdp_attr *attr;
1137         char msid[(AST_UUID_STR_LEN * 2) + 2];
1138         const char *stream_label = ast_stream_get_metadata(stream, "SDP:LABEL");
1139
1140         if (!session->endpoint->media.webrtc) {
1141                 return;
1142         }
1143
1144         if (ast_strlen_zero(session_media->mslabel)) {
1145                 /* If this stream is grouped with another then use its media stream label if possible */
1146                 if (ast_stream_get_group(stream) != -1) {
1147                         struct ast_sip_session_media *group_session_media = AST_VECTOR_GET(&session->pending_media_state->sessions, ast_stream_get_group(stream));
1148
1149                         ast_copy_string(session_media->mslabel, group_session_media->mslabel, sizeof(session_media->mslabel));
1150                 }
1151
1152                 if (ast_strlen_zero(session_media->mslabel)) {
1153                         ast_uuid_generate_str(session_media->mslabel, sizeof(session_media->mslabel));
1154                 }
1155         }
1156
1157         if (ast_strlen_zero(session_media->label)) {
1158                         ast_uuid_generate_str(session_media->label, sizeof(session_media->label));
1159         }
1160
1161         snprintf(msid, sizeof(msid), "%s %s", session_media->mslabel, session_media->label);
1162         ast_debug(3, "Stream msid: %p %s %s\n", stream,
1163                 ast_codec_media_type2str(ast_stream_get_type(stream)), msid);
1164         attr = pjmedia_sdp_attr_create(pool, "msid", pj_cstr(&stmp, msid));
1165         pjmedia_sdp_attr_add(&media->attr_count, media->attr, attr);
1166
1167         /* 'label' must come after 'msid' */
1168         if (!ast_strlen_zero(stream_label)) {
1169                 ast_debug(3, "Stream Label: %p %s %s\n", stream,
1170                         ast_codec_media_type2str(ast_stream_get_type(stream)), stream_label);
1171                 attr = pjmedia_sdp_attr_create(pool, "label", pj_cstr(&stmp, stream_label));
1172                 pjmedia_sdp_attr_add(&media->attr_count, media->attr, attr);
1173         }
1174 }
1175
1176 static void add_rtcp_fb_to_stream(struct ast_sip_session *session,
1177         struct ast_sip_session_media *session_media, pj_pool_t *pool, pjmedia_sdp_media *media)
1178 {
1179         pj_str_t stmp;
1180         pjmedia_sdp_attr *attr;
1181
1182         if (!session->endpoint->media.webrtc || session_media->type != AST_MEDIA_TYPE_VIDEO) {
1183                 return;
1184         }
1185
1186         /*
1187          * For now just automatically add it the stream even though it hasn't
1188          * necessarily been negotiated.
1189          */
1190         attr = pjmedia_sdp_attr_create(pool, "rtcp-fb", pj_cstr(&stmp, "* ccm fir"));
1191         pjmedia_sdp_attr_add(&media->attr_count, media->attr, attr);
1192
1193         attr = pjmedia_sdp_attr_create(pool, "rtcp-fb", pj_cstr(&stmp, "* goog-remb"));
1194         pjmedia_sdp_attr_add(&media->attr_count, media->attr, attr);
1195
1196         attr = pjmedia_sdp_attr_create(pool, "rtcp-fb", pj_cstr(&stmp, "* nack"));
1197         pjmedia_sdp_attr_add(&media->attr_count, media->attr, attr);
1198 }
1199
1200 static void add_extmap_to_stream(struct ast_sip_session *session,
1201         struct ast_sip_session_media *session_media, pj_pool_t *pool, pjmedia_sdp_media *media)
1202 {
1203         int idx;
1204         char extmap_value[256];
1205
1206         if (!session->endpoint->media.webrtc || session_media->type != AST_MEDIA_TYPE_VIDEO) {
1207                 return;
1208         }
1209
1210         /* RTP extension local unique identifiers start at '1' */
1211         for (idx = 1; idx <= ast_rtp_instance_extmap_count(session_media->rtp); ++idx) {
1212                 enum ast_rtp_extension extension = ast_rtp_instance_extmap_get_extension(session_media->rtp, idx);
1213                 const char *direction_str = "";
1214                 pj_str_t stmp;
1215                 pjmedia_sdp_attr *attr;
1216
1217                 /* If this is an unsupported RTP extension we can't place it into the SDP */
1218                 if (extension == AST_RTP_EXTENSION_UNSUPPORTED) {
1219                         continue;
1220                 }
1221
1222                 switch (ast_rtp_instance_extmap_get_direction(session_media->rtp, idx)) {
1223                 case AST_RTP_EXTENSION_DIRECTION_SENDRECV:
1224                         /* Lack of a direction indicates sendrecv, so we leave it out */
1225                         direction_str = "";
1226                         break;
1227                 case AST_RTP_EXTENSION_DIRECTION_SENDONLY:
1228                         direction_str = "/sendonly";
1229                         break;
1230                 case AST_RTP_EXTENSION_DIRECTION_RECVONLY:
1231                         direction_str = "/recvonly";
1232                         break;
1233                 case AST_RTP_EXTENSION_DIRECTION_NONE:
1234                         /* It is impossible for a "none" direction extension to be negotiated but just in case
1235                          * we treat it as inactive.
1236                          */
1237                 case AST_RTP_EXTENSION_DIRECTION_INACTIVE:
1238                         direction_str = "/inactive";
1239                         break;
1240                 }
1241
1242                 snprintf(extmap_value, sizeof(extmap_value), "%d%s %s", idx, direction_str,
1243                         ast_rtp_instance_extmap_get_uri(session_media->rtp, idx));
1244                 attr = pjmedia_sdp_attr_create(pool, "extmap", pj_cstr(&stmp, extmap_value));
1245                 pjmedia_sdp_attr_add(&media->attr_count, media->attr, attr);
1246         }
1247 }
1248
1249 /*! \brief Function which processes extmap attributes in a stream */
1250 static void process_extmap_attributes(struct ast_sip_session *session, struct ast_sip_session_media *session_media,
1251                                    const struct pjmedia_sdp_media *remote_stream)
1252 {
1253         int index;
1254
1255         if (!session->endpoint->media.webrtc || session_media->type != AST_MEDIA_TYPE_VIDEO) {
1256                 return;
1257         }
1258
1259         ast_rtp_instance_extmap_clear(session_media->rtp);
1260
1261         for (index = 0; index < remote_stream->attr_count; ++index) {
1262                 pjmedia_sdp_attr *attr = remote_stream->attr[index];
1263                 char attr_value[pj_strlen(&attr->value) + 1];
1264                 char *uri;
1265                 int id;
1266                 char direction_str[10] = "";
1267                 char *attributes;
1268                 enum ast_rtp_extension_direction direction = AST_RTP_EXTENSION_DIRECTION_SENDRECV;
1269
1270                 /* We only care about extmap attributes */
1271                 if (pj_strcmp2(&attr->name, "extmap")) {
1272                         continue;
1273                 }
1274
1275                 ast_copy_pj_str(attr_value, &attr->value, sizeof(attr_value));
1276
1277                 /* Split the combined unique identifier and direction away from the URI and attributes for easier parsing */
1278                 uri = strchr(attr_value, ' ');
1279                 if (ast_strlen_zero(uri)) {
1280                         continue;
1281                 }
1282                 *uri++ = '\0';
1283
1284                 if ((sscanf(attr_value, "%30d%9s", &id, direction_str) < 1) || (id < 1)) {
1285                         /* We require at a minimum the unique identifier */
1286                         continue;
1287                 }
1288
1289                 /* Convert from the string to the internal representation */
1290                 if (!strcasecmp(direction_str, "/sendonly")) {
1291                         direction = AST_RTP_EXTENSION_DIRECTION_SENDONLY;
1292                 } else if (!strcasecmp(direction_str, "/recvonly")) {
1293                         direction = AST_RTP_EXTENSION_DIRECTION_RECVONLY;
1294                 } else if (!strcasecmp(direction_str, "/inactive")) {
1295                         direction = AST_RTP_EXTENSION_DIRECTION_INACTIVE;
1296                 }
1297
1298                 attributes = strchr(uri, ' ');
1299                 if (!ast_strlen_zero(attributes)) {
1300                         *attributes++ = '\0';
1301                 }
1302
1303                 ast_rtp_instance_extmap_negotiate(session_media->rtp, id, direction, uri, attributes);
1304         }
1305 }
1306
1307 /*! \brief Function which negotiates an incoming media stream */
1308 static int negotiate_incoming_sdp_stream(struct ast_sip_session *session,
1309         struct ast_sip_session_media *session_media, const pjmedia_sdp_session *sdp,
1310         int index, struct ast_stream *asterisk_stream)
1311 {
1312         char host[NI_MAXHOST];
1313         RAII_VAR(struct ast_sockaddr *, addrs, NULL, ast_free);
1314         pjmedia_sdp_media *stream = sdp->media[index];
1315         struct ast_sip_session_media *session_media_transport;
1316         enum ast_media_type media_type = session_media->type;
1317         enum ast_sip_session_media_encryption encryption = AST_SIP_MEDIA_ENCRYPT_NONE;
1318         int res;
1319
1320         /* If no type formats have been configured reject this stream */
1321         if (!ast_format_cap_has_type(session->endpoint->media.codecs, media_type)) {
1322                 ast_debug(3, "Endpoint has no codecs for media type '%s', declining stream\n",
1323                         ast_codec_media_type2str(session_media->type));
1324                 return 0;
1325         }
1326
1327         /* Ensure incoming transport is compatible with the endpoint's configuration */
1328         if (!session->endpoint->media.rtp.use_received_transport) {
1329                 encryption = check_endpoint_media_transport(session->endpoint, stream);
1330
1331                 if (encryption == AST_SIP_MEDIA_TRANSPORT_INVALID) {
1332                         return -1;
1333                 }
1334         }
1335
1336         ast_copy_pj_str(host, stream->conn ? &stream->conn->addr : &sdp->conn->addr, sizeof(host));
1337
1338         /* Ensure that the address provided is valid */
1339         if (ast_sockaddr_resolve(&addrs, host, PARSE_PORT_FORBID, AST_AF_UNSPEC) <= 0) {
1340                 /* The provided host was actually invalid so we error out this negotiation */
1341                 return -1;
1342         }
1343
1344         /* Using the connection information create an appropriate RTP instance */
1345         if (!session_media->rtp && create_rtp(session, session_media, sdp)) {
1346                 return -1;
1347         }
1348
1349         process_ssrc_attributes(session, session_media, stream);
1350         process_extmap_attributes(session, session_media, stream);
1351         session_media_transport = ast_sip_session_media_get_transport(session, session_media);
1352
1353         if (session_media_transport == session_media || !session_media->bundled) {
1354                 /* If this media session is carrying actual traffic then set up those aspects */
1355                 session_media->remote_rtcp_mux = (pjmedia_sdp_media_find_attr2(stream, "rtcp-mux", NULL) != NULL);
1356                 set_ice_components(session, session_media);
1357
1358                 enable_rtcp(session, session_media, stream);
1359
1360                 res = setup_media_encryption(session, session_media, sdp, stream);
1361                 if (res) {
1362                         if (!session->endpoint->media.rtp.encryption_optimistic ||
1363                                 !pj_strncmp2(&stream->desc.transport, "RTP/SAVP", 8)) {
1364                                 /* If optimistic encryption is disabled and crypto should have been enabled
1365                                  * but was not this session must fail. This must also fail if crypto was
1366                                  * required in the offer but could not be set up.
1367                                  */
1368                                 return -1;
1369                         }
1370                         /* There is no encryption, sad. */
1371                         session_media->encryption = AST_SIP_MEDIA_ENCRYPT_NONE;
1372                 }
1373
1374                 /* If we've been explicitly configured to use the received transport OR if
1375                  * encryption is on and crypto is present use the received transport.
1376                  * This is done in case of optimistic because it may come in as RTP/AVP or RTP/SAVP depending
1377                  * on the configuration of the remote endpoint (optimistic themselves or mandatory).
1378                  */
1379                 if ((session->endpoint->media.rtp.use_received_transport) ||
1380                         ((encryption == AST_SIP_MEDIA_ENCRYPT_SDES) && !res)) {
1381                         pj_strdup(session->inv_session->pool, &session_media->transport, &stream->desc.transport);
1382                 }
1383         } else {
1384                 /* This is bundled with another session, so mark it as such */
1385                 ast_rtp_instance_bundle(session_media->rtp, session_media_transport->rtp);
1386
1387                 enable_rtcp(session, session_media, stream);
1388         }
1389
1390         /* If ICE support is enabled find all the needed attributes */
1391         check_ice_support(session, session_media, stream);
1392
1393         if (set_caps(session, session_media, session_media_transport, stream, 1, asterisk_stream)) {
1394                 return 0;
1395         }
1396
1397         return 1;
1398 }
1399
1400 static int add_crypto_to_stream(struct ast_sip_session *session,
1401         struct ast_sip_session_media *session_media,
1402         pj_pool_t *pool, pjmedia_sdp_media *media)
1403 {
1404         pj_str_t stmp;
1405         pjmedia_sdp_attr *attr;
1406         enum ast_rtp_dtls_hash hash;
1407         const char *crypto_attribute;
1408         struct ast_rtp_engine_dtls *dtls;
1409         struct ast_sdp_srtp *tmp;
1410         static const pj_str_t STR_NEW = { "new", 3 };
1411         static const pj_str_t STR_EXISTING = { "existing", 8 };
1412         static const pj_str_t STR_ACTIVE = { "active", 6 };
1413         static const pj_str_t STR_PASSIVE = { "passive", 7 };
1414         static const pj_str_t STR_ACTPASS = { "actpass", 7 };
1415         static const pj_str_t STR_HOLDCONN = { "holdconn", 8 };
1416         enum ast_rtp_dtls_setup setup;
1417
1418         switch (session_media->encryption) {
1419         case AST_SIP_MEDIA_ENCRYPT_NONE:
1420         case AST_SIP_MEDIA_TRANSPORT_INVALID:
1421                 break;
1422         case AST_SIP_MEDIA_ENCRYPT_SDES:
1423                 if (!session_media->srtp) {
1424                         session_media->srtp = ast_sdp_srtp_alloc();
1425                         if (!session_media->srtp) {
1426                                 return -1;
1427                         }
1428                 }
1429
1430                 tmp = session_media->srtp;
1431
1432                 do {
1433                         crypto_attribute = ast_sdp_srtp_get_attrib(tmp,
1434                                 0 /* DTLS running? No */,
1435                                 session->endpoint->media.rtp.srtp_tag_32 /* 32 byte tag length? */);
1436                         if (!crypto_attribute) {
1437                                 /* No crypto attribute to add, bad news */
1438                                 return -1;
1439                         }
1440
1441                         attr = pjmedia_sdp_attr_create(pool, "crypto",
1442                                 pj_cstr(&stmp, crypto_attribute));
1443                         media->attr[media->attr_count++] = attr;
1444                 } while ((tmp = AST_LIST_NEXT(tmp, sdp_srtp_list)));
1445
1446                 break;
1447         case AST_SIP_MEDIA_ENCRYPT_DTLS:
1448                 if (setup_dtls_srtp(session, session_media)) {
1449                         return -1;
1450                 }
1451
1452                 dtls = ast_rtp_instance_get_dtls(session_media->rtp);
1453                 if (!dtls) {
1454                         return -1;
1455                 }
1456
1457                 switch (dtls->get_connection(session_media->rtp)) {
1458                 case AST_RTP_DTLS_CONNECTION_NEW:
1459                         attr = pjmedia_sdp_attr_create(pool, "connection", &STR_NEW);
1460                         media->attr[media->attr_count++] = attr;
1461                         break;
1462                 case AST_RTP_DTLS_CONNECTION_EXISTING:
1463                         attr = pjmedia_sdp_attr_create(pool, "connection", &STR_EXISTING);
1464                         media->attr[media->attr_count++] = attr;
1465                         break;
1466                 default:
1467                         break;
1468                 }
1469
1470                 /* If this is an answer we need to use our current state, if it's an offer we need to use
1471                  * the configured value.
1472                  */
1473                 if (session->inv_session->neg
1474                         && pjmedia_sdp_neg_get_state(session->inv_session->neg) != PJMEDIA_SDP_NEG_STATE_DONE) {
1475                         setup = dtls->get_setup(session_media->rtp);
1476                 } else {
1477                         setup = session->endpoint->media.rtp.dtls_cfg.default_setup;
1478                 }
1479
1480                 switch (setup) {
1481                 case AST_RTP_DTLS_SETUP_ACTIVE:
1482                         attr = pjmedia_sdp_attr_create(pool, "setup", &STR_ACTIVE);
1483                         media->attr[media->attr_count++] = attr;
1484                         break;
1485                 case AST_RTP_DTLS_SETUP_PASSIVE:
1486                         attr = pjmedia_sdp_attr_create(pool, "setup", &STR_PASSIVE);
1487                         media->attr[media->attr_count++] = attr;
1488                         break;
1489                 case AST_RTP_DTLS_SETUP_ACTPASS:
1490                         attr = pjmedia_sdp_attr_create(pool, "setup", &STR_ACTPASS);
1491                         media->attr[media->attr_count++] = attr;
1492                         break;
1493                 case AST_RTP_DTLS_SETUP_HOLDCONN:
1494                         attr = pjmedia_sdp_attr_create(pool, "setup", &STR_HOLDCONN);
1495                         break;
1496                 default:
1497                         break;
1498                 }
1499
1500                 hash = dtls->get_fingerprint_hash(session_media->rtp);
1501                 crypto_attribute = dtls->get_fingerprint(session_media->rtp);
1502                 if (crypto_attribute && (hash == AST_RTP_DTLS_HASH_SHA1 || hash == AST_RTP_DTLS_HASH_SHA256)) {
1503                         RAII_VAR(struct ast_str *, fingerprint, ast_str_create(64), ast_free);
1504                         if (!fingerprint) {
1505                                 return -1;
1506                         }
1507
1508                         if (hash == AST_RTP_DTLS_HASH_SHA1) {
1509                                 ast_str_set(&fingerprint, 0, "SHA-1 %s", crypto_attribute);
1510                         } else {
1511                                 ast_str_set(&fingerprint, 0, "SHA-256 %s", crypto_attribute);
1512                         }
1513
1514                         attr = pjmedia_sdp_attr_create(pool, "fingerprint", pj_cstr(&stmp, ast_str_buffer(fingerprint)));
1515                         media->attr[media->attr_count++] = attr;
1516                 }
1517                 break;
1518         }
1519
1520         return 0;
1521 }
1522
1523 /*! \brief Function which creates an outgoing stream */
1524 static int create_outgoing_sdp_stream(struct ast_sip_session *session, struct ast_sip_session_media *session_media,
1525                                       struct pjmedia_sdp_session *sdp, const struct pjmedia_sdp_session *remote, struct ast_stream *stream)
1526 {
1527         pj_pool_t *pool = session->inv_session->pool_prov;
1528         static const pj_str_t STR_RTP_AVP = { "RTP/AVP", 7 };
1529         static const pj_str_t STR_IN = { "IN", 2 };
1530         static const pj_str_t STR_IP4 = { "IP4", 3};
1531         static const pj_str_t STR_IP6 = { "IP6", 3};
1532         static const pj_str_t STR_SENDRECV = { "sendrecv", 8 };
1533         static const pj_str_t STR_SENDONLY = { "sendonly", 8 };
1534         pjmedia_sdp_media *media;
1535         const char *hostip = NULL;
1536         struct ast_sockaddr addr;
1537         char tmp[512];
1538         pj_str_t stmp;
1539         pjmedia_sdp_attr *attr;
1540         int index = 0;
1541         int noncodec = (session->dtmf == AST_SIP_DTMF_RFC_4733 || session->dtmf == AST_SIP_DTMF_AUTO || session->dtmf == AST_SIP_DTMF_AUTO_INFO) ? AST_RTP_DTMF : 0;
1542         int min_packet_size = 0, max_packet_size = 0;
1543         int rtp_code;
1544         RAII_VAR(struct ast_format_cap *, caps, NULL, ao2_cleanup);
1545         enum ast_media_type media_type = session_media->type;
1546         struct ast_sip_session_media *session_media_transport;
1547         pj_sockaddr ip;
1548
1549         int direct_media_enabled = !ast_sockaddr_isnull(&session_media->direct_media_addr) &&
1550                 ast_format_cap_count(session->direct_media_cap);
1551
1552         media = pj_pool_zalloc(pool, sizeof(struct pjmedia_sdp_media));
1553         if (!media) {
1554                 return -1;
1555         }
1556         pj_strdup2(pool, &media->desc.media, ast_codec_media_type2str(session_media->type));
1557
1558         /* If this is a removed (or declined) stream OR if no formats exist then construct a minimal stream in SDP */
1559         if (ast_stream_get_state(stream) == AST_STREAM_STATE_REMOVED || !ast_stream_get_formats(stream) ||
1560                 !ast_format_cap_count(ast_stream_get_formats(stream))) {
1561                 media->desc.port = 0;
1562                 media->desc.port_count = 1;
1563
1564                 if (remote && remote->media[ast_stream_get_position(stream)]) {
1565                         pjmedia_sdp_media *remote_media = remote->media[ast_stream_get_position(stream)];
1566                         int index;
1567
1568                         media->desc.transport = remote_media->desc.transport;
1569
1570                         /* Preserve existing behavior by copying the formats provided from the offer */
1571                         for (index = 0; index < remote_media->desc.fmt_count; ++index) {
1572                                 media->desc.fmt[index] = remote_media->desc.fmt[index];
1573                         }
1574                         media->desc.fmt_count = remote_media->desc.fmt_count;
1575                 } else {
1576                         /* This is actually an offer so put a dummy payload in that is ignored and sane transport */
1577                         media->desc.transport = STR_RTP_AVP;
1578                         pj_strdup2(pool, &media->desc.fmt[media->desc.fmt_count++], "32");
1579                 }
1580
1581                 sdp->media[sdp->media_count++] = media;
1582                 ast_stream_set_state(stream, AST_STREAM_STATE_REMOVED);
1583
1584                 return 1;
1585         }
1586
1587         if (!session_media->rtp && create_rtp(session, session_media, sdp)) {
1588                 return -1;
1589         }
1590
1591         /* If this stream has not been bundled already it is new and we need to ensure there is no SSRC conflict */
1592         if (session_media->bundle_group != -1 && !session_media->bundled) {
1593                 for (index = 0; index < sdp->media_count; ++index) {
1594                         struct ast_sip_session_media *other_session_media;
1595
1596                         other_session_media = AST_VECTOR_GET(&session->pending_media_state->sessions, index);
1597                         if (!other_session_media->rtp || other_session_media->bundle_group != session_media->bundle_group) {
1598                                 continue;
1599                         }
1600
1601                         if (ast_rtp_instance_get_ssrc(session_media->rtp) == ast_rtp_instance_get_ssrc(other_session_media->rtp)) {
1602                                 ast_rtp_instance_change_source(session_media->rtp);
1603                                 /* Start the conflict check over again */
1604                                 index = -1;
1605                                 continue;
1606                         }
1607                 }
1608         }
1609
1610         session_media_transport = ast_sip_session_media_get_transport(session, session_media);
1611
1612         if (session_media_transport == session_media || !session_media->bundled) {
1613                 set_ice_components(session, session_media);
1614                 enable_rtcp(session, session_media, NULL);
1615
1616                 /* Crypto has to be added before setting the media transport so that SRTP is properly
1617                  * set up according to the configuration. This ends up changing the media transport.
1618                  */
1619                 if (add_crypto_to_stream(session, session_media, pool, media)) {
1620                         return -1;
1621                 }
1622
1623                 if (pj_strlen(&session_media->transport)) {
1624                         /* If a transport has already been specified use it */
1625                         media->desc.transport = session_media->transport;
1626                 } else {
1627                         media->desc.transport = pj_str(ast_sdp_get_rtp_profile(
1628                                 /* Optimistic encryption places crypto in the normal RTP/AVP profile */
1629                                 !session->endpoint->media.rtp.encryption_optimistic &&
1630                                         (session_media->encryption == AST_SIP_MEDIA_ENCRYPT_SDES),
1631                                 session_media->rtp, session->endpoint->media.rtp.use_avpf,
1632                                 session->endpoint->media.rtp.force_avp));
1633                 }
1634
1635                 media->conn = pj_pool_zalloc(pool, sizeof(struct pjmedia_sdp_conn));
1636                 if (!media->conn) {
1637                         return -1;
1638                 }
1639
1640                 /* Add connection level details */
1641                 if (direct_media_enabled) {
1642                         hostip = ast_sockaddr_stringify_fmt(&session_media->direct_media_addr, AST_SOCKADDR_STR_ADDR);
1643                 } else if (ast_strlen_zero(session->endpoint->media.address)) {
1644                         hostip = ast_sip_get_host_ip_string(session->endpoint->media.rtp.ipv6 ? pj_AF_INET6() : pj_AF_INET());
1645                 } else {
1646                         hostip = session->endpoint->media.address;
1647                 }
1648
1649                 if (ast_strlen_zero(hostip)) {
1650                         ast_log(LOG_ERROR, "No local host IP available for stream %s\n",
1651                                 ast_codec_media_type2str(session_media->type));
1652                         return -1;
1653                 }
1654
1655                 media->conn->net_type = STR_IN;
1656                 /* Assume that the connection will use IPv4 until proven otherwise */
1657                 media->conn->addr_type = STR_IP4;
1658                 pj_strdup2(pool, &media->conn->addr, hostip);
1659
1660                 if ((pj_sockaddr_parse(pj_AF_UNSPEC(), 0, &media->conn->addr, &ip) == PJ_SUCCESS) &&
1661                         (ip.addr.sa_family == pj_AF_INET6())) {
1662                         media->conn->addr_type = STR_IP6;
1663                 }
1664
1665                 /* Add ICE attributes and candidates */
1666                 add_ice_to_stream(session, session_media, pool, media, 1);
1667
1668                 ast_rtp_instance_get_local_address(session_media->rtp, &addr);
1669                 media->desc.port = direct_media_enabled ? ast_sockaddr_port(&session_media->direct_media_addr) : (pj_uint16_t) ast_sockaddr_port(&addr);
1670                 media->desc.port_count = 1;
1671         } else {
1672                 pjmedia_sdp_media *bundle_group_stream = sdp->media[session_media_transport->stream_num];
1673
1674                 /* As this is in a bundle group it shares the same details as the group instance */
1675                 media->desc.transport = bundle_group_stream->desc.transport;
1676                 media->conn = bundle_group_stream->conn;
1677                 media->desc.port = bundle_group_stream->desc.port;
1678
1679                 if (add_crypto_to_stream(session, session_media_transport, pool, media)) {
1680                         return -1;
1681                 }
1682
1683                 add_ice_to_stream(session, session_media_transport, pool, media, 0);
1684
1685                 enable_rtcp(session, session_media, NULL);
1686         }
1687
1688         if (!(caps = ast_format_cap_alloc(AST_FORMAT_CAP_FLAG_DEFAULT))) {
1689                 ast_log(LOG_ERROR, "Failed to allocate %s capabilities\n",
1690                         ast_codec_media_type2str(session_media->type));
1691                 return -1;
1692         }
1693
1694         if (direct_media_enabled) {
1695                 ast_format_cap_get_compatible(session->endpoint->media.codecs, session->direct_media_cap, caps);
1696         } else {
1697                 ast_format_cap_append_from_cap(caps, ast_stream_get_formats(stream), media_type);
1698         }
1699
1700         for (index = 0; index < ast_format_cap_count(caps); ++index) {
1701                 struct ast_format *format = ast_format_cap_get_format(caps, index);
1702
1703                 if (ast_format_get_type(format) != media_type) {
1704                         ao2_ref(format, -1);
1705                         continue;
1706                 }
1707
1708                 /* If this stream is not a transport we need to use the transport codecs structure for payload management to prevent
1709                  * conflicts.
1710                  */
1711                 if (session_media_transport != session_media) {
1712                         if ((rtp_code = ast_rtp_codecs_payload_code(ast_rtp_instance_get_codecs(session_media_transport->rtp), 1, format, 0)) == -1) {
1713                                 ast_log(LOG_WARNING,"Unable to get rtp codec payload code for %s\n", ast_format_get_name(format));
1714                                 ao2_ref(format, -1);
1715                                 continue;
1716                         }
1717                         /* Our instance has to match the payload number though */
1718                         ast_rtp_codecs_payload_set_rx(ast_rtp_instance_get_codecs(session_media->rtp), rtp_code, format);
1719                 } else {
1720                         if ((rtp_code = ast_rtp_codecs_payload_code(ast_rtp_instance_get_codecs(session_media->rtp), 1, format, 0)) == -1) {
1721                                 ast_log(LOG_WARNING,"Unable to get rtp codec payload code for %s\n", ast_format_get_name(format));
1722                                 ao2_ref(format, -1);
1723                                 continue;
1724                         }
1725                 }
1726
1727                 if ((attr = generate_rtpmap_attr(session, media, pool, rtp_code, 1, format, 0))) {
1728                         media->attr[media->attr_count++] = attr;
1729                 }
1730
1731                 if ((attr = generate_fmtp_attr(pool, format, rtp_code))) {
1732                         media->attr[media->attr_count++] = attr;
1733                 }
1734
1735                 if (ast_format_get_maximum_ms(format) &&
1736                         ((ast_format_get_maximum_ms(format) < max_packet_size) || !max_packet_size)) {
1737                         max_packet_size = ast_format_get_maximum_ms(format);
1738                 }
1739                 ao2_ref(format, -1);
1740
1741                 if (media->desc.fmt_count == PJMEDIA_MAX_SDP_FMT) {
1742                         break;
1743                 }
1744         }
1745
1746         /* Add non-codec formats */
1747         if (ast_sip_session_is_pending_stream_default(session, stream) && media_type != AST_MEDIA_TYPE_VIDEO
1748                 && media->desc.fmt_count < PJMEDIA_MAX_SDP_FMT) {
1749                 for (index = 1LL; index <= AST_RTP_MAX; index <<= 1) {
1750                         if (!(noncodec & index)) {
1751                                 continue;
1752                         }
1753                         rtp_code = ast_rtp_codecs_payload_code(
1754                                 ast_rtp_instance_get_codecs(session_media->rtp), 0, NULL, index);
1755                         if (rtp_code == -1) {
1756                                 continue;
1757                         }
1758
1759                         if ((attr = generate_rtpmap_attr(session, media, pool, rtp_code, 0, NULL, index))) {
1760                                 media->attr[media->attr_count++] = attr;
1761                         }
1762
1763                         if (index == AST_RTP_DTMF) {
1764                                 snprintf(tmp, sizeof(tmp), "%d 0-16", rtp_code);
1765                                 attr = pjmedia_sdp_attr_create(pool, "fmtp", pj_cstr(&stmp, tmp));
1766                                 media->attr[media->attr_count++] = attr;
1767                         }
1768
1769                         if (media->desc.fmt_count == PJMEDIA_MAX_SDP_FMT) {
1770                                 break;
1771                         }
1772                 }
1773         }
1774
1775
1776         /* If no formats were actually added to the media stream don't add it to the SDP */
1777         if (!media->desc.fmt_count) {
1778                 return 1;
1779         }
1780
1781         /* If ptime is set add it as an attribute */
1782         min_packet_size = ast_rtp_codecs_get_framing(ast_rtp_instance_get_codecs(session_media->rtp));
1783         if (!min_packet_size) {
1784                 min_packet_size = ast_format_cap_get_framing(caps);
1785         }
1786         if (min_packet_size) {
1787                 snprintf(tmp, sizeof(tmp), "%d", min_packet_size);
1788                 attr = pjmedia_sdp_attr_create(pool, "ptime", pj_cstr(&stmp, tmp));
1789                 media->attr[media->attr_count++] = attr;
1790         }
1791
1792         if (max_packet_size) {
1793                 snprintf(tmp, sizeof(tmp), "%d", max_packet_size);
1794                 attr = pjmedia_sdp_attr_create(pool, "maxptime", pj_cstr(&stmp, tmp));
1795                 media->attr[media->attr_count++] = attr;
1796         }
1797
1798         /* Add the sendrecv attribute - we purposely don't keep track because pjmedia-sdp will automatically change our offer for us */
1799         attr = PJ_POOL_ZALLOC_T(pool, pjmedia_sdp_attr);
1800         attr->name = !session_media->locally_held ? STR_SENDRECV : STR_SENDONLY;
1801         media->attr[media->attr_count++] = attr;
1802
1803         /* If we've got rtcp-mux enabled, add it unless we received an offer without it */
1804         if (session->endpoint->media.rtcp_mux && session_media->remote_rtcp_mux) {
1805                 attr = pjmedia_sdp_attr_create(pool, "rtcp-mux", NULL);
1806                 pjmedia_sdp_attr_add(&media->attr_count, media->attr, attr);
1807         }
1808
1809         add_ssrc_to_stream(session, session_media, pool, media);
1810         add_msid_to_stream(session, session_media, pool, media, stream);
1811         add_rtcp_fb_to_stream(session, session_media, pool, media);
1812         add_extmap_to_stream(session, session_media, pool, media);
1813
1814         /* Add the media stream to the SDP */
1815         sdp->media[sdp->media_count++] = media;
1816
1817         return 1;
1818 }
1819
1820 static struct ast_frame *media_session_rtp_read_callback(struct ast_sip_session *session, struct ast_sip_session_media *session_media)
1821 {
1822         struct ast_frame *f;
1823
1824         if (!session_media->rtp) {
1825                 return &ast_null_frame;
1826         }
1827
1828         f = ast_rtp_instance_read(session_media->rtp, 0);
1829         if (!f) {
1830                 return NULL;
1831         }
1832
1833         ast_rtp_instance_set_last_rx(session_media->rtp, time(NULL));
1834
1835         return f;
1836 }
1837
1838 static struct ast_frame *media_session_rtcp_read_callback(struct ast_sip_session *session, struct ast_sip_session_media *session_media)
1839 {
1840         struct ast_frame *f;
1841
1842         if (!session_media->rtp) {
1843                 return &ast_null_frame;
1844         }
1845
1846         f = ast_rtp_instance_read(session_media->rtp, 1);
1847         if (!f) {
1848                 return NULL;
1849         }
1850
1851         ast_rtp_instance_set_last_rx(session_media->rtp, time(NULL));
1852
1853         return f;
1854 }
1855
1856 static int media_session_rtp_write_callback(struct ast_sip_session *session, struct ast_sip_session_media *session_media, struct ast_frame *frame)
1857 {
1858         if (!session_media->rtp) {
1859                 return 0;
1860         }
1861
1862         return ast_rtp_instance_write(session_media->rtp, frame);
1863 }
1864
1865 static int apply_negotiated_sdp_stream(struct ast_sip_session *session,
1866         struct ast_sip_session_media *session_media, const struct pjmedia_sdp_session *local,
1867         const struct pjmedia_sdp_session *remote, int index, struct ast_stream *asterisk_stream)
1868 {
1869         RAII_VAR(struct ast_sockaddr *, addrs, NULL, ast_free);
1870         struct pjmedia_sdp_media *remote_stream = remote->media[index];
1871         enum ast_media_type media_type = session_media->type;
1872         char host[NI_MAXHOST];
1873         int res;
1874         struct ast_sip_session_media *session_media_transport;
1875
1876         if (!session->channel) {
1877                 return 1;
1878         }
1879
1880         /* Ensure incoming transport is compatible with the endpoint's configuration */
1881         if (!session->endpoint->media.rtp.use_received_transport &&
1882                 check_endpoint_media_transport(session->endpoint, remote_stream) == AST_SIP_MEDIA_TRANSPORT_INVALID) {
1883                 return -1;
1884         }
1885
1886         /* Create an RTP instance if need be */
1887         if (!session_media->rtp && create_rtp(session, session_media, local)) {
1888                 return -1;
1889         }
1890
1891         process_ssrc_attributes(session, session_media, remote_stream);
1892         process_extmap_attributes(session, session_media, remote_stream);
1893
1894         session_media_transport = ast_sip_session_media_get_transport(session, session_media);
1895
1896         if (session_media_transport == session_media || !session_media->bundled) {
1897                 session_media->remote_rtcp_mux = (pjmedia_sdp_media_find_attr2(remote_stream, "rtcp-mux", NULL) != NULL);
1898                 set_ice_components(session, session_media);
1899
1900                 enable_rtcp(session, session_media, remote_stream);
1901
1902                 res = setup_media_encryption(session, session_media, remote, remote_stream);
1903                 if (!session->endpoint->media.rtp.encryption_optimistic && res) {
1904                         /* If optimistic encryption is disabled and crypto should have been enabled but was not
1905                          * this session must fail.
1906                          */
1907                         return -1;
1908                 }
1909
1910                 if (!remote_stream->conn && !remote->conn) {
1911                         return 1;
1912                 }
1913
1914                 ast_copy_pj_str(host, remote_stream->conn ? &remote_stream->conn->addr : &remote->conn->addr, sizeof(host));
1915
1916                 /* Ensure that the address provided is valid */
1917                 if (ast_sockaddr_resolve(&addrs, host, PARSE_PORT_FORBID, AST_AF_UNSPEC) <= 0) {
1918                         /* The provided host was actually invalid so we error out this negotiation */
1919                         return -1;
1920                 }
1921
1922                 /* Apply connection information to the RTP instance */
1923                 ast_sockaddr_set_port(addrs, remote_stream->desc.port);
1924                 ast_rtp_instance_set_remote_address(session_media->rtp, addrs);
1925
1926                 ast_sip_session_media_set_write_callback(session, session_media, media_session_rtp_write_callback);
1927                 ast_sip_session_media_add_read_callback(session, session_media, ast_rtp_instance_fd(session_media->rtp, 0),
1928                         media_session_rtp_read_callback);
1929                 if (!session->endpoint->media.rtcp_mux || !session_media->remote_rtcp_mux) {
1930                         ast_sip_session_media_add_read_callback(session, session_media, ast_rtp_instance_fd(session_media->rtp, 1),
1931                                 media_session_rtcp_read_callback);
1932                 }
1933
1934                 /* If ICE support is enabled find all the needed attributes */
1935                 process_ice_attributes(session, session_media, remote, remote_stream);
1936         } else {
1937                 /* This is bundled with another session, so mark it as such */
1938                 ast_rtp_instance_bundle(session_media->rtp, session_media_transport->rtp);
1939                 ast_sip_session_media_set_write_callback(session, session_media, media_session_rtp_write_callback);
1940                 enable_rtcp(session, session_media, remote_stream);
1941         }
1942
1943         if (set_caps(session, session_media, session_media_transport, remote_stream, 0, asterisk_stream)) {
1944                 return 1;
1945         }
1946
1947         /* Set the channel uniqueid on the RTP instance now that it is becoming active */
1948         ast_channel_lock(session->channel);
1949         ast_rtp_instance_set_channel_id(session_media->rtp, ast_channel_uniqueid(session->channel));
1950         ast_channel_unlock(session->channel);
1951
1952         /* Ensure the RTP instance is active */
1953         ast_rtp_instance_set_stream_num(session_media->rtp, ast_stream_get_position(asterisk_stream));
1954         ast_rtp_instance_activate(session_media->rtp);
1955
1956         /* audio stream handles music on hold */
1957         if (media_type != AST_MEDIA_TYPE_AUDIO) {
1958                 if ((pjmedia_sdp_neg_was_answer_remote(session->inv_session->neg) == PJ_FALSE)
1959                         && (session->inv_session->state == PJSIP_INV_STATE_CONFIRMED)) {
1960                         ast_queue_control(session->channel, AST_CONTROL_UPDATE_RTP_PEER);
1961                 }
1962                 return 1;
1963         }
1964
1965         if (ast_sockaddr_isnull(addrs) ||
1966                 ast_sockaddr_is_any(addrs) ||
1967                 pjmedia_sdp_media_find_attr2(remote_stream, "sendonly", NULL) ||
1968                 pjmedia_sdp_media_find_attr2(remote_stream, "inactive", NULL)) {
1969                 if (!session_media->remotely_held) {
1970                         /* The remote side has put us on hold */
1971                         ast_queue_hold(session->channel, session->endpoint->mohsuggest);
1972                         ast_rtp_instance_stop(session_media->rtp);
1973                         ast_queue_frame(session->channel, &ast_null_frame);
1974                         session_media->remotely_held = 1;
1975                 }
1976         } else if (session_media->remotely_held) {
1977                 /* The remote side has taken us off hold */
1978                 ast_queue_unhold(session->channel);
1979                 ast_queue_frame(session->channel, &ast_null_frame);
1980                 session_media->remotely_held = 0;
1981         } else if ((pjmedia_sdp_neg_was_answer_remote(session->inv_session->neg) == PJ_FALSE)
1982                 && (session->inv_session->state == PJSIP_INV_STATE_CONFIRMED)) {
1983                 ast_queue_control(session->channel, AST_CONTROL_UPDATE_RTP_PEER);
1984         }
1985
1986         /* This purposely resets the encryption to the configured in case it gets added later */
1987         session_media->encryption = session->endpoint->media.rtp.encryption;
1988
1989         if (session->endpoint->media.rtp.keepalive > 0 &&
1990                         session_media->type == AST_MEDIA_TYPE_AUDIO) {
1991                 ast_rtp_instance_set_keepalive(session_media->rtp, session->endpoint->media.rtp.keepalive);
1992                 /* Schedule the initial keepalive early in case this is being used to punch holes through
1993                  * a NAT. This way there won't be an awkward delay before media starts flowing in some
1994                  * scenarios.
1995                  */
1996                 AST_SCHED_DEL(sched, session_media->keepalive_sched_id);
1997                 session_media->keepalive_sched_id = ast_sched_add_variable(sched, 500, send_keepalive,
1998                         session_media, 1);
1999         }
2000
2001         /* As the channel lock is not held during this process the scheduled item won't block if
2002          * it is hanging up the channel at the same point we are applying this negotiated SDP.
2003          */
2004         AST_SCHED_DEL(sched, session_media->timeout_sched_id);
2005
2006         /* Due to the fact that we only ever have one scheduled timeout item for when we are both
2007          * off hold and on hold we don't need to store the two timeouts differently on the RTP
2008          * instance itself.
2009          */
2010         ast_rtp_instance_set_timeout(session_media->rtp, 0);
2011         if (session->endpoint->media.rtp.timeout && !session_media->remotely_held) {
2012                 ast_rtp_instance_set_timeout(session_media->rtp, session->endpoint->media.rtp.timeout);
2013         } else if (session->endpoint->media.rtp.timeout_hold && session_media->remotely_held) {
2014                 ast_rtp_instance_set_timeout(session_media->rtp, session->endpoint->media.rtp.timeout_hold);
2015         }
2016
2017         if (ast_rtp_instance_get_timeout(session_media->rtp)) {
2018                 session_media->timeout_sched_id = ast_sched_add_variable(sched,
2019                         ast_rtp_instance_get_timeout(session_media->rtp) * 1000, rtp_check_timeout,
2020                         session_media, 1);
2021         }
2022
2023         return 1;
2024 }
2025
2026 /*! \brief Function which updates the media stream with external media address, if applicable */
2027 static void change_outgoing_sdp_stream_media_address(pjsip_tx_data *tdata, struct pjmedia_sdp_media *stream, struct ast_sip_transport *transport)
2028 {
2029         RAII_VAR(struct ast_sip_transport_state *, transport_state, ast_sip_get_transport_state(ast_sorcery_object_get_id(transport)), ao2_cleanup);
2030         char host[NI_MAXHOST];
2031         struct ast_sockaddr our_sdp_addr = { { 0, } };
2032
2033         /* If the stream has been rejected there will be no connection line */
2034         if (!stream->conn || !transport_state) {
2035                 return;
2036         }
2037
2038         ast_copy_pj_str(host, &stream->conn->addr, sizeof(host));
2039         ast_sockaddr_parse(&our_sdp_addr, host, PARSE_PORT_FORBID);
2040
2041         /* Reversed check here. We don't check the remote endpoint being
2042          * in our local net, but whether our outgoing session IP is
2043          * local. If it is not, we won't do rewriting. No localnet
2044          * configured? Always rewrite. */
2045         if (ast_sip_transport_is_nonlocal(transport_state, &our_sdp_addr) && transport_state->localnet) {
2046                 return;
2047         }
2048         ast_debug(5, "Setting media address to %s\n", ast_sockaddr_stringify_host(&transport_state->external_media_address));
2049         pj_strdup2(tdata->pool, &stream->conn->addr, ast_sockaddr_stringify_host(&transport_state->external_media_address));
2050 }
2051
2052 /*! \brief Function which stops the RTP instance */
2053 static void stream_stop(struct ast_sip_session_media *session_media)
2054 {
2055         if (!session_media->rtp) {
2056                 return;
2057         }
2058
2059         AST_SCHED_DEL(sched, session_media->keepalive_sched_id);
2060         AST_SCHED_DEL(sched, session_media->timeout_sched_id);
2061         ast_rtp_instance_stop(session_media->rtp);
2062 }
2063
2064 /*! \brief Function which destroys the RTP instance when session ends */
2065 static void stream_destroy(struct ast_sip_session_media *session_media)
2066 {
2067         if (session_media->rtp) {
2068                 stream_stop(session_media);
2069                 ast_rtp_instance_destroy(session_media->rtp);
2070         }
2071         session_media->rtp = NULL;
2072 }
2073
2074 /*! \brief SDP handler for 'audio' media stream */
2075 static struct ast_sip_session_sdp_handler audio_sdp_handler = {
2076         .id = STR_AUDIO,
2077         .negotiate_incoming_sdp_stream = negotiate_incoming_sdp_stream,
2078         .create_outgoing_sdp_stream = create_outgoing_sdp_stream,
2079         .apply_negotiated_sdp_stream = apply_negotiated_sdp_stream,
2080         .change_outgoing_sdp_stream_media_address = change_outgoing_sdp_stream_media_address,
2081         .stream_stop = stream_stop,
2082         .stream_destroy = stream_destroy,
2083 };
2084
2085 /*! \brief SDP handler for 'video' media stream */
2086 static struct ast_sip_session_sdp_handler video_sdp_handler = {
2087         .id = STR_VIDEO,
2088         .negotiate_incoming_sdp_stream = negotiate_incoming_sdp_stream,
2089         .create_outgoing_sdp_stream = create_outgoing_sdp_stream,
2090         .apply_negotiated_sdp_stream = apply_negotiated_sdp_stream,
2091         .change_outgoing_sdp_stream_media_address = change_outgoing_sdp_stream_media_address,
2092         .stream_stop = stream_stop,
2093         .stream_destroy = stream_destroy,
2094 };
2095
2096 static int video_info_incoming_request(struct ast_sip_session *session, struct pjsip_rx_data *rdata)
2097 {
2098         struct pjsip_transaction *tsx;
2099         pjsip_tx_data *tdata;
2100
2101         if (!session->channel
2102                 || !ast_sip_is_content_type(&rdata->msg_info.msg->body->content_type,
2103                         "application",
2104                         "media_control+xml")) {
2105                 return 0;
2106         }
2107
2108         tsx = pjsip_rdata_get_tsx(rdata);
2109
2110         ast_queue_control(session->channel, AST_CONTROL_VIDUPDATE);
2111
2112         if (pjsip_dlg_create_response(session->inv_session->dlg, rdata, 200, NULL, &tdata) == PJ_SUCCESS) {
2113                 pjsip_dlg_send_response(session->inv_session->dlg, tsx, tdata);
2114         }
2115
2116         return 0;
2117 }
2118
2119 static struct ast_sip_session_supplement video_info_supplement = {
2120         .method = "INFO",
2121         .incoming_request = video_info_incoming_request,
2122 };
2123
2124 /*! \brief Unloads the sdp RTP/AVP module from Asterisk */
2125 static int unload_module(void)
2126 {
2127         ast_sip_session_unregister_supplement(&video_info_supplement);
2128         ast_sip_session_unregister_sdp_handler(&video_sdp_handler, STR_VIDEO);
2129         ast_sip_session_unregister_sdp_handler(&audio_sdp_handler, STR_AUDIO);
2130
2131         if (sched) {
2132                 ast_sched_context_destroy(sched);
2133         }
2134
2135         return 0;
2136 }
2137
2138 /*!
2139  * \brief Load the module
2140  *
2141  * Module loading including tests for configuration or dependencies.
2142  * This function can return AST_MODULE_LOAD_FAILURE, AST_MODULE_LOAD_DECLINE,
2143  * or AST_MODULE_LOAD_SUCCESS. If a dependency or environment variable fails
2144  * tests return AST_MODULE_LOAD_FAILURE. If the module can not load the
2145  * configuration file or other non-critical problem return
2146  * AST_MODULE_LOAD_DECLINE. On success return AST_MODULE_LOAD_SUCCESS.
2147  */
2148 static int load_module(void)
2149 {
2150         if (ast_check_ipv6()) {
2151                 ast_sockaddr_parse(&address_rtp, "::", 0);
2152         } else {
2153                 ast_sockaddr_parse(&address_rtp, "0.0.0.0", 0);
2154         }
2155
2156         if (!(sched = ast_sched_context_create())) {
2157                 ast_log(LOG_ERROR, "Unable to create scheduler context.\n");
2158                 goto end;
2159         }
2160
2161         if (ast_sched_start_thread(sched)) {
2162                 ast_log(LOG_ERROR, "Unable to create scheduler context thread.\n");
2163                 goto end;
2164         }
2165
2166         if (ast_sip_session_register_sdp_handler(&audio_sdp_handler, STR_AUDIO)) {
2167                 ast_log(LOG_ERROR, "Unable to register SDP handler for %s stream type\n", STR_AUDIO);
2168                 goto end;
2169         }
2170
2171         if (ast_sip_session_register_sdp_handler(&video_sdp_handler, STR_VIDEO)) {
2172                 ast_log(LOG_ERROR, "Unable to register SDP handler for %s stream type\n", STR_VIDEO);
2173                 goto end;
2174         }
2175
2176         ast_sip_session_register_supplement(&video_info_supplement);
2177
2178         return AST_MODULE_LOAD_SUCCESS;
2179 end:
2180         unload_module();
2181
2182         return AST_MODULE_LOAD_DECLINE;
2183 }
2184
2185 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_LOAD_ORDER, "PJSIP SDP RTP/AVP stream handler",
2186         .support_level = AST_MODULE_SUPPORT_CORE,
2187         .load = load_module,
2188         .unload = unload_module,
2189         .load_pri = AST_MODPRI_CHANNEL_DRIVER,
2190         .requires = "res_pjsip,res_pjsip_session",
2191 );