226b229f29c972f9c908028718b97a652ebc9e9d
[asterisk/asterisk.git] / main / rtp_engine.c
1 /*
2  * Asterisk -- An open source telephony toolkit.
3  *
4  * Copyright (C) 1999 - 2008, Digium, Inc.
5  *
6  * Joshua Colp <jcolp@digium.com>
7  *
8  * See http://www.asterisk.org for more information about
9  * the Asterisk project. Please do not directly contact
10  * any of the maintainers of this project for assistance;
11  * the project provides a web site, mailing lists and IRC
12  * channels for your use.
13  *
14  * This program is free software, distributed under the terms of
15  * the GNU General Public License Version 2. See the LICENSE file
16  * at the top of the source tree.
17  */
18
19 /*! \file
20  *
21  * \brief Pluggable RTP Architecture
22  *
23  * \author Joshua Colp <jcolp@digium.com>
24  */
25
26 /*** MODULEINFO
27         <support_level>core</support_level>
28 ***/
29
30 /*** DOCUMENTATION
31         <managerEvent language="en_US" name="RTCPSent">
32                 <managerEventInstance class="EVENT_FLAG_REPORTING">
33                         <synopsis>Raised when an RTCP packet is sent.</synopsis>
34                         <syntax>
35                                 <channel_snapshot/>
36                                 <parameter name="SSRC">
37                                         <para>The SSRC identifier for our stream</para>
38                                 </parameter>
39                                 <parameter name="PT">
40                                         <para>The type of packet for this RTCP report.</para>
41                                         <enumlist>
42                                                 <enum name="200(SR)"/>
43                                                 <enum name="201(RR)"/>
44                                         </enumlist>
45                                 </parameter>
46                                 <parameter name="To">
47                                         <para>The address the report is sent to.</para>
48                                 </parameter>
49                                 <parameter name="ReportCount">
50                                         <para>The number of reports that were sent.</para>
51                                         <para>The report count determines the number of ReportX headers in
52                                         the message. The X for each set of report headers will range from 0 to
53                                         <literal>ReportCount - 1</literal>.</para>
54                                 </parameter>
55                                 <parameter name="SentNTP" required="false">
56                                         <para>The time the sender generated the report. Only valid when
57                                         PT is <literal>200(SR)</literal>.</para>
58                                 </parameter>
59                                 <parameter name="SentRTP" required="false">
60                                         <para>The sender's last RTP timestamp. Only valid when PT is
61                                         <literal>200(SR)</literal>.</para>
62                                 </parameter>
63                                 <parameter name="SentPackets" required="false">
64                                         <para>The number of packets the sender has sent. Only valid when PT
65                                         is <literal>200(SR)</literal>.</para>
66                                 </parameter>
67                                 <parameter name="SentOctets" required="false">
68                                         <para>The number of bytes the sender has sent. Only valid when PT is
69                                         <literal>200(SR)</literal>.</para>
70                                 </parameter>
71                                 <parameter name="ReportXSourceSSRC">
72                                         <para>The SSRC for the source of this report block.</para>
73                                 </parameter>
74                                 <parameter name="ReportXFractionLost">
75                                         <para>The fraction of RTP data packets from <literal>ReportXSourceSSRC</literal>
76                                         lost since the previous SR or RR report was sent.</para>
77                                 </parameter>
78                                 <parameter name="ReportXCumulativeLost">
79                                         <para>The total number of RTP data packets from <literal>ReportXSourceSSRC</literal>
80                                         lost since the beginning of reception.</para>
81                                 </parameter>
82                                 <parameter name="ReportXHighestSequence">
83                                         <para>The highest sequence number received in an RTP data packet from
84                                         <literal>ReportXSourceSSRC</literal>.</para>
85                                 </parameter>
86                                 <parameter name="ReportXSequenceNumberCycles">
87                                         <para>The number of sequence number cycles seen for the RTP data
88                                         received from <literal>ReportXSourceSSRC</literal>.</para>
89                                 </parameter>
90                                 <parameter name="ReportXIAJitter">
91                                         <para>An estimate of the statistical variance of the RTP data packet
92                                         interarrival time, measured in timestamp units.</para>
93                                 </parameter>
94                                 <parameter name="ReportXLSR">
95                                         <para>The last SR timestamp received from <literal>ReportXSourceSSRC</literal>.
96                                         If no SR has been received from <literal>ReportXSourceSSRC</literal>,
97                                         then 0.</para>
98                                 </parameter>
99                                 <parameter name="ReportXDLSR">
100                                         <para>The delay, expressed in units of 1/65536 seconds, between
101                                         receiving the last SR packet from <literal>ReportXSourceSSRC</literal>
102                                         and sending this report.</para>
103                                 </parameter>
104                         </syntax>
105                         <see-also>
106                                 <ref type="managerEvent">RTCPReceived</ref>
107                         </see-also>
108                 </managerEventInstance>
109         </managerEvent>
110         <managerEvent language="en_US" name="RTCPReceived">
111                 <managerEventInstance class="EVENT_FLAG_REPORTING">
112                         <synopsis>Raised when an RTCP packet is received.</synopsis>
113                         <syntax>
114                                 <channel_snapshot/>
115                                 <parameter name="SSRC">
116                                         <para>The SSRC identifier for the remote system</para>
117                                 </parameter>
118                                 <xi:include xpointer="xpointer(/docs/managerEvent[@name='RTCPSent']/managerEventInstance/syntax/parameter[@name='PT'])" />
119                                 <parameter name="From">
120                                         <para>The address the report was received from.</para>
121                                 </parameter>
122                                 <parameter name="RTT">
123                                         <para>Calculated Round-Trip Time in seconds</para>
124                                 </parameter>
125                                 <parameter name="ReportCount">
126                                         <para>The number of reports that were received.</para>
127                                         <para>The report count determines the number of ReportX headers in
128                                         the message. The X for each set of report headers will range from 0 to
129                                         <literal>ReportCount - 1</literal>.</para>
130                                 </parameter>
131                                 <xi:include xpointer="xpointer(/docs/managerEvent[@name='RTCPSent']/managerEventInstance/syntax/parameter[@name='SentNTP'])" />
132                                 <xi:include xpointer="xpointer(/docs/managerEvent[@name='RTCPSent']/managerEventInstance/syntax/parameter[@name='SentRTP'])" />
133                                 <xi:include xpointer="xpointer(/docs/managerEvent[@name='RTCPSent']/managerEventInstance/syntax/parameter[@name='SentPackets'])" />
134                                 <xi:include xpointer="xpointer(/docs/managerEvent[@name='RTCPSent']/managerEventInstance/syntax/parameter[@name='SentOctets'])" />
135                                 <xi:include xpointer="xpointer(/docs/managerEvent[@name='RTCPSent']/managerEventInstance/syntax/parameter[contains(@name, 'ReportX')])" />
136                         </syntax>
137                         <see-also>
138                                 <ref type="managerEvent">RTCPSent</ref>
139                         </see-also>
140                 </managerEventInstance>
141         </managerEvent>
142  ***/
143
144 #include "asterisk.h"
145
146 #include <math.h>                       /* for sqrt, MAX */
147 #include <sched.h>                      /* for sched_yield */
148 #include <sys/time.h>                   /* for timeval */
149 #include <time.h>                       /* for time_t */
150
151 #include "asterisk/_private.h"          /* for ast_rtp_engine_init prototype */
152 #include "asterisk/astobj2.h"           /* for ao2_cleanup, ao2_ref, etc */
153 #include "asterisk/channel.h"           /* for ast_channel_name, etc */
154 #include "asterisk/codec.h"             /* for ast_codec_media_type2str, etc */
155 #include "asterisk/format.h"            /* for ast_format_cmp, etc */
156 #include "asterisk/format_cache.h"      /* for ast_format_adpcm, etc */
157 #include "asterisk/format_cap.h"        /* for ast_format_cap_alloc, etc */
158 #include "asterisk/json.h"              /* for ast_json_ref, etc */
159 #include "asterisk/linkedlists.h"       /* for ast_rtp_engine::<anonymous>, etc */
160 #include "asterisk/lock.h"              /* for ast_rwlock_unlock, etc */
161 #include "asterisk/logger.h"            /* for ast_log, ast_debug, etc */
162 #include "asterisk/manager.h"
163 #include "asterisk/module.h"            /* for ast_module_unref, etc */
164 #include "asterisk/netsock2.h"          /* for ast_sockaddr_copy, etc */
165 #include "asterisk/options.h"           /* for ast_option_rtpptdynamic */
166 #include "asterisk/pbx.h"               /* for pbx_builtin_setvar_helper */
167 #include "asterisk/res_srtp.h"          /* for ast_srtp_res */
168 #include "asterisk/rtp_engine.h"        /* for ast_rtp_codecs, etc */
169 #include "asterisk/stasis.h"            /* for stasis_message_data, etc */
170 #include "asterisk/stasis_channels.h"   /* for ast_channel_stage_snapshot, etc */
171 #include "asterisk/strings.h"           /* for ast_str_append, etc */
172 #include "asterisk/time.h"              /* for ast_tvdiff_ms, ast_tvnow */
173 #include "asterisk/translate.h"         /* for ast_translate_available_formats */
174 #include "asterisk/utils.h"             /* for ast_free, ast_strdup, etc */
175 #include "asterisk/vector.h"            /* for AST_VECTOR_GET, etc */
176
177 struct ast_srtp_res *res_srtp = NULL;
178 struct ast_srtp_policy_res *res_srtp_policy = NULL;
179
180 /*! Structure that represents an RTP session (instance) */
181 struct ast_rtp_instance {
182         /*! Engine that is handling this RTP instance */
183         struct ast_rtp_engine *engine;
184         /*! Data unique to the RTP engine */
185         void *data;
186         /*! RTP properties that have been set and their value */
187         int properties[AST_RTP_PROPERTY_MAX];
188         /*! Address that we are expecting RTP to come in to */
189         struct ast_sockaddr local_address;
190         /*! The original source address */
191         struct ast_sockaddr requested_target_address;
192         /*! Address that we are sending RTP to */
193         struct ast_sockaddr incoming_source_address;
194         /*! Instance that we are bridged to if doing remote or local bridging */
195         struct ast_rtp_instance *bridged;
196         /*! Payload and packetization information */
197         struct ast_rtp_codecs codecs;
198         /*! RTP timeout time (negative or zero means disabled, negative value means temporarily disabled) */
199         int timeout;
200         /*! RTP timeout when on hold (negative or zero means disabled, negative value means temporarily disabled). */
201         int holdtimeout;
202         /*! RTP keepalive interval */
203         int keepalive;
204         /*! Glue currently in use */
205         struct ast_rtp_glue *glue;
206         /*! SRTP info associated with the instance */
207         struct ast_srtp *srtp;
208         /*! SRTP info dedicated for RTCP associated with the instance */
209         struct ast_srtp *rtcp_srtp;
210         /*! Channel unique ID */
211         char channel_uniqueid[AST_MAX_UNIQUEID];
212         /*! Time of last packet sent */
213         time_t last_tx;
214         /*! Time of last packet received */
215         time_t last_rx;
216 };
217
218 /*! List of RTP engines that are currently registered */
219 static AST_RWLIST_HEAD_STATIC(engines, ast_rtp_engine);
220
221 /*! List of RTP glues */
222 static AST_RWLIST_HEAD_STATIC(glues, ast_rtp_glue);
223
224 #define MAX_RTP_MIME_TYPES 128
225
226 /*! The following array defines the MIME Media type (and subtype) for each
227    of our codecs, or RTP-specific data type. */
228 static struct ast_rtp_mime_type {
229         /*! \brief A mapping object between the Asterisk codec and this RTP payload */
230         struct ast_rtp_payload_type payload_type;
231         /*! \brief The media type */
232         char type[16];
233         /*! \brief The format type */
234         char subtype[64];
235         /*! \brief Expected sample rate of the /c subtype */
236         unsigned int sample_rate;
237 } ast_rtp_mime_types[128]; /* This will Likely not need to grow any time soon. */
238 static ast_rwlock_t mime_types_lock;
239 static int mime_types_len = 0;
240
241 /*!
242  * \brief Mapping between Asterisk codecs and rtp payload types
243  *
244  * Static (i.e., well-known) RTP payload types for our "AST_FORMAT..."s:
245  * also, our own choices for dynamic payload types.  This is our master
246  * table for transmission
247  *
248  * See http://www.iana.org/assignments/rtp-parameters for a list of
249  * assigned values
250  */
251 static struct ast_rtp_payload_type *static_RTP_PT[AST_RTP_MAX_PT];
252 static ast_rwlock_t static_RTP_PT_lock;
253
254 /*! \brief \ref stasis topic for RTP related messages */
255 static struct stasis_topic *rtp_topic;
256
257
258 /*!
259  * \internal
260  * \brief Destructor for \c ast_rtp_payload_type
261  */
262 static void rtp_payload_type_dtor(void *obj)
263 {
264         struct ast_rtp_payload_type *payload = obj;
265
266         ao2_cleanup(payload->format);
267 }
268
269 static struct ast_rtp_payload_type *rtp_payload_type_alloc(struct ast_format *format,
270         int payload, int rtp_code, int primary_mapping)
271 {
272         struct ast_rtp_payload_type *type = ao2_alloc_options(
273                 sizeof(*type), rtp_payload_type_dtor, AO2_ALLOC_OPT_LOCK_NOLOCK);
274
275         if (!type) {
276                 return NULL;
277         }
278
279         type->format = ao2_bump(format);
280         type->asterisk_format = type->format != NULL;
281         type->payload = payload;
282         type->rtp_code = rtp_code;
283         type->primary_mapping = primary_mapping;
284
285         return type;
286 }
287
288 struct ast_rtp_payload_type *ast_rtp_engine_alloc_payload_type(void)
289 {
290         return rtp_payload_type_alloc(NULL, 0, 0, 0);
291 }
292
293 int ast_rtp_engine_register2(struct ast_rtp_engine *engine, struct ast_module *module)
294 {
295         struct ast_rtp_engine *current_engine;
296
297         /* Perform a sanity check on the engine structure to make sure it has the basics */
298         if (ast_strlen_zero(engine->name) || !engine->new || !engine->destroy || !engine->write || !engine->read) {
299                 ast_log(LOG_WARNING, "RTP Engine '%s' failed sanity check so it was not registered.\n", !ast_strlen_zero(engine->name) ? engine->name : "Unknown");
300                 return -1;
301         }
302
303         /* Link owner module to the RTP engine for reference counting purposes */
304         engine->mod = module;
305
306         AST_RWLIST_WRLOCK(&engines);
307
308         /* Ensure that no two modules with the same name are registered at the same time */
309         AST_RWLIST_TRAVERSE(&engines, current_engine, entry) {
310                 if (!strcmp(current_engine->name, engine->name)) {
311                         ast_log(LOG_WARNING, "An RTP engine with the name '%s' has already been registered.\n", engine->name);
312                         AST_RWLIST_UNLOCK(&engines);
313                         return -1;
314                 }
315         }
316
317         /* The engine survived our critique. Off to the list it goes to be used */
318         AST_RWLIST_INSERT_TAIL(&engines, engine, entry);
319
320         AST_RWLIST_UNLOCK(&engines);
321
322         ast_verb(2, "Registered RTP engine '%s'\n", engine->name);
323
324         return 0;
325 }
326
327 int ast_rtp_engine_unregister(struct ast_rtp_engine *engine)
328 {
329         struct ast_rtp_engine *current_engine = NULL;
330
331         AST_RWLIST_WRLOCK(&engines);
332
333         if ((current_engine = AST_RWLIST_REMOVE(&engines, engine, entry))) {
334                 ast_verb(2, "Unregistered RTP engine '%s'\n", engine->name);
335         }
336
337         AST_RWLIST_UNLOCK(&engines);
338
339         return current_engine ? 0 : -1;
340 }
341
342 int ast_rtp_glue_register2(struct ast_rtp_glue *glue, struct ast_module *module)
343 {
344         struct ast_rtp_glue *current_glue = NULL;
345
346         if (ast_strlen_zero(glue->type)) {
347                 return -1;
348         }
349
350         glue->mod = module;
351
352         AST_RWLIST_WRLOCK(&glues);
353
354         AST_RWLIST_TRAVERSE(&glues, current_glue, entry) {
355                 if (!strcasecmp(current_glue->type, glue->type)) {
356                         ast_log(LOG_WARNING, "RTP glue with the name '%s' has already been registered.\n", glue->type);
357                         AST_RWLIST_UNLOCK(&glues);
358                         return -1;
359                 }
360         }
361
362         AST_RWLIST_INSERT_TAIL(&glues, glue, entry);
363
364         AST_RWLIST_UNLOCK(&glues);
365
366         ast_verb(2, "Registered RTP glue '%s'\n", glue->type);
367
368         return 0;
369 }
370
371 int ast_rtp_glue_unregister(struct ast_rtp_glue *glue)
372 {
373         struct ast_rtp_glue *current_glue = NULL;
374
375         AST_RWLIST_WRLOCK(&glues);
376
377         if ((current_glue = AST_RWLIST_REMOVE(&glues, glue, entry))) {
378                 ast_verb(2, "Unregistered RTP glue '%s'\n", glue->type);
379         }
380
381         AST_RWLIST_UNLOCK(&glues);
382
383         return current_glue ? 0 : -1;
384 }
385
386 static void instance_destructor(void *obj)
387 {
388         struct ast_rtp_instance *instance = obj;
389
390         /* Pass us off to the engine to destroy */
391         if (instance->data) {
392                 /*
393                  * Lock in case the RTP engine has other threads that
394                  * need synchronization with the destruction.
395                  */
396                 ao2_lock(instance);
397                 instance->engine->destroy(instance);
398                 ao2_unlock(instance);
399         }
400
401         if (instance->srtp) {
402                 res_srtp->destroy(instance->srtp);
403         }
404
405         if (instance->rtcp_srtp) {
406                 res_srtp->destroy(instance->rtcp_srtp);
407         }
408
409         ast_rtp_codecs_payloads_destroy(&instance->codecs);
410
411         /* Drop our engine reference */
412         ast_module_unref(instance->engine->mod);
413
414         ast_debug(1, "Destroyed RTP instance '%p'\n", instance);
415 }
416
417 int ast_rtp_instance_destroy(struct ast_rtp_instance *instance)
418 {
419         ao2_ref(instance, -1);
420
421         return 0;
422 }
423
424 struct ast_rtp_instance *ast_rtp_instance_new(const char *engine_name,
425                 struct ast_sched_context *sched, const struct ast_sockaddr *sa,
426                 void *data)
427 {
428         struct ast_sockaddr address = {{0,}};
429         struct ast_rtp_instance *instance = NULL;
430         struct ast_rtp_engine *engine = NULL;
431
432         AST_RWLIST_RDLOCK(&engines);
433
434         /* If an engine name was specified try to use it or otherwise use the first one registered */
435         if (!ast_strlen_zero(engine_name)) {
436                 AST_RWLIST_TRAVERSE(&engines, engine, entry) {
437                         if (!strcmp(engine->name, engine_name)) {
438                                 break;
439                         }
440                 }
441         } else {
442                 engine = AST_RWLIST_FIRST(&engines);
443         }
444
445         /* If no engine was actually found bail out now */
446         if (!engine) {
447                 ast_log(LOG_ERROR, "No RTP engine was found. Do you have one loaded?\n");
448                 AST_RWLIST_UNLOCK(&engines);
449                 return NULL;
450         }
451
452         /* Bump up the reference count before we return so the module can not be unloaded */
453         ast_module_ref(engine->mod);
454
455         AST_RWLIST_UNLOCK(&engines);
456
457         /* Allocate a new RTP instance */
458         if (!(instance = ao2_alloc(sizeof(*instance), instance_destructor))) {
459                 ast_module_unref(engine->mod);
460                 return NULL;
461         }
462         instance->engine = engine;
463         ast_sockaddr_copy(&instance->local_address, sa);
464         ast_sockaddr_copy(&address, sa);
465
466         if (ast_rtp_codecs_payloads_initialize(&instance->codecs)) {
467                 ao2_ref(instance, -1);
468                 return NULL;
469         }
470
471         ast_debug(1, "Using engine '%s' for RTP instance '%p'\n", engine->name, instance);
472
473         /*
474          * And pass it off to the engine to setup
475          *
476          * Lock in case the RTP engine has other threads that
477          * need synchronization with the construction.
478          */
479         ao2_lock(instance);
480         if (instance->engine->new(instance, sched, &address, data)) {
481                 ast_debug(1, "Engine '%s' failed to setup RTP instance '%p'\n", engine->name, instance);
482                 ao2_unlock(instance);
483                 ao2_ref(instance, -1);
484                 return NULL;
485         }
486         ao2_unlock(instance);
487
488         ast_debug(1, "RTP instance '%p' is setup and ready to go\n", instance);
489
490         return instance;
491 }
492
493 const char *ast_rtp_instance_get_channel_id(struct ast_rtp_instance *instance)
494 {
495         return instance->channel_uniqueid;
496 }
497
498 void ast_rtp_instance_set_channel_id(struct ast_rtp_instance *instance, const char *uniqueid)
499 {
500         ast_copy_string(instance->channel_uniqueid, uniqueid, sizeof(instance->channel_uniqueid));
501 }
502
503 void ast_rtp_instance_set_data(struct ast_rtp_instance *instance, void *data)
504 {
505         instance->data = data;
506 }
507
508 void *ast_rtp_instance_get_data(struct ast_rtp_instance *instance)
509 {
510         return instance->data;
511 }
512
513 int ast_rtp_instance_write(struct ast_rtp_instance *instance, struct ast_frame *frame)
514 {
515         int res;
516
517         ao2_lock(instance);
518         res = instance->engine->write(instance, frame);
519         ao2_unlock(instance);
520         return res;
521 }
522
523 struct ast_frame *ast_rtp_instance_read(struct ast_rtp_instance *instance, int rtcp)
524 {
525         struct ast_frame *frame;
526
527         ao2_lock(instance);
528         frame = instance->engine->read(instance, rtcp);
529         ao2_unlock(instance);
530         return frame;
531 }
532
533 int ast_rtp_instance_set_local_address(struct ast_rtp_instance *instance,
534                 const struct ast_sockaddr *address)
535 {
536         ao2_lock(instance);
537         ast_sockaddr_copy(&instance->local_address, address);
538         ao2_unlock(instance);
539         return 0;
540 }
541
542 static void rtp_instance_set_incoming_source_address_nolock(struct ast_rtp_instance *instance,
543         const struct ast_sockaddr *address)
544 {
545         ast_sockaddr_copy(&instance->incoming_source_address, address);
546         if (instance->engine->remote_address_set) {
547                 instance->engine->remote_address_set(instance, &instance->incoming_source_address);
548         }
549 }
550
551 int ast_rtp_instance_set_incoming_source_address(struct ast_rtp_instance *instance,
552         const struct ast_sockaddr *address)
553 {
554         ao2_lock(instance);
555         rtp_instance_set_incoming_source_address_nolock(instance, address);
556         ao2_unlock(instance);
557
558         return 0;
559 }
560
561 int ast_rtp_instance_set_requested_target_address(struct ast_rtp_instance *instance,
562                                                   const struct ast_sockaddr *address)
563 {
564         ao2_lock(instance);
565
566         ast_sockaddr_copy(&instance->requested_target_address, address);
567         rtp_instance_set_incoming_source_address_nolock(instance, address);
568
569         ao2_unlock(instance);
570
571         return 0;
572 }
573
574 int ast_rtp_instance_get_and_cmp_local_address(struct ast_rtp_instance *instance,
575                 struct ast_sockaddr *address)
576 {
577         ao2_lock(instance);
578         if (ast_sockaddr_cmp(address, &instance->local_address) != 0) {
579                 ast_sockaddr_copy(address, &instance->local_address);
580                 ao2_unlock(instance);
581                 return 1;
582         }
583         ao2_unlock(instance);
584
585         return 0;
586 }
587
588 void ast_rtp_instance_get_local_address(struct ast_rtp_instance *instance,
589                 struct ast_sockaddr *address)
590 {
591         ao2_lock(instance);
592         ast_sockaddr_copy(address, &instance->local_address);
593         ao2_unlock(instance);
594 }
595
596 int ast_rtp_instance_get_and_cmp_requested_target_address(struct ast_rtp_instance *instance,
597                 struct ast_sockaddr *address)
598 {
599         ao2_lock(instance);
600         if (ast_sockaddr_cmp(address, &instance->requested_target_address) != 0) {
601                 ast_sockaddr_copy(address, &instance->requested_target_address);
602                 ao2_unlock(instance);
603                 return 1;
604         }
605         ao2_unlock(instance);
606
607         return 0;
608 }
609
610 void ast_rtp_instance_get_incoming_source_address(struct ast_rtp_instance *instance,
611                                                   struct ast_sockaddr *address)
612 {
613         ao2_lock(instance);
614         ast_sockaddr_copy(address, &instance->incoming_source_address);
615         ao2_unlock(instance);
616 }
617
618 void ast_rtp_instance_get_requested_target_address(struct ast_rtp_instance *instance,
619                                                    struct ast_sockaddr *address)
620 {
621         ao2_lock(instance);
622         ast_sockaddr_copy(address, &instance->requested_target_address);
623         ao2_unlock(instance);
624 }
625
626 void ast_rtp_instance_set_extended_prop(struct ast_rtp_instance *instance, int property, void *value)
627 {
628         if (instance->engine->extended_prop_set) {
629                 ao2_lock(instance);
630                 instance->engine->extended_prop_set(instance, property, value);
631                 ao2_unlock(instance);
632         }
633 }
634
635 void *ast_rtp_instance_get_extended_prop(struct ast_rtp_instance *instance, int property)
636 {
637         void *prop;
638
639         if (instance->engine->extended_prop_get) {
640                 ao2_lock(instance);
641                 prop = instance->engine->extended_prop_get(instance, property);
642                 ao2_unlock(instance);
643         } else {
644                 prop = NULL;
645         }
646
647         return prop;
648 }
649
650 void ast_rtp_instance_set_prop(struct ast_rtp_instance *instance, enum ast_rtp_property property, int value)
651 {
652         ao2_lock(instance);
653         instance->properties[property] = value;
654
655         if (instance->engine->prop_set) {
656                 instance->engine->prop_set(instance, property, value);
657         }
658         ao2_unlock(instance);
659 }
660
661 int ast_rtp_instance_get_prop(struct ast_rtp_instance *instance, enum ast_rtp_property property)
662 {
663         int prop;
664
665         ao2_lock(instance);
666         prop = instance->properties[property];
667         ao2_unlock(instance);
668
669         return prop;
670 }
671
672 struct ast_rtp_codecs *ast_rtp_instance_get_codecs(struct ast_rtp_instance *instance)
673 {
674         return &instance->codecs;
675 }
676
677 int ast_rtp_codecs_payloads_initialize(struct ast_rtp_codecs *codecs)
678 {
679         int res;
680
681         codecs->framing = 0;
682         ast_rwlock_init(&codecs->codecs_lock);
683         res = AST_VECTOR_INIT(&codecs->payload_mapping_rx, AST_RTP_MAX_PT);
684         res |= AST_VECTOR_INIT(&codecs->payload_mapping_tx, AST_RTP_MAX_PT);
685         if (res) {
686                 AST_VECTOR_FREE(&codecs->payload_mapping_rx);
687                 AST_VECTOR_FREE(&codecs->payload_mapping_tx);
688         }
689
690         return res;
691 }
692
693 void ast_rtp_codecs_payloads_destroy(struct ast_rtp_codecs *codecs)
694 {
695         int idx;
696         struct ast_rtp_payload_type *type;
697
698         for (idx = 0; idx < AST_VECTOR_SIZE(&codecs->payload_mapping_rx); ++idx) {
699                 type = AST_VECTOR_GET(&codecs->payload_mapping_rx, idx);
700                 ao2_t_cleanup(type, "destroying ast_rtp_codec rx mapping");
701         }
702         AST_VECTOR_FREE(&codecs->payload_mapping_rx);
703
704         for (idx = 0; idx < AST_VECTOR_SIZE(&codecs->payload_mapping_tx); ++idx) {
705                 type = AST_VECTOR_GET(&codecs->payload_mapping_tx, idx);
706                 ao2_t_cleanup(type, "destroying ast_rtp_codec tx mapping");
707         }
708         AST_VECTOR_FREE(&codecs->payload_mapping_tx);
709
710         ast_rwlock_destroy(&codecs->codecs_lock);
711 }
712
713 void ast_rtp_codecs_payloads_clear(struct ast_rtp_codecs *codecs, struct ast_rtp_instance *instance)
714 {
715         ast_rtp_codecs_payloads_destroy(codecs);
716         ast_rtp_codecs_payloads_initialize(codecs);
717
718         if (instance && instance->engine && instance->engine->payload_set) {
719                 int i;
720
721                 ao2_lock(instance);
722                 for (i = 0; i < AST_RTP_MAX_PT; i++) {
723                         instance->engine->payload_set(instance, i, 0, NULL, 0);
724                 }
725                 ao2_unlock(instance);
726         }
727 }
728
729 /*!
730  * \internal
731  * \brief Clear the rx primary mapping flag on all other matching mappings.
732  * \since 14.0.0
733  *
734  * \param codecs Codecs that need rx clearing.
735  * \param to_match Payload type object to compare against.
736  *
737  * \note It is assumed that codecs is write locked before calling.
738  *
739  * \return Nothing
740  */
741 static void payload_mapping_rx_clear_primary(struct ast_rtp_codecs *codecs, struct ast_rtp_payload_type *to_match)
742 {
743         int idx;
744         struct ast_rtp_payload_type *current;
745         struct ast_rtp_payload_type *new_type;
746         struct timeval now;
747
748         if (!to_match->primary_mapping) {
749                 return;
750         }
751
752         now = ast_tvnow();
753         for (idx = 0; idx < AST_VECTOR_SIZE(&codecs->payload_mapping_rx); ++idx) {
754                 current = AST_VECTOR_GET(&codecs->payload_mapping_rx, idx);
755
756                 if (!current || current == to_match || !current->primary_mapping) {
757                         continue;
758                 }
759                 if (current->asterisk_format && to_match->asterisk_format) {
760                         if (ast_format_cmp(current->format, to_match->format) == AST_FORMAT_CMP_NOT_EQUAL) {
761                                 continue;
762                         }
763                 } else if (!current->asterisk_format && !to_match->asterisk_format) {
764                         if (current->rtp_code != to_match->rtp_code) {
765                                 continue;
766                         }
767                 } else {
768                         continue;
769                 }
770
771                 /* Replace current with non-primary marked version */
772                 new_type = ast_rtp_engine_alloc_payload_type();
773                 if (!new_type) {
774                         continue;
775                 }
776                 *new_type = *current;
777                 new_type->primary_mapping = 0;
778                 new_type->when_retired = now;
779                 ao2_bump(new_type->format);
780                 AST_VECTOR_REPLACE(&codecs->payload_mapping_rx, idx, new_type);
781                 ao2_ref(current, -1);
782         }
783 }
784
785 /*!
786  * \internal
787  * \brief Put the new_type into the rx payload type mapping.
788  * \since 14.0.0
789  *
790  * \param codecs Codecs structure to put new_type into
791  * \param payload type position to replace.
792  * \param new_type RTP payload mapping object to store.
793  *
794  * \note It is assumed that codecs is write locked before calling.
795  *
796  * \return Nothing
797  */
798 static void rtp_codecs_payload_replace_rx(struct ast_rtp_codecs *codecs, int payload, struct ast_rtp_payload_type *new_type)
799 {
800         ao2_ref(new_type, +1);
801         if (payload < AST_VECTOR_SIZE(&codecs->payload_mapping_rx)) {
802                 ao2_t_cleanup(AST_VECTOR_GET(&codecs->payload_mapping_rx, payload),
803                         "cleaning up rx mapping vector element about to be replaced");
804         }
805         AST_VECTOR_REPLACE(&codecs->payload_mapping_rx, payload, new_type);
806
807         payload_mapping_rx_clear_primary(codecs, new_type);
808 }
809
810 /*!
811  * \internal
812  * \brief Copy the rx payload type mapping to the destination.
813  * \since 14.0.0
814  *
815  * \param src The source codecs structure
816  * \param dest The destination codecs structure that the values from src will be copied to
817  * \param instance Optionally the instance that the dst codecs structure belongs to
818  *
819  * \note It is assumed that src is at least read locked before calling.
820  * \note It is assumed that dest is write locked before calling.
821  *
822  * \return Nothing
823  */
824 static void rtp_codecs_payloads_copy_rx(struct ast_rtp_codecs *src, struct ast_rtp_codecs *dest, struct ast_rtp_instance *instance)
825 {
826         int idx;
827         struct ast_rtp_payload_type *type;
828
829         for (idx = 0; idx < AST_VECTOR_SIZE(&src->payload_mapping_rx); ++idx) {
830                 type = AST_VECTOR_GET(&src->payload_mapping_rx, idx);
831                 if (!type) {
832                         continue;
833                 }
834
835                 ast_debug(2, "Copying rx payload mapping %d (%p) from %p to %p\n",
836                         idx, type, src, dest);
837                 rtp_codecs_payload_replace_rx(dest, idx, type);
838
839                 if (instance && instance->engine && instance->engine->payload_set) {
840                         ao2_lock(instance);
841                         instance->engine->payload_set(instance, idx, type->asterisk_format, type->format, type->rtp_code);
842                         ao2_unlock(instance);
843                 }
844         }
845 }
846
847 /*!
848  * \internal
849  * \brief Determine if a type of payload is already present in mappings.
850  * \since 14.0.0
851  *
852  * \param codecs Codecs to be checked for mappings.
853  * \param to_match Payload type object to compare against.
854  *
855  * \note It is assumed that codecs is write locked before calling.
856  *
857  * \retval 0 not found
858  * \retval 1 found
859  */
860 static int payload_mapping_tx_is_present(const struct ast_rtp_codecs *codecs, const struct ast_rtp_payload_type *to_match)
861 {
862         int idx;
863         struct ast_rtp_payload_type *current;
864
865         for (idx = 0; idx < AST_VECTOR_SIZE(&codecs->payload_mapping_tx); ++idx) {
866                 current = AST_VECTOR_GET(&codecs->payload_mapping_tx, idx);
867
868                 if (!current) {
869                         continue;
870                 }
871                 if (current == to_match) {
872                         /* The exact object is already in the mapping. */
873                         return 1;
874                 }
875                 if (current->asterisk_format && to_match->asterisk_format) {
876                         if (ast_format_get_codec_id(current->format) != ast_format_get_codec_id(to_match->format)) {
877                                 continue;
878                         } else if (current->payload == to_match->payload) {
879                                 return 0;
880                         }
881                 } else if (!current->asterisk_format && !to_match->asterisk_format) {
882                         if (current->rtp_code != to_match->rtp_code) {
883                                 continue;
884                         }
885                 } else {
886                         continue;
887                 }
888
889                 return 1;
890         }
891
892         return 0;
893 }
894
895 /*!
896  * \internal
897  * \brief Copy the tx payload type mapping to the destination.
898  * \since 14.0.0
899  *
900  * \param src The source codecs structure
901  * \param dest The destination codecs structure that the values from src will be copied to
902  * \param instance Optionally the instance that the dst codecs structure belongs to
903  *
904  * \note It is assumed that src is at least read locked before calling.
905  * \note It is assumed that dest is write locked before calling.
906  *
907  * \return Nothing
908  */
909 static void rtp_codecs_payloads_copy_tx(struct ast_rtp_codecs *src, struct ast_rtp_codecs *dest, struct ast_rtp_instance *instance)
910 {
911         int idx;
912         struct ast_rtp_payload_type *type;
913
914         for (idx = 0; idx < AST_VECTOR_SIZE(&src->payload_mapping_tx); ++idx) {
915                 type = AST_VECTOR_GET(&src->payload_mapping_tx, idx);
916                 if (!type) {
917                         continue;
918                 }
919
920                 ast_debug(2, "Copying tx payload mapping %d (%p) from %p to %p\n",
921                         idx, type, src, dest);
922                 ao2_ref(type, +1);
923                 if (idx < AST_VECTOR_SIZE(&dest->payload_mapping_tx)) {
924                         ao2_t_cleanup(AST_VECTOR_GET(&dest->payload_mapping_tx, idx),
925                                 "cleaning up tx mapping vector element about to be replaced");
926                 }
927                 AST_VECTOR_REPLACE(&dest->payload_mapping_tx, idx, type);
928
929                 if (instance && instance->engine && instance->engine->payload_set) {
930                         ao2_lock(instance);
931                         instance->engine->payload_set(instance, idx, type->asterisk_format, type->format, type->rtp_code);
932                         ao2_unlock(instance);
933                 }
934         }
935 }
936
937 void ast_rtp_codecs_payloads_copy(struct ast_rtp_codecs *src, struct ast_rtp_codecs *dest, struct ast_rtp_instance *instance)
938 {
939         int idx;
940         struct ast_rtp_payload_type *type;
941
942         ast_rwlock_wrlock(&dest->codecs_lock);
943
944         /* Deadlock avoidance because of held write lock. */
945         while (ast_rwlock_tryrdlock(&src->codecs_lock)) {
946                 ast_rwlock_unlock(&dest->codecs_lock);
947                 sched_yield();
948                 ast_rwlock_wrlock(&dest->codecs_lock);
949         }
950
951         /*
952          * This represents a completely new mapping of what the remote party is
953          * expecting for payloads, so we clear out the entire tx payload mapping
954          * vector and replace it.
955          */
956         for (idx = 0; idx < AST_VECTOR_SIZE(&dest->payload_mapping_tx); ++idx) {
957                 type = AST_VECTOR_GET(&dest->payload_mapping_tx, idx);
958                 ao2_t_cleanup(type, "destroying ast_rtp_codec tx mapping");
959                 AST_VECTOR_REPLACE(&dest->payload_mapping_tx, idx, NULL);
960         }
961
962         rtp_codecs_payloads_copy_rx(src, dest, instance);
963         rtp_codecs_payloads_copy_tx(src, dest, instance);
964         dest->framing = src->framing;
965
966         ast_rwlock_unlock(&src->codecs_lock);
967         ast_rwlock_unlock(&dest->codecs_lock);
968 }
969
970 void ast_rtp_codecs_payloads_xover(struct ast_rtp_codecs *src, struct ast_rtp_codecs *dest, struct ast_rtp_instance *instance)
971 {
972         int idx;
973         struct ast_rtp_payload_type *type;
974
975         ast_rwlock_wrlock(&dest->codecs_lock);
976         if (src != dest) {
977                 /* Deadlock avoidance because of held write lock. */
978                 while (ast_rwlock_tryrdlock(&src->codecs_lock)) {
979                         ast_rwlock_unlock(&dest->codecs_lock);
980                         sched_yield();
981                         ast_rwlock_wrlock(&dest->codecs_lock);
982                 }
983         }
984
985         /* Crossover copy payload type tx mapping to rx mapping. */
986         for (idx = 0; idx < AST_VECTOR_SIZE(&src->payload_mapping_tx); ++idx) {
987                 type = AST_VECTOR_GET(&src->payload_mapping_tx, idx);
988                 if (!type) {
989                         continue;
990                 }
991
992                 /* All tx mapping elements should have the primary flag set. */
993                 ast_assert(type->primary_mapping);
994
995                 ast_debug(2, "Crossover copying tx to rx payload mapping %d (%p) from %p to %p\n",
996                         idx, type, src, dest);
997                 rtp_codecs_payload_replace_rx(dest, idx, type);
998
999                 if (instance && instance->engine && instance->engine->payload_set) {
1000                         ao2_lock(instance);
1001                         instance->engine->payload_set(instance, idx, type->asterisk_format, type->format, type->rtp_code);
1002                         ao2_unlock(instance);
1003                 }
1004         }
1005
1006         dest->framing = src->framing;
1007
1008         if (src != dest) {
1009                 ast_rwlock_unlock(&src->codecs_lock);
1010         }
1011         ast_rwlock_unlock(&dest->codecs_lock);
1012 }
1013
1014 void ast_rtp_codecs_payloads_set_m_type(struct ast_rtp_codecs *codecs, struct ast_rtp_instance *instance, int payload)
1015 {
1016         struct ast_rtp_payload_type *new_type;
1017
1018         if (payload < 0 || payload >= AST_RTP_MAX_PT) {
1019                 return;
1020         }
1021
1022         ast_rwlock_rdlock(&static_RTP_PT_lock);
1023         new_type = ao2_bump(static_RTP_PT[payload]);
1024         ast_rwlock_unlock(&static_RTP_PT_lock);
1025         if (!new_type) {
1026                 ast_debug(1, "Don't have a default tx payload type %d format for m type on %p\n",
1027                         payload, codecs);
1028                 return;
1029         }
1030
1031         ast_debug(1, "Setting tx payload type %d based on m type on %p\n",
1032                 payload, codecs);
1033
1034         ast_rwlock_wrlock(&codecs->codecs_lock);
1035
1036         if (!payload_mapping_tx_is_present(codecs, new_type)) {
1037                 if (payload < AST_VECTOR_SIZE(&codecs->payload_mapping_tx)) {
1038                         ao2_t_cleanup(AST_VECTOR_GET(&codecs->payload_mapping_tx, payload),
1039                                 "cleaning up replaced tx payload type");
1040                 }
1041                 AST_VECTOR_REPLACE(&codecs->payload_mapping_tx, payload, new_type);
1042
1043                 if (instance && instance->engine && instance->engine->payload_set) {
1044                         ao2_lock(instance);
1045                         instance->engine->payload_set(instance, payload, new_type->asterisk_format, new_type->format, new_type->rtp_code);
1046                         ao2_unlock(instance);
1047                 }
1048         } else {
1049                 ao2_ref(new_type, -1);
1050         }
1051
1052         ast_rwlock_unlock(&codecs->codecs_lock);
1053 }
1054
1055 int ast_rtp_codecs_payloads_set_rtpmap_type_rate(struct ast_rtp_codecs *codecs, struct ast_rtp_instance *instance, int pt,
1056                                  char *mimetype, char *mimesubtype,
1057                                  enum ast_rtp_options options,
1058                                  unsigned int sample_rate)
1059 {
1060         unsigned int idx;
1061         int found = 0;
1062
1063         if (pt < 0 || pt >= AST_RTP_MAX_PT) {
1064                 return -1; /* bogus payload type */
1065         }
1066
1067         ast_rwlock_rdlock(&mime_types_lock);
1068         ast_rwlock_wrlock(&codecs->codecs_lock);
1069
1070         for (idx = 0; idx < mime_types_len; ++idx) {
1071                 const struct ast_rtp_mime_type *t = &ast_rtp_mime_types[idx];
1072                 struct ast_rtp_payload_type *new_type;
1073
1074                 if (strcasecmp(mimesubtype, t->subtype)) {
1075                         continue;
1076                 }
1077
1078                 if (strcasecmp(mimetype, t->type)) {
1079                         continue;
1080                 }
1081
1082                 /* if both sample rates have been supplied, and they don't match,
1083                  * then this not a match; if one has not been supplied, then the
1084                  * rates are not compared */
1085                 if (sample_rate && t->sample_rate &&
1086                     (sample_rate != t->sample_rate)) {
1087                         continue;
1088                 }
1089
1090                 found = 1;
1091
1092                 new_type = ast_rtp_engine_alloc_payload_type();
1093                 if (!new_type) {
1094                         continue;
1095                 }
1096
1097                 new_type->asterisk_format = t->payload_type.asterisk_format;
1098                 new_type->rtp_code = t->payload_type.rtp_code;
1099                 new_type->payload = pt;
1100                 new_type->primary_mapping = 1;
1101                 if (t->payload_type.asterisk_format
1102                         && ast_format_cmp(t->payload_type.format, ast_format_g726) == AST_FORMAT_CMP_EQUAL
1103                         && (options & AST_RTP_OPT_G726_NONSTANDARD)) {
1104                         new_type->format = ast_format_g726_aal2;
1105                 } else {
1106                         new_type->format = t->payload_type.format;
1107                 }
1108
1109                 if (new_type->format) {
1110                         /* SDP parsing automatically increases the reference count */
1111                         new_type->format = ast_format_parse_sdp_fmtp(new_type->format, "");
1112                 }
1113
1114                 if (!payload_mapping_tx_is_present(codecs, new_type)) {
1115                         if (pt < AST_VECTOR_SIZE(&codecs->payload_mapping_tx)) {
1116                                 ao2_t_cleanup(AST_VECTOR_GET(&codecs->payload_mapping_tx, pt),
1117                                         "cleaning up replaced tx payload type");
1118                         }
1119                         AST_VECTOR_REPLACE(&codecs->payload_mapping_tx, pt, new_type);
1120
1121                         if (instance && instance->engine && instance->engine->payload_set) {
1122                                 ao2_lock(instance);
1123                                 instance->engine->payload_set(instance, pt, new_type->asterisk_format, new_type->format, new_type->rtp_code);
1124                                 ao2_unlock(instance);
1125                         }
1126                 } else {
1127                         ao2_ref(new_type, -1);
1128                 }
1129
1130                 break;
1131         }
1132
1133         ast_rwlock_unlock(&codecs->codecs_lock);
1134         ast_rwlock_unlock(&mime_types_lock);
1135
1136         return (found ? 0 : -2);
1137 }
1138
1139 int ast_rtp_codecs_payloads_set_rtpmap_type(struct ast_rtp_codecs *codecs, struct ast_rtp_instance *instance, int payload, char *mimetype, char *mimesubtype, enum ast_rtp_options options)
1140 {
1141         return ast_rtp_codecs_payloads_set_rtpmap_type_rate(codecs, instance, payload, mimetype, mimesubtype, options, 0);
1142 }
1143
1144 void ast_rtp_codecs_payloads_unset(struct ast_rtp_codecs *codecs, struct ast_rtp_instance *instance, int payload)
1145 {
1146         struct ast_rtp_payload_type *type;
1147
1148         if (payload < 0 || payload >= AST_RTP_MAX_PT) {
1149                 return;
1150         }
1151
1152         ast_debug(2, "Unsetting payload %d on %p\n", payload, codecs);
1153
1154         ast_rwlock_wrlock(&codecs->codecs_lock);
1155
1156         if (payload < AST_VECTOR_SIZE(&codecs->payload_mapping_tx)) {
1157                 type = AST_VECTOR_GET(&codecs->payload_mapping_tx, payload);
1158                 ao2_cleanup(type);
1159                 AST_VECTOR_REPLACE(&codecs->payload_mapping_tx, payload, NULL);
1160         }
1161
1162         if (instance && instance->engine && instance->engine->payload_set) {
1163                 ao2_lock(instance);
1164                 instance->engine->payload_set(instance, payload, 0, NULL, 0);
1165                 ao2_unlock(instance);
1166         }
1167
1168         ast_rwlock_unlock(&codecs->codecs_lock);
1169 }
1170
1171 struct ast_rtp_payload_type *ast_rtp_codecs_get_payload(struct ast_rtp_codecs *codecs, int payload)
1172 {
1173         struct ast_rtp_payload_type *type = NULL;
1174
1175         if (payload < 0 || payload >= AST_RTP_MAX_PT) {
1176                 return NULL;
1177         }
1178
1179         ast_rwlock_rdlock(&codecs->codecs_lock);
1180         if (payload < AST_VECTOR_SIZE(&codecs->payload_mapping_rx)) {
1181                 type = AST_VECTOR_GET(&codecs->payload_mapping_rx, payload);
1182                 ao2_bump(type);
1183         }
1184         ast_rwlock_unlock(&codecs->codecs_lock);
1185
1186         if (!type) {
1187                 ast_rwlock_rdlock(&static_RTP_PT_lock);
1188                 type = ao2_bump(static_RTP_PT[payload]);
1189                 ast_rwlock_unlock(&static_RTP_PT_lock);
1190         }
1191
1192         return type;
1193 }
1194
1195 int ast_rtp_codecs_payload_replace_format(struct ast_rtp_codecs *codecs, int payload, struct ast_format *format)
1196 {
1197         struct ast_rtp_payload_type *type;
1198
1199         if (payload < 0 || payload >= AST_RTP_MAX_PT || !format) {
1200                 return -1;
1201         }
1202
1203         type = ast_rtp_engine_alloc_payload_type();
1204         if (!type) {
1205                 return -1;
1206         }
1207         ao2_ref(format, +1);
1208         type->format = format;
1209         type->asterisk_format = 1;
1210         type->payload = payload;
1211         type->primary_mapping = 1;
1212
1213         ast_rwlock_wrlock(&codecs->codecs_lock);
1214         if (!payload_mapping_tx_is_present(codecs, type)) {
1215                 if (payload < AST_VECTOR_SIZE(&codecs->payload_mapping_tx)) {
1216                         ao2_cleanup(AST_VECTOR_GET(&codecs->payload_mapping_tx, payload));
1217                 }
1218                 AST_VECTOR_REPLACE(&codecs->payload_mapping_tx, payload, type);
1219         } else {
1220                 ao2_ref(type, -1);
1221         }
1222         ast_rwlock_unlock(&codecs->codecs_lock);
1223
1224         return 0;
1225 }
1226
1227 struct ast_format *ast_rtp_codecs_get_payload_format(struct ast_rtp_codecs *codecs, int payload)
1228 {
1229         struct ast_rtp_payload_type *type;
1230         struct ast_format *format = NULL;
1231
1232         if (payload < 0 || payload >= AST_RTP_MAX_PT) {
1233                 return NULL;
1234         }
1235
1236         ast_rwlock_rdlock(&codecs->codecs_lock);
1237         if (payload < AST_VECTOR_SIZE(&codecs->payload_mapping_tx)) {
1238                 type = AST_VECTOR_GET(&codecs->payload_mapping_tx, payload);
1239                 if (type && type->asterisk_format) {
1240                         format = ao2_bump(type->format);
1241                 }
1242         }
1243         ast_rwlock_unlock(&codecs->codecs_lock);
1244
1245         return format;
1246 }
1247
1248 void ast_rtp_codecs_set_framing(struct ast_rtp_codecs *codecs, unsigned int framing)
1249 {
1250         if (!framing) {
1251                 return;
1252         }
1253
1254         ast_rwlock_wrlock(&codecs->codecs_lock);
1255         codecs->framing = framing;
1256         ast_rwlock_unlock(&codecs->codecs_lock);
1257 }
1258
1259 unsigned int ast_rtp_codecs_get_framing(struct ast_rtp_codecs *codecs)
1260 {
1261         unsigned int framing;
1262
1263         ast_rwlock_rdlock(&codecs->codecs_lock);
1264         framing = codecs->framing;
1265         ast_rwlock_unlock(&codecs->codecs_lock);
1266
1267         return framing;
1268 }
1269
1270 void ast_rtp_codecs_payload_formats(struct ast_rtp_codecs *codecs, struct ast_format_cap *astformats, int *nonastformats)
1271 {
1272         int idx;
1273
1274         ast_format_cap_remove_by_type(astformats, AST_MEDIA_TYPE_UNKNOWN);
1275         *nonastformats = 0;
1276
1277         ast_rwlock_rdlock(&codecs->codecs_lock);
1278
1279         for (idx = 0; idx < AST_VECTOR_SIZE(&codecs->payload_mapping_tx); ++idx) {
1280                 struct ast_rtp_payload_type *type;
1281
1282                 type = AST_VECTOR_GET(&codecs->payload_mapping_tx, idx);
1283                 if (!type) {
1284                         continue;
1285                 }
1286
1287                 if (type->asterisk_format) {
1288                         ast_format_cap_append(astformats, type->format, 0);
1289                 } else {
1290                         *nonastformats |= type->rtp_code;
1291                 }
1292         }
1293         if (codecs->framing) {
1294                 ast_format_cap_set_framing(astformats, codecs->framing);
1295         }
1296
1297         ast_rwlock_unlock(&codecs->codecs_lock);
1298 }
1299
1300 /*!
1301  * \internal
1302  * \brief Find the static payload type mapping for the format.
1303  * \since 14.0.0
1304  *
1305  * \param asterisk_format Non-zero if the given Asterisk format is present
1306  * \param format Asterisk format to look for
1307  * \param code The non-Asterisk format code to look for
1308  *
1309  * \note It is assumed that static_RTP_PT_lock is at least read locked before calling.
1310  *
1311  * \retval Numerical payload type
1312  * \retval -1 if not found.
1313  */
1314 static int find_static_payload_type(int asterisk_format, const struct ast_format *format, int code)
1315 {
1316         int idx;
1317         int payload = -1;
1318
1319         if (!asterisk_format) {
1320                 for (idx = 0; idx < AST_RTP_MAX_PT; ++idx) {
1321                         if (static_RTP_PT[idx]
1322                                 && !static_RTP_PT[idx]->asterisk_format
1323                                 && static_RTP_PT[idx]->rtp_code == code) {
1324                                 payload = idx;
1325                                 break;
1326                         }
1327                 }
1328         } else if (format) {
1329                 for (idx = 0; idx < AST_RTP_MAX_PT; ++idx) {
1330                         if (static_RTP_PT[idx]
1331                                 && static_RTP_PT[idx]->asterisk_format
1332                                 && ast_format_cmp(format, static_RTP_PT[idx]->format)
1333                                         != AST_FORMAT_CMP_NOT_EQUAL) {
1334                                 payload = idx;
1335                                 break;
1336                         }
1337                 }
1338         }
1339
1340         return payload;
1341 }
1342
1343 /*!
1344  * \internal
1345  * \brief Find the first unused payload type in a given range
1346  *
1347  * \param codecs The codec structure to look in
1348  * \param start Starting index
1349  * \param end Ending index
1350  * \param ignore Skip these payloads types
1351  *
1352  * \note The static_RTP_PT_lock object must be locked before calling
1353  *
1354  * \retval Numerical payload type
1355  * \retval -1 if not found.
1356  */
1357 static int find_unused_payload_in_range(const struct ast_rtp_codecs *codecs,
1358                 int start, int end, struct ast_rtp_payload_type *ignore[])
1359 {
1360         int x;
1361
1362         for (x = start; x < end; ++x) {
1363                 struct ast_rtp_payload_type *type;
1364
1365                 if (ignore[x]) {
1366                         continue;
1367                 } else if (!codecs || x >= AST_VECTOR_SIZE(&codecs->payload_mapping_rx)) {
1368                         return x;
1369                 }
1370
1371                 type = AST_VECTOR_GET(&codecs->payload_mapping_rx, x);
1372                 if (!type) {
1373                         return x;
1374                 }
1375         }
1376         return -1;
1377 }
1378
1379 /*!
1380  * \internal
1381  * \brief Find an unused payload type
1382  *
1383  * \param codecs Codecs structure to look in
1384  *
1385  * \note Both static_RTP_PT_lock and codecs (if given) must be at least
1386  *       read locked before calling.
1387  *
1388  * \retval Numerical payload type
1389  * \retval -1 if not found.
1390  */
1391 static int find_unused_payload(const struct ast_rtp_codecs *codecs)
1392 {
1393         int res;
1394
1395         /* find next available dynamic payload slot */
1396         res = find_unused_payload_in_range(
1397                 codecs, AST_RTP_PT_FIRST_DYNAMIC, AST_RTP_MAX_PT, static_RTP_PT);
1398         if (res != -1) {
1399                 return res;
1400         }
1401
1402         if (ast_option_rtpusedynamic) {
1403                 /*
1404                  * We're using default values for some dynamic types. So if an unused
1405                  * slot was not found try again, but this time ignore the default
1406                  * values declared for dynamic types (except for 101 and 121) .
1407                  */
1408                 static struct ast_rtp_payload_type *ignore[AST_RTP_MAX_PT] = {0};
1409
1410                 ignore[101] = static_RTP_PT[101];
1411                 ignore[121] = static_RTP_PT[121];
1412
1413                 res = find_unused_payload_in_range(
1414                         codecs, AST_RTP_PT_FIRST_DYNAMIC, AST_RTP_MAX_PT, ignore);
1415                 if (res != -1) {
1416                         return res;
1417                 }
1418         }
1419
1420         /* http://www.iana.org/assignments/rtp-parameters
1421          * RFC 3551, Section 3: "[...] applications which need to define more
1422          * than 32 dynamic payload types MAY bind codes below 96, in which case
1423          * it is RECOMMENDED that unassigned payload type numbers be used
1424          * first". Updated by RFC 5761, Section 4: "[...] values in the range
1425          * 64-95 MUST NOT be used [to avoid conflicts with RTCP]". Summaries:
1426          * https://tools.ietf.org/html/draft-roach-mmusic-unified-plan#section-3.2.1.2
1427          * https://tools.ietf.org/html/draft-wu-avtcore-dynamic-pt-usage#section-3
1428          */
1429         res = find_unused_payload_in_range(
1430                 codecs, MAX(ast_option_rtpptdynamic, AST_RTP_PT_LAST_STATIC + 1),
1431                 AST_RTP_PT_LAST_REASSIGN, static_RTP_PT);
1432         if (res != -1) {
1433                 return res;
1434         }
1435
1436         /* Yet, reusing mappings below AST_RTP_PT_LAST_STATIC (35) is not supported
1437          * in Asterisk because when Compact Headers are activated, no rtpmap is
1438          * send for those below 35. If you want to use 35 and below
1439          * A) do not use Compact Headers,
1440          * B) remove that code in chan_sip/res_pjsip, or
1441          * C) add a flag that this RTP Payload Type got reassigned dynamically
1442          *    and requires a rtpmap even with Compact Headers enabled.
1443          */
1444         res = find_unused_payload_in_range(
1445                 codecs, MAX(ast_option_rtpptdynamic, 20),
1446                 AST_RTP_PT_LAST_STATIC + 1, static_RTP_PT);
1447         if (res != -1) {
1448                 return res;
1449         }
1450
1451         return find_unused_payload_in_range(
1452                 codecs, MAX(ast_option_rtpptdynamic, 0),
1453                 20, static_RTP_PT);
1454 }
1455
1456 /*!
1457  * \internal
1458  * \brief Find the oldest non-primary dynamic rx payload type.
1459  * \since 14.0.0
1460  *
1461  * \param codecs Codecs structure to look in
1462  *
1463  * \note It is assumed that codecs is at least read locked before calling.
1464  *
1465  * \retval Numerical payload type
1466  * \retval -1 if not found.
1467  */
1468 static int rtp_codecs_find_non_primary_dynamic_rx(struct ast_rtp_codecs *codecs)
1469 {
1470         struct ast_rtp_payload_type *type;
1471         struct timeval oldest;
1472         int idx;
1473         int payload = -1;
1474
1475         idx = AST_RTP_PT_FIRST_DYNAMIC;
1476         for (; idx < AST_VECTOR_SIZE(&codecs->payload_mapping_rx); ++idx) {
1477                 type = AST_VECTOR_GET(&codecs->payload_mapping_rx, idx);
1478                 if (type
1479                         && !type->primary_mapping
1480                         && (payload == -1
1481                                 || ast_tvdiff_ms(type->when_retired, oldest) < 0)) {
1482                         oldest = type->when_retired;
1483                         payload = idx;
1484                 }
1485         }
1486         return payload;
1487 }
1488
1489 /*!
1490  * \internal
1491  * \brief Assign a payload type for the rx mapping.
1492  * \since 14.0.0
1493  *
1494  * \param codecs Codecs structure to look in
1495  * \param asterisk_format Non-zero if the given Asterisk format is present
1496  * \param format Asterisk format to look for
1497  * \param code The format to look for
1498  * \param explicit Require the provided code to be explicitly used
1499  *
1500  * \note It is assumed that static_RTP_PT_lock is at least read locked before calling.
1501  *
1502  * \retval Numerical payload type
1503  * \retval -1 if could not assign.
1504  */
1505 static int rtp_codecs_assign_payload_code_rx(struct ast_rtp_codecs *codecs, int asterisk_format, struct ast_format *format, int code, int explicit)
1506 {
1507         int payload = code;
1508         struct ast_rtp_payload_type *new_type;
1509
1510         if (!explicit) {
1511                 payload = find_static_payload_type(asterisk_format, format, code);
1512
1513                 if (payload < 0 && (!asterisk_format || ast_option_rtpusedynamic)) {
1514                         return payload;
1515                 }
1516         }
1517
1518         new_type = rtp_payload_type_alloc(format, payload, code, 1);
1519         if (!new_type) {
1520                 return -1;
1521         }
1522
1523         ast_rwlock_wrlock(&codecs->codecs_lock);
1524         if (payload > -1 && (payload < AST_RTP_PT_FIRST_DYNAMIC
1525                 || AST_VECTOR_SIZE(&codecs->payload_mapping_rx) <= payload
1526                 || !AST_VECTOR_GET(&codecs->payload_mapping_rx, payload))) {
1527                 /*
1528                  * The payload type is a static assignment
1529                  * or our default dynamic position is available.
1530                  */
1531                 rtp_codecs_payload_replace_rx(codecs, payload, new_type);
1532         } else if (!explicit && (-1 < (payload = find_unused_payload(codecs))
1533                 || -1 < (payload = rtp_codecs_find_non_primary_dynamic_rx(codecs)))) {
1534                 /*
1535                  * We found the first available empty dynamic position
1536                  * or we found a mapping that should no longer be
1537                  * actively used.
1538                  */
1539                 new_type->payload = payload;
1540                 rtp_codecs_payload_replace_rx(codecs, payload, new_type);
1541         } else if (explicit) {
1542                 /*
1543                 * They explicitly requested this payload number be used but it couldn't be
1544                 */
1545                 payload = -1;
1546         } else {
1547                 /*
1548                  * There are no empty or non-primary dynamic positions
1549                  * left.  Sadness.
1550                  *
1551                  * I don't think this is really possible.
1552                  */
1553                 ast_log(LOG_WARNING, "No dynamic RTP payload type values available "
1554                         "for %s - %d!\n", format ? ast_format_get_name(format) : "", code);
1555         }
1556         ast_rwlock_unlock(&codecs->codecs_lock);
1557
1558         ao2_ref(new_type, -1);
1559
1560         return payload;
1561 }
1562
1563 int ast_rtp_codecs_payload_code(struct ast_rtp_codecs *codecs, int asterisk_format, struct ast_format *format, int code)
1564 {
1565         struct ast_rtp_payload_type *type;
1566         int idx;
1567         int payload = -1;
1568
1569         ast_rwlock_rdlock(&static_RTP_PT_lock);
1570         if (!asterisk_format) {
1571                 ast_rwlock_rdlock(&codecs->codecs_lock);
1572                 for (idx = 0; idx < AST_VECTOR_SIZE(&codecs->payload_mapping_rx); ++idx) {
1573                         type = AST_VECTOR_GET(&codecs->payload_mapping_rx, idx);
1574                         if (!type) {
1575                                 continue;
1576                         }
1577
1578                         if (!type->asterisk_format
1579                                 && type->primary_mapping
1580                                 && type->rtp_code == code) {
1581                                 payload = idx;
1582                                 break;
1583                         }
1584                 }
1585                 ast_rwlock_unlock(&codecs->codecs_lock);
1586         } else if (format) {
1587                 ast_rwlock_rdlock(&codecs->codecs_lock);
1588                 for (idx = 0; idx < AST_VECTOR_SIZE(&codecs->payload_mapping_rx); ++idx) {
1589                         type = AST_VECTOR_GET(&codecs->payload_mapping_rx, idx);
1590                         if (!type) {
1591                                 continue;
1592                         }
1593
1594                         if (type->asterisk_format
1595                                 && type->primary_mapping
1596                                 && ast_format_cmp(format, type->format) == AST_FORMAT_CMP_EQUAL) {
1597                                 payload = idx;
1598                                 break;
1599                         }
1600                 }
1601                 ast_rwlock_unlock(&codecs->codecs_lock);
1602         }
1603
1604         if (payload < 0) {
1605                 payload = rtp_codecs_assign_payload_code_rx(codecs, asterisk_format, format,
1606                         code, 0);
1607         }
1608         ast_rwlock_unlock(&static_RTP_PT_lock);
1609
1610         return payload;
1611 }
1612
1613 int ast_rtp_codecs_payload_set_rx(struct ast_rtp_codecs *codecs, int code, struct ast_format *format)
1614 {
1615         return rtp_codecs_assign_payload_code_rx(codecs, 1, format, code, 1);
1616 }
1617
1618 int ast_rtp_codecs_payload_code_tx(struct ast_rtp_codecs *codecs, int asterisk_format, const struct ast_format *format, int code)
1619 {
1620         struct ast_rtp_payload_type *type;
1621         int idx;
1622         int payload = -1;
1623
1624         if (!asterisk_format) {
1625                 ast_rwlock_rdlock(&codecs->codecs_lock);
1626                 for (idx = 0; idx < AST_VECTOR_SIZE(&codecs->payload_mapping_tx); ++idx) {
1627                         type = AST_VECTOR_GET(&codecs->payload_mapping_tx, idx);
1628                         if (!type) {
1629                                 continue;
1630                         }
1631
1632                         if (!type->asterisk_format
1633                                 && type->rtp_code == code) {
1634                                 payload = idx;
1635                                 break;
1636                         }
1637                 }
1638                 ast_rwlock_unlock(&codecs->codecs_lock);
1639         } else if (format) {
1640                 ast_rwlock_rdlock(&codecs->codecs_lock);
1641                 for (idx = 0; idx < AST_VECTOR_SIZE(&codecs->payload_mapping_tx); ++idx) {
1642                         type = AST_VECTOR_GET(&codecs->payload_mapping_tx, idx);
1643                         if (!type) {
1644                                 continue;
1645                         }
1646
1647                         if (type->asterisk_format
1648                                 && ast_format_cmp(format, type->format) == AST_FORMAT_CMP_EQUAL) {
1649                                 payload = idx;
1650                                 break;
1651                         }
1652                 }
1653                 ast_rwlock_unlock(&codecs->codecs_lock);
1654         }
1655
1656         if (payload < 0) {
1657                 ast_rwlock_rdlock(&static_RTP_PT_lock);
1658                 payload = find_static_payload_type(asterisk_format, format, code);
1659                 ast_rwlock_unlock(&static_RTP_PT_lock);
1660         }
1661
1662         return payload;
1663 }
1664
1665 int ast_rtp_codecs_find_payload_code(struct ast_rtp_codecs *codecs, int payload)
1666 {
1667         struct ast_rtp_payload_type *type;
1668         int res = -1;
1669
1670         ast_rwlock_rdlock(&codecs->codecs_lock);
1671         if (payload < AST_VECTOR_SIZE(&codecs->payload_mapping_tx)) {
1672                 type = AST_VECTOR_GET(&codecs->payload_mapping_tx, payload);
1673                 if (type) {
1674                         res = payload;
1675                 }
1676         }
1677         ast_rwlock_unlock(&codecs->codecs_lock);
1678
1679         return res;
1680 }
1681
1682 const char *ast_rtp_lookup_mime_subtype2(const int asterisk_format,
1683         const struct ast_format *format, int code, enum ast_rtp_options options)
1684 {
1685         int i;
1686         const char *res = "";
1687
1688         ast_rwlock_rdlock(&mime_types_lock);
1689         for (i = 0; i < mime_types_len; i++) {
1690                 if (ast_rtp_mime_types[i].payload_type.asterisk_format && asterisk_format && format &&
1691                         (ast_format_cmp(format, ast_rtp_mime_types[i].payload_type.format) != AST_FORMAT_CMP_NOT_EQUAL)) {
1692                         if ((ast_format_cmp(format, ast_format_g726_aal2) == AST_FORMAT_CMP_EQUAL) &&
1693                                         (options & AST_RTP_OPT_G726_NONSTANDARD)) {
1694                                 res = "G726-32";
1695                                 break;
1696                         } else {
1697                                 res = ast_rtp_mime_types[i].subtype;
1698                                 break;
1699                         }
1700                 } else if (!ast_rtp_mime_types[i].payload_type.asterisk_format && !asterisk_format &&
1701                         ast_rtp_mime_types[i].payload_type.rtp_code == code) {
1702
1703                         res = ast_rtp_mime_types[i].subtype;
1704                         break;
1705                 }
1706         }
1707         ast_rwlock_unlock(&mime_types_lock);
1708
1709         return res;
1710 }
1711
1712 unsigned int ast_rtp_lookup_sample_rate2(int asterisk_format,
1713         const struct ast_format *format, int code)
1714 {
1715         unsigned int i;
1716         unsigned int res = 0;
1717
1718         ast_rwlock_rdlock(&mime_types_lock);
1719         for (i = 0; i < mime_types_len; ++i) {
1720                 if (ast_rtp_mime_types[i].payload_type.asterisk_format && asterisk_format && format &&
1721                         (ast_format_cmp(format, ast_rtp_mime_types[i].payload_type.format) != AST_FORMAT_CMP_NOT_EQUAL)) {
1722                         res = ast_rtp_mime_types[i].sample_rate;
1723                         break;
1724                 } else if (!ast_rtp_mime_types[i].payload_type.asterisk_format && !asterisk_format &&
1725                         ast_rtp_mime_types[i].payload_type.rtp_code == code) {
1726                         res = ast_rtp_mime_types[i].sample_rate;
1727                         break;
1728                 }
1729         }
1730         ast_rwlock_unlock(&mime_types_lock);
1731
1732         return res;
1733 }
1734
1735 char *ast_rtp_lookup_mime_multiple2(struct ast_str *buf, struct ast_format_cap *ast_format_capability, int rtp_capability, const int asterisk_format, enum ast_rtp_options options)
1736 {
1737         int found = 0;
1738         const char *name;
1739         if (!buf) {
1740                 return NULL;
1741         }
1742
1743
1744         if (asterisk_format) {
1745                 int x;
1746                 struct ast_format *tmp_fmt;
1747                 for (x = 0; x < ast_format_cap_count(ast_format_capability); x++) {
1748                         tmp_fmt = ast_format_cap_get_format(ast_format_capability, x);
1749                         name = ast_rtp_lookup_mime_subtype2(asterisk_format, tmp_fmt, 0, options);
1750                         ao2_ref(tmp_fmt, -1);
1751                         ast_str_append(&buf, 0, "%s|", name);
1752                         found = 1;
1753                 }
1754         } else {
1755                 int x;
1756                 ast_str_append(&buf, 0, "0x%x (", (unsigned int) rtp_capability);
1757                 for (x = 1; x <= AST_RTP_MAX; x <<= 1) {
1758                         if (rtp_capability & x) {
1759                                 name = ast_rtp_lookup_mime_subtype2(asterisk_format, NULL, x, options);
1760                                 ast_str_append(&buf, 0, "%s|", name);
1761                                 found = 1;
1762                         }
1763                 }
1764         }
1765
1766         ast_str_append(&buf, 0, "%s", found ? ")" : "nothing)");
1767
1768         return ast_str_buffer(buf);
1769 }
1770
1771 int ast_rtp_instance_dtmf_begin(struct ast_rtp_instance *instance, char digit)
1772 {
1773         int res;
1774
1775         if (instance->engine->dtmf_begin) {
1776                 ao2_lock(instance);
1777                 res = instance->engine->dtmf_begin(instance, digit);
1778                 ao2_unlock(instance);
1779         } else {
1780                 res = -1;
1781         }
1782         return res;
1783 }
1784
1785 int ast_rtp_instance_dtmf_end(struct ast_rtp_instance *instance, char digit)
1786 {
1787         int res;
1788
1789         if (instance->engine->dtmf_end) {
1790                 ao2_lock(instance);
1791                 res = instance->engine->dtmf_end(instance, digit);
1792                 ao2_unlock(instance);
1793         } else {
1794                 res = -1;
1795         }
1796         return res;
1797 }
1798
1799 int ast_rtp_instance_dtmf_end_with_duration(struct ast_rtp_instance *instance, char digit, unsigned int duration)
1800 {
1801         int res;
1802
1803         if (instance->engine->dtmf_end_with_duration) {
1804                 ao2_lock(instance);
1805                 res = instance->engine->dtmf_end_with_duration(instance, digit, duration);
1806                 ao2_unlock(instance);
1807         } else {
1808                 res = -1;
1809         }
1810         return res;
1811 }
1812
1813 int ast_rtp_instance_dtmf_mode_set(struct ast_rtp_instance *instance, enum ast_rtp_dtmf_mode dtmf_mode)
1814 {
1815         int res;
1816
1817         if (instance->engine->dtmf_mode_set) {
1818                 ao2_lock(instance);
1819                 res = instance->engine->dtmf_mode_set(instance, dtmf_mode);
1820                 ao2_unlock(instance);
1821         } else {
1822                 res = -1;
1823         }
1824         return res;
1825 }
1826
1827 enum ast_rtp_dtmf_mode ast_rtp_instance_dtmf_mode_get(struct ast_rtp_instance *instance)
1828 {
1829         int res;
1830
1831         if (instance->engine->dtmf_mode_get) {
1832                 ao2_lock(instance);
1833                 res = instance->engine->dtmf_mode_get(instance);
1834                 ao2_unlock(instance);
1835         } else {
1836                 res = 0;
1837         }
1838         return res;
1839 }
1840
1841 void ast_rtp_instance_update_source(struct ast_rtp_instance *instance)
1842 {
1843         if (instance->engine->update_source) {
1844                 ao2_lock(instance);
1845                 instance->engine->update_source(instance);
1846                 ao2_unlock(instance);
1847         }
1848 }
1849
1850 void ast_rtp_instance_change_source(struct ast_rtp_instance *instance)
1851 {
1852         if (instance->engine->change_source) {
1853                 ao2_lock(instance);
1854                 instance->engine->change_source(instance);
1855                 ao2_unlock(instance);
1856         }
1857 }
1858
1859 int ast_rtp_instance_set_qos(struct ast_rtp_instance *instance, int tos, int cos, const char *desc)
1860 {
1861         int res;
1862
1863         if (instance->engine->qos) {
1864                 ao2_lock(instance);
1865                 res = instance->engine->qos(instance, tos, cos, desc);
1866                 ao2_unlock(instance);
1867         } else {
1868                 res = -1;
1869         }
1870         return res;
1871 }
1872
1873 void ast_rtp_instance_stop(struct ast_rtp_instance *instance)
1874 {
1875         if (instance->engine->stop) {
1876                 ao2_lock(instance);
1877                 instance->engine->stop(instance);
1878                 ao2_unlock(instance);
1879         }
1880 }
1881
1882 int ast_rtp_instance_fd(struct ast_rtp_instance *instance, int rtcp)
1883 {
1884         int res;
1885
1886         if (instance->engine->fd) {
1887                 ao2_lock(instance);
1888                 res = instance->engine->fd(instance, rtcp);
1889                 ao2_unlock(instance);
1890         } else {
1891                 res = -1;
1892         }
1893         return res;
1894 }
1895
1896 struct ast_rtp_glue *ast_rtp_instance_get_glue(const char *type)
1897 {
1898         struct ast_rtp_glue *glue = NULL;
1899
1900         AST_RWLIST_RDLOCK(&glues);
1901
1902         AST_RWLIST_TRAVERSE(&glues, glue, entry) {
1903                 if (!strcasecmp(glue->type, type)) {
1904                         break;
1905                 }
1906         }
1907
1908         AST_RWLIST_UNLOCK(&glues);
1909
1910         return glue;
1911 }
1912
1913 /*!
1914  * \brief Conditionally unref an rtp instance
1915  */
1916 static void unref_instance_cond(struct ast_rtp_instance **instance)
1917 {
1918         if (*instance) {
1919                 ao2_ref(*instance, -1);
1920                 *instance = NULL;
1921         }
1922 }
1923
1924 struct ast_rtp_instance *ast_rtp_instance_get_bridged(struct ast_rtp_instance *instance)
1925 {
1926         struct ast_rtp_instance *bridged;
1927
1928         ao2_lock(instance);
1929         bridged = instance->bridged;
1930         ao2_unlock(instance);
1931         return bridged;
1932 }
1933
1934 void ast_rtp_instance_set_bridged(struct ast_rtp_instance *instance, struct ast_rtp_instance *bridged)
1935 {
1936         ao2_lock(instance);
1937         instance->bridged = bridged;
1938         ao2_unlock(instance);
1939 }
1940
1941 void ast_rtp_instance_early_bridge_make_compatible(struct ast_channel *c_dst, struct ast_channel *c_src)
1942 {
1943         struct ast_rtp_instance *instance_dst = NULL, *instance_src = NULL,
1944                 *vinstance_dst = NULL, *vinstance_src = NULL,
1945                 *tinstance_dst = NULL, *tinstance_src = NULL;
1946         struct ast_rtp_glue *glue_dst, *glue_src;
1947         enum ast_rtp_glue_result audio_glue_dst_res = AST_RTP_GLUE_RESULT_FORBID, video_glue_dst_res = AST_RTP_GLUE_RESULT_FORBID;
1948         enum ast_rtp_glue_result audio_glue_src_res = AST_RTP_GLUE_RESULT_FORBID, video_glue_src_res = AST_RTP_GLUE_RESULT_FORBID;
1949         struct ast_format_cap *cap_dst = ast_format_cap_alloc(AST_FORMAT_CAP_FLAG_DEFAULT);
1950         struct ast_format_cap *cap_src = ast_format_cap_alloc(AST_FORMAT_CAP_FLAG_DEFAULT);
1951
1952         /* Lock both channels so we can look for the glue that binds them together */
1953         ast_channel_lock_both(c_dst, c_src);
1954
1955         if (!cap_src || !cap_dst) {
1956                 goto done;
1957         }
1958
1959         /* Grab glue that binds each channel to something using the RTP engine */
1960         if (!(glue_dst = ast_rtp_instance_get_glue(ast_channel_tech(c_dst)->type)) || !(glue_src = ast_rtp_instance_get_glue(ast_channel_tech(c_src)->type))) {
1961                 ast_debug(1, "Can't find native functions for channel '%s'\n", glue_dst ? ast_channel_name(c_src) : ast_channel_name(c_dst));
1962                 goto done;
1963         }
1964
1965         audio_glue_dst_res = glue_dst->get_rtp_info(c_dst, &instance_dst);
1966         video_glue_dst_res = glue_dst->get_vrtp_info ? glue_dst->get_vrtp_info(c_dst, &vinstance_dst) : AST_RTP_GLUE_RESULT_FORBID;
1967
1968         audio_glue_src_res = glue_src->get_rtp_info(c_src, &instance_src);
1969         video_glue_src_res = glue_src->get_vrtp_info ? glue_src->get_vrtp_info(c_src, &vinstance_src) : AST_RTP_GLUE_RESULT_FORBID;
1970
1971         /* If we are carrying video, and both sides are not going to remotely bridge... fail the native bridge */
1972         if (video_glue_dst_res != AST_RTP_GLUE_RESULT_FORBID && (audio_glue_dst_res != AST_RTP_GLUE_RESULT_REMOTE || video_glue_dst_res != AST_RTP_GLUE_RESULT_REMOTE)) {
1973                 audio_glue_dst_res = AST_RTP_GLUE_RESULT_FORBID;
1974         }
1975         if (video_glue_src_res != AST_RTP_GLUE_RESULT_FORBID && (audio_glue_src_res != AST_RTP_GLUE_RESULT_REMOTE || video_glue_src_res != AST_RTP_GLUE_RESULT_REMOTE)) {
1976                 audio_glue_src_res = AST_RTP_GLUE_RESULT_FORBID;
1977         }
1978         if (audio_glue_dst_res == AST_RTP_GLUE_RESULT_REMOTE && (video_glue_dst_res == AST_RTP_GLUE_RESULT_FORBID || video_glue_dst_res == AST_RTP_GLUE_RESULT_REMOTE) && glue_dst->get_codec) {
1979                 glue_dst->get_codec(c_dst, cap_dst);
1980         }
1981         if (audio_glue_src_res == AST_RTP_GLUE_RESULT_REMOTE && (video_glue_src_res == AST_RTP_GLUE_RESULT_FORBID || video_glue_src_res == AST_RTP_GLUE_RESULT_REMOTE) && glue_src->get_codec) {
1982                 glue_src->get_codec(c_src, cap_src);
1983         }
1984
1985         /* If any sort of bridge is forbidden just completely bail out and go back to generic bridging */
1986         if (audio_glue_dst_res != AST_RTP_GLUE_RESULT_REMOTE || audio_glue_src_res != AST_RTP_GLUE_RESULT_REMOTE) {
1987                 goto done;
1988         }
1989
1990         /* Make sure we have matching codecs */
1991         if (!ast_format_cap_iscompatible(cap_dst, cap_src)) {
1992                 goto done;
1993         }
1994
1995         ast_rtp_codecs_payloads_xover(&instance_src->codecs, &instance_dst->codecs, instance_dst);
1996
1997         if (vinstance_dst && vinstance_src) {
1998                 ast_rtp_codecs_payloads_xover(&vinstance_src->codecs, &vinstance_dst->codecs, vinstance_dst);
1999         }
2000         if (tinstance_dst && tinstance_src) {
2001                 ast_rtp_codecs_payloads_xover(&tinstance_src->codecs, &tinstance_dst->codecs, tinstance_dst);
2002         }
2003
2004         if (glue_dst->update_peer(c_dst, instance_src, vinstance_src, tinstance_src, cap_src, 0)) {
2005                 ast_log(LOG_WARNING, "Channel '%s' failed to setup early bridge to '%s'\n",
2006                         ast_channel_name(c_dst), ast_channel_name(c_src));
2007         } else {
2008                 ast_debug(1, "Seeded SDP of '%s' with that of '%s'\n",
2009                         ast_channel_name(c_dst), ast_channel_name(c_src));
2010         }
2011
2012 done:
2013         ast_channel_unlock(c_dst);
2014         ast_channel_unlock(c_src);
2015
2016         ao2_cleanup(cap_dst);
2017         ao2_cleanup(cap_src);
2018
2019         unref_instance_cond(&instance_dst);
2020         unref_instance_cond(&instance_src);
2021         unref_instance_cond(&vinstance_dst);
2022         unref_instance_cond(&vinstance_src);
2023         unref_instance_cond(&tinstance_dst);
2024         unref_instance_cond(&tinstance_src);
2025 }
2026
2027 int ast_rtp_instance_early_bridge(struct ast_channel *c0, struct ast_channel *c1)
2028 {
2029         struct ast_rtp_instance *instance0 = NULL, *instance1 = NULL,
2030                         *vinstance0 = NULL, *vinstance1 = NULL,
2031                         *tinstance0 = NULL, *tinstance1 = NULL;
2032         struct ast_rtp_glue *glue0, *glue1;
2033         enum ast_rtp_glue_result audio_glue0_res = AST_RTP_GLUE_RESULT_FORBID, video_glue0_res = AST_RTP_GLUE_RESULT_FORBID;
2034         enum ast_rtp_glue_result audio_glue1_res = AST_RTP_GLUE_RESULT_FORBID, video_glue1_res = AST_RTP_GLUE_RESULT_FORBID;
2035         struct ast_format_cap *cap0 = ast_format_cap_alloc(AST_FORMAT_CAP_FLAG_DEFAULT);
2036         struct ast_format_cap *cap1 = ast_format_cap_alloc(AST_FORMAT_CAP_FLAG_DEFAULT);
2037
2038         /* If there is no second channel just immediately bail out, we are of no use in that scenario */
2039         if (!c1 || !cap1 || !cap0) {
2040                 ao2_cleanup(cap0);
2041                 ao2_cleanup(cap1);
2042                 return -1;
2043         }
2044
2045         /* Lock both channels so we can look for the glue that binds them together */
2046         ast_channel_lock_both(c0, c1);
2047
2048         /* Grab glue that binds each channel to something using the RTP engine */
2049         if (!(glue0 = ast_rtp_instance_get_glue(ast_channel_tech(c0)->type)) || !(glue1 = ast_rtp_instance_get_glue(ast_channel_tech(c1)->type))) {
2050                 ast_log(LOG_WARNING, "Can't find native functions for channel '%s'\n", glue0 ? ast_channel_name(c1) : ast_channel_name(c0));
2051                 goto done;
2052         }
2053
2054         audio_glue0_res = glue0->get_rtp_info(c0, &instance0);
2055         video_glue0_res = glue0->get_vrtp_info ? glue0->get_vrtp_info(c0, &vinstance0) : AST_RTP_GLUE_RESULT_FORBID;
2056
2057         audio_glue1_res = glue1->get_rtp_info(c1, &instance1);
2058         video_glue1_res = glue1->get_vrtp_info ? glue1->get_vrtp_info(c1, &vinstance1) : AST_RTP_GLUE_RESULT_FORBID;
2059
2060         /* If we are carrying video, and both sides are not going to remotely bridge... fail the native bridge */
2061         if (video_glue0_res != AST_RTP_GLUE_RESULT_FORBID && (audio_glue0_res != AST_RTP_GLUE_RESULT_REMOTE || video_glue0_res != AST_RTP_GLUE_RESULT_REMOTE)) {
2062                 audio_glue0_res = AST_RTP_GLUE_RESULT_FORBID;
2063         }
2064         if (video_glue1_res != AST_RTP_GLUE_RESULT_FORBID && (audio_glue1_res != AST_RTP_GLUE_RESULT_REMOTE || video_glue1_res != AST_RTP_GLUE_RESULT_REMOTE)) {
2065                 audio_glue1_res = AST_RTP_GLUE_RESULT_FORBID;
2066         }
2067         if (audio_glue0_res == AST_RTP_GLUE_RESULT_REMOTE && (video_glue0_res == AST_RTP_GLUE_RESULT_FORBID || video_glue0_res == AST_RTP_GLUE_RESULT_REMOTE) && glue0->get_codec) {
2068                 glue0->get_codec(c0, cap0);
2069         }
2070         if (audio_glue1_res == AST_RTP_GLUE_RESULT_REMOTE && (video_glue1_res == AST_RTP_GLUE_RESULT_FORBID || video_glue1_res == AST_RTP_GLUE_RESULT_REMOTE) && glue1->get_codec) {
2071                 glue1->get_codec(c1, cap1);
2072         }
2073
2074         /* If any sort of bridge is forbidden just completely bail out and go back to generic bridging */
2075         if (audio_glue0_res != AST_RTP_GLUE_RESULT_REMOTE || audio_glue1_res != AST_RTP_GLUE_RESULT_REMOTE) {
2076                 goto done;
2077         }
2078
2079         /* Make sure we have matching codecs */
2080         if (!ast_format_cap_iscompatible(cap0, cap1)) {
2081                 goto done;
2082         }
2083
2084         /* Bridge media early */
2085         if (glue0->update_peer(c0, instance1, vinstance1, tinstance1, cap1, 0)) {
2086                 ast_log(LOG_WARNING, "Channel '%s' failed to setup early bridge to '%s'\n", ast_channel_name(c0), c1 ? ast_channel_name(c1) : "<unspecified>");
2087         }
2088
2089 done:
2090         ast_channel_unlock(c0);
2091         ast_channel_unlock(c1);
2092
2093         ao2_cleanup(cap0);
2094         ao2_cleanup(cap1);
2095
2096         unref_instance_cond(&instance0);
2097         unref_instance_cond(&instance1);
2098         unref_instance_cond(&vinstance0);
2099         unref_instance_cond(&vinstance1);
2100         unref_instance_cond(&tinstance0);
2101         unref_instance_cond(&tinstance1);
2102
2103         ast_debug(1, "Setting early bridge SDP of '%s' with that of '%s'\n", ast_channel_name(c0), c1 ? ast_channel_name(c1) : "<unspecified>");
2104
2105         return 0;
2106 }
2107
2108 int ast_rtp_red_init(struct ast_rtp_instance *instance, int buffer_time, int *payloads, int generations)
2109 {
2110         int res;
2111
2112         if (instance->engine->red_init) {
2113                 ao2_lock(instance);
2114                 res = instance->engine->red_init(instance, buffer_time, payloads, generations);
2115                 ao2_unlock(instance);
2116         } else {
2117                 res = -1;
2118         }
2119         return res;
2120 }
2121
2122 int ast_rtp_red_buffer(struct ast_rtp_instance *instance, struct ast_frame *frame)
2123 {
2124         int res;
2125
2126         if (instance->engine->red_buffer) {
2127                 ao2_lock(instance);
2128                 res = instance->engine->red_buffer(instance, frame);
2129                 ao2_unlock(instance);
2130         } else {
2131                 res = -1;
2132         }
2133         return res;
2134 }
2135
2136 int ast_rtp_instance_get_stats(struct ast_rtp_instance *instance, struct ast_rtp_instance_stats *stats, enum ast_rtp_instance_stat stat)
2137 {
2138         int res;
2139
2140         if (instance->engine->get_stat) {
2141                 ao2_lock(instance);
2142                 res = instance->engine->get_stat(instance, stats, stat);
2143                 ao2_unlock(instance);
2144         } else {
2145                 res = -1;
2146         }
2147         return res;
2148 }
2149
2150 char *ast_rtp_instance_get_quality(struct ast_rtp_instance *instance, enum ast_rtp_instance_stat_field field, char *buf, size_t size)
2151 {
2152         struct ast_rtp_instance_stats stats = { 0, };
2153         enum ast_rtp_instance_stat stat;
2154
2155         /* Determine what statistics we will need to retrieve based on field passed in */
2156         if (field == AST_RTP_INSTANCE_STAT_FIELD_QUALITY) {
2157                 stat = AST_RTP_INSTANCE_STAT_ALL;
2158         } else if (field == AST_RTP_INSTANCE_STAT_FIELD_QUALITY_JITTER) {
2159                 stat = AST_RTP_INSTANCE_STAT_COMBINED_JITTER;
2160         } else if (field == AST_RTP_INSTANCE_STAT_FIELD_QUALITY_LOSS) {
2161                 stat = AST_RTP_INSTANCE_STAT_COMBINED_LOSS;
2162         } else if (field == AST_RTP_INSTANCE_STAT_FIELD_QUALITY_RTT) {
2163                 stat = AST_RTP_INSTANCE_STAT_COMBINED_RTT;
2164         } else {
2165                 return NULL;
2166         }
2167
2168         /* Attempt to actually retrieve the statistics we need to generate the quality string */
2169         if (ast_rtp_instance_get_stats(instance, &stats, stat)) {
2170                 return NULL;
2171         }
2172
2173         /* Now actually fill the buffer with the good information */
2174         if (field == AST_RTP_INSTANCE_STAT_FIELD_QUALITY) {
2175                 snprintf(buf, size, "ssrc=%u;themssrc=%u;lp=%u;rxjitter=%f;rxcount=%u;txjitter=%f;txcount=%u;rlp=%u;rtt=%f",
2176                          stats.local_ssrc, stats.remote_ssrc, stats.rxploss, stats.rxjitter, stats.rxcount, stats.txjitter, stats.txcount, stats.txploss, stats.rtt);
2177         } else if (field == AST_RTP_INSTANCE_STAT_FIELD_QUALITY_JITTER) {
2178                 snprintf(buf, size, "minrxjitter=%f;maxrxjitter=%f;avgrxjitter=%f;stdevrxjitter=%f;reported_minjitter=%f;reported_maxjitter=%f;reported_avgjitter=%f;reported_stdevjitter=%f;",
2179                          stats.local_minjitter, stats.local_maxjitter, stats.local_normdevjitter, sqrt(stats.local_stdevjitter), stats.remote_minjitter, stats.remote_maxjitter, stats.remote_normdevjitter, sqrt(stats.remote_stdevjitter));
2180         } else if (field == AST_RTP_INSTANCE_STAT_FIELD_QUALITY_LOSS) {
2181                 snprintf(buf, size, "minrxlost=%f;maxrxlost=%f;avgrxlost=%f;stdevrxlost=%f;reported_minlost=%f;reported_maxlost=%f;reported_avglost=%f;reported_stdevlost=%f;",
2182                          stats.local_minrxploss, stats.local_maxrxploss, stats.local_normdevrxploss, sqrt(stats.local_stdevrxploss), stats.remote_minrxploss, stats.remote_maxrxploss, stats.remote_normdevrxploss, sqrt(stats.remote_stdevrxploss));
2183         } else if (field == AST_RTP_INSTANCE_STAT_FIELD_QUALITY_RTT) {
2184                 snprintf(buf, size, "minrtt=%f;maxrtt=%f;avgrtt=%f;stdevrtt=%f;", stats.minrtt, stats.maxrtt, stats.normdevrtt, stats.stdevrtt);
2185         }
2186
2187         return buf;
2188 }
2189
2190 void ast_rtp_instance_set_stats_vars(struct ast_channel *chan, struct ast_rtp_instance *instance)
2191 {
2192         char quality_buf[AST_MAX_USER_FIELD];
2193         char *quality;
2194         struct ast_channel *bridge;
2195
2196         bridge = ast_channel_bridge_peer(chan);
2197         if (bridge) {
2198                 ast_channel_lock_both(chan, bridge);
2199                 ast_channel_stage_snapshot(bridge);
2200         } else {
2201                 ast_channel_lock(chan);
2202         }
2203         ast_channel_stage_snapshot(chan);
2204
2205         quality = ast_rtp_instance_get_quality(instance, AST_RTP_INSTANCE_STAT_FIELD_QUALITY,
2206                 quality_buf, sizeof(quality_buf));
2207         if (quality) {
2208                 pbx_builtin_setvar_helper(chan, "RTPAUDIOQOS", quality);
2209                 if (bridge) {
2210                         pbx_builtin_setvar_helper(bridge, "RTPAUDIOQOSBRIDGED", quality);
2211                 }
2212         }
2213
2214         quality = ast_rtp_instance_get_quality(instance,
2215                 AST_RTP_INSTANCE_STAT_FIELD_QUALITY_JITTER, quality_buf, sizeof(quality_buf));
2216         if (quality) {
2217                 pbx_builtin_setvar_helper(chan, "RTPAUDIOQOSJITTER", quality);
2218                 if (bridge) {
2219                         pbx_builtin_setvar_helper(bridge, "RTPAUDIOQOSJITTERBRIDGED", quality);
2220                 }
2221         }
2222
2223         quality = ast_rtp_instance_get_quality(instance,
2224                 AST_RTP_INSTANCE_STAT_FIELD_QUALITY_LOSS, quality_buf, sizeof(quality_buf));
2225         if (quality) {
2226                 pbx_builtin_setvar_helper(chan, "RTPAUDIOQOSLOSS", quality);
2227                 if (bridge) {
2228                         pbx_builtin_setvar_helper(bridge, "RTPAUDIOQOSLOSSBRIDGED", quality);
2229                 }
2230         }
2231
2232         quality = ast_rtp_instance_get_quality(instance,
2233                 AST_RTP_INSTANCE_STAT_FIELD_QUALITY_RTT, quality_buf, sizeof(quality_buf));
2234         if (quality) {
2235                 pbx_builtin_setvar_helper(chan, "RTPAUDIOQOSRTT", quality);
2236                 if (bridge) {
2237                         pbx_builtin_setvar_helper(bridge, "RTPAUDIOQOSRTTBRIDGED", quality);
2238                 }
2239         }
2240
2241         ast_channel_stage_snapshot_done(chan);
2242         ast_channel_unlock(chan);
2243         if (bridge) {
2244                 ast_channel_stage_snapshot_done(bridge);
2245                 ast_channel_unlock(bridge);
2246                 ast_channel_unref(bridge);
2247         }
2248 }
2249
2250 int ast_rtp_instance_set_read_format(struct ast_rtp_instance *instance, struct ast_format *format)
2251 {
2252         int res;
2253
2254         if (instance->engine->set_read_format) {
2255                 ao2_lock(instance);
2256                 res = instance->engine->set_read_format(instance, format);
2257                 ao2_unlock(instance);
2258         } else {
2259                 res = -1;
2260         }
2261         return res;
2262 }
2263
2264 int ast_rtp_instance_set_write_format(struct ast_rtp_instance *instance, struct ast_format *format)
2265 {
2266         int res;
2267
2268         if (instance->engine->set_read_format) {
2269                 ao2_lock(instance);
2270                 res = instance->engine->set_write_format(instance, format);
2271                 ao2_unlock(instance);
2272         } else {
2273                 res = -1;
2274         }
2275         return res;
2276 }
2277
2278 /* XXX Nothing calls this */
2279 int ast_rtp_instance_make_compatible(struct ast_channel *chan, struct ast_rtp_instance *instance, struct ast_channel *peer)
2280 {
2281         struct ast_rtp_glue *glue;
2282         struct ast_rtp_instance *peer_instance = NULL;
2283         int res = -1;
2284
2285         if (!instance->engine->make_compatible) {
2286                 return -1;
2287         }
2288
2289         ast_channel_lock(peer);
2290
2291         if (!(glue = ast_rtp_instance_get_glue(ast_channel_tech(peer)->type))) {
2292                 ast_channel_unlock(peer);
2293                 return -1;
2294         }
2295
2296         glue->get_rtp_info(peer, &peer_instance);
2297         if (!peer_instance) {
2298                 ast_log(LOG_ERROR, "Unable to get_rtp_info for peer type %s\n", glue->type);
2299                 ast_channel_unlock(peer);
2300                 return -1;
2301         }
2302         if (peer_instance->engine != instance->engine) {
2303                 ast_log(LOG_ERROR, "Peer engine mismatch for type %s\n", glue->type);
2304                 ast_channel_unlock(peer);
2305                 ao2_ref(peer_instance, -1);
2306                 return -1;
2307         }
2308
2309         /*
2310          * XXX Good thing nothing calls this function because we would need
2311          * deadlock avoidance to get the two instance locks.
2312          */
2313         res = instance->engine->make_compatible(chan, instance, peer, peer_instance);
2314
2315         ast_channel_unlock(peer);
2316
2317         ao2_ref(peer_instance, -1);
2318         peer_instance = NULL;
2319
2320         return res;
2321 }
2322
2323 void ast_rtp_instance_available_formats(struct ast_rtp_instance *instance, struct ast_format_cap *to_endpoint, struct ast_format_cap *to_asterisk, struct ast_format_cap *result)
2324 {
2325         if (instance->engine->available_formats) {
2326                 ao2_lock(instance);
2327                 instance->engine->available_formats(instance, to_endpoint, to_asterisk, result);
2328                 ao2_unlock(instance);
2329                 if (ast_format_cap_count(result)) {
2330                         return;
2331                 }
2332         }
2333
2334         ast_translate_available_formats(to_endpoint, to_asterisk, result);
2335 }
2336
2337 int ast_rtp_instance_activate(struct ast_rtp_instance *instance)
2338 {
2339         int res;
2340
2341         if (instance->engine->activate) {
2342                 ao2_lock(instance);
2343                 res = instance->engine->activate(instance);
2344                 ao2_unlock(instance);
2345         } else {
2346                 res = 0;
2347         }
2348         return res;
2349 }
2350
2351 void ast_rtp_instance_stun_request(struct ast_rtp_instance *instance,
2352                                    struct ast_sockaddr *suggestion,
2353                                    const char *username)
2354 {
2355         if (instance->engine->stun_request) {
2356                 instance->engine->stun_request(instance, suggestion, username);
2357         }
2358 }
2359
2360 void ast_rtp_instance_set_timeout(struct ast_rtp_instance *instance, int timeout)
2361 {
2362         instance->timeout = timeout;
2363 }
2364
2365 void ast_rtp_instance_set_hold_timeout(struct ast_rtp_instance *instance, int timeout)
2366 {
2367         instance->holdtimeout = timeout;
2368 }
2369
2370 void ast_rtp_instance_set_keepalive(struct ast_rtp_instance *instance, int interval)
2371 {
2372         instance->keepalive = interval;
2373 }
2374
2375 int ast_rtp_instance_get_timeout(struct ast_rtp_instance *instance)
2376 {
2377         return instance->timeout;
2378 }
2379
2380 int ast_rtp_instance_get_hold_timeout(struct ast_rtp_instance *instance)
2381 {
2382         return instance->holdtimeout;
2383 }
2384
2385 int ast_rtp_instance_get_keepalive(struct ast_rtp_instance *instance)
2386 {
2387         return instance->keepalive;
2388 }
2389
2390 struct ast_rtp_engine *ast_rtp_instance_get_engine(struct ast_rtp_instance *instance)
2391 {
2392         return instance->engine;
2393 }
2394
2395 struct ast_rtp_glue *ast_rtp_instance_get_active_glue(struct ast_rtp_instance *instance)
2396 {
2397         return instance->glue;
2398 }
2399
2400 int ast_rtp_engine_register_srtp(struct ast_srtp_res *srtp_res, struct ast_srtp_policy_res *policy_res)
2401 {
2402         if (res_srtp || res_srtp_policy) {
2403                 return -1;
2404         }
2405         if (!srtp_res || !policy_res) {
2406                 return -1;
2407         }
2408
2409         res_srtp = srtp_res;
2410         res_srtp_policy = policy_res;
2411
2412         return 0;
2413 }
2414
2415 void ast_rtp_engine_unregister_srtp(void)
2416 {
2417         res_srtp = NULL;
2418         res_srtp_policy = NULL;
2419 }
2420
2421 int ast_rtp_engine_srtp_is_registered(void)
2422 {
2423         return res_srtp && res_srtp_policy;
2424 }
2425
2426 int ast_rtp_instance_add_srtp_policy(struct ast_rtp_instance *instance, struct ast_srtp_policy *remote_policy, struct ast_srtp_policy *local_policy, int rtcp)
2427 {
2428         int res = 0;
2429         struct ast_srtp **srtp;
2430
2431         if (!res_srtp) {
2432                 return -1;
2433         }
2434
2435
2436         srtp = rtcp ? &instance->rtcp_srtp : &instance->srtp;
2437
2438         if (!*srtp) {
2439                 res = res_srtp->create(srtp, instance, remote_policy);
2440         } else if (remote_policy) {
2441                 res = res_srtp->replace(srtp, instance, remote_policy);
2442         }
2443         if (!res) {
2444                 res = res_srtp->add_stream(*srtp, local_policy);
2445         }
2446
2447         return res;
2448 }
2449
2450 struct ast_srtp *ast_rtp_instance_get_srtp(struct ast_rtp_instance *instance, int rtcp)
2451 {
2452         if (rtcp && instance->rtcp_srtp) {
2453                 return instance->rtcp_srtp;
2454         } else {
2455                 return instance->srtp;
2456         }
2457 }
2458
2459 int ast_rtp_instance_sendcng(struct ast_rtp_instance *instance, int level)
2460 {
2461         int res;
2462
2463         if (instance->engine->sendcng) {
2464                 ao2_lock(instance);
2465                 res = instance->engine->sendcng(instance, level);
2466                 ao2_unlock(instance);
2467         } else {
2468                 res = -1;
2469         }
2470         return res;
2471 }
2472
2473 static void rtp_ice_wrap_set_authentication(struct ast_rtp_instance *instance, const char *ufrag, const char *password)
2474 {
2475         ao2_lock(instance);
2476         instance->engine->ice->set_authentication(instance, ufrag, password);
2477         ao2_unlock(instance);
2478 }
2479
2480 static void rtp_ice_wrap_add_remote_candidate(struct ast_rtp_instance *instance, const struct ast_rtp_engine_ice_candidate *candidate)
2481 {
2482         ao2_lock(instance);
2483         instance->engine->ice->add_remote_candidate(instance, candidate);
2484         ao2_unlock(instance);
2485 }
2486
2487 static void rtp_ice_wrap_start(struct ast_rtp_instance *instance)
2488 {
2489         ao2_lock(instance);
2490         instance->engine->ice->start(instance);
2491         ao2_unlock(instance);
2492 }
2493
2494 static void rtp_ice_wrap_stop(struct ast_rtp_instance *instance)
2495 {
2496         ao2_lock(instance);
2497         instance->engine->ice->stop(instance);
2498         ao2_unlock(instance);
2499 }
2500
2501 static const char *rtp_ice_wrap_get_ufrag(struct ast_rtp_instance *instance)
2502 {
2503         const char *ufrag;
2504
2505         ao2_lock(instance);
2506         ufrag = instance->engine->ice->get_ufrag(instance);
2507         ao2_unlock(instance);
2508         return ufrag;
2509 }
2510
2511 static const char *rtp_ice_wrap_get_password(struct ast_rtp_instance *instance)
2512 {
2513         const char *password;
2514
2515         ao2_lock(instance);
2516         password = instance->engine->ice->get_password(instance);
2517         ao2_unlock(instance);
2518         return password;
2519 }
2520
2521 static struct ao2_container *rtp_ice_wrap_get_local_candidates(struct ast_rtp_instance *instance)
2522 {
2523         struct ao2_container *local_candidates;
2524
2525         ao2_lock(instance);
2526         local_candidates = instance->engine->ice->get_local_candidates(instance);
2527         ao2_unlock(instance);
2528         return local_candidates;
2529 }
2530
2531 static void rtp_ice_wrap_ice_lite(struct ast_rtp_instance *instance)
2532 {
2533         ao2_lock(instance);
2534         instance->engine->ice->ice_lite(instance);
2535         ao2_unlock(instance);
2536 }
2537
2538 static void rtp_ice_wrap_set_role(struct ast_rtp_instance *instance,
2539         enum ast_rtp_ice_role role)
2540 {
2541         ao2_lock(instance);
2542         instance->engine->ice->set_role(instance, role);
2543         ao2_unlock(instance);
2544 }
2545
2546 static void rtp_ice_wrap_turn_request(struct ast_rtp_instance *instance,
2547         enum ast_rtp_ice_component_type component, enum ast_transport transport,
2548         const char *server, unsigned int port, const char *username, const char *password)
2549 {
2550         ao2_lock(instance);
2551         instance->engine->ice->turn_request(instance, component, transport, server, port,
2552                 username, password);
2553         ao2_unlock(instance);
2554 }
2555
2556 static void rtp_ice_wrap_change_components(struct ast_rtp_instance *instance,
2557         int num_components)
2558 {
2559         ao2_lock(instance);
2560         instance->engine->ice->change_components(instance, num_components);
2561         ao2_unlock(instance);
2562 }
2563
2564 static struct ast_rtp_engine_ice rtp_ice_wrappers = {
2565         .set_authentication = rtp_ice_wrap_set_authentication,
2566         .add_remote_candidate = rtp_ice_wrap_add_remote_candidate,
2567         .start = rtp_ice_wrap_start,
2568         .stop = rtp_ice_wrap_stop,
2569         .get_ufrag = rtp_ice_wrap_get_ufrag,
2570         .get_password = rtp_ice_wrap_get_password,
2571         .get_local_candidates = rtp_ice_wrap_get_local_candidates,
2572         .ice_lite = rtp_ice_wrap_ice_lite,
2573         .set_role = rtp_ice_wrap_set_role,
2574         .turn_request = rtp_ice_wrap_turn_request,
2575         .change_components = rtp_ice_wrap_change_components,
2576 };
2577
2578 struct ast_rtp_engine_ice *ast_rtp_instance_get_ice(struct ast_rtp_instance *instance)
2579 {
2580         if (instance->engine->ice) {
2581                 return &rtp_ice_wrappers;
2582         }
2583         /* ICE not available */
2584         return NULL;
2585 }
2586
2587 static int rtp_dtls_wrap_set_configuration(struct ast_rtp_instance *instance,
2588         const struct ast_rtp_dtls_cfg *dtls_cfg)
2589 {
2590         int set_configuration;
2591
2592         ao2_lock(instance);
2593         set_configuration = instance->engine->dtls->set_configuration(instance, dtls_cfg);
2594         ao2_unlock(instance);
2595         return set_configuration;
2596 }
2597
2598 static int rtp_dtls_wrap_active(struct ast_rtp_instance *instance)
2599 {
2600         int active;
2601
2602         ao2_lock(instance);
2603         active = instance->engine->dtls->active(instance);
2604         ao2_unlock(instance);
2605         return active;
2606 }
2607
2608 static void rtp_dtls_wrap_stop(struct ast_rtp_instance *instance)
2609 {
2610         ao2_lock(instance);
2611         instance->engine->dtls->stop(instance);
2612         ao2_unlock(instance);
2613 }
2614
2615 static void rtp_dtls_wrap_reset(struct ast_rtp_instance *instance)
2616 {
2617         ao2_lock(instance);
2618         instance->engine->dtls->reset(instance);
2619         ao2_unlock(instance);
2620 }
2621
2622 static enum ast_rtp_dtls_connection rtp_dtls_wrap_get_connection(struct ast_rtp_instance *instance)
2623 {
2624         enum ast_rtp_dtls_connection get_connection;
2625
2626         ao2_lock(instance);
2627         get_connection = instance->engine->dtls->get_connection(instance);
2628         ao2_unlock(instance);
2629         return get_connection;
2630 }
2631
2632 static enum ast_rtp_dtls_setup rtp_dtls_wrap_get_setup(struct ast_rtp_instance *instance)
2633 {
2634         enum ast_rtp_dtls_setup get_setup;
2635
2636         ao2_lock(instance);
2637         get_setup = instance->engine->dtls->get_setup(instance);
2638         ao2_unlock(instance);
2639         return get_setup;
2640 }
2641
2642 static void rtp_dtls_wrap_set_setup(struct ast_rtp_instance *instance,
2643         enum ast_rtp_dtls_setup setup)
2644 {
2645         ao2_lock(instance);
2646         instance->engine->dtls->set_setup(instance, setup);
2647         ao2_unlock(instance);
2648 }
2649
2650 static void rtp_dtls_wrap_set_fingerprint(struct ast_rtp_instance *instance,
2651         enum ast_rtp_dtls_hash hash, const char *fingerprint)
2652 {
2653         ao2_lock(instance);
2654         instance->engine->dtls->set_fingerprint(instance, hash, fingerprint);
2655         ao2_unlock(instance);
2656 }
2657
2658 static enum ast_rtp_dtls_hash rtp_dtls_wrap_get_fingerprint_hash(struct ast_rtp_instance *instance)
2659 {
2660         enum ast_rtp_dtls_hash get_fingerprint_hash;
2661
2662         ao2_lock(instance);
2663         get_fingerprint_hash = instance->engine->dtls->get_fingerprint_hash(instance);
2664         ao2_unlock(instance);
2665         return get_fingerprint_hash;
2666 }
2667
2668 static const char *rtp_dtls_wrap_get_fingerprint(struct ast_rtp_instance *instance)
2669 {
2670         const char *get_fingerprint;
2671
2672         ao2_lock(instance);
2673         get_fingerprint = instance->engine->dtls->get_fingerprint(instance);
2674         ao2_unlock(instance);
2675         return get_fingerprint;
2676 }
2677
2678 static struct ast_rtp_engine_dtls rtp_dtls_wrappers = {
2679         .set_configuration = rtp_dtls_wrap_set_configuration,
2680         .active = rtp_dtls_wrap_active,
2681         .stop = rtp_dtls_wrap_stop,
2682         .reset = rtp_dtls_wrap_reset,
2683         .get_connection = rtp_dtls_wrap_get_connection,
2684         .get_setup = rtp_dtls_wrap_get_setup,
2685         .set_setup = rtp_dtls_wrap_set_setup,
2686         .set_fingerprint = rtp_dtls_wrap_set_fingerprint,
2687         .get_fingerprint_hash = rtp_dtls_wrap_get_fingerprint_hash,
2688         .get_fingerprint = rtp_dtls_wrap_get_fingerprint,
2689 };
2690
2691 struct ast_rtp_engine_dtls *ast_rtp_instance_get_dtls(struct ast_rtp_instance *instance)
2692 {
2693         if (instance->engine->dtls) {
2694                 return &rtp_dtls_wrappers;
2695         }
2696         /* DTLS not available */
2697         return NULL;
2698 }
2699
2700 int ast_rtp_dtls_cfg_parse(struct ast_rtp_dtls_cfg *dtls_cfg, const char *name, const char *value)
2701 {
2702         if (!strcasecmp(name, "dtlsenable")) {
2703                 dtls_cfg->enabled = ast_true(value) ? 1 : 0;
2704         } else if (!strcasecmp(name, "dtlsverify")) {
2705                 if (!strcasecmp(value, "yes")) {
2706                         dtls_cfg->verify = AST_RTP_DTLS_VERIFY_FINGERPRINT | AST_RTP_DTLS_VERIFY_CERTIFICATE;
2707                 } else if (!strcasecmp(value, "fingerprint")) {
2708                         dtls_cfg->verify = AST_RTP_DTLS_VERIFY_FINGERPRINT;
2709                 } else if (!strcasecmp(value, "certificate")) {
2710                         dtls_cfg->verify = AST_RTP_DTLS_VERIFY_CERTIFICATE;
2711                 } else if (!strcasecmp(value, "no")) {
2712                         dtls_cfg->verify = AST_RTP_DTLS_VERIFY_NONE;
2713                 } else {
2714                         return -1;
2715                 }
2716         } else if (!strcasecmp(name, "dtlsrekey")) {
2717                 if (sscanf(value, "%30u", &dtls_cfg->rekey) != 1) {
2718                         return -1;
2719                 }
2720         } else if (!strcasecmp(name, "dtlscertfile")) {
2721                 if (!ast_strlen_zero(value) && !ast_file_is_readable(value)) {
2722                         ast_log(LOG_ERROR, "%s file %s does not exist or is not readable\n", name, value);
2723                         return -1;
2724                 }
2725                 ast_free(dtls_cfg->certfile);
2726                 dtls_cfg->certfile = ast_strdup(value);
2727         } else if (!strcasecmp(name, "dtlsprivatekey")) {
2728                 if (!ast_strlen_zero(value) && !ast_file_is_readable(value)) {
2729                         ast_log(LOG_ERROR, "%s file %s does not exist or is not readable\n", name, value);
2730                         return -1;
2731                 }
2732                 ast_free(dtls_cfg->pvtfile);
2733                 dtls_cfg->pvtfile = ast_strdup(value);
2734         } else if (!strcasecmp(name, "dtlscipher")) {
2735                 ast_free(dtls_cfg->cipher);
2736                 dtls_cfg->cipher = ast_strdup(value);
2737         } else if (!strcasecmp(name, "dtlscafile")) {
2738                 if (!ast_strlen_zero(value) && !ast_file_is_readable(value)) {
2739                         ast_log(LOG_ERROR, "%s file %s does not exist or is not readable\n", name, value);
2740                         return -1;
2741                 }
2742                 ast_free(dtls_cfg->cafile);
2743                 dtls_cfg->cafile = ast_strdup(value);
2744         } else if (!strcasecmp(name, "dtlscapath") || !strcasecmp(name, "dtlscadir")) {
2745                 if (!ast_strlen_zero(value) && !ast_file_is_readable(value)) {
2746                         ast_log(LOG_ERROR, "%s file %s does not exist or is not readable\n", name, value);
2747                         return -1;
2748                 }
2749                 ast_free(dtls_cfg->capath);
2750                 dtls_cfg->capath = ast_strdup(value);
2751         } else if (!strcasecmp(name, "dtlssetup")) {
2752                 if (!strcasecmp(value, "active")) {
2753                         dtls_cfg->default_setup = AST_RTP_DTLS_SETUP_ACTIVE;
2754                 } else if (!strcasecmp(value, "passive")) {
2755                         dtls_cfg->default_setup = AST_RTP_DTLS_SETUP_PASSIVE;
2756                 } else if (!strcasecmp(value, "actpass")) {
2757                         dtls_cfg->default_setup = AST_RTP_DTLS_SETUP_ACTPASS;
2758                 }
2759         } else if (!strcasecmp(name, "dtlsfingerprint")) {
2760                 if (!strcasecmp(value, "sha-256")) {
2761                         dtls_cfg->hash = AST_RTP_DTLS_HASH_SHA256;
2762                 } else if (!strcasecmp(value, "sha-1")) {
2763                         dtls_cfg->hash = AST_RTP_DTLS_HASH_SHA1;
2764                 }
2765         } else {
2766                 return -1;
2767         }
2768
2769         return 0;
2770 }
2771
2772 void ast_rtp_dtls_cfg_copy(const struct ast_rtp_dtls_cfg *src_cfg, struct ast_rtp_dtls_cfg *dst_cfg)
2773 {
2774         ast_rtp_dtls_cfg_free(dst_cfg);         /* Prevent a double-call leaking memory via ast_strdup */
2775
2776         dst_cfg->enabled = src_cfg->enabled;
2777         dst_cfg->verify = src_cfg->verify;
2778         dst_cfg->rekey = src_cfg->rekey;
2779         dst_cfg->suite = src_cfg->suite;
2780         dst_cfg->hash = src_cfg->hash;
2781         dst_cfg->certfile = ast_strdup(src_cfg->certfile);
2782         dst_cfg->pvtfile = ast_strdup(src_cfg->pvtfile);
2783         dst_cfg->cipher = ast_strdup(src_cfg->cipher);
2784         dst_cfg->cafile = ast_strdup(src_cfg->cafile);
2785         dst_cfg->capath = ast_strdup(src_cfg->capath);
2786         dst_cfg->default_setup = src_cfg->default_setup;
2787 }
2788
2789 void ast_rtp_dtls_cfg_free(struct ast_rtp_dtls_cfg *dtls_cfg)
2790 {
2791         ast_free(dtls_cfg->certfile);
2792         dtls_cfg->certfile = NULL;
2793         ast_free(dtls_cfg->pvtfile);
2794         dtls_cfg->pvtfile = NULL;
2795         ast_free(dtls_cfg->cipher);
2796         dtls_cfg->cipher = NULL;
2797         ast_free(dtls_cfg->cafile);
2798         dtls_cfg->cafile = NULL;
2799         ast_free(dtls_cfg->capath);
2800         dtls_cfg->capath = NULL;
2801 }
2802
2803 /*! \internal
2804  * \brief Small helper routine that cleans up entry i in
2805  * \c ast_rtp_mime_types.
2806  */
2807 static void rtp_engine_mime_type_cleanup(int i)
2808 {
2809         ao2_cleanup(ast_rtp_mime_types[i].payload_type.format);
2810         memset(&ast_rtp_mime_types[i], 0, sizeof(struct ast_rtp_mime_type));
2811 }
2812
2813 static void set_next_mime_type(struct ast_format *format, int rtp_code, const char *type, const char *subtype, unsigned int sample_rate)
2814 {
2815         int x;
2816
2817         ast_rwlock_wrlock(&mime_types_lock);
2818
2819         x = mime_types_len;
2820         if (ARRAY_LEN(ast_rtp_mime_types) <= x) {
2821                 ast_rwlock_unlock(&mime_types_lock);
2822                 return;
2823         }
2824
2825         /* Make sure any previous value in ast_rtp_mime_types is cleaned up */
2826         memset(&ast_rtp_mime_types[x], 0, sizeof(struct ast_rtp_mime_type));    
2827         if (format) {
2828                 ast_rtp_mime_types[x].payload_type.asterisk_format = 1;
2829                 ast_rtp_mime_types[x].payload_type.format = ao2_bump(format);
2830         } else {
2831                 ast_rtp_mime_types[x].payload_type.rtp_code = rtp_code;
2832         }
2833         ast_copy_string(ast_rtp_mime_types[x].type, type, sizeof(ast_rtp_mime_types[x].type));
2834         ast_copy_string(ast_rtp_mime_types[x].subtype, subtype, sizeof(ast_rtp_mime_types[x].subtype));
2835         ast_rtp_mime_types[x].sample_rate = sample_rate;
2836         mime_types_len++;
2837
2838         ast_rwlock_unlock(&mime_types_lock);
2839 }
2840
2841 static void add_static_payload(int payload, struct ast_format *format, int rtp_code)
2842 {
2843         struct ast_rtp_payload_type *type;
2844
2845         /*
2846          * ARRAY_LEN's result is cast to an int so 'map' is not autocast to a size_t,
2847          * which if negative would cause an assertion.
2848          */
2849         ast_assert(payload < (int)ARRAY_LEN(static_RTP_PT));
2850
2851         if (ast_option_rtpusedynamic && payload < 0) {
2852                 /*
2853                  * We're going to build dynamic payloads dynamically. An RTP code is
2854                  * required otherwise one will be dynamically allocated per instance.
2855                  */
2856                 return;
2857         }
2858
2859         /*
2860          * Either the given payload is truly a static type, or Asterisk is
2861          * globally storing the dynamic payloads in the static_RTP_PT object.
2862          */
2863         ast_rwlock_wrlock(&static_RTP_PT_lock);
2864
2865         if (payload < 0) {
2866                 /*
2867                  * This is a dynamic payload that will be stored globally,
2868                  * so find the next available empty slot.
2869                  */
2870                 payload = find_unused_payload(NULL);
2871                 if (payload < 0) {
2872                         ast_log(LOG_WARNING, "No dynamic RTP payload type values available "
2873                                 "for %s - %d!\n", format ? ast_format_get_name(format) : "", rtp_code);
2874                         return;
2875                 }
2876         }
2877
2878         type = rtp_payload_type_alloc(format, payload, rtp_code, 1);
2879         if (type) {
2880                 ao2_cleanup(static_RTP_PT[payload]);
2881                 static_RTP_PT[payload] = type;
2882         }
2883         ast_rwlock_unlock(&static_RTP_PT_lock);
2884 }
2885
2886 int ast_rtp_engine_load_format(struct ast_format *format)
2887 {
2888         set_next_mime_type(format,
2889                 0,
2890                 ast_codec_media_type2str(ast_format_get_type(format)),
2891                 ast_format_get_codec_name(format),
2892                 ast_format_get_sample_rate(format));
2893         add_static_payload(-1, format, 0);
2894
2895         return 0;
2896 }
2897
2898 int ast_rtp_engine_unload_format(struct ast_format *format)
2899 {
2900         int x;
2901         int y = 0;
2902
2903         ast_rwlock_wrlock(&static_RTP_PT_lock);
2904         /* remove everything pertaining to this format id from the lists */
2905         for (x = 0; x < AST_RTP_MAX_PT; x++) {
2906                 if (static_RTP_PT[x]
2907                         && ast_format_cmp(static_RTP_PT[x]->format, format) == AST_FORMAT_CMP_EQUAL) {
2908                         ao2_ref(static_RTP_PT[x], -1);
2909                         static_RTP_PT[x] = NULL;
2910                 }
2911         }
2912         ast_rwlock_unlock(&static_RTP_PT_lock);
2913
2914         ast_rwlock_wrlock(&mime_types_lock);
2915         /* rebuild the list skipping the items matching this id */
2916         for (x = 0; x < mime_types_len; x++) {
2917                 if (ast_format_cmp(ast_rtp_mime_types[x].payload_type.format, format) == AST_FORMAT_CMP_EQUAL) {
2918                         rtp_engine_mime_type_cleanup(x);
2919                         continue;
2920                 }
2921                 if (x != y) {
2922                         ast_rtp_mime_types[y] = ast_rtp_mime_types[x];
2923                 }
2924                 y++;
2925         }
2926         mime_types_len = y;
2927         ast_rwlock_unlock(&mime_types_lock);
2928         return 0;
2929 }
2930
2931 /*!
2932  * \internal
2933  * \brief \ref stasis message payload for RTCP messages
2934  */
2935 struct rtcp_message_payload {
2936         struct ast_channel_snapshot *snapshot;  /*< The channel snapshot, if available */
2937         struct ast_rtp_rtcp_report *report;     /*< The RTCP report */
2938         struct ast_json *blob;                  /*< Extra JSON data to publish */
2939 };
2940
2941 static void rtcp_message_payload_dtor(void *obj)
2942 {
2943         struct rtcp_message_payload *payload = obj;
2944
2945         ao2_cleanup(payload->report);
2946         ao2_cleanup(payload->snapshot);
2947         ast_json_unref(payload->blob);
2948 }
2949
2950 static struct ast_manager_event_blob *rtcp_report_to_ami(struct stasis_message *msg)
2951 {
2952         struct rtcp_message_payload *payload = stasis_message_data(msg);
2953         RAII_VAR(struct ast_str *, channel_string, NULL, ast_free);
2954         RAII_VAR(struct ast_str *, packet_string, ast_str_create(512), ast_free);
2955         unsigned int ssrc = payload->report->ssrc;
2956         unsigned int type = payload->report->type;
2957         unsigned int report_count = payload->report->reception_report_count;
2958         int i;
2959
2960         if (!packet_string) {
2961                 return NULL;
2962         }
2963
2964         if (payload->snapshot) {
2965                 channel_string = ast_manager_build_channel_state_string(payload->snapshot);
2966                 if (!channel_string) {
2967                         return NULL;
2968                 }
2969         }
2970
2971         if (payload->blob) {
2972                 /* Optional data */
2973                 struct ast_json *to = ast_json_object_get(payload->blob, "to");
2974                 struct ast_json *from = ast_json_object_get(payload->blob, "from");
2975                 struct ast_json *rtt = ast_json_object_get(payload->blob, "rtt");
2976                 if (to) {
2977                         ast_str_append(&packet_string, 0, "To: %s\r\n", ast_json_string_get(to));
2978                 }
2979                 if (from) {
2980                         ast_str_append(&packet_string, 0, "From: %s\r\n", ast_json_string_get(from));
2981                 }
2982                 if (rtt) {
2983                         ast_str_append(&packet_string, 0, "RTT: %4.4f\r\n", ast_json_real_get(rtt));
2984                 }
2985         }
2986
2987         ast_str_append(&packet_string, 0, "SSRC: 0x%.8x\r\n", ssrc);
2988         ast_str_append(&packet_string, 0, "PT: %u(%s)\r\n", type, type== AST_RTP_RTCP_SR ? "SR" : "RR");
2989         ast_str_append(&packet_string, 0, "ReportCount: %u\r\n", report_count);
2990         if (type == AST_RTP_RTCP_SR) {
2991                 ast_str_append(&packet_string, 0, "SentNTP: %lu.%06lu\r\n",
2992                         (unsigned long)payload->report->sender_information.ntp_timestamp.tv_sec,
2993                         (unsigned long)payload->report->sender_information.ntp_timestamp.tv_usec);
2994                 ast_str_append(&packet_string, 0, "SentRTP: %u\r\n",
2995                                 payload->report->sender_information.rtp_timestamp);
2996                 ast_str_append(&packet_string, 0, "SentPackets: %u\r\n",
2997                                 payload->report->sender_information.packet_count);
2998                 ast_str_append(&packet_string, 0, "SentOctets: %u\r\n",
2999                                 payload->report->sender_information.octet_count);
3000         }
3001
3002         for (i = 0; i < report_count; i++) {
3003                 RAII_VAR(struct ast_str *, report_string, NULL, ast_free);
3004
3005                 if (!payload->report->report_block[i]) {
3006                         break;
3007                 }
3008
3009                 report_string = ast_str_create(256);
3010                 if (!report_string) {
3011                         return NULL;
3012                 }
3013
3014                 ast_str_append(&report_string, 0, "Report%dSourceSSRC: 0x%.8x\r\n",
3015                                 i, payload->report->report_block[i]->source_ssrc);
3016                 ast_str_append(&report_string, 0, "Report%dFractionLost: %d\r\n",
3017                                 i, payload->report->report_block[i]->lost_count.fraction);
3018                 ast_str_append(&report_string, 0, "Report%dCumulativeLost: %u\r\n",
3019                                 i, payload->report->report_block[i]->lost_count.packets);
3020                 ast_str_append(&report_string, 0, "Report%dHighestSequence: %u\r\n",
3021                                 i, payload->report->report_block[i]->highest_seq_no & 0xffff);
3022                 ast_str_append(&report_string, 0, "Report%dSequenceNumberCycles: %u\r\n",
3023                                 i, payload->report->report_block[i]->highest_seq_no >> 16);
3024                 ast_str_append(&report_string, 0, "Report%dIAJitter: %u\r\n",
3025                                 i, payload->report->report_block[i]->ia_jitter);
3026                 ast_str_append(&report_string, 0, "Report%dLSR: %u\r\n",
3027                                 i, payload->report->report_block[i]->lsr);
3028                 ast_str_append(&report_string, 0, "Report%dDLSR: %4.4f\r\n",
3029                                 i, ((double)payload->report->report_block[i]->dlsr) / 65536);
3030                 ast_str_append(&packet_string, 0, "%s", ast_str_buffer(report_string));
3031         }
3032
3033         return ast_manager_event_blob_create(EVENT_FLAG_REPORTING,
3034                 stasis_message_type(msg) == ast_rtp_rtcp_received_type() ? "RTCPReceived" : "RTCPSent",
3035                 "%s%s",
3036                 AS_OR(channel_string, ""),
3037                 ast_str_buffer(packet_string));
3038 }
3039
3040 static struct ast_json *rtcp_report_to_json(struct stasis_message *msg,
3041         const struct stasis_message_sanitizer *sanitize)
3042 {
3043         struct rtcp_message_payload *payload = stasis_message_data(msg);
3044         RAII_VAR(struct ast_json *, json_rtcp_report, NULL, ast_json_unref);
3045         RAII_VAR(struct ast_json *, json_rtcp_report_blocks, NULL, ast_json_unref);
3046         RAII_VAR(struct ast_json *, json_rtcp_sender_info, NULL, ast_json_unref);
3047         RAII_VAR(struct ast_json *, json_channel, NULL, ast_json_unref);
3048         int i;
3049
3050         json_rtcp_report_blocks = ast_json_array_create();
3051         if (!json_rtcp_report_blocks) {
3052                 return NULL;
3053         }
3054
3055         for (i = 0; i < payload->report->reception_report_count && payload->report->report_block[i]; i++) {
3056                 struct ast_json *json_report_block;
3057                 char str_lsr[32];
3058                 snprintf(str_lsr, sizeof(str_lsr), "%u", payload->report->report_block[i]->lsr);
3059                 json_report_block = ast_json_pack("{s: i, s: i, s: i, s: i, s: i, s: s, s: i}",
3060                                 "source_ssrc", payload->report->report_block[i]->source_ssrc,
3061                                 "fraction_lost", payload->report->report_block[i]->lost_count.fraction,
3062                                 "packets_lost", payload->report->report_block[i]->lost_count.packets,
3063                                 "highest_seq_no", payload->report->report_block[i]->highest_seq_no,
3064                                 "ia_jitter", payload->report->report_block[i]->ia_jitter,
3065                                 "lsr", str_lsr,
3066                                 "dlsr", payload->report->report_block[i]->dlsr);
3067                 if (!json_report_block) {
3068                         return NULL;
3069                 }
3070
3071                 if (ast_json_array_append(json_rtcp_report_blocks, json_report_block)) {
3072                         return NULL;
3073                 }
3074         }
3075
3076         if (payload->report->type == AST_RTP_RTCP_SR) {
3077                 char sec[32];
3078                 char usec[32];
3079                 snprintf(sec, sizeof(sec), "%lu", (unsigned long)payload->report->sender_information.ntp_timestamp.tv_sec);
3080                 snprintf(usec, sizeof(usec), "%lu", (unsigned long)payload->report->sender_information.ntp_timestamp.tv_usec);
3081                 json_rtcp_sender_info = ast_json_pack("{s: s, s: s, s: i, s: i, s: i}",
3082                                 "ntp_timestamp_sec", sec,
3083                                 "ntp_timestamp_usec", usec,
3084                                 "rtp_timestamp", payload->report->sender_information.rtp_timestamp,
3085                                 "packets", payload->report->sender_information.packet_count,
3086                                 "octets", payload->report->sender_information.octet_count);
3087                 if (!json_rtcp_sender_info) {
3088                         return NULL;
3089                 }
3090         }
3091
3092         json_rtcp_report = ast_json_pack("{s: i, s: i, s: i, s: o, s: o}",
3093                         "ssrc", payload->report->ssrc,
3094                         "type", payload->report->type,
3095                         "report_count", payload->report->reception_report_count,
3096                         "sender_information", json_rtcp_sender_info ? ast_json_ref(json_rtcp_sender_info) : ast_json_ref(ast_json_null()),
3097                         "report_blocks", ast_json_ref(json_rtcp_report_blocks));
3098         if (!json_rtcp_report) {
3099                 return NULL;
3100         }
3101
3102         if (payload->snapshot) {
3103                 json_channel = ast_channel_snapshot_to_json(payload->snapshot, sanitize);
3104                 if (!json_channel) {
3105                         return NULL;
3106                 }
3107         }
3108
3109         return ast_json_pack("{s: o, s: o, s: o}",
3110                 "channel", payload->snapshot ? ast_json_ref(json_channel) : ast_json_ref(ast_json_null()),
3111                 "rtcp_report", ast_json_ref(json_rtcp_report),
3112                 "blob", ast_json_deep_copy(payload->blob));
3113 }
3114
3115 static void rtp_rtcp_report_dtor(void *obj)
3116 {
3117         int i;
3118         struct ast_rtp_rtcp_report *rtcp_report = obj;
3119
3120         for (i = 0; i < rtcp_report->reception_report_count; i++) {
3121                 ast_free(rtcp_report->report_block[i]);
3122         }
3123 }
3124
3125 struct ast_rtp_rtcp_report *ast_rtp_rtcp_report_alloc(unsigned int report_blocks)
3126 {
3127         struct ast_rtp_rtcp_report *rtcp_report;
3128
3129         /* Size of object is sizeof the report + the number of report_blocks * sizeof pointer */
3130         rtcp_report = ao2_alloc((sizeof(*rtcp_report) + report_blocks * sizeof(struct ast_rtp_rtcp_report_block *)),
3131                 rtp_rtcp_report_dtor);
3132
3133         return rtcp_report;
3134 }
3135
3136 void ast_rtp_publish_rtcp_message(struct ast_rtp_instance *rtp,
3137                 struct stasis_message_type *message_type,
3138                 struct ast_rtp_rtcp_report *report,
3139                 struct ast_json *blob)
3140 {
3141         RAII_VAR(struct rtcp_message_payload *, payload, NULL, ao2_cleanup);
3142         RAII_VAR(struct stasis_message *, message, NULL, ao2_cleanup);
3143
3144         if (!message_type) {
3145                 return;
3146         }
3147
3148         payload = ao2_alloc(sizeof(*payload), rtcp_message_payload_dtor);
3149         if (!payload || !report) {
3150                 return;
3151         }
3152
3153         if (!ast_strlen_zero(rtp->channel_uniqueid)) {
3154                 payload->snapshot = ast_channel_snapshot_get_latest(rtp->channel_uniqueid);
3155         }
3156         if (blob) {
3157                 payload->blob = blob;
3158                 ast_json_ref(blob);
3159         }
3160         ao2_ref(report, +1);
3161         payload->report = report;
3162
3163         message = stasis_message_create(message_type, payload);
3164         if (!message) {
3165                 return;
3166         }
3167
3168         stasis_publish(ast_rtp_topic(), message);
3169 }
3170
3171 /*!
3172  * @{ \brief Define RTCP/RTP message types.
3173  */
3174 STASIS_MESSAGE_TYPE_DEFN(ast_rtp_rtcp_sent_type,
3175                 .to_ami = rtcp_report_to_ami,
3176                 .to_json = rtcp_report_to_json,);
3177 STASIS_MESSAGE_TYPE_DEFN(ast_rtp_rtcp_received_type,
3178                 .to_ami = rtcp_report_to_ami,
3179                 .to_json = rtcp_report_to_json,);
3180 /*! @} */
3181
3182 struct stasis_topic *ast_rtp_topic(void)
3183 {
3184         return rtp_topic;
3185 }
3186
3187 static void rtp_engine_shutdown(void)
3188 {
3189         int x;
3190
3191         ao2_cleanup(rtp_topic);
3192         rtp_topic = NULL;
3193         STASIS_MESSAGE_TYPE_CLEANUP(ast_rtp_rtcp_received_type);
3194         STASIS_MESSAGE_TYPE_CLEANUP(ast_rtp_rtcp_sent_type);
3195
3196         ast_rwlock_wrlock(&static_RTP_PT_lock);
3197         for (x = 0; x < AST_RTP_MAX_PT; x++) {
3198                 ao2_cleanup(static_RTP_PT[x]);
3199                 static_RTP_PT[x] = NULL;
3200         }
3201         ast_rwlock_unlock(&static_RTP_PT_lock);
3202
3203         ast_rwlock_wrlock(&mime_types_lock);
3204         for (x = 0; x < mime_types_len; x++) {
3205                 if (ast_rtp_mime_types[x].payload_type.format) {
3206                         rtp_engine_mime_type_cleanup(x);
3207                 }
3208         }
3209         mime_types_len = 0;
3210         ast_rwlock_unlock(&mime_types_lock);
3211 }
3212
3213 int ast_rtp_engine_init(void)
3214 {
3215         ast_rwlock_init(&mime_types_lock);
3216         ast_rwlock_init(&static_RTP_PT_lock);
3217
3218         rtp_topic = stasis_topic_create("rtp_topic");
3219         if (!rtp_topic) {
3220                 return -1;
3221         }
3222         STASIS_MESSAGE_TYPE_INIT(ast_rtp_rtcp_sent_type);
3223         STASIS_MESSAGE_TYPE_INIT(ast_rtp_rtcp_received_type);
3224         ast_register_cleanup(rtp_engine_shutdown);
3225
3226         /* Define all the RTP mime types available */
3227         set_next_mime_type(ast_format_g723, 0, "audio", "G723", 8000);
3228         set_next_mime_type(ast_format_gsm, 0, "audio", "GSM", 8000);
3229         set_next_mime_type(ast_format_ulaw, 0, "audio", "PCMU", 8000);
3230         set_next_mime_type(ast_format_ulaw, 0, "audio", "G711U", 8000);
3231         set_next_mime_type(ast_format_alaw, 0, "audio", "PCMA", 8000);
3232         set_next_mime_type(ast_format_alaw, 0, "audio", "G711A", 8000);
3233         set_next_mime_type(ast_format_g726, 0, "audio", "G726-32", 8000);
3234         set_next_mime_type(ast_format_adpcm, 0, "audio", "DVI4", 8000);
3235         set_next_mime_type(ast_format_slin, 0, "audio", "L16", 8000);
3236         set_next_mime_type(ast_format_slin16, 0, "audio", "L16", 16000);
3237         set_next_mime_type(ast_format_slin16, 0, "audio", "L16-256", 16000);
3238         set_next_mime_type(ast_format_slin12, 0, "audio", "L16", 12000);
3239         set_next_mime_type(ast_format_slin24, 0, "audio", "L16", 24000);
3240         set_next_mime_type(ast_format_slin32, 0, "audio", "L16", 32000);
3241         set_next_mime_type(ast_format_slin44, 0, "audio", "L16", 44000);
3242         set_next_mime_type(ast_format_slin48, 0, "audio", "L16", 48000);
3243         set_next_mime_type(ast_format_slin96, 0, "audio", "L16", 96000);
3244         set_next_mime_type(ast_format_slin192, 0, "audio", "L16", 192000);
3245         set_next_mime_type(ast_format_lpc10, 0, "audio", "LPC", 8000);
3246         set_next_mime_type(ast_format_g729, 0, "audio", "G729", 8000);
3247         set_next_mime_type(ast_format_g729, 0, "audio", "G729A", 8000);
3248         set_next_mime_type(ast_format_g729, 0, "audio", "G.729", 8000);
3249         set_next_mime_type(ast_format_speex, 0, "audio", "speex", 8000);
3250         set_next_mime_type(ast_format_speex16, 0,  "audio", "speex", 16000);
3251         set_next_mime_type(ast_format_speex32, 0,  "audio", "speex", 32000);
3252         set_next_mime_type(ast_format_ilbc, 0, "audio", "iLBC", 8000);
3253         /* this is the sample rate listed in the RTP profile for the G.722 codec, *NOT* the actual sample rate of the media stream */
3254         set_next_mime_type(ast_format_g722, 0, "audio", "G722", 8000);
3255         set_next_mime_type(ast_format_g726_aal2, 0, "audio", "AAL2-G726-32", 8000);
3256         set_next_mime_type(NULL, AST_RTP_DTMF, "audio", "telephone-event", 8000);
3257         set_next_mime_type(NULL, AST_RTP_CISCO_DTMF, "audio", "cisco-telephone-event", 8000);
3258         set_next_mime_type(NULL, AST_RTP_CN, "audio", "CN", 8000);
3259         set_next_mime_type(ast_format_jpeg, 0, "video", "JPEG", 90000);
3260         set_next_mime_type(ast_format_png, 0, "video", "PNG", 90000);
3261         set_next_mime_type(ast_format_h261, 0, "video", "H261", 90000);
3262         set_next_mime_type(ast_format_h263, 0, "video", "H263", 90000);
3263         set_next_mime_type(ast_format_h263p, 0, "video", "h263-1998", 90000);
3264         set_next_mime_type(ast_format_h264, 0, "video", "H264", 90000);
3265         set_next_mime_type(ast_format_mp4, 0, "video", "MP4V-ES", 90000);
3266         set_next_mime_type(ast_format_t140_red, 0, "text", "RED", 1000);
3267         set_next_mime_type(ast_format_t140, 0, "text", "T140", 1000);
3268         set_next_mime_type(ast_format_siren7, 0, "audio", "G7221", 16000);
3269         set_next_mime_type(ast_format_siren14, 0, "audio", "G7221", 32000);
3270         set_next_mime_type(ast_format_g719, 0, "audio", "G719", 48000);
3271         /* Opus, VP8, and VP9 */
3272         set_next_mime_type(ast_format_opus, 0,  "audio", "opus", 48000);
3273         set_next_mime_type(ast_format_vp8, 0,  "video", "VP8", 90000);
3274         set_next_mime_type(ast_format_vp9, 0, "video", "VP9", 90000);
3275
3276         /* Define the static rtp payload mappings */
3277         add_static_payload(0, ast_format_ulaw, 0);
3278         #ifdef USE_DEPRECATED_G726
3279         add_static_payload(2, ast_format_g726, 0);/* Technically this is G.721, but if Cisco can do it, so can we... */
3280         #endif
3281         add_static_payload(3, ast_format_gsm, 0);
3282         add_static_payload(4, ast_format_g723, 0);
3283         add_static_payload(5, ast_format_adpcm, 0);/* 8 kHz */
3284         add_static_payload(6, ast_format_adpcm, 0); /* 16 kHz */
3285         add_static_payload(7, ast_format_lpc10, 0);
3286         add_static_payload(8, ast_format_alaw, 0);
3287         add_static_payload(9, ast_format_g722, 0);
3288         add_static_payload(10, ast_format_slin, 0); /* 2 channels */
3289         add_static_payload(11, ast_format_slin, 0); /* 1 channel */
3290         add_static_payload(13, NULL, AST_RTP_CN);
3291         add_static_payload(16, ast_format_adpcm, 0); /* 11.025 kHz */
3292         add_static_payload(17, ast_format_adpcm, 0); /* 22.050 kHz */
3293         add_static_payload(18, ast_format_g729, 0);
3294         add_static_payload(19, NULL, AST_RTP_CN);         /* Also used for CN */
3295         add_static_payload(26, ast_format_jpeg, 0);
3296         add_static_payload(31, ast_format_h261, 0);
3297         add_static_payload(34, ast_format_h263, 0);
3298
3299         /*
3300          * Dynamic payload types - Even when dynamically assigning them we'll fall
3301          * back to using the statically declared values as the default number.
3302          */
3303         add_static_payload(96, ast_format_slin192, 0);
3304         add_static_payload(97, ast_format_ilbc, 0);
3305         add_static_payload(98, ast_format_h263p, 0);
3306         add_static_payload(99, ast_format_h264, 0);
3307         add_static_payload(100, ast_format_vp8, 0);
3308         add_static_payload(101, NULL, AST_RTP_DTMF);
3309         add_static_payload(102, ast_format_siren7, 0);
3310         add_static_payload(103, ast_format_h263p, 0);
3311         add_static_payload(104, ast_format_mp4, 0);
3312         add_static_payload(105, ast_format_t140_red, 0);   /* Real time text chat (with redundancy encoding) */
3313         add_static_payload(106, ast_format_t140, 0);     /* Real time text chat */
3314         add_static_payload(107, ast_format_opus, 0);
3315         add_static_payload(108, ast_format_vp9, 0);
3316
3317         add_static_payload(110, ast_format_speex, 0);
3318         add_static_payload(111, ast_format_g726, 0);
3319         add_static_payload(112, ast_format_g726_aal2, 0);
3320
3321         add_static_payload(115, ast_format_siren14, 0);
3322         add_static_payload(116, ast_format_g719, 0);
3323         add_static_payload(117, ast_format_speex16, 0);
3324         add_static_payload(118, ast_format_slin16, 0); /* 16 Khz signed linear */
3325         add_static_payload(119, ast_format_speex32, 0);
3326
3327         add_static_payload(121, NULL, AST_RTP_CISCO_DTMF);   /* Must be type 121 */
3328         add_static_payload(122, ast_format_slin12, 0);
3329         add_static_payload(123, ast_format_slin24, 0);
3330         add_static_payload(124, ast_format_slin32, 0);
3331         add_static_payload(125, ast_format_slin44, 0);
3332         add_static_payload(126, ast_format_slin48, 0);
3333         add_static_payload(127, ast_format_slin96, 0);
3334         /* payload types above 127 are not valid */
3335
3336         return 0;
3337 }
3338
3339 time_t ast_rtp_instance_get_last_tx(const struct ast_rtp_instance *rtp)
3340 {
3341         return rtp->last_tx;
3342 }
3343
3344 void ast_rtp_instance_set_last_tx(struct ast_rtp_instance *rtp, time_t time)
3345 {
3346         rtp->last_tx = time;
3347 }
3348
3349 time_t ast_rtp_instance_get_last_rx(const struct ast_rtp_instance *rtp)
3350 {
3351         return rtp->last_rx;
3352 }
3353
3354 void ast_rtp_instance_set_last_rx(struct ast_rtp_instance *rtp, time_t time)
3355 {
3356         rtp->last_rx = time;
3357 }
3358
3359 unsigned int ast_rtp_instance_get_ssrc(struct ast_rtp_instance *rtp)
3360 {
3361         unsigned int ssrc = 0;
3362
3363         ao2_lock(rtp);
3364         if (rtp->engine->ssrc_get) {
3365                 ssrc = rtp->engine->ssrc_get(rtp);
3366         }
3367         ao2_unlock(rtp);
3368
3369         return ssrc;
3370 }
3371
3372 const char *ast_rtp_instance_get_cname(struct ast_rtp_instance *rtp)
3373 {
3374         const char *cname = "";
3375
3376         ao2_lock(rtp);
3377         if (rtp->engine->cname_get) {
3378                 cname = rtp->engine->cname_get(rtp);
3379         }
3380         ao2_unlock(rtp);
3381
3382         return cname;
3383 }
3384
3385 int ast_rtp_instance_bundle(struct ast_rtp_instance *child, struct ast_rtp_instance *parent)
3386 {
3387         int res = -1;
3388
3389         if (parent && (child->engine != parent->engine)) {
3390                 return -1;
3391         }
3392
3393         ao2_lock(child);
3394         if (child->engine->bundle) {
3395                 res = child->engine->bundle(child, parent);
3396         }
3397         ao2_unlock(child);
3398
3399         return res;
3400 }
3401
3402 void ast_rtp_instance_set_remote_ssrc(struct ast_rtp_instance *rtp, unsigned int ssrc)
3403 {
3404         ao2_lock(rtp);
3405         if (rtp->engine->set_remote_ssrc) {
3406                 rtp->engine->set_remote_ssrc(rtp, ssrc);
3407         }
3408         ao2_unlock(rtp);
3409 }
3410
3411 void ast_rtp_instance_set_stream_num(struct ast_rtp_instance *rtp, int stream_num)
3412 {
3413         ao2_lock(rtp);
3414         if (rtp->engine->set_stream_num) {
3415                 rtp->engine->set_stream_num(rtp, stream_num);
3416         }
3417         ao2_unlock(rtp);
3418 }